File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 15170, column 20 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// | |||
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 semantic analysis for expressions. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "TreeTransform.h" | |||
14 | #include "UsedDeclVisitor.h" | |||
15 | #include "clang/AST/ASTConsumer.h" | |||
16 | #include "clang/AST/ASTContext.h" | |||
17 | #include "clang/AST/ASTLambda.h" | |||
18 | #include "clang/AST/ASTMutationListener.h" | |||
19 | #include "clang/AST/CXXInheritance.h" | |||
20 | #include "clang/AST/DeclObjC.h" | |||
21 | #include "clang/AST/DeclTemplate.h" | |||
22 | #include "clang/AST/EvaluatedExprVisitor.h" | |||
23 | #include "clang/AST/Expr.h" | |||
24 | #include "clang/AST/ExprCXX.h" | |||
25 | #include "clang/AST/ExprObjC.h" | |||
26 | #include "clang/AST/ExprOpenMP.h" | |||
27 | #include "clang/AST/OperationKinds.h" | |||
28 | #include "clang/AST/RecursiveASTVisitor.h" | |||
29 | #include "clang/AST/TypeLoc.h" | |||
30 | #include "clang/Basic/Builtins.h" | |||
31 | #include "clang/Basic/PartialDiagnostic.h" | |||
32 | #include "clang/Basic/SourceManager.h" | |||
33 | #include "clang/Basic/TargetInfo.h" | |||
34 | #include "clang/Lex/LiteralSupport.h" | |||
35 | #include "clang/Lex/Preprocessor.h" | |||
36 | #include "clang/Sema/AnalysisBasedWarnings.h" | |||
37 | #include "clang/Sema/DeclSpec.h" | |||
38 | #include "clang/Sema/DelayedDiagnostic.h" | |||
39 | #include "clang/Sema/Designator.h" | |||
40 | #include "clang/Sema/Initialization.h" | |||
41 | #include "clang/Sema/Lookup.h" | |||
42 | #include "clang/Sema/Overload.h" | |||
43 | #include "clang/Sema/ParsedTemplate.h" | |||
44 | #include "clang/Sema/Scope.h" | |||
45 | #include "clang/Sema/ScopeInfo.h" | |||
46 | #include "clang/Sema/SemaFixItUtils.h" | |||
47 | #include "clang/Sema/SemaInternal.h" | |||
48 | #include "clang/Sema/Template.h" | |||
49 | #include "llvm/Support/ConvertUTF.h" | |||
50 | #include "llvm/Support/SaveAndRestore.h" | |||
51 | using namespace clang; | |||
52 | using namespace sema; | |||
53 | using llvm::RoundingMode; | |||
54 | ||||
55 | /// Determine whether the use of this declaration is valid, without | |||
56 | /// emitting diagnostics. | |||
57 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | |||
58 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
59 | if (ParsingInitForAutoVars.count(D)) | |||
60 | return false; | |||
61 | ||||
62 | // See if this is a deleted function. | |||
63 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
64 | if (FD->isDeleted()) | |||
65 | return false; | |||
66 | ||||
67 | // If the function has a deduced return type, and we can't deduce it, | |||
68 | // then we can't use it either. | |||
69 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
70 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | |||
71 | return false; | |||
72 | ||||
73 | // See if this is an aligned allocation/deallocation function that is | |||
74 | // unavailable. | |||
75 | if (TreatUnavailableAsInvalid && | |||
76 | isUnavailableAlignedAllocationFunction(*FD)) | |||
77 | return false; | |||
78 | } | |||
79 | ||||
80 | // See if this function is unavailable. | |||
81 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | |||
82 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | |||
83 | return false; | |||
84 | ||||
85 | return true; | |||
86 | } | |||
87 | ||||
88 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | |||
89 | // Warn if this is used but marked unused. | |||
90 | if (const auto *A = D->getAttr<UnusedAttr>()) { | |||
91 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | |||
92 | // should diagnose them. | |||
93 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | |||
94 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | |||
95 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | |||
96 | if (DC && !DC->hasAttr<UnusedAttr>()) | |||
97 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | |||
98 | } | |||
99 | } | |||
100 | } | |||
101 | ||||
102 | /// Emit a note explaining that this function is deleted. | |||
103 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | |||
104 | assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void > (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 104, __PRETTY_FUNCTION__)); | |||
105 | ||||
106 | if (Decl->isDefaulted()) { | |||
107 | // If the method was explicitly defaulted, point at that declaration. | |||
108 | if (!Decl->isImplicit()) | |||
109 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | |||
110 | ||||
111 | // Try to diagnose why this special member function was implicitly | |||
112 | // deleted. This might fail, if that reason no longer applies. | |||
113 | DiagnoseDeletedDefaultedFunction(Decl); | |||
114 | return; | |||
115 | } | |||
116 | ||||
117 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | |||
118 | if (Ctor && Ctor->isInheritingConstructor()) | |||
119 | return NoteDeletedInheritingConstructor(Ctor); | |||
120 | ||||
121 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | |||
122 | << Decl << 1; | |||
123 | } | |||
124 | ||||
125 | /// Determine whether a FunctionDecl was ever declared with an | |||
126 | /// explicit storage class. | |||
127 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | |||
128 | for (auto I : D->redecls()) { | |||
129 | if (I->getStorageClass() != SC_None) | |||
130 | return true; | |||
131 | } | |||
132 | return false; | |||
133 | } | |||
134 | ||||
135 | /// Check whether we're in an extern inline function and referring to a | |||
136 | /// variable or function with internal linkage (C11 6.7.4p3). | |||
137 | /// | |||
138 | /// This is only a warning because we used to silently accept this code, but | |||
139 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | |||
140 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | |||
141 | /// and so while there may still be user mistakes, most of the time we can't | |||
142 | /// prove that there are errors. | |||
143 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | |||
144 | const NamedDecl *D, | |||
145 | SourceLocation Loc) { | |||
146 | // This is disabled under C++; there are too many ways for this to fire in | |||
147 | // contexts where the warning is a false positive, or where it is technically | |||
148 | // correct but benign. | |||
149 | if (S.getLangOpts().CPlusPlus) | |||
150 | return; | |||
151 | ||||
152 | // Check if this is an inlined function or method. | |||
153 | FunctionDecl *Current = S.getCurFunctionDecl(); | |||
154 | if (!Current) | |||
155 | return; | |||
156 | if (!Current->isInlined()) | |||
157 | return; | |||
158 | if (!Current->isExternallyVisible()) | |||
159 | return; | |||
160 | ||||
161 | // Check if the decl has internal linkage. | |||
162 | if (D->getFormalLinkage() != InternalLinkage) | |||
163 | return; | |||
164 | ||||
165 | // Downgrade from ExtWarn to Extension if | |||
166 | // (1) the supposedly external inline function is in the main file, | |||
167 | // and probably won't be included anywhere else. | |||
168 | // (2) the thing we're referencing is a pure function. | |||
169 | // (3) the thing we're referencing is another inline function. | |||
170 | // This last can give us false negatives, but it's better than warning on | |||
171 | // wrappers for simple C library functions. | |||
172 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | |||
173 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | |||
174 | if (!DowngradeWarning && UsedFn) | |||
175 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | |||
176 | ||||
177 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | |||
178 | : diag::ext_internal_in_extern_inline) | |||
179 | << /*IsVar=*/!UsedFn << D; | |||
180 | ||||
181 | S.MaybeSuggestAddingStaticToDecl(Current); | |||
182 | ||||
183 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | |||
184 | << D; | |||
185 | } | |||
186 | ||||
187 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | |||
188 | const FunctionDecl *First = Cur->getFirstDecl(); | |||
189 | ||||
190 | // Suggest "static" on the function, if possible. | |||
191 | if (!hasAnyExplicitStorageClass(First)) { | |||
192 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | |||
193 | Diag(DeclBegin, diag::note_convert_inline_to_static) | |||
194 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | |||
195 | } | |||
196 | } | |||
197 | ||||
198 | /// Determine whether the use of this declaration is valid, and | |||
199 | /// emit any corresponding diagnostics. | |||
200 | /// | |||
201 | /// This routine diagnoses various problems with referencing | |||
202 | /// declarations that can occur when using a declaration. For example, | |||
203 | /// it might warn if a deprecated or unavailable declaration is being | |||
204 | /// used, or produce an error (and return true) if a C++0x deleted | |||
205 | /// function is being used. | |||
206 | /// | |||
207 | /// \returns true if there was an error (this declaration cannot be | |||
208 | /// referenced), false otherwise. | |||
209 | /// | |||
210 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | |||
211 | const ObjCInterfaceDecl *UnknownObjCClass, | |||
212 | bool ObjCPropertyAccess, | |||
213 | bool AvoidPartialAvailabilityChecks, | |||
214 | ObjCInterfaceDecl *ClassReceiver) { | |||
215 | SourceLocation Loc = Locs.front(); | |||
216 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | |||
217 | // If there were any diagnostics suppressed by template argument deduction, | |||
218 | // emit them now. | |||
219 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | |||
220 | if (Pos != SuppressedDiagnostics.end()) { | |||
221 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | |||
222 | Diag(Suppressed.first, Suppressed.second); | |||
223 | ||||
224 | // Clear out the list of suppressed diagnostics, so that we don't emit | |||
225 | // them again for this specialization. However, we don't obsolete this | |||
226 | // entry from the table, because we want to avoid ever emitting these | |||
227 | // diagnostics again. | |||
228 | Pos->second.clear(); | |||
229 | } | |||
230 | ||||
231 | // C++ [basic.start.main]p3: | |||
232 | // The function 'main' shall not be used within a program. | |||
233 | if (cast<FunctionDecl>(D)->isMain()) | |||
234 | Diag(Loc, diag::ext_main_used); | |||
235 | ||||
236 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | |||
237 | } | |||
238 | ||||
239 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
240 | if (ParsingInitForAutoVars.count(D)) { | |||
241 | if (isa<BindingDecl>(D)) { | |||
242 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | |||
243 | << D->getDeclName(); | |||
244 | } else { | |||
245 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | |||
246 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | |||
247 | } | |||
248 | return true; | |||
249 | } | |||
250 | ||||
251 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
252 | // See if this is a deleted function. | |||
253 | if (FD->isDeleted()) { | |||
254 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | |||
255 | if (Ctor && Ctor->isInheritingConstructor()) | |||
256 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | |||
257 | << Ctor->getParent() | |||
258 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | |||
259 | else | |||
260 | Diag(Loc, diag::err_deleted_function_use); | |||
261 | NoteDeletedFunction(FD); | |||
262 | return true; | |||
263 | } | |||
264 | ||||
265 | // [expr.prim.id]p4 | |||
266 | // A program that refers explicitly or implicitly to a function with a | |||
267 | // trailing requires-clause whose constraint-expression is not satisfied, | |||
268 | // other than to declare it, is ill-formed. [...] | |||
269 | // | |||
270 | // See if this is a function with constraints that need to be satisfied. | |||
271 | // Check this before deducing the return type, as it might instantiate the | |||
272 | // definition. | |||
273 | if (FD->getTrailingRequiresClause()) { | |||
274 | ConstraintSatisfaction Satisfaction; | |||
275 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | |||
276 | // A diagnostic will have already been generated (non-constant | |||
277 | // constraint expression, for example) | |||
278 | return true; | |||
279 | if (!Satisfaction.IsSatisfied) { | |||
280 | Diag(Loc, | |||
281 | diag::err_reference_to_function_with_unsatisfied_constraints) | |||
282 | << D; | |||
283 | DiagnoseUnsatisfiedConstraint(Satisfaction); | |||
284 | return true; | |||
285 | } | |||
286 | } | |||
287 | ||||
288 | // If the function has a deduced return type, and we can't deduce it, | |||
289 | // then we can't use it either. | |||
290 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
291 | DeduceReturnType(FD, Loc)) | |||
292 | return true; | |||
293 | ||||
294 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | |||
295 | return true; | |||
296 | ||||
297 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | |||
298 | return true; | |||
299 | } | |||
300 | ||||
301 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
302 | // Lambdas are only default-constructible or assignable in C++2a onwards. | |||
303 | if (MD->getParent()->isLambda() && | |||
304 | ((isa<CXXConstructorDecl>(MD) && | |||
305 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | |||
306 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | |||
307 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | |||
308 | << !isa<CXXConstructorDecl>(MD); | |||
309 | } | |||
310 | } | |||
311 | ||||
312 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | |||
313 | const ObjCPropertyDecl * { | |||
314 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | |||
315 | return MD->findPropertyDecl(); | |||
316 | return nullptr; | |||
317 | }; | |||
318 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | |||
319 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | |||
320 | return true; | |||
321 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | |||
322 | return true; | |||
323 | } | |||
324 | ||||
325 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | |||
326 | // Only the variables omp_in and omp_out are allowed in the combiner. | |||
327 | // Only the variables omp_priv and omp_orig are allowed in the | |||
328 | // initializer-clause. | |||
329 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | |||
330 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | |||
331 | isa<VarDecl>(D)) { | |||
332 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | |||
333 | << getCurFunction()->HasOMPDeclareReductionCombiner; | |||
334 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
335 | return true; | |||
336 | } | |||
337 | ||||
338 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | |||
339 | // List-items in map clauses on this construct may only refer to the declared | |||
340 | // variable var and entities that could be referenced by a procedure defined | |||
341 | // at the same location | |||
342 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | |||
343 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | |||
344 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | |||
345 | << getOpenMPDeclareMapperVarName(); | |||
346 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
347 | return true; | |||
348 | } | |||
349 | ||||
350 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | |||
351 | AvoidPartialAvailabilityChecks, ClassReceiver); | |||
352 | ||||
353 | DiagnoseUnusedOfDecl(*this, D, Loc); | |||
354 | ||||
355 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | |||
356 | ||||
357 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | |||
358 | if (const auto *VD = dyn_cast<ValueDecl>(D)) | |||
359 | checkDeviceDecl(VD, Loc); | |||
360 | ||||
361 | if (!Context.getTargetInfo().isTLSSupported()) | |||
362 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
363 | if (VD->getTLSKind() != VarDecl::TLS_None) | |||
364 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | |||
365 | } | |||
366 | ||||
367 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | |||
368 | !isUnevaluatedContext()) { | |||
369 | // C++ [expr.prim.req.nested] p3 | |||
370 | // A local parameter shall only appear as an unevaluated operand | |||
371 | // (Clause 8) within the constraint-expression. | |||
372 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | |||
373 | << D; | |||
374 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
375 | return true; | |||
376 | } | |||
377 | ||||
378 | return false; | |||
379 | } | |||
380 | ||||
381 | /// DiagnoseSentinelCalls - This routine checks whether a call or | |||
382 | /// message-send is to a declaration with the sentinel attribute, and | |||
383 | /// if so, it checks that the requirements of the sentinel are | |||
384 | /// satisfied. | |||
385 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | |||
386 | ArrayRef<Expr *> Args) { | |||
387 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | |||
388 | if (!attr) | |||
389 | return; | |||
390 | ||||
391 | // The number of formal parameters of the declaration. | |||
392 | unsigned numFormalParams; | |||
393 | ||||
394 | // The kind of declaration. This is also an index into a %select in | |||
395 | // the diagnostic. | |||
396 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | |||
397 | ||||
398 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | |||
399 | numFormalParams = MD->param_size(); | |||
400 | calleeType = CT_Method; | |||
401 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
402 | numFormalParams = FD->param_size(); | |||
403 | calleeType = CT_Function; | |||
404 | } else if (isa<VarDecl>(D)) { | |||
405 | QualType type = cast<ValueDecl>(D)->getType(); | |||
406 | const FunctionType *fn = nullptr; | |||
407 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
408 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | |||
409 | if (!fn) return; | |||
410 | calleeType = CT_Function; | |||
411 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | |||
412 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | |||
413 | calleeType = CT_Block; | |||
414 | } else { | |||
415 | return; | |||
416 | } | |||
417 | ||||
418 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | |||
419 | numFormalParams = proto->getNumParams(); | |||
420 | } else { | |||
421 | numFormalParams = 0; | |||
422 | } | |||
423 | } else { | |||
424 | return; | |||
425 | } | |||
426 | ||||
427 | // "nullPos" is the number of formal parameters at the end which | |||
428 | // effectively count as part of the variadic arguments. This is | |||
429 | // useful if you would prefer to not have *any* formal parameters, | |||
430 | // but the language forces you to have at least one. | |||
431 | unsigned nullPos = attr->getNullPos(); | |||
432 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel" ) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 432, __PRETTY_FUNCTION__)); | |||
433 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | |||
434 | ||||
435 | // The number of arguments which should follow the sentinel. | |||
436 | unsigned numArgsAfterSentinel = attr->getSentinel(); | |||
437 | ||||
438 | // If there aren't enough arguments for all the formal parameters, | |||
439 | // the sentinel, and the args after the sentinel, complain. | |||
440 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | |||
441 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | |||
442 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
443 | return; | |||
444 | } | |||
445 | ||||
446 | // Otherwise, find the sentinel expression. | |||
447 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | |||
448 | if (!sentinelExpr) return; | |||
449 | if (sentinelExpr->isValueDependent()) return; | |||
450 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | |||
451 | ||||
452 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | |||
453 | // or 'NULL' if those are actually defined in the context. Only use | |||
454 | // 'nil' for ObjC methods, where it's much more likely that the | |||
455 | // variadic arguments form a list of object pointers. | |||
456 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | |||
457 | std::string NullValue; | |||
458 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | |||
459 | NullValue = "nil"; | |||
460 | else if (getLangOpts().CPlusPlus11) | |||
461 | NullValue = "nullptr"; | |||
462 | else if (PP.isMacroDefined("NULL")) | |||
463 | NullValue = "NULL"; | |||
464 | else | |||
465 | NullValue = "(void*) 0"; | |||
466 | ||||
467 | if (MissingNilLoc.isInvalid()) | |||
468 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | |||
469 | else | |||
470 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | |||
471 | << int(calleeType) | |||
472 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | |||
473 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
474 | } | |||
475 | ||||
476 | SourceRange Sema::getExprRange(Expr *E) const { | |||
477 | return E ? E->getSourceRange() : SourceRange(); | |||
478 | } | |||
479 | ||||
480 | //===----------------------------------------------------------------------===// | |||
481 | // Standard Promotions and Conversions | |||
482 | //===----------------------------------------------------------------------===// | |||
483 | ||||
484 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | |||
485 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | |||
486 | // Handle any placeholder expressions which made it here. | |||
487 | if (E->getType()->isPlaceholderType()) { | |||
488 | ExprResult result = CheckPlaceholderExpr(E); | |||
489 | if (result.isInvalid()) return ExprError(); | |||
490 | E = result.get(); | |||
491 | } | |||
492 | ||||
493 | QualType Ty = E->getType(); | |||
494 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 494, __PRETTY_FUNCTION__)); | |||
495 | ||||
496 | if (Ty->isFunctionType()) { | |||
497 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | |||
498 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | |||
499 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | |||
500 | return ExprError(); | |||
501 | ||||
502 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
503 | CK_FunctionToPointerDecay).get(); | |||
504 | } else if (Ty->isArrayType()) { | |||
505 | // In C90 mode, arrays only promote to pointers if the array expression is | |||
506 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | |||
507 | // type 'array of type' is converted to an expression that has type 'pointer | |||
508 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | |||
509 | // that has type 'array of type' ...". The relevant change is "an lvalue" | |||
510 | // (C90) to "an expression" (C99). | |||
511 | // | |||
512 | // C++ 4.2p1: | |||
513 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | |||
514 | // T" can be converted to an rvalue of type "pointer to T". | |||
515 | // | |||
516 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | |||
517 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | |||
518 | CK_ArrayToPointerDecay).get(); | |||
519 | } | |||
520 | return E; | |||
521 | } | |||
522 | ||||
523 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | |||
524 | // Check to see if we are dereferencing a null pointer. If so, | |||
525 | // and if not volatile-qualified, this is undefined behavior that the | |||
526 | // optimizer will delete, so warn about it. People sometimes try to use this | |||
527 | // to get a deterministic trap and are surprised by clang's behavior. This | |||
528 | // only handles the pattern "*null", which is a very syntactic check. | |||
529 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | |||
530 | if (UO && UO->getOpcode() == UO_Deref && | |||
531 | UO->getSubExpr()->getType()->isPointerType()) { | |||
532 | const LangAS AS = | |||
533 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | |||
534 | if ((!isTargetAddressSpace(AS) || | |||
535 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | |||
536 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | |||
537 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | |||
538 | !UO->getType().isVolatileQualified()) { | |||
539 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
540 | S.PDiag(diag::warn_indirection_through_null) | |||
541 | << UO->getSubExpr()->getSourceRange()); | |||
542 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
543 | S.PDiag(diag::note_indirection_through_null)); | |||
544 | } | |||
545 | } | |||
546 | } | |||
547 | ||||
548 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | |||
549 | SourceLocation AssignLoc, | |||
550 | const Expr* RHS) { | |||
551 | const ObjCIvarDecl *IV = OIRE->getDecl(); | |||
552 | if (!IV) | |||
553 | return; | |||
554 | ||||
555 | DeclarationName MemberName = IV->getDeclName(); | |||
556 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | |||
557 | if (!Member || !Member->isStr("isa")) | |||
558 | return; | |||
559 | ||||
560 | const Expr *Base = OIRE->getBase(); | |||
561 | QualType BaseType = Base->getType(); | |||
562 | if (OIRE->isArrow()) | |||
563 | BaseType = BaseType->getPointeeType(); | |||
564 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | |||
565 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | |||
566 | ObjCInterfaceDecl *ClassDeclared = nullptr; | |||
567 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | |||
568 | if (!ClassDeclared->getSuperClass() | |||
569 | && (*ClassDeclared->ivar_begin()) == IV) { | |||
570 | if (RHS) { | |||
571 | NamedDecl *ObjectSetClass = | |||
572 | S.LookupSingleName(S.TUScope, | |||
573 | &S.Context.Idents.get("object_setClass"), | |||
574 | SourceLocation(), S.LookupOrdinaryName); | |||
575 | if (ObjectSetClass) { | |||
576 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | |||
577 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | |||
578 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | |||
579 | "object_setClass(") | |||
580 | << FixItHint::CreateReplacement( | |||
581 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | |||
582 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
583 | } | |||
584 | else | |||
585 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | |||
586 | } else { | |||
587 | NamedDecl *ObjectGetClass = | |||
588 | S.LookupSingleName(S.TUScope, | |||
589 | &S.Context.Idents.get("object_getClass"), | |||
590 | SourceLocation(), S.LookupOrdinaryName); | |||
591 | if (ObjectGetClass) | |||
592 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | |||
593 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | |||
594 | "object_getClass(") | |||
595 | << FixItHint::CreateReplacement( | |||
596 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | |||
597 | else | |||
598 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | |||
599 | } | |||
600 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | |||
601 | } | |||
602 | } | |||
603 | } | |||
604 | ||||
605 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | |||
606 | // Handle any placeholder expressions which made it here. | |||
607 | if (E->getType()->isPlaceholderType()) { | |||
608 | ExprResult result = CheckPlaceholderExpr(E); | |||
609 | if (result.isInvalid()) return ExprError(); | |||
610 | E = result.get(); | |||
611 | } | |||
612 | ||||
613 | // C++ [conv.lval]p1: | |||
614 | // A glvalue of a non-function, non-array type T can be | |||
615 | // converted to a prvalue. | |||
616 | if (!E->isGLValue()) return E; | |||
617 | ||||
618 | QualType T = E->getType(); | |||
619 | assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 619, __PRETTY_FUNCTION__)); | |||
620 | ||||
621 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | |||
622 | if (T->isFunctionType() || T->isArrayType()) | |||
623 | return E; | |||
624 | ||||
625 | // We don't want to throw lvalue-to-rvalue casts on top of | |||
626 | // expressions of certain types in C++. | |||
627 | if (getLangOpts().CPlusPlus && | |||
628 | (E->getType() == Context.OverloadTy || | |||
629 | T->isDependentType() || | |||
630 | T->isRecordType())) | |||
631 | return E; | |||
632 | ||||
633 | // The C standard is actually really unclear on this point, and | |||
634 | // DR106 tells us what the result should be but not why. It's | |||
635 | // generally best to say that void types just doesn't undergo | |||
636 | // lvalue-to-rvalue at all. Note that expressions of unqualified | |||
637 | // 'void' type are never l-values, but qualified void can be. | |||
638 | if (T->isVoidType()) | |||
639 | return E; | |||
640 | ||||
641 | // OpenCL usually rejects direct accesses to values of 'half' type. | |||
642 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | |||
643 | T->isHalfType()) { | |||
644 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | |||
645 | << 0 << T; | |||
646 | return ExprError(); | |||
647 | } | |||
648 | ||||
649 | CheckForNullPointerDereference(*this, E); | |||
650 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | |||
651 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | |||
652 | &Context.Idents.get("object_getClass"), | |||
653 | SourceLocation(), LookupOrdinaryName); | |||
654 | if (ObjectGetClass) | |||
655 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | |||
656 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | |||
657 | << FixItHint::CreateReplacement( | |||
658 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | |||
659 | else | |||
660 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | |||
661 | } | |||
662 | else if (const ObjCIvarRefExpr *OIRE = | |||
663 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | |||
664 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | |||
665 | ||||
666 | // C++ [conv.lval]p1: | |||
667 | // [...] If T is a non-class type, the type of the prvalue is the | |||
668 | // cv-unqualified version of T. Otherwise, the type of the | |||
669 | // rvalue is T. | |||
670 | // | |||
671 | // C99 6.3.2.1p2: | |||
672 | // If the lvalue has qualified type, the value has the unqualified | |||
673 | // version of the type of the lvalue; otherwise, the value has the | |||
674 | // type of the lvalue. | |||
675 | if (T.hasQualifiers()) | |||
676 | T = T.getUnqualifiedType(); | |||
677 | ||||
678 | // Under the MS ABI, lock down the inheritance model now. | |||
679 | if (T->isMemberPointerType() && | |||
680 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
681 | (void)isCompleteType(E->getExprLoc(), T); | |||
682 | ||||
683 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | |||
684 | if (Res.isInvalid()) | |||
685 | return Res; | |||
686 | E = Res.get(); | |||
687 | ||||
688 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | |||
689 | // balance that. | |||
690 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
691 | Cleanup.setExprNeedsCleanups(true); | |||
692 | ||||
693 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
694 | Cleanup.setExprNeedsCleanups(true); | |||
695 | ||||
696 | // C++ [conv.lval]p3: | |||
697 | // If T is cv std::nullptr_t, the result is a null pointer constant. | |||
698 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | |||
699 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, | |||
700 | CurFPFeatureOverrides()); | |||
701 | ||||
702 | // C11 6.3.2.1p2: | |||
703 | // ... if the lvalue has atomic type, the value has the non-atomic version | |||
704 | // of the type of the lvalue ... | |||
705 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | |||
706 | T = Atomic->getValueType().getUnqualifiedType(); | |||
707 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | |||
708 | nullptr, VK_RValue, FPOptionsOverride()); | |||
709 | } | |||
710 | ||||
711 | return Res; | |||
712 | } | |||
713 | ||||
714 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | |||
715 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | |||
716 | if (Res.isInvalid()) | |||
717 | return ExprError(); | |||
718 | Res = DefaultLvalueConversion(Res.get()); | |||
719 | if (Res.isInvalid()) | |||
720 | return ExprError(); | |||
721 | return Res; | |||
722 | } | |||
723 | ||||
724 | /// CallExprUnaryConversions - a special case of an unary conversion | |||
725 | /// performed on a function designator of a call expression. | |||
726 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | |||
727 | QualType Ty = E->getType(); | |||
728 | ExprResult Res = E; | |||
729 | // Only do implicit cast for a function type, but not for a pointer | |||
730 | // to function type. | |||
731 | if (Ty->isFunctionType()) { | |||
732 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
733 | CK_FunctionToPointerDecay); | |||
734 | if (Res.isInvalid()) | |||
735 | return ExprError(); | |||
736 | } | |||
737 | Res = DefaultLvalueConversion(Res.get()); | |||
738 | if (Res.isInvalid()) | |||
739 | return ExprError(); | |||
740 | return Res.get(); | |||
741 | } | |||
742 | ||||
743 | /// UsualUnaryConversions - Performs various conversions that are common to most | |||
744 | /// operators (C99 6.3). The conversions of array and function types are | |||
745 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | |||
746 | /// apply if the array is an argument to the sizeof or address (&) operators. | |||
747 | /// In these instances, this routine should *not* be called. | |||
748 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | |||
749 | // First, convert to an r-value. | |||
750 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
751 | if (Res.isInvalid()) | |||
752 | return ExprError(); | |||
753 | E = Res.get(); | |||
754 | ||||
755 | QualType Ty = E->getType(); | |||
756 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 756, __PRETTY_FUNCTION__)); | |||
757 | ||||
758 | // Half FP have to be promoted to float unless it is natively supported | |||
759 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | |||
760 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | |||
761 | ||||
762 | // Try to perform integral promotions if the object has a theoretically | |||
763 | // promotable type. | |||
764 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | |||
765 | // C99 6.3.1.1p2: | |||
766 | // | |||
767 | // The following may be used in an expression wherever an int or | |||
768 | // unsigned int may be used: | |||
769 | // - an object or expression with an integer type whose integer | |||
770 | // conversion rank is less than or equal to the rank of int | |||
771 | // and unsigned int. | |||
772 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | |||
773 | // | |||
774 | // If an int can represent all values of the original type, the | |||
775 | // value is converted to an int; otherwise, it is converted to an | |||
776 | // unsigned int. These are called the integer promotions. All | |||
777 | // other types are unchanged by the integer promotions. | |||
778 | ||||
779 | QualType PTy = Context.isPromotableBitField(E); | |||
780 | if (!PTy.isNull()) { | |||
781 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | |||
782 | return E; | |||
783 | } | |||
784 | if (Ty->isPromotableIntegerType()) { | |||
785 | QualType PT = Context.getPromotedIntegerType(Ty); | |||
786 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | |||
787 | return E; | |||
788 | } | |||
789 | } | |||
790 | return E; | |||
791 | } | |||
792 | ||||
793 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | |||
794 | /// do not have a prototype. Arguments that have type float or __fp16 | |||
795 | /// are promoted to double. All other argument types are converted by | |||
796 | /// UsualUnaryConversions(). | |||
797 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | |||
798 | QualType Ty = E->getType(); | |||
799 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 799, __PRETTY_FUNCTION__)); | |||
800 | ||||
801 | ExprResult Res = UsualUnaryConversions(E); | |||
802 | if (Res.isInvalid()) | |||
803 | return ExprError(); | |||
804 | E = Res.get(); | |||
805 | ||||
806 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | |||
807 | // promote to double. | |||
808 | // Note that default argument promotion applies only to float (and | |||
809 | // half/fp16); it does not apply to _Float16. | |||
810 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
811 | if (BTy && (BTy->getKind() == BuiltinType::Half || | |||
812 | BTy->getKind() == BuiltinType::Float)) { | |||
813 | if (getLangOpts().OpenCL && | |||
814 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | |||
815 | if (BTy->getKind() == BuiltinType::Half) { | |||
816 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | |||
817 | } | |||
818 | } else { | |||
819 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | |||
820 | } | |||
821 | } | |||
822 | ||||
823 | // C++ performs lvalue-to-rvalue conversion as a default argument | |||
824 | // promotion, even on class types, but note: | |||
825 | // C++11 [conv.lval]p2: | |||
826 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | |||
827 | // operand or a subexpression thereof the value contained in the | |||
828 | // referenced object is not accessed. Otherwise, if the glvalue | |||
829 | // has a class type, the conversion copy-initializes a temporary | |||
830 | // of type T from the glvalue and the result of the conversion | |||
831 | // is a prvalue for the temporary. | |||
832 | // FIXME: add some way to gate this entire thing for correctness in | |||
833 | // potentially potentially evaluated contexts. | |||
834 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | |||
835 | ExprResult Temp = PerformCopyInitialization( | |||
836 | InitializedEntity::InitializeTemporary(E->getType()), | |||
837 | E->getExprLoc(), E); | |||
838 | if (Temp.isInvalid()) | |||
839 | return ExprError(); | |||
840 | E = Temp.get(); | |||
841 | } | |||
842 | ||||
843 | return E; | |||
844 | } | |||
845 | ||||
846 | /// Determine the degree of POD-ness for an expression. | |||
847 | /// Incomplete types are considered POD, since this check can be performed | |||
848 | /// when we're in an unevaluated context. | |||
849 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | |||
850 | if (Ty->isIncompleteType()) { | |||
851 | // C++11 [expr.call]p7: | |||
852 | // After these conversions, if the argument does not have arithmetic, | |||
853 | // enumeration, pointer, pointer to member, or class type, the program | |||
854 | // is ill-formed. | |||
855 | // | |||
856 | // Since we've already performed array-to-pointer and function-to-pointer | |||
857 | // decay, the only such type in C++ is cv void. This also handles | |||
858 | // initializer lists as variadic arguments. | |||
859 | if (Ty->isVoidType()) | |||
860 | return VAK_Invalid; | |||
861 | ||||
862 | if (Ty->isObjCObjectType()) | |||
863 | return VAK_Invalid; | |||
864 | return VAK_Valid; | |||
865 | } | |||
866 | ||||
867 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
868 | return VAK_Invalid; | |||
869 | ||||
870 | if (Ty.isCXX98PODType(Context)) | |||
871 | return VAK_Valid; | |||
872 | ||||
873 | // C++11 [expr.call]p7: | |||
874 | // Passing a potentially-evaluated argument of class type (Clause 9) | |||
875 | // having a non-trivial copy constructor, a non-trivial move constructor, | |||
876 | // or a non-trivial destructor, with no corresponding parameter, | |||
877 | // is conditionally-supported with implementation-defined semantics. | |||
878 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | |||
879 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | |||
880 | if (!Record->hasNonTrivialCopyConstructor() && | |||
881 | !Record->hasNonTrivialMoveConstructor() && | |||
882 | !Record->hasNonTrivialDestructor()) | |||
883 | return VAK_ValidInCXX11; | |||
884 | ||||
885 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | |||
886 | return VAK_Valid; | |||
887 | ||||
888 | if (Ty->isObjCObjectType()) | |||
889 | return VAK_Invalid; | |||
890 | ||||
891 | if (getLangOpts().MSVCCompat) | |||
892 | return VAK_MSVCUndefined; | |||
893 | ||||
894 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | |||
895 | // permitted to reject them. We should consider doing so. | |||
896 | return VAK_Undefined; | |||
897 | } | |||
898 | ||||
899 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | |||
900 | // Don't allow one to pass an Objective-C interface to a vararg. | |||
901 | const QualType &Ty = E->getType(); | |||
902 | VarArgKind VAK = isValidVarArgType(Ty); | |||
903 | ||||
904 | // Complain about passing non-POD types through varargs. | |||
905 | switch (VAK) { | |||
906 | case VAK_ValidInCXX11: | |||
907 | DiagRuntimeBehavior( | |||
908 | E->getBeginLoc(), nullptr, | |||
909 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | |||
910 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
911 | case VAK_Valid: | |||
912 | if (Ty->isRecordType()) { | |||
913 | // This is unlikely to be what the user intended. If the class has a | |||
914 | // 'c_str' member function, the user probably meant to call that. | |||
915 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
916 | PDiag(diag::warn_pass_class_arg_to_vararg) | |||
917 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | |||
918 | } | |||
919 | break; | |||
920 | ||||
921 | case VAK_Undefined: | |||
922 | case VAK_MSVCUndefined: | |||
923 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
924 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | |||
925 | << getLangOpts().CPlusPlus11 << Ty << CT); | |||
926 | break; | |||
927 | ||||
928 | case VAK_Invalid: | |||
929 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
930 | Diag(E->getBeginLoc(), | |||
931 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | |||
932 | << Ty << CT; | |||
933 | else if (Ty->isObjCObjectType()) | |||
934 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
935 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | |||
936 | << Ty << CT); | |||
937 | else | |||
938 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | |||
939 | << isa<InitListExpr>(E) << Ty << CT; | |||
940 | break; | |||
941 | } | |||
942 | } | |||
943 | ||||
944 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | |||
945 | /// will create a trap if the resulting type is not a POD type. | |||
946 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | |||
947 | FunctionDecl *FDecl) { | |||
948 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | |||
949 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
950 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | |||
951 | (CT == VariadicMethod || | |||
952 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | |||
953 | E = stripARCUnbridgedCast(E); | |||
954 | ||||
955 | // Otherwise, do normal placeholder checking. | |||
956 | } else { | |||
957 | ExprResult ExprRes = CheckPlaceholderExpr(E); | |||
958 | if (ExprRes.isInvalid()) | |||
959 | return ExprError(); | |||
960 | E = ExprRes.get(); | |||
961 | } | |||
962 | } | |||
963 | ||||
964 | ExprResult ExprRes = DefaultArgumentPromotion(E); | |||
965 | if (ExprRes.isInvalid()) | |||
966 | return ExprError(); | |||
967 | ||||
968 | // Copy blocks to the heap. | |||
969 | if (ExprRes.get()->getType()->isBlockPointerType()) | |||
970 | maybeExtendBlockObject(ExprRes); | |||
971 | ||||
972 | E = ExprRes.get(); | |||
973 | ||||
974 | // Diagnostics regarding non-POD argument types are | |||
975 | // emitted along with format string checking in Sema::CheckFunctionCall(). | |||
976 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | |||
977 | // Turn this into a trap. | |||
978 | CXXScopeSpec SS; | |||
979 | SourceLocation TemplateKWLoc; | |||
980 | UnqualifiedId Name; | |||
981 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | |||
982 | E->getBeginLoc()); | |||
983 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | |||
984 | /*HasTrailingLParen=*/true, | |||
985 | /*IsAddressOfOperand=*/false); | |||
986 | if (TrapFn.isInvalid()) | |||
987 | return ExprError(); | |||
988 | ||||
989 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | |||
990 | None, E->getEndLoc()); | |||
991 | if (Call.isInvalid()) | |||
992 | return ExprError(); | |||
993 | ||||
994 | ExprResult Comma = | |||
995 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | |||
996 | if (Comma.isInvalid()) | |||
997 | return ExprError(); | |||
998 | return Comma.get(); | |||
999 | } | |||
1000 | ||||
1001 | if (!getLangOpts().CPlusPlus && | |||
1002 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
1003 | diag::err_call_incomplete_argument)) | |||
1004 | return ExprError(); | |||
1005 | ||||
1006 | return E; | |||
1007 | } | |||
1008 | ||||
1009 | /// Converts an integer to complex float type. Helper function of | |||
1010 | /// UsualArithmeticConversions() | |||
1011 | /// | |||
1012 | /// \return false if the integer expression is an integer type and is | |||
1013 | /// successfully converted to the complex type. | |||
1014 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | |||
1015 | ExprResult &ComplexExpr, | |||
1016 | QualType IntTy, | |||
1017 | QualType ComplexTy, | |||
1018 | bool SkipCast) { | |||
1019 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | |||
1020 | if (SkipCast) return false; | |||
1021 | if (IntTy->isIntegerType()) { | |||
1022 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | |||
1023 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | |||
1024 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
1025 | CK_FloatingRealToComplex); | |||
1026 | } else { | |||
1027 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1027, __PRETTY_FUNCTION__)); | |||
1028 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
1029 | CK_IntegralComplexToFloatingComplex); | |||
1030 | } | |||
1031 | return false; | |||
1032 | } | |||
1033 | ||||
1034 | /// Handle arithmetic conversion with complex types. Helper function of | |||
1035 | /// UsualArithmeticConversions() | |||
1036 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | |||
1037 | ExprResult &RHS, QualType LHSType, | |||
1038 | QualType RHSType, | |||
1039 | bool IsCompAssign) { | |||
1040 | // if we have an integer operand, the result is the complex type. | |||
1041 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
1042 | /*skipCast*/false)) | |||
1043 | return LHSType; | |||
1044 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
1045 | /*skipCast*/IsCompAssign)) | |||
1046 | return RHSType; | |||
1047 | ||||
1048 | // This handles complex/complex, complex/float, or float/complex. | |||
1049 | // When both operands are complex, the shorter operand is converted to the | |||
1050 | // type of the longer, and that is the type of the result. This corresponds | |||
1051 | // to what is done when combining two real floating-point operands. | |||
1052 | // The fun begins when size promotion occur across type domains. | |||
1053 | // From H&S 6.3.4: When one operand is complex and the other is a real | |||
1054 | // floating-point type, the less precise type is converted, within it's | |||
1055 | // real or complex domain, to the precision of the other type. For example, | |||
1056 | // when combining a "long double" with a "double _Complex", the | |||
1057 | // "double _Complex" is promoted to "long double _Complex". | |||
1058 | ||||
1059 | // Compute the rank of the two types, regardless of whether they are complex. | |||
1060 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1061 | ||||
1062 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | |||
1063 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | |||
1064 | QualType LHSElementType = | |||
1065 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | |||
1066 | QualType RHSElementType = | |||
1067 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | |||
1068 | ||||
1069 | QualType ResultType = S.Context.getComplexType(LHSElementType); | |||
1070 | if (Order < 0) { | |||
1071 | // Promote the precision of the LHS if not an assignment. | |||
1072 | ResultType = S.Context.getComplexType(RHSElementType); | |||
1073 | if (!IsCompAssign) { | |||
1074 | if (LHSComplexType) | |||
1075 | LHS = | |||
1076 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | |||
1077 | else | |||
1078 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | |||
1079 | } | |||
1080 | } else if (Order > 0) { | |||
1081 | // Promote the precision of the RHS. | |||
1082 | if (RHSComplexType) | |||
1083 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | |||
1084 | else | |||
1085 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | |||
1086 | } | |||
1087 | return ResultType; | |||
1088 | } | |||
1089 | ||||
1090 | /// Handle arithmetic conversion from integer to float. Helper function | |||
1091 | /// of UsualArithmeticConversions() | |||
1092 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | |||
1093 | ExprResult &IntExpr, | |||
1094 | QualType FloatTy, QualType IntTy, | |||
1095 | bool ConvertFloat, bool ConvertInt) { | |||
1096 | if (IntTy->isIntegerType()) { | |||
1097 | if (ConvertInt) | |||
1098 | // Convert intExpr to the lhs floating point type. | |||
1099 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | |||
1100 | CK_IntegralToFloating); | |||
1101 | return FloatTy; | |||
1102 | } | |||
1103 | ||||
1104 | // Convert both sides to the appropriate complex float. | |||
1105 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1105, __PRETTY_FUNCTION__)); | |||
1106 | QualType result = S.Context.getComplexType(FloatTy); | |||
1107 | ||||
1108 | // _Complex int -> _Complex float | |||
1109 | if (ConvertInt) | |||
1110 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | |||
1111 | CK_IntegralComplexToFloatingComplex); | |||
1112 | ||||
1113 | // float -> _Complex float | |||
1114 | if (ConvertFloat) | |||
1115 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | |||
1116 | CK_FloatingRealToComplex); | |||
1117 | ||||
1118 | return result; | |||
1119 | } | |||
1120 | ||||
1121 | /// Handle arithmethic conversion with floating point types. Helper | |||
1122 | /// function of UsualArithmeticConversions() | |||
1123 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | |||
1124 | ExprResult &RHS, QualType LHSType, | |||
1125 | QualType RHSType, bool IsCompAssign) { | |||
1126 | bool LHSFloat = LHSType->isRealFloatingType(); | |||
1127 | bool RHSFloat = RHSType->isRealFloatingType(); | |||
1128 | ||||
1129 | // N1169 4.1.4: If one of the operands has a floating type and the other | |||
1130 | // operand has a fixed-point type, the fixed-point operand | |||
1131 | // is converted to the floating type [...] | |||
1132 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | |||
1133 | if (LHSFloat) | |||
1134 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | |||
1135 | else if (!IsCompAssign) | |||
1136 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | |||
1137 | return LHSFloat ? LHSType : RHSType; | |||
1138 | } | |||
1139 | ||||
1140 | // If we have two real floating types, convert the smaller operand | |||
1141 | // to the bigger result. | |||
1142 | if (LHSFloat && RHSFloat) { | |||
1143 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1144 | if (order > 0) { | |||
1145 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | |||
1146 | return LHSType; | |||
1147 | } | |||
1148 | ||||
1149 | assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast <void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1149, __PRETTY_FUNCTION__)); | |||
1150 | if (!IsCompAssign) | |||
1151 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | |||
1152 | return RHSType; | |||
1153 | } | |||
1154 | ||||
1155 | if (LHSFloat) { | |||
1156 | // Half FP has to be promoted to float unless it is natively supported | |||
1157 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | |||
1158 | LHSType = S.Context.FloatTy; | |||
1159 | ||||
1160 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
1161 | /*ConvertFloat=*/!IsCompAssign, | |||
1162 | /*ConvertInt=*/ true); | |||
1163 | } | |||
1164 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1164, __PRETTY_FUNCTION__)); | |||
1165 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
1166 | /*ConvertFloat=*/ true, | |||
1167 | /*ConvertInt=*/!IsCompAssign); | |||
1168 | } | |||
1169 | ||||
1170 | /// Diagnose attempts to convert between __float128 and long double if | |||
1171 | /// there is no support for such conversion. Helper function of | |||
1172 | /// UsualArithmeticConversions(). | |||
1173 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | |||
1174 | QualType RHSType) { | |||
1175 | /* No issue converting if at least one of the types is not a floating point | |||
1176 | type or the two types have the same rank. | |||
1177 | */ | |||
1178 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | |||
1179 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | |||
1180 | return false; | |||
1181 | ||||
1182 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1183, __PRETTY_FUNCTION__)) | |||
1183 | "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1183, __PRETTY_FUNCTION__)); | |||
1184 | ||||
1185 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | |||
1186 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | |||
1187 | ||||
1188 | QualType LHSElemType = LHSComplex ? | |||
1189 | LHSComplex->getElementType() : LHSType; | |||
1190 | QualType RHSElemType = RHSComplex ? | |||
1191 | RHSComplex->getElementType() : RHSType; | |||
1192 | ||||
1193 | // No issue if the two types have the same representation | |||
1194 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | |||
1195 | &S.Context.getFloatTypeSemantics(RHSElemType)) | |||
1196 | return false; | |||
1197 | ||||
1198 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | |||
1199 | RHSElemType == S.Context.LongDoubleTy); | |||
1200 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | |||
1201 | RHSElemType == S.Context.Float128Ty); | |||
1202 | ||||
1203 | // We've handled the situation where __float128 and long double have the same | |||
1204 | // representation. We allow all conversions for all possible long double types | |||
1205 | // except PPC's double double. | |||
1206 | return Float128AndLongDouble && | |||
1207 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | |||
1208 | &llvm::APFloat::PPCDoubleDouble()); | |||
1209 | } | |||
1210 | ||||
1211 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | |||
1212 | ||||
1213 | namespace { | |||
1214 | /// These helper callbacks are placed in an anonymous namespace to | |||
1215 | /// permit their use as function template parameters. | |||
1216 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1217 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | |||
1218 | } | |||
1219 | ||||
1220 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1221 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | |||
1222 | CK_IntegralComplexCast); | |||
1223 | } | |||
1224 | } | |||
1225 | ||||
1226 | /// Handle integer arithmetic conversions. Helper function of | |||
1227 | /// UsualArithmeticConversions() | |||
1228 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | |||
1229 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | |||
1230 | ExprResult &RHS, QualType LHSType, | |||
1231 | QualType RHSType, bool IsCompAssign) { | |||
1232 | // The rules for this case are in C99 6.3.1.8 | |||
1233 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | |||
1234 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | |||
1235 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | |||
1236 | if (LHSSigned == RHSSigned) { | |||
1237 | // Same signedness; use the higher-ranked type | |||
1238 | if (order >= 0) { | |||
1239 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1240 | return LHSType; | |||
1241 | } else if (!IsCompAssign) | |||
1242 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1243 | return RHSType; | |||
1244 | } else if (order != (LHSSigned ? 1 : -1)) { | |||
1245 | // The unsigned type has greater than or equal rank to the | |||
1246 | // signed type, so use the unsigned type | |||
1247 | if (RHSSigned) { | |||
1248 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1249 | return LHSType; | |||
1250 | } else if (!IsCompAssign) | |||
1251 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1252 | return RHSType; | |||
1253 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | |||
1254 | // The two types are different widths; if we are here, that | |||
1255 | // means the signed type is larger than the unsigned type, so | |||
1256 | // use the signed type. | |||
1257 | if (LHSSigned) { | |||
1258 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1259 | return LHSType; | |||
1260 | } else if (!IsCompAssign) | |||
1261 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1262 | return RHSType; | |||
1263 | } else { | |||
1264 | // The signed type is higher-ranked than the unsigned type, | |||
1265 | // but isn't actually any bigger (like unsigned int and long | |||
1266 | // on most 32-bit systems). Use the unsigned type corresponding | |||
1267 | // to the signed type. | |||
1268 | QualType result = | |||
1269 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | |||
1270 | RHS = (*doRHSCast)(S, RHS.get(), result); | |||
1271 | if (!IsCompAssign) | |||
1272 | LHS = (*doLHSCast)(S, LHS.get(), result); | |||
1273 | return result; | |||
1274 | } | |||
1275 | } | |||
1276 | ||||
1277 | /// Handle conversions with GCC complex int extension. Helper function | |||
1278 | /// of UsualArithmeticConversions() | |||
1279 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | |||
1280 | ExprResult &RHS, QualType LHSType, | |||
1281 | QualType RHSType, | |||
1282 | bool IsCompAssign) { | |||
1283 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | |||
1284 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | |||
1285 | ||||
1286 | if (LHSComplexInt && RHSComplexInt) { | |||
1287 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1288 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1289 | QualType ScalarType = | |||
1290 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | |||
1291 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | |||
1292 | ||||
1293 | return S.Context.getComplexType(ScalarType); | |||
1294 | } | |||
1295 | ||||
1296 | if (LHSComplexInt) { | |||
1297 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1298 | QualType ScalarType = | |||
1299 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | |||
1300 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | |||
1301 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1302 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | |||
1303 | CK_IntegralRealToComplex); | |||
1304 | ||||
1305 | return ComplexType; | |||
1306 | } | |||
1307 | ||||
1308 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1308, __PRETTY_FUNCTION__)); | |||
1309 | ||||
1310 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1311 | QualType ScalarType = | |||
1312 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | |||
1313 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | |||
1314 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1315 | ||||
1316 | if (!IsCompAssign) | |||
1317 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | |||
1318 | CK_IntegralRealToComplex); | |||
1319 | return ComplexType; | |||
1320 | } | |||
1321 | ||||
1322 | /// Return the rank of a given fixed point or integer type. The value itself | |||
1323 | /// doesn't matter, but the values must be increasing with proper increasing | |||
1324 | /// rank as described in N1169 4.1.1. | |||
1325 | static unsigned GetFixedPointRank(QualType Ty) { | |||
1326 | const auto *BTy = Ty->getAs<BuiltinType>(); | |||
1327 | assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast< void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1327, __PRETTY_FUNCTION__)); | |||
1328 | ||||
1329 | switch (BTy->getKind()) { | |||
1330 | case BuiltinType::ShortFract: | |||
1331 | case BuiltinType::UShortFract: | |||
1332 | case BuiltinType::SatShortFract: | |||
1333 | case BuiltinType::SatUShortFract: | |||
1334 | return 1; | |||
1335 | case BuiltinType::Fract: | |||
1336 | case BuiltinType::UFract: | |||
1337 | case BuiltinType::SatFract: | |||
1338 | case BuiltinType::SatUFract: | |||
1339 | return 2; | |||
1340 | case BuiltinType::LongFract: | |||
1341 | case BuiltinType::ULongFract: | |||
1342 | case BuiltinType::SatLongFract: | |||
1343 | case BuiltinType::SatULongFract: | |||
1344 | return 3; | |||
1345 | case BuiltinType::ShortAccum: | |||
1346 | case BuiltinType::UShortAccum: | |||
1347 | case BuiltinType::SatShortAccum: | |||
1348 | case BuiltinType::SatUShortAccum: | |||
1349 | return 4; | |||
1350 | case BuiltinType::Accum: | |||
1351 | case BuiltinType::UAccum: | |||
1352 | case BuiltinType::SatAccum: | |||
1353 | case BuiltinType::SatUAccum: | |||
1354 | return 5; | |||
1355 | case BuiltinType::LongAccum: | |||
1356 | case BuiltinType::ULongAccum: | |||
1357 | case BuiltinType::SatLongAccum: | |||
1358 | case BuiltinType::SatULongAccum: | |||
1359 | return 6; | |||
1360 | default: | |||
1361 | if (BTy->isInteger()) | |||
1362 | return 0; | |||
1363 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1363); | |||
1364 | } | |||
1365 | } | |||
1366 | ||||
1367 | /// handleFixedPointConversion - Fixed point operations between fixed | |||
1368 | /// point types and integers or other fixed point types do not fall under | |||
1369 | /// usual arithmetic conversion since these conversions could result in loss | |||
1370 | /// of precsision (N1169 4.1.4). These operations should be calculated with | |||
1371 | /// the full precision of their result type (N1169 4.1.6.2.1). | |||
1372 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | |||
1373 | QualType RHSTy) { | |||
1374 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1375, __PRETTY_FUNCTION__)) | |||
1375 | "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1375, __PRETTY_FUNCTION__)); | |||
1376 | assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)) | |||
1377 | RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)) | |||
1378 | "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)) | |||
1379 | "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)); | |||
1380 | ||||
1381 | // If one operand has signed fixed-point type and the other operand has | |||
1382 | // unsigned fixed-point type, then the unsigned fixed-point operand is | |||
1383 | // converted to its corresponding signed fixed-point type and the resulting | |||
1384 | // type is the type of the converted operand. | |||
1385 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | |||
1386 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | |||
1387 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | |||
1388 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | |||
1389 | ||||
1390 | // The result type is the type with the highest rank, whereby a fixed-point | |||
1391 | // conversion rank is always greater than an integer conversion rank; if the | |||
1392 | // type of either of the operands is a saturating fixedpoint type, the result | |||
1393 | // type shall be the saturating fixed-point type corresponding to the type | |||
1394 | // with the highest rank; the resulting value is converted (taking into | |||
1395 | // account rounding and overflow) to the precision of the resulting type. | |||
1396 | // Same ranks between signed and unsigned types are resolved earlier, so both | |||
1397 | // types are either signed or both unsigned at this point. | |||
1398 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | |||
1399 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | |||
1400 | ||||
1401 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | |||
1402 | ||||
1403 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | |||
1404 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | |||
1405 | ||||
1406 | return ResultTy; | |||
1407 | } | |||
1408 | ||||
1409 | /// Check that the usual arithmetic conversions can be performed on this pair of | |||
1410 | /// expressions that might be of enumeration type. | |||
1411 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | |||
1412 | SourceLocation Loc, | |||
1413 | Sema::ArithConvKind ACK) { | |||
1414 | // C++2a [expr.arith.conv]p1: | |||
1415 | // If one operand is of enumeration type and the other operand is of a | |||
1416 | // different enumeration type or a floating-point type, this behavior is | |||
1417 | // deprecated ([depr.arith.conv.enum]). | |||
1418 | // | |||
1419 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | |||
1420 | // Eventually we will presumably reject these cases (in C++23 onwards?). | |||
1421 | QualType L = LHS->getType(), R = RHS->getType(); | |||
1422 | bool LEnum = L->isUnscopedEnumerationType(), | |||
1423 | REnum = R->isUnscopedEnumerationType(); | |||
1424 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | |||
1425 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | |||
1426 | (REnum && L->isFloatingType())) { | |||
1427 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | |||
1428 | ? diag::warn_arith_conv_enum_float_cxx20 | |||
1429 | : diag::warn_arith_conv_enum_float) | |||
1430 | << LHS->getSourceRange() << RHS->getSourceRange() | |||
1431 | << (int)ACK << LEnum << L << R; | |||
1432 | } else if (!IsCompAssign && LEnum && REnum && | |||
1433 | !S.Context.hasSameUnqualifiedType(L, R)) { | |||
1434 | unsigned DiagID; | |||
1435 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | |||
1436 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | |||
1437 | // If either enumeration type is unnamed, it's less likely that the | |||
1438 | // user cares about this, but this situation is still deprecated in | |||
1439 | // C++2a. Use a different warning group. | |||
1440 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1441 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | |||
1442 | : diag::warn_arith_conv_mixed_anon_enum_types; | |||
1443 | } else if (ACK == Sema::ACK_Conditional) { | |||
1444 | // Conditional expressions are separated out because they have | |||
1445 | // historically had a different warning flag. | |||
1446 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1447 | ? diag::warn_conditional_mixed_enum_types_cxx20 | |||
1448 | : diag::warn_conditional_mixed_enum_types; | |||
1449 | } else if (ACK == Sema::ACK_Comparison) { | |||
1450 | // Comparison expressions are separated out because they have | |||
1451 | // historically had a different warning flag. | |||
1452 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1453 | ? diag::warn_comparison_mixed_enum_types_cxx20 | |||
1454 | : diag::warn_comparison_mixed_enum_types; | |||
1455 | } else { | |||
1456 | DiagID = S.getLangOpts().CPlusPlus20 | |||
1457 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | |||
1458 | : diag::warn_arith_conv_mixed_enum_types; | |||
1459 | } | |||
1460 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | |||
1461 | << (int)ACK << L << R; | |||
1462 | } | |||
1463 | } | |||
1464 | ||||
1465 | /// UsualArithmeticConversions - Performs various conversions that are common to | |||
1466 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | |||
1467 | /// routine returns the first non-arithmetic type found. The client is | |||
1468 | /// responsible for emitting appropriate error diagnostics. | |||
1469 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | |||
1470 | SourceLocation Loc, | |||
1471 | ArithConvKind ACK) { | |||
1472 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | |||
1473 | ||||
1474 | if (ACK != ACK_CompAssign) { | |||
1475 | LHS = UsualUnaryConversions(LHS.get()); | |||
1476 | if (LHS.isInvalid()) | |||
1477 | return QualType(); | |||
1478 | } | |||
1479 | ||||
1480 | RHS = UsualUnaryConversions(RHS.get()); | |||
1481 | if (RHS.isInvalid()) | |||
1482 | return QualType(); | |||
1483 | ||||
1484 | // For conversion purposes, we ignore any qualifiers. | |||
1485 | // For example, "const float" and "float" are equivalent. | |||
1486 | QualType LHSType = | |||
1487 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
1488 | QualType RHSType = | |||
1489 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
1490 | ||||
1491 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | |||
1492 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | |||
1493 | LHSType = AtomicLHS->getValueType(); | |||
1494 | ||||
1495 | // If both types are identical, no conversion is needed. | |||
1496 | if (LHSType == RHSType) | |||
1497 | return LHSType; | |||
1498 | ||||
1499 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | |||
1500 | // The caller can deal with this (e.g. pointer + int). | |||
1501 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | |||
1502 | return QualType(); | |||
1503 | ||||
1504 | // Apply unary and bitfield promotions to the LHS's type. | |||
1505 | QualType LHSUnpromotedType = LHSType; | |||
1506 | if (LHSType->isPromotableIntegerType()) | |||
1507 | LHSType = Context.getPromotedIntegerType(LHSType); | |||
1508 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | |||
1509 | if (!LHSBitfieldPromoteTy.isNull()) | |||
1510 | LHSType = LHSBitfieldPromoteTy; | |||
1511 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | |||
1512 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | |||
1513 | ||||
1514 | // If both types are identical, no conversion is needed. | |||
1515 | if (LHSType == RHSType) | |||
1516 | return LHSType; | |||
1517 | ||||
1518 | // ExtInt types aren't subject to conversions between them or normal integers, | |||
1519 | // so this fails. | |||
1520 | if(LHSType->isExtIntType() || RHSType->isExtIntType()) | |||
1521 | return QualType(); | |||
1522 | ||||
1523 | // At this point, we have two different arithmetic types. | |||
1524 | ||||
1525 | // Diagnose attempts to convert between __float128 and long double where | |||
1526 | // such conversions currently can't be handled. | |||
1527 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
1528 | return QualType(); | |||
1529 | ||||
1530 | // Handle complex types first (C99 6.3.1.8p1). | |||
1531 | if (LHSType->isComplexType() || RHSType->isComplexType()) | |||
1532 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1533 | ACK == ACK_CompAssign); | |||
1534 | ||||
1535 | // Now handle "real" floating types (i.e. float, double, long double). | |||
1536 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
1537 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1538 | ACK == ACK_CompAssign); | |||
1539 | ||||
1540 | // Handle GCC complex int extension. | |||
1541 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | |||
1542 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1543 | ACK == ACK_CompAssign); | |||
1544 | ||||
1545 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | |||
1546 | return handleFixedPointConversion(*this, LHSType, RHSType); | |||
1547 | ||||
1548 | // Finally, we have two differing integer types. | |||
1549 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
1550 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | |||
1551 | } | |||
1552 | ||||
1553 | //===----------------------------------------------------------------------===// | |||
1554 | // Semantic Analysis for various Expression Types | |||
1555 | //===----------------------------------------------------------------------===// | |||
1556 | ||||
1557 | ||||
1558 | ExprResult | |||
1559 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | |||
1560 | SourceLocation DefaultLoc, | |||
1561 | SourceLocation RParenLoc, | |||
1562 | Expr *ControllingExpr, | |||
1563 | ArrayRef<ParsedType> ArgTypes, | |||
1564 | ArrayRef<Expr *> ArgExprs) { | |||
1565 | unsigned NumAssocs = ArgTypes.size(); | |||
1566 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1566, __PRETTY_FUNCTION__)); | |||
1567 | ||||
1568 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | |||
1569 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1570 | if (ArgTypes[i]) | |||
1571 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | |||
1572 | else | |||
1573 | Types[i] = nullptr; | |||
1574 | } | |||
1575 | ||||
1576 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | |||
1577 | ControllingExpr, | |||
1578 | llvm::makeArrayRef(Types, NumAssocs), | |||
1579 | ArgExprs); | |||
1580 | delete [] Types; | |||
1581 | return ER; | |||
1582 | } | |||
1583 | ||||
1584 | ExprResult | |||
1585 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | |||
1586 | SourceLocation DefaultLoc, | |||
1587 | SourceLocation RParenLoc, | |||
1588 | Expr *ControllingExpr, | |||
1589 | ArrayRef<TypeSourceInfo *> Types, | |||
1590 | ArrayRef<Expr *> Exprs) { | |||
1591 | unsigned NumAssocs = Types.size(); | |||
1592 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1592, __PRETTY_FUNCTION__)); | |||
1593 | ||||
1594 | // Decay and strip qualifiers for the controlling expression type, and handle | |||
1595 | // placeholder type replacement. See committee discussion from WG14 DR423. | |||
1596 | { | |||
1597 | EnterExpressionEvaluationContext Unevaluated( | |||
1598 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
1599 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | |||
1600 | if (R.isInvalid()) | |||
1601 | return ExprError(); | |||
1602 | ControllingExpr = R.get(); | |||
1603 | } | |||
1604 | ||||
1605 | // The controlling expression is an unevaluated operand, so side effects are | |||
1606 | // likely unintended. | |||
1607 | if (!inTemplateInstantiation() && | |||
1608 | ControllingExpr->HasSideEffects(Context, false)) | |||
1609 | Diag(ControllingExpr->getExprLoc(), | |||
1610 | diag::warn_side_effects_unevaluated_context); | |||
1611 | ||||
1612 | bool TypeErrorFound = false, | |||
1613 | IsResultDependent = ControllingExpr->isTypeDependent(), | |||
1614 | ContainsUnexpandedParameterPack | |||
1615 | = ControllingExpr->containsUnexpandedParameterPack(); | |||
1616 | ||||
1617 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1618 | if (Exprs[i]->containsUnexpandedParameterPack()) | |||
1619 | ContainsUnexpandedParameterPack = true; | |||
1620 | ||||
1621 | if (Types[i]) { | |||
1622 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | |||
1623 | ContainsUnexpandedParameterPack = true; | |||
1624 | ||||
1625 | if (Types[i]->getType()->isDependentType()) { | |||
1626 | IsResultDependent = true; | |||
1627 | } else { | |||
1628 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | |||
1629 | // complete object type other than a variably modified type." | |||
1630 | unsigned D = 0; | |||
1631 | if (Types[i]->getType()->isIncompleteType()) | |||
1632 | D = diag::err_assoc_type_incomplete; | |||
1633 | else if (!Types[i]->getType()->isObjectType()) | |||
1634 | D = diag::err_assoc_type_nonobject; | |||
1635 | else if (Types[i]->getType()->isVariablyModifiedType()) | |||
1636 | D = diag::err_assoc_type_variably_modified; | |||
1637 | ||||
1638 | if (D != 0) { | |||
1639 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | |||
1640 | << Types[i]->getTypeLoc().getSourceRange() | |||
1641 | << Types[i]->getType(); | |||
1642 | TypeErrorFound = true; | |||
1643 | } | |||
1644 | ||||
1645 | // C11 6.5.1.1p2 "No two generic associations in the same generic | |||
1646 | // selection shall specify compatible types." | |||
1647 | for (unsigned j = i+1; j < NumAssocs; ++j) | |||
1648 | if (Types[j] && !Types[j]->getType()->isDependentType() && | |||
1649 | Context.typesAreCompatible(Types[i]->getType(), | |||
1650 | Types[j]->getType())) { | |||
1651 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | |||
1652 | diag::err_assoc_compatible_types) | |||
1653 | << Types[j]->getTypeLoc().getSourceRange() | |||
1654 | << Types[j]->getType() | |||
1655 | << Types[i]->getType(); | |||
1656 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | |||
1657 | diag::note_compat_assoc) | |||
1658 | << Types[i]->getTypeLoc().getSourceRange() | |||
1659 | << Types[i]->getType(); | |||
1660 | TypeErrorFound = true; | |||
1661 | } | |||
1662 | } | |||
1663 | } | |||
1664 | } | |||
1665 | if (TypeErrorFound) | |||
1666 | return ExprError(); | |||
1667 | ||||
1668 | // If we determined that the generic selection is result-dependent, don't | |||
1669 | // try to compute the result expression. | |||
1670 | if (IsResultDependent) | |||
1671 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | |||
1672 | Exprs, DefaultLoc, RParenLoc, | |||
1673 | ContainsUnexpandedParameterPack); | |||
1674 | ||||
1675 | SmallVector<unsigned, 1> CompatIndices; | |||
1676 | unsigned DefaultIndex = -1U; | |||
1677 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1678 | if (!Types[i]) | |||
1679 | DefaultIndex = i; | |||
1680 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | |||
1681 | Types[i]->getType())) | |||
1682 | CompatIndices.push_back(i); | |||
1683 | } | |||
1684 | ||||
1685 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | |||
1686 | // type compatible with at most one of the types named in its generic | |||
1687 | // association list." | |||
1688 | if (CompatIndices.size() > 1) { | |||
1689 | // We strip parens here because the controlling expression is typically | |||
1690 | // parenthesized in macro definitions. | |||
1691 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1692 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | |||
1693 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | |||
1694 | << (unsigned)CompatIndices.size(); | |||
1695 | for (unsigned I : CompatIndices) { | |||
1696 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | |||
1697 | diag::note_compat_assoc) | |||
1698 | << Types[I]->getTypeLoc().getSourceRange() | |||
1699 | << Types[I]->getType(); | |||
1700 | } | |||
1701 | return ExprError(); | |||
1702 | } | |||
1703 | ||||
1704 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | |||
1705 | // its controlling expression shall have type compatible with exactly one of | |||
1706 | // the types named in its generic association list." | |||
1707 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | |||
1708 | // We strip parens here because the controlling expression is typically | |||
1709 | // parenthesized in macro definitions. | |||
1710 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1711 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | |||
1712 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | |||
1713 | return ExprError(); | |||
1714 | } | |||
1715 | ||||
1716 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | |||
1717 | // type name that is compatible with the type of the controlling expression, | |||
1718 | // then the result expression of the generic selection is the expression | |||
1719 | // in that generic association. Otherwise, the result expression of the | |||
1720 | // generic selection is the expression in the default generic association." | |||
1721 | unsigned ResultIndex = | |||
1722 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | |||
1723 | ||||
1724 | return GenericSelectionExpr::Create( | |||
1725 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | |||
1726 | ContainsUnexpandedParameterPack, ResultIndex); | |||
1727 | } | |||
1728 | ||||
1729 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | |||
1730 | /// location of the token and the offset of the ud-suffix within it. | |||
1731 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | |||
1732 | unsigned Offset) { | |||
1733 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | |||
1734 | S.getLangOpts()); | |||
1735 | } | |||
1736 | ||||
1737 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | |||
1738 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | |||
1739 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | |||
1740 | IdentifierInfo *UDSuffix, | |||
1741 | SourceLocation UDSuffixLoc, | |||
1742 | ArrayRef<Expr*> Args, | |||
1743 | SourceLocation LitEndLoc) { | |||
1744 | assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator" ) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1744, __PRETTY_FUNCTION__)); | |||
1745 | ||||
1746 | QualType ArgTy[2]; | |||
1747 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | |||
1748 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | |||
1749 | if (ArgTy[ArgIdx]->isArrayType()) | |||
1750 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | |||
1751 | } | |||
1752 | ||||
1753 | DeclarationName OpName = | |||
1754 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1755 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1756 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1757 | ||||
1758 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | |||
1759 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | |||
1760 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | |||
1761 | /*AllowStringTemplatePack*/ false, | |||
1762 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | |||
1763 | return ExprError(); | |||
1764 | ||||
1765 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | |||
1766 | } | |||
1767 | ||||
1768 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | |||
1769 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | |||
1770 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | |||
1771 | /// multiple tokens. However, the common case is that StringToks points to one | |||
1772 | /// string. | |||
1773 | /// | |||
1774 | ExprResult | |||
1775 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | |||
1776 | assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!" ) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1776, __PRETTY_FUNCTION__)); | |||
1777 | ||||
1778 | StringLiteralParser Literal(StringToks, PP); | |||
1779 | if (Literal.hadError) | |||
1780 | return ExprError(); | |||
1781 | ||||
1782 | SmallVector<SourceLocation, 4> StringTokLocs; | |||
1783 | for (const Token &Tok : StringToks) | |||
1784 | StringTokLocs.push_back(Tok.getLocation()); | |||
1785 | ||||
1786 | QualType CharTy = Context.CharTy; | |||
1787 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | |||
1788 | if (Literal.isWide()) { | |||
1789 | CharTy = Context.getWideCharType(); | |||
1790 | Kind = StringLiteral::Wide; | |||
1791 | } else if (Literal.isUTF8()) { | |||
1792 | if (getLangOpts().Char8) | |||
1793 | CharTy = Context.Char8Ty; | |||
1794 | Kind = StringLiteral::UTF8; | |||
1795 | } else if (Literal.isUTF16()) { | |||
1796 | CharTy = Context.Char16Ty; | |||
1797 | Kind = StringLiteral::UTF16; | |||
1798 | } else if (Literal.isUTF32()) { | |||
1799 | CharTy = Context.Char32Ty; | |||
1800 | Kind = StringLiteral::UTF32; | |||
1801 | } else if (Literal.isPascal()) { | |||
1802 | CharTy = Context.UnsignedCharTy; | |||
1803 | } | |||
1804 | ||||
1805 | // Warn on initializing an array of char from a u8 string literal; this | |||
1806 | // becomes ill-formed in C++2a. | |||
1807 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | |||
1808 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | |||
1809 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | |||
1810 | ||||
1811 | // Create removals for all 'u8' prefixes in the string literal(s). This | |||
1812 | // ensures C++2a compatibility (but may change the program behavior when | |||
1813 | // built by non-Clang compilers for which the execution character set is | |||
1814 | // not always UTF-8). | |||
1815 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | |||
1816 | SourceLocation RemovalDiagLoc; | |||
1817 | for (const Token &Tok : StringToks) { | |||
1818 | if (Tok.getKind() == tok::utf8_string_literal) { | |||
1819 | if (RemovalDiagLoc.isInvalid()) | |||
1820 | RemovalDiagLoc = Tok.getLocation(); | |||
1821 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | |||
1822 | Tok.getLocation(), | |||
1823 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | |||
1824 | getSourceManager(), getLangOpts()))); | |||
1825 | } | |||
1826 | } | |||
1827 | Diag(RemovalDiagLoc, RemovalDiag); | |||
1828 | } | |||
1829 | ||||
1830 | QualType StrTy = | |||
1831 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | |||
1832 | ||||
1833 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | |||
1834 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | |||
1835 | Kind, Literal.Pascal, StrTy, | |||
1836 | &StringTokLocs[0], | |||
1837 | StringTokLocs.size()); | |||
1838 | if (Literal.getUDSuffix().empty()) | |||
1839 | return Lit; | |||
1840 | ||||
1841 | // We're building a user-defined literal. | |||
1842 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
1843 | SourceLocation UDSuffixLoc = | |||
1844 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | |||
1845 | Literal.getUDSuffixOffset()); | |||
1846 | ||||
1847 | // Make sure we're allowed user-defined literals here. | |||
1848 | if (!UDLScope) | |||
1849 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | |||
1850 | ||||
1851 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | |||
1852 | // operator "" X (str, len) | |||
1853 | QualType SizeType = Context.getSizeType(); | |||
1854 | ||||
1855 | DeclarationName OpName = | |||
1856 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1857 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1858 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1859 | ||||
1860 | QualType ArgTy[] = { | |||
1861 | Context.getArrayDecayedType(StrTy), SizeType | |||
1862 | }; | |||
1863 | ||||
1864 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
1865 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | |||
1866 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | |||
1867 | /*AllowStringTemplatePack*/ true, | |||
1868 | /*DiagnoseMissing*/ true, Lit)) { | |||
1869 | ||||
1870 | case LOLR_Cooked: { | |||
1871 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | |||
1872 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | |||
1873 | StringTokLocs[0]); | |||
1874 | Expr *Args[] = { Lit, LenArg }; | |||
1875 | ||||
1876 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | |||
1877 | } | |||
1878 | ||||
1879 | case LOLR_Template: { | |||
1880 | TemplateArgumentListInfo ExplicitArgs; | |||
1881 | TemplateArgument Arg(Lit); | |||
1882 | TemplateArgumentLocInfo ArgInfo(Lit); | |||
1883 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
1884 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | |||
1885 | &ExplicitArgs); | |||
1886 | } | |||
1887 | ||||
1888 | case LOLR_StringTemplatePack: { | |||
1889 | TemplateArgumentListInfo ExplicitArgs; | |||
1890 | ||||
1891 | unsigned CharBits = Context.getIntWidth(CharTy); | |||
1892 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | |||
1893 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
1894 | ||||
1895 | TemplateArgument TypeArg(CharTy); | |||
1896 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | |||
1897 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | |||
1898 | ||||
1899 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | |||
1900 | Value = Lit->getCodeUnit(I); | |||
1901 | TemplateArgument Arg(Context, Value, CharTy); | |||
1902 | TemplateArgumentLocInfo ArgInfo; | |||
1903 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
1904 | } | |||
1905 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | |||
1906 | &ExplicitArgs); | |||
1907 | } | |||
1908 | case LOLR_Raw: | |||
1909 | case LOLR_ErrorNoDiagnostic: | |||
1910 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1910); | |||
1911 | case LOLR_Error: | |||
1912 | return ExprError(); | |||
1913 | } | |||
1914 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 1914); | |||
1915 | } | |||
1916 | ||||
1917 | DeclRefExpr * | |||
1918 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1919 | SourceLocation Loc, | |||
1920 | const CXXScopeSpec *SS) { | |||
1921 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | |||
1922 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | |||
1923 | } | |||
1924 | ||||
1925 | DeclRefExpr * | |||
1926 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1927 | const DeclarationNameInfo &NameInfo, | |||
1928 | const CXXScopeSpec *SS, NamedDecl *FoundD, | |||
1929 | SourceLocation TemplateKWLoc, | |||
1930 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1931 | NestedNameSpecifierLoc NNS = | |||
1932 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | |||
1933 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | |||
1934 | TemplateArgs); | |||
1935 | } | |||
1936 | ||||
1937 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | |||
1938 | // A declaration named in an unevaluated operand never constitutes an odr-use. | |||
1939 | if (isUnevaluatedContext()) | |||
1940 | return NOUR_Unevaluated; | |||
1941 | ||||
1942 | // C++2a [basic.def.odr]p4: | |||
1943 | // A variable x whose name appears as a potentially-evaluated expression e | |||
1944 | // is odr-used by e unless [...] x is a reference that is usable in | |||
1945 | // constant expressions. | |||
1946 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1947 | if (VD->getType()->isReferenceType() && | |||
1948 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | |||
1949 | VD->isUsableInConstantExpressions(Context)) | |||
1950 | return NOUR_Constant; | |||
1951 | } | |||
1952 | ||||
1953 | // All remaining non-variable cases constitute an odr-use. For variables, we | |||
1954 | // need to wait and see how the expression is used. | |||
1955 | return NOUR_None; | |||
1956 | } | |||
1957 | ||||
1958 | /// BuildDeclRefExpr - Build an expression that references a | |||
1959 | /// declaration that does not require a closure capture. | |||
1960 | DeclRefExpr * | |||
1961 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1962 | const DeclarationNameInfo &NameInfo, | |||
1963 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | |||
1964 | SourceLocation TemplateKWLoc, | |||
1965 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1966 | bool RefersToCapturedVariable = | |||
1967 | isa<VarDecl>(D) && | |||
1968 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | |||
1969 | ||||
1970 | DeclRefExpr *E = DeclRefExpr::Create( | |||
1971 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | |||
1972 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | |||
1973 | MarkDeclRefReferenced(E); | |||
1974 | ||||
1975 | // C++ [except.spec]p17: | |||
1976 | // An exception-specification is considered to be needed when: | |||
1977 | // - in an expression, the function is the unique lookup result or | |||
1978 | // the selected member of a set of overloaded functions. | |||
1979 | // | |||
1980 | // We delay doing this until after we've built the function reference and | |||
1981 | // marked it as used so that: | |||
1982 | // a) if the function is defaulted, we get errors from defining it before / | |||
1983 | // instead of errors from computing its exception specification, and | |||
1984 | // b) if the function is a defaulted comparison, we can use the body we | |||
1985 | // build when defining it as input to the exception specification | |||
1986 | // computation rather than computing a new body. | |||
1987 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | |||
1988 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | |||
1989 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | |||
1990 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | |||
1991 | } | |||
1992 | } | |||
1993 | ||||
1994 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | |||
1995 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | |||
1996 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | |||
1997 | getCurFunction()->recordUseOfWeak(E); | |||
1998 | ||||
1999 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
2000 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | |||
2001 | FD = IFD->getAnonField(); | |||
2002 | if (FD) { | |||
2003 | UnusedPrivateFields.remove(FD); | |||
2004 | // Just in case we're building an illegal pointer-to-member. | |||
2005 | if (FD->isBitField()) | |||
2006 | E->setObjectKind(OK_BitField); | |||
2007 | } | |||
2008 | ||||
2009 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | |||
2010 | // designates a bit-field. | |||
2011 | if (auto *BD = dyn_cast<BindingDecl>(D)) | |||
2012 | if (auto *BE = BD->getBinding()) | |||
2013 | E->setObjectKind(BE->getObjectKind()); | |||
2014 | ||||
2015 | return E; | |||
2016 | } | |||
2017 | ||||
2018 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | |||
2019 | /// possibly a list of template arguments. | |||
2020 | /// | |||
2021 | /// If this produces template arguments, it is permitted to call | |||
2022 | /// DecomposeTemplateName. | |||
2023 | /// | |||
2024 | /// This actually loses a lot of source location information for | |||
2025 | /// non-standard name kinds; we should consider preserving that in | |||
2026 | /// some way. | |||
2027 | void | |||
2028 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | |||
2029 | TemplateArgumentListInfo &Buffer, | |||
2030 | DeclarationNameInfo &NameInfo, | |||
2031 | const TemplateArgumentListInfo *&TemplateArgs) { | |||
2032 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
2033 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | |||
2034 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | |||
2035 | ||||
2036 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | |||
2037 | Id.TemplateId->NumArgs); | |||
2038 | translateTemplateArguments(TemplateArgsPtr, Buffer); | |||
2039 | ||||
2040 | TemplateName TName = Id.TemplateId->Template.get(); | |||
2041 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | |||
2042 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | |||
2043 | TemplateArgs = &Buffer; | |||
2044 | } else { | |||
2045 | NameInfo = GetNameFromUnqualifiedId(Id); | |||
2046 | TemplateArgs = nullptr; | |||
2047 | } | |||
2048 | } | |||
2049 | ||||
2050 | static void emitEmptyLookupTypoDiagnostic( | |||
2051 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | |||
2052 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | |||
2053 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | |||
2054 | DeclContext *Ctx = | |||
2055 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | |||
2056 | if (!TC) { | |||
2057 | // Emit a special diagnostic for failed member lookups. | |||
2058 | // FIXME: computing the declaration context might fail here (?) | |||
2059 | if (Ctx) | |||
2060 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | |||
2061 | << SS.getRange(); | |||
2062 | else | |||
2063 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | |||
2064 | return; | |||
2065 | } | |||
2066 | ||||
2067 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | |||
2068 | bool DroppedSpecifier = | |||
2069 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | |||
2070 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | |||
2071 | ? diag::note_implicit_param_decl | |||
2072 | : diag::note_previous_decl; | |||
2073 | if (!Ctx) | |||
2074 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | |||
2075 | SemaRef.PDiag(NoteID)); | |||
2076 | else | |||
2077 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | |||
2078 | << Typo << Ctx << DroppedSpecifier | |||
2079 | << SS.getRange(), | |||
2080 | SemaRef.PDiag(NoteID)); | |||
2081 | } | |||
2082 | ||||
2083 | /// Diagnose an empty lookup. | |||
2084 | /// | |||
2085 | /// \return false if new lookup candidates were found | |||
2086 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | |||
2087 | CorrectionCandidateCallback &CCC, | |||
2088 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
2089 | ArrayRef<Expr *> Args, TypoExpr **Out) { | |||
2090 | DeclarationName Name = R.getLookupName(); | |||
2091 | ||||
2092 | unsigned diagnostic = diag::err_undeclared_var_use; | |||
2093 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | |||
2094 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | |||
2095 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | |||
2096 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
2097 | diagnostic = diag::err_undeclared_use; | |||
2098 | diagnostic_suggest = diag::err_undeclared_use_suggest; | |||
2099 | } | |||
2100 | ||||
2101 | // If the original lookup was an unqualified lookup, fake an | |||
2102 | // unqualified lookup. This is useful when (for example) the | |||
2103 | // original lookup would not have found something because it was a | |||
2104 | // dependent name. | |||
2105 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | |||
2106 | while (DC) { | |||
2107 | if (isa<CXXRecordDecl>(DC)) { | |||
2108 | LookupQualifiedName(R, DC); | |||
2109 | ||||
2110 | if (!R.empty()) { | |||
2111 | // Don't give errors about ambiguities in this lookup. | |||
2112 | R.suppressDiagnostics(); | |||
2113 | ||||
2114 | // During a default argument instantiation the CurContext points | |||
2115 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | |||
2116 | // function parameter list, hence add an explicit check. | |||
2117 | bool isDefaultArgument = | |||
2118 | !CodeSynthesisContexts.empty() && | |||
2119 | CodeSynthesisContexts.back().Kind == | |||
2120 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | |||
2121 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | |||
2122 | bool isInstance = CurMethod && | |||
2123 | CurMethod->isInstance() && | |||
2124 | DC == CurMethod->getParent() && !isDefaultArgument; | |||
2125 | ||||
2126 | // Give a code modification hint to insert 'this->'. | |||
2127 | // TODO: fixit for inserting 'Base<T>::' in the other cases. | |||
2128 | // Actually quite difficult! | |||
2129 | if (getLangOpts().MSVCCompat) | |||
2130 | diagnostic = diag::ext_found_via_dependent_bases_lookup; | |||
2131 | if (isInstance) { | |||
2132 | Diag(R.getNameLoc(), diagnostic) << Name | |||
2133 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | |||
2134 | CheckCXXThisCapture(R.getNameLoc()); | |||
2135 | } else { | |||
2136 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
2137 | } | |||
2138 | ||||
2139 | // Do we really want to note all of these? | |||
2140 | for (NamedDecl *D : R) | |||
2141 | Diag(D->getLocation(), diag::note_dependent_var_use); | |||
2142 | ||||
2143 | // Return true if we are inside a default argument instantiation | |||
2144 | // and the found name refers to an instance member function, otherwise | |||
2145 | // the function calling DiagnoseEmptyLookup will try to create an | |||
2146 | // implicit member call and this is wrong for default argument. | |||
2147 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | |||
2148 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | |||
2149 | return true; | |||
2150 | } | |||
2151 | ||||
2152 | // Tell the callee to try to recover. | |||
2153 | return false; | |||
2154 | } | |||
2155 | ||||
2156 | R.clear(); | |||
2157 | } | |||
2158 | ||||
2159 | DC = DC->getLookupParent(); | |||
2160 | } | |||
2161 | ||||
2162 | // We didn't find anything, so try to correct for a typo. | |||
2163 | TypoCorrection Corrected; | |||
2164 | if (S && Out) { | |||
2165 | SourceLocation TypoLoc = R.getNameLoc(); | |||
2166 | assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2167, __PRETTY_FUNCTION__)) | |||
2167 | "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2167, __PRETTY_FUNCTION__)); | |||
2168 | *Out = CorrectTypoDelayed( | |||
2169 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | |||
2170 | [=](const TypoCorrection &TC) { | |||
2171 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | |||
2172 | diagnostic, diagnostic_suggest); | |||
2173 | }, | |||
2174 | nullptr, CTK_ErrorRecovery); | |||
2175 | if (*Out) | |||
2176 | return true; | |||
2177 | } else if (S && | |||
2178 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | |||
2179 | S, &SS, CCC, CTK_ErrorRecovery))) { | |||
2180 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
2181 | bool DroppedSpecifier = | |||
2182 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | |||
2183 | R.setLookupName(Corrected.getCorrection()); | |||
2184 | ||||
2185 | bool AcceptableWithRecovery = false; | |||
2186 | bool AcceptableWithoutRecovery = false; | |||
2187 | NamedDecl *ND = Corrected.getFoundDecl(); | |||
2188 | if (ND) { | |||
2189 | if (Corrected.isOverloaded()) { | |||
2190 | OverloadCandidateSet OCS(R.getNameLoc(), | |||
2191 | OverloadCandidateSet::CSK_Normal); | |||
2192 | OverloadCandidateSet::iterator Best; | |||
2193 | for (NamedDecl *CD : Corrected) { | |||
2194 | if (FunctionTemplateDecl *FTD = | |||
2195 | dyn_cast<FunctionTemplateDecl>(CD)) | |||
2196 | AddTemplateOverloadCandidate( | |||
2197 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | |||
2198 | Args, OCS); | |||
2199 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
2200 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | |||
2201 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | |||
2202 | Args, OCS); | |||
2203 | } | |||
2204 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | |||
2205 | case OR_Success: | |||
2206 | ND = Best->FoundDecl; | |||
2207 | Corrected.setCorrectionDecl(ND); | |||
2208 | break; | |||
2209 | default: | |||
2210 | // FIXME: Arbitrarily pick the first declaration for the note. | |||
2211 | Corrected.setCorrectionDecl(ND); | |||
2212 | break; | |||
2213 | } | |||
2214 | } | |||
2215 | R.addDecl(ND); | |||
2216 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | |||
2217 | CXXRecordDecl *Record = nullptr; | |||
2218 | if (Corrected.getCorrectionSpecifier()) { | |||
2219 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | |||
2220 | Record = Ty->getAsCXXRecordDecl(); | |||
2221 | } | |||
2222 | if (!Record) | |||
2223 | Record = cast<CXXRecordDecl>( | |||
2224 | ND->getDeclContext()->getRedeclContext()); | |||
2225 | R.setNamingClass(Record); | |||
2226 | } | |||
2227 | ||||
2228 | auto *UnderlyingND = ND->getUnderlyingDecl(); | |||
2229 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | |||
2230 | isa<FunctionTemplateDecl>(UnderlyingND); | |||
2231 | // FIXME: If we ended up with a typo for a type name or | |||
2232 | // Objective-C class name, we're in trouble because the parser | |||
2233 | // is in the wrong place to recover. Suggest the typo | |||
2234 | // correction, but don't make it a fix-it since we're not going | |||
2235 | // to recover well anyway. | |||
2236 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | |||
2237 | getAsTypeTemplateDecl(UnderlyingND) || | |||
2238 | isa<ObjCInterfaceDecl>(UnderlyingND); | |||
2239 | } else { | |||
2240 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | |||
2241 | // because we aren't able to recover. | |||
2242 | AcceptableWithoutRecovery = true; | |||
2243 | } | |||
2244 | ||||
2245 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | |||
2246 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | |||
2247 | ? diag::note_implicit_param_decl | |||
2248 | : diag::note_previous_decl; | |||
2249 | if (SS.isEmpty()) | |||
2250 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | |||
2251 | PDiag(NoteID), AcceptableWithRecovery); | |||
2252 | else | |||
2253 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
2254 | << Name << computeDeclContext(SS, false) | |||
2255 | << DroppedSpecifier << SS.getRange(), | |||
2256 | PDiag(NoteID), AcceptableWithRecovery); | |||
2257 | ||||
2258 | // Tell the callee whether to try to recover. | |||
2259 | return !AcceptableWithRecovery; | |||
2260 | } | |||
2261 | } | |||
2262 | R.clear(); | |||
2263 | ||||
2264 | // Emit a special diagnostic for failed member lookups. | |||
2265 | // FIXME: computing the declaration context might fail here (?) | |||
2266 | if (!SS.isEmpty()) { | |||
2267 | Diag(R.getNameLoc(), diag::err_no_member) | |||
2268 | << Name << computeDeclContext(SS, false) | |||
2269 | << SS.getRange(); | |||
2270 | return true; | |||
2271 | } | |||
2272 | ||||
2273 | // Give up, we can't recover. | |||
2274 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
2275 | return true; | |||
2276 | } | |||
2277 | ||||
2278 | /// In Microsoft mode, if we are inside a template class whose parent class has | |||
2279 | /// dependent base classes, and we can't resolve an unqualified identifier, then | |||
2280 | /// assume the identifier is a member of a dependent base class. We can only | |||
2281 | /// recover successfully in static methods, instance methods, and other contexts | |||
2282 | /// where 'this' is available. This doesn't precisely match MSVC's | |||
2283 | /// instantiation model, but it's close enough. | |||
2284 | static Expr * | |||
2285 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | |||
2286 | DeclarationNameInfo &NameInfo, | |||
2287 | SourceLocation TemplateKWLoc, | |||
2288 | const TemplateArgumentListInfo *TemplateArgs) { | |||
2289 | // Only try to recover from lookup into dependent bases in static methods or | |||
2290 | // contexts where 'this' is available. | |||
2291 | QualType ThisType = S.getCurrentThisType(); | |||
2292 | const CXXRecordDecl *RD = nullptr; | |||
2293 | if (!ThisType.isNull()) | |||
2294 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | |||
2295 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | |||
2296 | RD = MD->getParent(); | |||
2297 | if (!RD || !RD->hasAnyDependentBases()) | |||
2298 | return nullptr; | |||
2299 | ||||
2300 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | |||
2301 | // is available, suggest inserting 'this->' as a fixit. | |||
2302 | SourceLocation Loc = NameInfo.getLoc(); | |||
2303 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | |||
2304 | DB << NameInfo.getName() << RD; | |||
2305 | ||||
2306 | if (!ThisType.isNull()) { | |||
2307 | DB << FixItHint::CreateInsertion(Loc, "this->"); | |||
2308 | return CXXDependentScopeMemberExpr::Create( | |||
2309 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | |||
2310 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | |||
2311 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | |||
2312 | } | |||
2313 | ||||
2314 | // Synthesize a fake NNS that points to the derived class. This will | |||
2315 | // perform name lookup during template instantiation. | |||
2316 | CXXScopeSpec SS; | |||
2317 | auto *NNS = | |||
2318 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | |||
2319 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | |||
2320 | return DependentScopeDeclRefExpr::Create( | |||
2321 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | |||
2322 | TemplateArgs); | |||
2323 | } | |||
2324 | ||||
2325 | ExprResult | |||
2326 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | |||
2327 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | |||
2328 | bool HasTrailingLParen, bool IsAddressOfOperand, | |||
2329 | CorrectionCandidateCallback *CCC, | |||
2330 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | |||
2331 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2332, __PRETTY_FUNCTION__)) | |||
2332 | "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2332, __PRETTY_FUNCTION__)); | |||
2333 | if (SS.isInvalid()) | |||
2334 | return ExprError(); | |||
2335 | ||||
2336 | TemplateArgumentListInfo TemplateArgsBuffer; | |||
2337 | ||||
2338 | // Decompose the UnqualifiedId into the following data. | |||
2339 | DeclarationNameInfo NameInfo; | |||
2340 | const TemplateArgumentListInfo *TemplateArgs; | |||
2341 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | |||
2342 | ||||
2343 | DeclarationName Name = NameInfo.getName(); | |||
2344 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
2345 | SourceLocation NameLoc = NameInfo.getLoc(); | |||
2346 | ||||
2347 | if (II && II->isEditorPlaceholder()) { | |||
2348 | // FIXME: When typed placeholders are supported we can create a typed | |||
2349 | // placeholder expression node. | |||
2350 | return ExprError(); | |||
2351 | } | |||
2352 | ||||
2353 | // C++ [temp.dep.expr]p3: | |||
2354 | // An id-expression is type-dependent if it contains: | |||
2355 | // -- an identifier that was declared with a dependent type, | |||
2356 | // (note: handled after lookup) | |||
2357 | // -- a template-id that is dependent, | |||
2358 | // (note: handled in BuildTemplateIdExpr) | |||
2359 | // -- a conversion-function-id that specifies a dependent type, | |||
2360 | // -- a nested-name-specifier that contains a class-name that | |||
2361 | // names a dependent type. | |||
2362 | // Determine whether this is a member of an unknown specialization; | |||
2363 | // we need to handle these differently. | |||
2364 | bool DependentID = false; | |||
2365 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | |||
2366 | Name.getCXXNameType()->isDependentType()) { | |||
2367 | DependentID = true; | |||
2368 | } else if (SS.isSet()) { | |||
2369 | if (DeclContext *DC = computeDeclContext(SS, false)) { | |||
2370 | if (RequireCompleteDeclContext(SS, DC)) | |||
2371 | return ExprError(); | |||
2372 | } else { | |||
2373 | DependentID = true; | |||
2374 | } | |||
2375 | } | |||
2376 | ||||
2377 | if (DependentID) | |||
2378 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2379 | IsAddressOfOperand, TemplateArgs); | |||
2380 | ||||
2381 | // Perform the required lookup. | |||
2382 | LookupResult R(*this, NameInfo, | |||
2383 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | |||
2384 | ? LookupObjCImplicitSelfParam | |||
2385 | : LookupOrdinaryName); | |||
2386 | if (TemplateKWLoc.isValid() || TemplateArgs) { | |||
2387 | // Lookup the template name again to correctly establish the context in | |||
2388 | // which it was found. This is really unfortunate as we already did the | |||
2389 | // lookup to determine that it was a template name in the first place. If | |||
2390 | // this becomes a performance hit, we can work harder to preserve those | |||
2391 | // results until we get here but it's likely not worth it. | |||
2392 | bool MemberOfUnknownSpecialization; | |||
2393 | AssumedTemplateKind AssumedTemplate; | |||
2394 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | |||
2395 | MemberOfUnknownSpecialization, TemplateKWLoc, | |||
2396 | &AssumedTemplate)) | |||
2397 | return ExprError(); | |||
2398 | ||||
2399 | if (MemberOfUnknownSpecialization || | |||
2400 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | |||
2401 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2402 | IsAddressOfOperand, TemplateArgs); | |||
2403 | } else { | |||
2404 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | |||
2405 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | |||
2406 | ||||
2407 | // If the result might be in a dependent base class, this is a dependent | |||
2408 | // id-expression. | |||
2409 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2410 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2411 | IsAddressOfOperand, TemplateArgs); | |||
2412 | ||||
2413 | // If this reference is in an Objective-C method, then we need to do | |||
2414 | // some special Objective-C lookup, too. | |||
2415 | if (IvarLookupFollowUp) { | |||
2416 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | |||
2417 | if (E.isInvalid()) | |||
2418 | return ExprError(); | |||
2419 | ||||
2420 | if (Expr *Ex = E.getAs<Expr>()) | |||
2421 | return Ex; | |||
2422 | } | |||
2423 | } | |||
2424 | ||||
2425 | if (R.isAmbiguous()) | |||
2426 | return ExprError(); | |||
2427 | ||||
2428 | // This could be an implicitly declared function reference (legal in C90, | |||
2429 | // extension in C99, forbidden in C++). | |||
2430 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | |||
2431 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | |||
2432 | if (D) R.addDecl(D); | |||
2433 | } | |||
2434 | ||||
2435 | // Determine whether this name might be a candidate for | |||
2436 | // argument-dependent lookup. | |||
2437 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | |||
2438 | ||||
2439 | if (R.empty() && !ADL) { | |||
2440 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
2441 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | |||
2442 | TemplateKWLoc, TemplateArgs)) | |||
2443 | return E; | |||
2444 | } | |||
2445 | ||||
2446 | // Don't diagnose an empty lookup for inline assembly. | |||
2447 | if (IsInlineAsmIdentifier) | |||
2448 | return ExprError(); | |||
2449 | ||||
2450 | // If this name wasn't predeclared and if this is not a function | |||
2451 | // call, diagnose the problem. | |||
2452 | TypoExpr *TE = nullptr; | |||
2453 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | |||
2454 | : nullptr); | |||
2455 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | |||
2456 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2457, __PRETTY_FUNCTION__)) | |||
2457 | "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2457, __PRETTY_FUNCTION__)); | |||
2458 | if (CCC) { | |||
2459 | // Make sure the callback knows what the typo being diagnosed is. | |||
2460 | CCC->setTypoName(II); | |||
2461 | if (SS.isValid()) | |||
2462 | CCC->setTypoNNS(SS.getScopeRep()); | |||
2463 | } | |||
2464 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | |||
2465 | // a template name, but we happen to have always already looked up the name | |||
2466 | // before we get here if it must be a template name. | |||
2467 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | |||
2468 | None, &TE)) { | |||
2469 | if (TE && KeywordReplacement) { | |||
2470 | auto &State = getTypoExprState(TE); | |||
2471 | auto BestTC = State.Consumer->getNextCorrection(); | |||
2472 | if (BestTC.isKeyword()) { | |||
2473 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | |||
2474 | if (State.DiagHandler) | |||
2475 | State.DiagHandler(BestTC); | |||
2476 | KeywordReplacement->startToken(); | |||
2477 | KeywordReplacement->setKind(II->getTokenID()); | |||
2478 | KeywordReplacement->setIdentifierInfo(II); | |||
2479 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | |||
2480 | // Clean up the state associated with the TypoExpr, since it has | |||
2481 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | |||
2482 | clearDelayedTypo(TE); | |||
2483 | // Signal that a correction to a keyword was performed by returning a | |||
2484 | // valid-but-null ExprResult. | |||
2485 | return (Expr*)nullptr; | |||
2486 | } | |||
2487 | State.Consumer->resetCorrectionStream(); | |||
2488 | } | |||
2489 | return TE ? TE : ExprError(); | |||
2490 | } | |||
2491 | ||||
2492 | assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2493, __PRETTY_FUNCTION__)) | |||
2493 | "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2493, __PRETTY_FUNCTION__)); | |||
2494 | ||||
2495 | // If we found an Objective-C instance variable, let | |||
2496 | // LookupInObjCMethod build the appropriate expression to | |||
2497 | // reference the ivar. | |||
2498 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | |||
2499 | R.clear(); | |||
2500 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | |||
2501 | // In a hopelessly buggy code, Objective-C instance variable | |||
2502 | // lookup fails and no expression will be built to reference it. | |||
2503 | if (!E.isInvalid() && !E.get()) | |||
2504 | return ExprError(); | |||
2505 | return E; | |||
2506 | } | |||
2507 | } | |||
2508 | ||||
2509 | // This is guaranteed from this point on. | |||
2510 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2510, __PRETTY_FUNCTION__)); | |||
2511 | ||||
2512 | // Check whether this might be a C++ implicit instance member access. | |||
2513 | // C++ [class.mfct.non-static]p3: | |||
2514 | // When an id-expression that is not part of a class member access | |||
2515 | // syntax and not used to form a pointer to member is used in the | |||
2516 | // body of a non-static member function of class X, if name lookup | |||
2517 | // resolves the name in the id-expression to a non-static non-type | |||
2518 | // member of some class C, the id-expression is transformed into a | |||
2519 | // class member access expression using (*this) as the | |||
2520 | // postfix-expression to the left of the . operator. | |||
2521 | // | |||
2522 | // But we don't actually need to do this for '&' operands if R | |||
2523 | // resolved to a function or overloaded function set, because the | |||
2524 | // expression is ill-formed if it actually works out to be a | |||
2525 | // non-static member function: | |||
2526 | // | |||
2527 | // C++ [expr.ref]p4: | |||
2528 | // Otherwise, if E1.E2 refers to a non-static member function. . . | |||
2529 | // [t]he expression can be used only as the left-hand operand of a | |||
2530 | // member function call. | |||
2531 | // | |||
2532 | // There are other safeguards against such uses, but it's important | |||
2533 | // to get this right here so that we don't end up making a | |||
2534 | // spuriously dependent expression if we're inside a dependent | |||
2535 | // instance method. | |||
2536 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | |||
2537 | bool MightBeImplicitMember; | |||
2538 | if (!IsAddressOfOperand) | |||
2539 | MightBeImplicitMember = true; | |||
2540 | else if (!SS.isEmpty()) | |||
2541 | MightBeImplicitMember = false; | |||
2542 | else if (R.isOverloadedResult()) | |||
2543 | MightBeImplicitMember = false; | |||
2544 | else if (R.isUnresolvableResult()) | |||
2545 | MightBeImplicitMember = true; | |||
2546 | else | |||
2547 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | |||
2548 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | |||
2549 | isa<MSPropertyDecl>(R.getFoundDecl()); | |||
2550 | ||||
2551 | if (MightBeImplicitMember) | |||
2552 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | |||
2553 | R, TemplateArgs, S); | |||
2554 | } | |||
2555 | ||||
2556 | if (TemplateArgs || TemplateKWLoc.isValid()) { | |||
2557 | ||||
2558 | // In C++1y, if this is a variable template id, then check it | |||
2559 | // in BuildTemplateIdExpr(). | |||
2560 | // The single lookup result must be a variable template declaration. | |||
2561 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | |||
2562 | Id.TemplateId->Kind == TNK_Var_template) { | |||
2563 | assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2564, __PRETTY_FUNCTION__)) | |||
2564 | "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2564, __PRETTY_FUNCTION__)); | |||
2565 | } | |||
2566 | ||||
2567 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | |||
2568 | } | |||
2569 | ||||
2570 | return BuildDeclarationNameExpr(SS, R, ADL); | |||
2571 | } | |||
2572 | ||||
2573 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | |||
2574 | /// declaration name, generally during template instantiation. | |||
2575 | /// There's a large number of things which don't need to be done along | |||
2576 | /// this path. | |||
2577 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | |||
2578 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | |||
2579 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | |||
2580 | DeclContext *DC = computeDeclContext(SS, false); | |||
2581 | if (!DC) | |||
2582 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2583 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2584 | ||||
2585 | if (RequireCompleteDeclContext(SS, DC)) | |||
2586 | return ExprError(); | |||
2587 | ||||
2588 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
2589 | LookupQualifiedName(R, DC); | |||
2590 | ||||
2591 | if (R.isAmbiguous()) | |||
2592 | return ExprError(); | |||
2593 | ||||
2594 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2595 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2596 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2597 | ||||
2598 | if (R.empty()) { | |||
2599 | // Don't diagnose problems with invalid record decl, the secondary no_member | |||
2600 | // diagnostic during template instantiation is likely bogus, e.g. if a class | |||
2601 | // is invalid because it's derived from an invalid base class, then missing | |||
2602 | // members were likely supposed to be inherited. | |||
2603 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | |||
2604 | if (CD->isInvalidDecl()) | |||
2605 | return ExprError(); | |||
2606 | Diag(NameInfo.getLoc(), diag::err_no_member) | |||
2607 | << NameInfo.getName() << DC << SS.getRange(); | |||
2608 | return ExprError(); | |||
2609 | } | |||
2610 | ||||
2611 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | |||
2612 | // Diagnose a missing typename if this resolved unambiguously to a type in | |||
2613 | // a dependent context. If we can recover with a type, downgrade this to | |||
2614 | // a warning in Microsoft compatibility mode. | |||
2615 | unsigned DiagID = diag::err_typename_missing; | |||
2616 | if (RecoveryTSI && getLangOpts().MSVCCompat) | |||
2617 | DiagID = diag::ext_typename_missing; | |||
2618 | SourceLocation Loc = SS.getBeginLoc(); | |||
2619 | auto D = Diag(Loc, DiagID); | |||
2620 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | |||
2621 | << SourceRange(Loc, NameInfo.getEndLoc()); | |||
2622 | ||||
2623 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | |||
2624 | // context. | |||
2625 | if (!RecoveryTSI) | |||
2626 | return ExprError(); | |||
2627 | ||||
2628 | // Only issue the fixit if we're prepared to recover. | |||
2629 | D << FixItHint::CreateInsertion(Loc, "typename "); | |||
2630 | ||||
2631 | // Recover by pretending this was an elaborated type. | |||
2632 | QualType Ty = Context.getTypeDeclType(TD); | |||
2633 | TypeLocBuilder TLB; | |||
2634 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | |||
2635 | ||||
2636 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | |||
2637 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | |||
2638 | QTL.setElaboratedKeywordLoc(SourceLocation()); | |||
2639 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
2640 | ||||
2641 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | |||
2642 | ||||
2643 | return ExprEmpty(); | |||
2644 | } | |||
2645 | ||||
2646 | // Defend against this resolving to an implicit member access. We usually | |||
2647 | // won't get here if this might be a legitimate a class member (we end up in | |||
2648 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | |||
2649 | // a pointer-to-member or in an unevaluated context in C++11. | |||
2650 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | |||
2651 | return BuildPossibleImplicitMemberExpr(SS, | |||
2652 | /*TemplateKWLoc=*/SourceLocation(), | |||
2653 | R, /*TemplateArgs=*/nullptr, S); | |||
2654 | ||||
2655 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | |||
2656 | } | |||
2657 | ||||
2658 | /// The parser has read a name in, and Sema has detected that we're currently | |||
2659 | /// inside an ObjC method. Perform some additional checks and determine if we | |||
2660 | /// should form a reference to an ivar. | |||
2661 | /// | |||
2662 | /// Ideally, most of this would be done by lookup, but there's | |||
2663 | /// actually quite a lot of extra work involved. | |||
2664 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2665 | IdentifierInfo *II) { | |||
2666 | SourceLocation Loc = Lookup.getNameLoc(); | |||
2667 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2668 | ||||
2669 | // Check for error condition which is already reported. | |||
2670 | if (!CurMethod) | |||
2671 | return DeclResult(true); | |||
2672 | ||||
2673 | // There are two cases to handle here. 1) scoped lookup could have failed, | |||
2674 | // in which case we should look for an ivar. 2) scoped lookup could have | |||
2675 | // found a decl, but that decl is outside the current instance method (i.e. | |||
2676 | // a global variable). In these two cases, we do a lookup for an ivar with | |||
2677 | // this name, if the lookup sucedes, we replace it our current decl. | |||
2678 | ||||
2679 | // If we're in a class method, we don't normally want to look for | |||
2680 | // ivars. But if we don't find anything else, and there's an | |||
2681 | // ivar, that's an error. | |||
2682 | bool IsClassMethod = CurMethod->isClassMethod(); | |||
2683 | ||||
2684 | bool LookForIvars; | |||
2685 | if (Lookup.empty()) | |||
2686 | LookForIvars = true; | |||
2687 | else if (IsClassMethod) | |||
2688 | LookForIvars = false; | |||
2689 | else | |||
2690 | LookForIvars = (Lookup.isSingleResult() && | |||
2691 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | |||
2692 | ObjCInterfaceDecl *IFace = nullptr; | |||
2693 | if (LookForIvars) { | |||
2694 | IFace = CurMethod->getClassInterface(); | |||
2695 | ObjCInterfaceDecl *ClassDeclared; | |||
2696 | ObjCIvarDecl *IV = nullptr; | |||
2697 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | |||
2698 | // Diagnose using an ivar in a class method. | |||
2699 | if (IsClassMethod) { | |||
2700 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | |||
2701 | return DeclResult(true); | |||
2702 | } | |||
2703 | ||||
2704 | // Diagnose the use of an ivar outside of the declaring class. | |||
2705 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | |||
2706 | !declaresSameEntity(ClassDeclared, IFace) && | |||
2707 | !getLangOpts().DebuggerSupport) | |||
2708 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | |||
2709 | ||||
2710 | // Success. | |||
2711 | return IV; | |||
2712 | } | |||
2713 | } else if (CurMethod->isInstanceMethod()) { | |||
2714 | // We should warn if a local variable hides an ivar. | |||
2715 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | |||
2716 | ObjCInterfaceDecl *ClassDeclared; | |||
2717 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | |||
2718 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | |||
2719 | declaresSameEntity(IFace, ClassDeclared)) | |||
2720 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | |||
2721 | } | |||
2722 | } | |||
2723 | } else if (Lookup.isSingleResult() && | |||
2724 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | |||
2725 | // If accessing a stand-alone ivar in a class method, this is an error. | |||
2726 | if (const ObjCIvarDecl *IV = | |||
2727 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | |||
2728 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | |||
2729 | return DeclResult(true); | |||
2730 | } | |||
2731 | } | |||
2732 | ||||
2733 | // Didn't encounter an error, didn't find an ivar. | |||
2734 | return DeclResult(false); | |||
2735 | } | |||
2736 | ||||
2737 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | |||
2738 | ObjCIvarDecl *IV) { | |||
2739 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2740 | assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2741, __PRETTY_FUNCTION__)) | |||
2741 | "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2741, __PRETTY_FUNCTION__)); | |||
2742 | ||||
2743 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | |||
2744 | assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context" ) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2744, __PRETTY_FUNCTION__)); | |||
2745 | ||||
2746 | // If we're referencing an invalid decl, just return this as a silent | |||
2747 | // error node. The error diagnostic was already emitted on the decl. | |||
2748 | if (IV->isInvalidDecl()) | |||
2749 | return ExprError(); | |||
2750 | ||||
2751 | // Check if referencing a field with __attribute__((deprecated)). | |||
2752 | if (DiagnoseUseOfDecl(IV, Loc)) | |||
2753 | return ExprError(); | |||
2754 | ||||
2755 | // FIXME: This should use a new expr for a direct reference, don't | |||
2756 | // turn this into Self->ivar, just return a BareIVarExpr or something. | |||
2757 | IdentifierInfo &II = Context.Idents.get("self"); | |||
2758 | UnqualifiedId SelfName; | |||
2759 | SelfName.setIdentifier(&II, SourceLocation()); | |||
2760 | SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); | |||
2761 | CXXScopeSpec SelfScopeSpec; | |||
2762 | SourceLocation TemplateKWLoc; | |||
2763 | ExprResult SelfExpr = | |||
2764 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | |||
2765 | /*HasTrailingLParen=*/false, | |||
2766 | /*IsAddressOfOperand=*/false); | |||
2767 | if (SelfExpr.isInvalid()) | |||
2768 | return ExprError(); | |||
2769 | ||||
2770 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | |||
2771 | if (SelfExpr.isInvalid()) | |||
2772 | return ExprError(); | |||
2773 | ||||
2774 | MarkAnyDeclReferenced(Loc, IV, true); | |||
2775 | ||||
2776 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | |||
2777 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | |||
2778 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | |||
2779 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | |||
2780 | ||||
2781 | ObjCIvarRefExpr *Result = new (Context) | |||
2782 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | |||
2783 | IV->getLocation(), SelfExpr.get(), true, true); | |||
2784 | ||||
2785 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
2786 | if (!isUnevaluatedContext() && | |||
2787 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | |||
2788 | getCurFunction()->recordUseOfWeak(Result); | |||
2789 | } | |||
2790 | if (getLangOpts().ObjCAutoRefCount) | |||
2791 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | |||
2792 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | |||
2793 | ||||
2794 | return Result; | |||
2795 | } | |||
2796 | ||||
2797 | /// The parser has read a name in, and Sema has detected that we're currently | |||
2798 | /// inside an ObjC method. Perform some additional checks and determine if we | |||
2799 | /// should form a reference to an ivar. If so, build an expression referencing | |||
2800 | /// that ivar. | |||
2801 | ExprResult | |||
2802 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2803 | IdentifierInfo *II, bool AllowBuiltinCreation) { | |||
2804 | // FIXME: Integrate this lookup step into LookupParsedName. | |||
2805 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | |||
2806 | if (Ivar.isInvalid()) | |||
2807 | return ExprError(); | |||
2808 | if (Ivar.isUsable()) | |||
2809 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | |||
2810 | cast<ObjCIvarDecl>(Ivar.get())); | |||
2811 | ||||
2812 | if (Lookup.empty() && II && AllowBuiltinCreation) | |||
2813 | LookupBuiltin(Lookup); | |||
2814 | ||||
2815 | // Sentinel value saying that we didn't do anything special. | |||
2816 | return ExprResult(false); | |||
2817 | } | |||
2818 | ||||
2819 | /// Cast a base object to a member's actual type. | |||
2820 | /// | |||
2821 | /// Logically this happens in three phases: | |||
2822 | /// | |||
2823 | /// * First we cast from the base type to the naming class. | |||
2824 | /// The naming class is the class into which we were looking | |||
2825 | /// when we found the member; it's the qualifier type if a | |||
2826 | /// qualifier was provided, and otherwise it's the base type. | |||
2827 | /// | |||
2828 | /// * Next we cast from the naming class to the declaring class. | |||
2829 | /// If the member we found was brought into a class's scope by | |||
2830 | /// a using declaration, this is that class; otherwise it's | |||
2831 | /// the class declaring the member. | |||
2832 | /// | |||
2833 | /// * Finally we cast from the declaring class to the "true" | |||
2834 | /// declaring class of the member. This conversion does not | |||
2835 | /// obey access control. | |||
2836 | ExprResult | |||
2837 | Sema::PerformObjectMemberConversion(Expr *From, | |||
2838 | NestedNameSpecifier *Qualifier, | |||
2839 | NamedDecl *FoundDecl, | |||
2840 | NamedDecl *Member) { | |||
2841 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | |||
2842 | if (!RD) | |||
2843 | return From; | |||
2844 | ||||
2845 | QualType DestRecordType; | |||
2846 | QualType DestType; | |||
2847 | QualType FromRecordType; | |||
2848 | QualType FromType = From->getType(); | |||
2849 | bool PointerConversions = false; | |||
2850 | if (isa<FieldDecl>(Member)) { | |||
2851 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | |||
2852 | auto FromPtrType = FromType->getAs<PointerType>(); | |||
2853 | DestRecordType = Context.getAddrSpaceQualType( | |||
2854 | DestRecordType, FromPtrType | |||
2855 | ? FromType->getPointeeType().getAddressSpace() | |||
2856 | : FromType.getAddressSpace()); | |||
2857 | ||||
2858 | if (FromPtrType) { | |||
2859 | DestType = Context.getPointerType(DestRecordType); | |||
2860 | FromRecordType = FromPtrType->getPointeeType(); | |||
2861 | PointerConversions = true; | |||
2862 | } else { | |||
2863 | DestType = DestRecordType; | |||
2864 | FromRecordType = FromType; | |||
2865 | } | |||
2866 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | |||
2867 | if (Method->isStatic()) | |||
2868 | return From; | |||
2869 | ||||
2870 | DestType = Method->getThisType(); | |||
2871 | DestRecordType = DestType->getPointeeType(); | |||
2872 | ||||
2873 | if (FromType->getAs<PointerType>()) { | |||
2874 | FromRecordType = FromType->getPointeeType(); | |||
2875 | PointerConversions = true; | |||
2876 | } else { | |||
2877 | FromRecordType = FromType; | |||
2878 | DestType = DestRecordType; | |||
2879 | } | |||
2880 | ||||
2881 | LangAS FromAS = FromRecordType.getAddressSpace(); | |||
2882 | LangAS DestAS = DestRecordType.getAddressSpace(); | |||
2883 | if (FromAS != DestAS) { | |||
2884 | QualType FromRecordTypeWithoutAS = | |||
2885 | Context.removeAddrSpaceQualType(FromRecordType); | |||
2886 | QualType FromTypeWithDestAS = | |||
2887 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | |||
2888 | if (PointerConversions) | |||
2889 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | |||
2890 | From = ImpCastExprToType(From, FromTypeWithDestAS, | |||
2891 | CK_AddressSpaceConversion, From->getValueKind()) | |||
2892 | .get(); | |||
2893 | } | |||
2894 | } else { | |||
2895 | // No conversion necessary. | |||
2896 | return From; | |||
2897 | } | |||
2898 | ||||
2899 | if (DestType->isDependentType() || FromType->isDependentType()) | |||
2900 | return From; | |||
2901 | ||||
2902 | // If the unqualified types are the same, no conversion is necessary. | |||
2903 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2904 | return From; | |||
2905 | ||||
2906 | SourceRange FromRange = From->getSourceRange(); | |||
2907 | SourceLocation FromLoc = FromRange.getBegin(); | |||
2908 | ||||
2909 | ExprValueKind VK = From->getValueKind(); | |||
2910 | ||||
2911 | // C++ [class.member.lookup]p8: | |||
2912 | // [...] Ambiguities can often be resolved by qualifying a name with its | |||
2913 | // class name. | |||
2914 | // | |||
2915 | // If the member was a qualified name and the qualified referred to a | |||
2916 | // specific base subobject type, we'll cast to that intermediate type | |||
2917 | // first and then to the object in which the member is declared. That allows | |||
2918 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | |||
2919 | // | |||
2920 | // class Base { public: int x; }; | |||
2921 | // class Derived1 : public Base { }; | |||
2922 | // class Derived2 : public Base { }; | |||
2923 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | |||
2924 | // | |||
2925 | // void VeryDerived::f() { | |||
2926 | // x = 17; // error: ambiguous base subobjects | |||
2927 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | |||
2928 | // } | |||
2929 | if (Qualifier && Qualifier->getAsType()) { | |||
2930 | QualType QType = QualType(Qualifier->getAsType(), 0); | |||
2931 | assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type" ) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2931, __PRETTY_FUNCTION__)); | |||
2932 | ||||
2933 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | |||
2934 | ||||
2935 | // In C++98, the qualifier type doesn't actually have to be a base | |||
2936 | // type of the object type, in which case we just ignore it. | |||
2937 | // Otherwise build the appropriate casts. | |||
2938 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | |||
2939 | CXXCastPath BasePath; | |||
2940 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | |||
2941 | FromLoc, FromRange, &BasePath)) | |||
2942 | return ExprError(); | |||
2943 | ||||
2944 | if (PointerConversions) | |||
2945 | QType = Context.getPointerType(QType); | |||
2946 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | |||
2947 | VK, &BasePath).get(); | |||
2948 | ||||
2949 | FromType = QType; | |||
2950 | FromRecordType = QRecordType; | |||
2951 | ||||
2952 | // If the qualifier type was the same as the destination type, | |||
2953 | // we're done. | |||
2954 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2955 | return From; | |||
2956 | } | |||
2957 | } | |||
2958 | ||||
2959 | bool IgnoreAccess = false; | |||
2960 | ||||
2961 | // If we actually found the member through a using declaration, cast | |||
2962 | // down to the using declaration's type. | |||
2963 | // | |||
2964 | // Pointer equality is fine here because only one declaration of a | |||
2965 | // class ever has member declarations. | |||
2966 | if (FoundDecl->getDeclContext() != Member->getDeclContext()) { | |||
2967 | assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void > (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2967, __PRETTY_FUNCTION__)); | |||
2968 | QualType URecordType = Context.getTypeDeclType( | |||
2969 | cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | |||
2970 | ||||
2971 | // We only need to do this if the naming-class to declaring-class | |||
2972 | // conversion is non-trivial. | |||
2973 | if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { | |||
2974 | assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast <void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 2974, __PRETTY_FUNCTION__)); | |||
2975 | CXXCastPath BasePath; | |||
2976 | if (CheckDerivedToBaseConversion(FromRecordType, URecordType, | |||
2977 | FromLoc, FromRange, &BasePath)) | |||
2978 | return ExprError(); | |||
2979 | ||||
2980 | QualType UType = URecordType; | |||
2981 | if (PointerConversions) | |||
2982 | UType = Context.getPointerType(UType); | |||
2983 | From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, | |||
2984 | VK, &BasePath).get(); | |||
2985 | FromType = UType; | |||
2986 | FromRecordType = URecordType; | |||
2987 | } | |||
2988 | ||||
2989 | // We don't do access control for the conversion from the | |||
2990 | // declaring class to the true declaring class. | |||
2991 | IgnoreAccess = true; | |||
2992 | } | |||
2993 | ||||
2994 | CXXCastPath BasePath; | |||
2995 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | |||
2996 | FromLoc, FromRange, &BasePath, | |||
2997 | IgnoreAccess)) | |||
2998 | return ExprError(); | |||
2999 | ||||
3000 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | |||
3001 | VK, &BasePath); | |||
3002 | } | |||
3003 | ||||
3004 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | |||
3005 | const LookupResult &R, | |||
3006 | bool HasTrailingLParen) { | |||
3007 | // Only when used directly as the postfix-expression of a call. | |||
3008 | if (!HasTrailingLParen) | |||
3009 | return false; | |||
3010 | ||||
3011 | // Never if a scope specifier was provided. | |||
3012 | if (SS.isSet()) | |||
3013 | return false; | |||
3014 | ||||
3015 | // Only in C++ or ObjC++. | |||
3016 | if (!getLangOpts().CPlusPlus) | |||
3017 | return false; | |||
3018 | ||||
3019 | // Turn off ADL when we find certain kinds of declarations during | |||
3020 | // normal lookup: | |||
3021 | for (NamedDecl *D : R) { | |||
3022 | // C++0x [basic.lookup.argdep]p3: | |||
3023 | // -- a declaration of a class member | |||
3024 | // Since using decls preserve this property, we check this on the | |||
3025 | // original decl. | |||
3026 | if (D->isCXXClassMember()) | |||
3027 | return false; | |||
3028 | ||||
3029 | // C++0x [basic.lookup.argdep]p3: | |||
3030 | // -- a block-scope function declaration that is not a | |||
3031 | // using-declaration | |||
3032 | // NOTE: we also trigger this for function templates (in fact, we | |||
3033 | // don't check the decl type at all, since all other decl types | |||
3034 | // turn off ADL anyway). | |||
3035 | if (isa<UsingShadowDecl>(D)) | |||
3036 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
3037 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | |||
3038 | return false; | |||
3039 | ||||
3040 | // C++0x [basic.lookup.argdep]p3: | |||
3041 | // -- a declaration that is neither a function or a function | |||
3042 | // template | |||
3043 | // And also for builtin functions. | |||
3044 | if (isa<FunctionDecl>(D)) { | |||
3045 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | |||
3046 | ||||
3047 | // But also builtin functions. | |||
3048 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | |||
3049 | return false; | |||
3050 | } else if (!isa<FunctionTemplateDecl>(D)) | |||
3051 | return false; | |||
3052 | } | |||
3053 | ||||
3054 | return true; | |||
3055 | } | |||
3056 | ||||
3057 | ||||
3058 | /// Diagnoses obvious problems with the use of the given declaration | |||
3059 | /// as an expression. This is only actually called for lookups that | |||
3060 | /// were not overloaded, and it doesn't promise that the declaration | |||
3061 | /// will in fact be used. | |||
3062 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | |||
3063 | if (D->isInvalidDecl()) | |||
3064 | return true; | |||
3065 | ||||
3066 | if (isa<TypedefNameDecl>(D)) { | |||
3067 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | |||
3068 | return true; | |||
3069 | } | |||
3070 | ||||
3071 | if (isa<ObjCInterfaceDecl>(D)) { | |||
3072 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | |||
3073 | return true; | |||
3074 | } | |||
3075 | ||||
3076 | if (isa<NamespaceDecl>(D)) { | |||
3077 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | |||
3078 | return true; | |||
3079 | } | |||
3080 | ||||
3081 | return false; | |||
3082 | } | |||
3083 | ||||
3084 | // Certain multiversion types should be treated as overloaded even when there is | |||
3085 | // only one result. | |||
3086 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | |||
3087 | assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result" ) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3087, __PRETTY_FUNCTION__)); | |||
3088 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | |||
3089 | return FD && | |||
3090 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | |||
3091 | } | |||
3092 | ||||
3093 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | |||
3094 | LookupResult &R, bool NeedsADL, | |||
3095 | bool AcceptInvalidDecl) { | |||
3096 | // If this is a single, fully-resolved result and we don't need ADL, | |||
3097 | // just build an ordinary singleton decl ref. | |||
3098 | if (!NeedsADL && R.isSingleResult() && | |||
3099 | !R.getAsSingle<FunctionTemplateDecl>() && | |||
3100 | !ShouldLookupResultBeMultiVersionOverload(R)) | |||
3101 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | |||
3102 | R.getRepresentativeDecl(), nullptr, | |||
3103 | AcceptInvalidDecl); | |||
3104 | ||||
3105 | // We only need to check the declaration if there's exactly one | |||
3106 | // result, because in the overloaded case the results can only be | |||
3107 | // functions and function templates. | |||
3108 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | |||
3109 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | |||
3110 | return ExprError(); | |||
3111 | ||||
3112 | // Otherwise, just build an unresolved lookup expression. Suppress | |||
3113 | // any lookup-related diagnostics; we'll hash these out later, when | |||
3114 | // we've picked a target. | |||
3115 | R.suppressDiagnostics(); | |||
3116 | ||||
3117 | UnresolvedLookupExpr *ULE | |||
3118 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | |||
3119 | SS.getWithLocInContext(Context), | |||
3120 | R.getLookupNameInfo(), | |||
3121 | NeedsADL, R.isOverloadedResult(), | |||
3122 | R.begin(), R.end()); | |||
3123 | ||||
3124 | return ULE; | |||
3125 | } | |||
3126 | ||||
3127 | static void | |||
3128 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
3129 | ValueDecl *var, DeclContext *DC); | |||
3130 | ||||
3131 | /// Complete semantic analysis for a reference to the given declaration. | |||
3132 | ExprResult Sema::BuildDeclarationNameExpr( | |||
3133 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | |||
3134 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | |||
3135 | bool AcceptInvalidDecl) { | |||
3136 | assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast <void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3136, __PRETTY_FUNCTION__)); | |||
3137 | assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3138, __PRETTY_FUNCTION__)) | |||
3138 | "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3138, __PRETTY_FUNCTION__)); | |||
3139 | ||||
3140 | SourceLocation Loc = NameInfo.getLoc(); | |||
3141 | if (CheckDeclInExpr(*this, Loc, D)) | |||
3142 | return ExprError(); | |||
3143 | ||||
3144 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | |||
3145 | // Specifically diagnose references to class templates that are missing | |||
3146 | // a template argument list. | |||
3147 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | |||
3148 | return ExprError(); | |||
3149 | } | |||
3150 | ||||
3151 | // Make sure that we're referring to a value. | |||
3152 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | |||
3153 | if (!VD) { | |||
3154 | Diag(Loc, diag::err_ref_non_value) | |||
3155 | << D << SS.getRange(); | |||
3156 | Diag(D->getLocation(), diag::note_declared_at); | |||
3157 | return ExprError(); | |||
3158 | } | |||
3159 | ||||
3160 | // Check whether this declaration can be used. Note that we suppress | |||
3161 | // this check when we're going to perform argument-dependent lookup | |||
3162 | // on this function name, because this might not be the function | |||
3163 | // that overload resolution actually selects. | |||
3164 | if (DiagnoseUseOfDecl(VD, Loc)) | |||
3165 | return ExprError(); | |||
3166 | ||||
3167 | // Only create DeclRefExpr's for valid Decl's. | |||
3168 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | |||
3169 | return ExprError(); | |||
3170 | ||||
3171 | // Handle members of anonymous structs and unions. If we got here, | |||
3172 | // and the reference is to a class member indirect field, then this | |||
3173 | // must be the subject of a pointer-to-member expression. | |||
3174 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | |||
3175 | if (!indirectField->isCXXClassMember()) | |||
3176 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | |||
3177 | indirectField); | |||
3178 | ||||
3179 | { | |||
3180 | QualType type = VD->getType(); | |||
3181 | if (type.isNull()) | |||
3182 | return ExprError(); | |||
3183 | ExprValueKind valueKind = VK_RValue; | |||
3184 | ||||
3185 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | |||
3186 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | |||
3187 | // is expanded by some outer '...' in the context of the use. | |||
3188 | type = type.getNonPackExpansionType(); | |||
3189 | ||||
3190 | switch (D->getKind()) { | |||
3191 | // Ignore all the non-ValueDecl kinds. | |||
3192 | #define ABSTRACT_DECL(kind) | |||
3193 | #define VALUE(type, base) | |||
3194 | #define DECL(type, base) \ | |||
3195 | case Decl::type: | |||
3196 | #include "clang/AST/DeclNodes.inc" | |||
3197 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3197); | |||
3198 | ||||
3199 | // These shouldn't make it here. | |||
3200 | case Decl::ObjCAtDefsField: | |||
3201 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3201); | |||
3202 | ||||
3203 | // Enum constants are always r-values and never references. | |||
3204 | // Unresolved using declarations are dependent. | |||
3205 | case Decl::EnumConstant: | |||
3206 | case Decl::UnresolvedUsingValue: | |||
3207 | case Decl::OMPDeclareReduction: | |||
3208 | case Decl::OMPDeclareMapper: | |||
3209 | valueKind = VK_RValue; | |||
3210 | break; | |||
3211 | ||||
3212 | // Fields and indirect fields that got here must be for | |||
3213 | // pointer-to-member expressions; we just call them l-values for | |||
3214 | // internal consistency, because this subexpression doesn't really | |||
3215 | // exist in the high-level semantics. | |||
3216 | case Decl::Field: | |||
3217 | case Decl::IndirectField: | |||
3218 | case Decl::ObjCIvar: | |||
3219 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3220, __PRETTY_FUNCTION__)) | |||
3220 | "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3220, __PRETTY_FUNCTION__)); | |||
3221 | ||||
3222 | // These can't have reference type in well-formed programs, but | |||
3223 | // for internal consistency we do this anyway. | |||
3224 | type = type.getNonReferenceType(); | |||
3225 | valueKind = VK_LValue; | |||
3226 | break; | |||
3227 | ||||
3228 | // Non-type template parameters are either l-values or r-values | |||
3229 | // depending on the type. | |||
3230 | case Decl::NonTypeTemplateParm: { | |||
3231 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | |||
3232 | type = reftype->getPointeeType(); | |||
3233 | valueKind = VK_LValue; // even if the parameter is an r-value reference | |||
3234 | break; | |||
3235 | } | |||
3236 | ||||
3237 | // [expr.prim.id.unqual]p2: | |||
3238 | // If the entity is a template parameter object for a template | |||
3239 | // parameter of type T, the type of the expression is const T. | |||
3240 | // [...] The expression is an lvalue if the entity is a [...] template | |||
3241 | // parameter object. | |||
3242 | if (type->isRecordType()) { | |||
3243 | type = type.getUnqualifiedType().withConst(); | |||
3244 | valueKind = VK_LValue; | |||
3245 | break; | |||
3246 | } | |||
3247 | ||||
3248 | // For non-references, we need to strip qualifiers just in case | |||
3249 | // the template parameter was declared as 'const int' or whatever. | |||
3250 | valueKind = VK_RValue; | |||
3251 | type = type.getUnqualifiedType(); | |||
3252 | break; | |||
3253 | } | |||
3254 | ||||
3255 | case Decl::Var: | |||
3256 | case Decl::VarTemplateSpecialization: | |||
3257 | case Decl::VarTemplatePartialSpecialization: | |||
3258 | case Decl::Decomposition: | |||
3259 | case Decl::OMPCapturedExpr: | |||
3260 | // In C, "extern void blah;" is valid and is an r-value. | |||
3261 | if (!getLangOpts().CPlusPlus && | |||
3262 | !type.hasQualifiers() && | |||
3263 | type->isVoidType()) { | |||
3264 | valueKind = VK_RValue; | |||
3265 | break; | |||
3266 | } | |||
3267 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3268 | ||||
3269 | case Decl::ImplicitParam: | |||
3270 | case Decl::ParmVar: { | |||
3271 | // These are always l-values. | |||
3272 | valueKind = VK_LValue; | |||
3273 | type = type.getNonReferenceType(); | |||
3274 | ||||
3275 | // FIXME: Does the addition of const really only apply in | |||
3276 | // potentially-evaluated contexts? Since the variable isn't actually | |||
3277 | // captured in an unevaluated context, it seems that the answer is no. | |||
3278 | if (!isUnevaluatedContext()) { | |||
3279 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | |||
3280 | if (!CapturedType.isNull()) | |||
3281 | type = CapturedType; | |||
3282 | } | |||
3283 | ||||
3284 | break; | |||
3285 | } | |||
3286 | ||||
3287 | case Decl::Binding: { | |||
3288 | // These are always lvalues. | |||
3289 | valueKind = VK_LValue; | |||
3290 | type = type.getNonReferenceType(); | |||
3291 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | |||
3292 | // decides how that's supposed to work. | |||
3293 | auto *BD = cast<BindingDecl>(VD); | |||
3294 | if (BD->getDeclContext() != CurContext) { | |||
3295 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | |||
3296 | if (DD && DD->hasLocalStorage()) | |||
3297 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | |||
3298 | } | |||
3299 | break; | |||
3300 | } | |||
3301 | ||||
3302 | case Decl::Function: { | |||
3303 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | |||
3304 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | |||
3305 | type = Context.BuiltinFnTy; | |||
3306 | valueKind = VK_RValue; | |||
3307 | break; | |||
3308 | } | |||
3309 | } | |||
3310 | ||||
3311 | const FunctionType *fty = type->castAs<FunctionType>(); | |||
3312 | ||||
3313 | // If we're referring to a function with an __unknown_anytype | |||
3314 | // result type, make the entire expression __unknown_anytype. | |||
3315 | if (fty->getReturnType() == Context.UnknownAnyTy) { | |||
3316 | type = Context.UnknownAnyTy; | |||
3317 | valueKind = VK_RValue; | |||
3318 | break; | |||
3319 | } | |||
3320 | ||||
3321 | // Functions are l-values in C++. | |||
3322 | if (getLangOpts().CPlusPlus) { | |||
3323 | valueKind = VK_LValue; | |||
3324 | break; | |||
3325 | } | |||
3326 | ||||
3327 | // C99 DR 316 says that, if a function type comes from a | |||
3328 | // function definition (without a prototype), that type is only | |||
3329 | // used for checking compatibility. Therefore, when referencing | |||
3330 | // the function, we pretend that we don't have the full function | |||
3331 | // type. | |||
3332 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | |||
3333 | isa<FunctionProtoType>(fty)) | |||
3334 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | |||
3335 | fty->getExtInfo()); | |||
3336 | ||||
3337 | // Functions are r-values in C. | |||
3338 | valueKind = VK_RValue; | |||
3339 | break; | |||
3340 | } | |||
3341 | ||||
3342 | case Decl::CXXDeductionGuide: | |||
3343 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3343); | |||
3344 | ||||
3345 | case Decl::MSProperty: | |||
3346 | case Decl::MSGuid: | |||
3347 | case Decl::TemplateParamObject: | |||
3348 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | |||
3349 | // capture in OpenMP, or duplicated between host and device? | |||
3350 | valueKind = VK_LValue; | |||
3351 | break; | |||
3352 | ||||
3353 | case Decl::CXXMethod: | |||
3354 | // If we're referring to a method with an __unknown_anytype | |||
3355 | // result type, make the entire expression __unknown_anytype. | |||
3356 | // This should only be possible with a type written directly. | |||
3357 | if (const FunctionProtoType *proto | |||
3358 | = dyn_cast<FunctionProtoType>(VD->getType())) | |||
3359 | if (proto->getReturnType() == Context.UnknownAnyTy) { | |||
3360 | type = Context.UnknownAnyTy; | |||
3361 | valueKind = VK_RValue; | |||
3362 | break; | |||
3363 | } | |||
3364 | ||||
3365 | // C++ methods are l-values if static, r-values if non-static. | |||
3366 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | |||
3367 | valueKind = VK_LValue; | |||
3368 | break; | |||
3369 | } | |||
3370 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3371 | ||||
3372 | case Decl::CXXConversion: | |||
3373 | case Decl::CXXDestructor: | |||
3374 | case Decl::CXXConstructor: | |||
3375 | valueKind = VK_RValue; | |||
3376 | break; | |||
3377 | } | |||
3378 | ||||
3379 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | |||
3380 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | |||
3381 | TemplateArgs); | |||
3382 | } | |||
3383 | } | |||
3384 | ||||
3385 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | |||
3386 | SmallString<32> &Target) { | |||
3387 | Target.resize(CharByteWidth * (Source.size() + 1)); | |||
3388 | char *ResultPtr = &Target[0]; | |||
3389 | const llvm::UTF8 *ErrorPtr; | |||
3390 | bool success = | |||
3391 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | |||
3392 | (void)success; | |||
3393 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3393, __PRETTY_FUNCTION__)); | |||
3394 | Target.resize(ResultPtr - &Target[0]); | |||
3395 | } | |||
3396 | ||||
3397 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | |||
3398 | PredefinedExpr::IdentKind IK) { | |||
3399 | // Pick the current block, lambda, captured statement or function. | |||
3400 | Decl *currentDecl = nullptr; | |||
3401 | if (const BlockScopeInfo *BSI = getCurBlock()) | |||
3402 | currentDecl = BSI->TheDecl; | |||
3403 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | |||
3404 | currentDecl = LSI->CallOperator; | |||
3405 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | |||
3406 | currentDecl = CSI->TheCapturedDecl; | |||
3407 | else | |||
3408 | currentDecl = getCurFunctionOrMethodDecl(); | |||
3409 | ||||
3410 | if (!currentDecl) { | |||
3411 | Diag(Loc, diag::ext_predef_outside_function); | |||
3412 | currentDecl = Context.getTranslationUnitDecl(); | |||
3413 | } | |||
3414 | ||||
3415 | QualType ResTy; | |||
3416 | StringLiteral *SL = nullptr; | |||
3417 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | |||
3418 | ResTy = Context.DependentTy; | |||
3419 | else { | |||
3420 | // Pre-defined identifiers are of type char[x], where x is the length of | |||
3421 | // the string. | |||
3422 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | |||
3423 | unsigned Length = Str.length(); | |||
3424 | ||||
3425 | llvm::APInt LengthI(32, Length + 1); | |||
3426 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | |||
3427 | ResTy = | |||
3428 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | |||
3429 | SmallString<32> RawChars; | |||
3430 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | |||
3431 | Str, RawChars); | |||
3432 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | |||
3433 | ArrayType::Normal, | |||
3434 | /*IndexTypeQuals*/ 0); | |||
3435 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | |||
3436 | /*Pascal*/ false, ResTy, Loc); | |||
3437 | } else { | |||
3438 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | |||
3439 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | |||
3440 | ArrayType::Normal, | |||
3441 | /*IndexTypeQuals*/ 0); | |||
3442 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | |||
3443 | /*Pascal*/ false, ResTy, Loc); | |||
3444 | } | |||
3445 | } | |||
3446 | ||||
3447 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | |||
3448 | } | |||
3449 | ||||
3450 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | |||
3451 | PredefinedExpr::IdentKind IK; | |||
3452 | ||||
3453 | switch (Kind) { | |||
3454 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3454); | |||
3455 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | |||
3456 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | |||
3457 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | |||
3458 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | |||
3459 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | |||
3460 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | |||
3461 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | |||
3462 | } | |||
3463 | ||||
3464 | return BuildPredefinedExpr(Loc, IK); | |||
3465 | } | |||
3466 | ||||
3467 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | |||
3468 | SmallString<16> CharBuffer; | |||
3469 | bool Invalid = false; | |||
3470 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | |||
3471 | if (Invalid) | |||
3472 | return ExprError(); | |||
3473 | ||||
3474 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | |||
3475 | PP, Tok.getKind()); | |||
3476 | if (Literal.hadError()) | |||
3477 | return ExprError(); | |||
3478 | ||||
3479 | QualType Ty; | |||
3480 | if (Literal.isWide()) | |||
3481 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | |||
3482 | else if (Literal.isUTF8() && getLangOpts().Char8) | |||
3483 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | |||
3484 | else if (Literal.isUTF16()) | |||
3485 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | |||
3486 | else if (Literal.isUTF32()) | |||
3487 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | |||
3488 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | |||
3489 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | |||
3490 | else | |||
3491 | Ty = Context.CharTy; // 'x' -> char in C++ | |||
3492 | ||||
3493 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | |||
3494 | if (Literal.isWide()) | |||
3495 | Kind = CharacterLiteral::Wide; | |||
3496 | else if (Literal.isUTF16()) | |||
3497 | Kind = CharacterLiteral::UTF16; | |||
3498 | else if (Literal.isUTF32()) | |||
3499 | Kind = CharacterLiteral::UTF32; | |||
3500 | else if (Literal.isUTF8()) | |||
3501 | Kind = CharacterLiteral::UTF8; | |||
3502 | ||||
3503 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | |||
3504 | Tok.getLocation()); | |||
3505 | ||||
3506 | if (Literal.getUDSuffix().empty()) | |||
3507 | return Lit; | |||
3508 | ||||
3509 | // We're building a user-defined literal. | |||
3510 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3511 | SourceLocation UDSuffixLoc = | |||
3512 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3513 | ||||
3514 | // Make sure we're allowed user-defined literals here. | |||
3515 | if (!UDLScope) | |||
3516 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | |||
3517 | ||||
3518 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | |||
3519 | // operator "" X (ch) | |||
3520 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | |||
3521 | Lit, Tok.getLocation()); | |||
3522 | } | |||
3523 | ||||
3524 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | |||
3525 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3526 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | |||
3527 | Context.IntTy, Loc); | |||
3528 | } | |||
3529 | ||||
3530 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | |||
3531 | QualType Ty, SourceLocation Loc) { | |||
3532 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | |||
3533 | ||||
3534 | using llvm::APFloat; | |||
3535 | APFloat Val(Format); | |||
3536 | ||||
3537 | APFloat::opStatus result = Literal.GetFloatValue(Val); | |||
3538 | ||||
3539 | // Overflow is always an error, but underflow is only an error if | |||
3540 | // we underflowed to zero (APFloat reports denormals as underflow). | |||
3541 | if ((result & APFloat::opOverflow) || | |||
3542 | ((result & APFloat::opUnderflow) && Val.isZero())) { | |||
3543 | unsigned diagnostic; | |||
3544 | SmallString<20> buffer; | |||
3545 | if (result & APFloat::opOverflow) { | |||
3546 | diagnostic = diag::warn_float_overflow; | |||
3547 | APFloat::getLargest(Format).toString(buffer); | |||
3548 | } else { | |||
3549 | diagnostic = diag::warn_float_underflow; | |||
3550 | APFloat::getSmallest(Format).toString(buffer); | |||
3551 | } | |||
3552 | ||||
3553 | S.Diag(Loc, diagnostic) | |||
3554 | << Ty | |||
3555 | << StringRef(buffer.data(), buffer.size()); | |||
3556 | } | |||
3557 | ||||
3558 | bool isExact = (result == APFloat::opOK); | |||
3559 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | |||
3560 | } | |||
3561 | ||||
3562 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | |||
3563 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3563, __PRETTY_FUNCTION__)); | |||
3564 | ||||
3565 | if (E->isValueDependent()) | |||
3566 | return false; | |||
3567 | ||||
3568 | QualType QT = E->getType(); | |||
3569 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | |||
3570 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | |||
3571 | return true; | |||
3572 | } | |||
3573 | ||||
3574 | llvm::APSInt ValueAPS; | |||
3575 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | |||
3576 | ||||
3577 | if (R.isInvalid()) | |||
3578 | return true; | |||
3579 | ||||
3580 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | |||
3581 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | |||
3582 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | |||
3583 | << ValueAPS.toString(10) << ValueIsPositive; | |||
3584 | return true; | |||
3585 | } | |||
3586 | ||||
3587 | return false; | |||
3588 | } | |||
3589 | ||||
3590 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | |||
3591 | // Fast path for a single digit (which is quite common). A single digit | |||
3592 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | |||
3593 | if (Tok.getLength() == 1) { | |||
3594 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | |||
3595 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | |||
3596 | } | |||
3597 | ||||
3598 | SmallString<128> SpellingBuffer; | |||
3599 | // NumericLiteralParser wants to overread by one character. Add padding to | |||
3600 | // the buffer in case the token is copied to the buffer. If getSpelling() | |||
3601 | // returns a StringRef to the memory buffer, it should have a null char at | |||
3602 | // the EOF, so it is also safe. | |||
3603 | SpellingBuffer.resize(Tok.getLength() + 1); | |||
3604 | ||||
3605 | // Get the spelling of the token, which eliminates trigraphs, etc. | |||
3606 | bool Invalid = false; | |||
3607 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | |||
3608 | if (Invalid) | |||
3609 | return ExprError(); | |||
3610 | ||||
3611 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | |||
3612 | PP.getSourceManager(), PP.getLangOpts(), | |||
3613 | PP.getTargetInfo(), PP.getDiagnostics()); | |||
3614 | if (Literal.hadError) | |||
3615 | return ExprError(); | |||
3616 | ||||
3617 | if (Literal.hasUDSuffix()) { | |||
3618 | // We're building a user-defined literal. | |||
3619 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3620 | SourceLocation UDSuffixLoc = | |||
3621 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3622 | ||||
3623 | // Make sure we're allowed user-defined literals here. | |||
3624 | if (!UDLScope) | |||
3625 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | |||
3626 | ||||
3627 | QualType CookedTy; | |||
3628 | if (Literal.isFloatingLiteral()) { | |||
3629 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | |||
3630 | // long double, the literal is treated as a call of the form | |||
3631 | // operator "" X (f L) | |||
3632 | CookedTy = Context.LongDoubleTy; | |||
3633 | } else { | |||
3634 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | |||
3635 | // unsigned long long, the literal is treated as a call of the form | |||
3636 | // operator "" X (n ULL) | |||
3637 | CookedTy = Context.UnsignedLongLongTy; | |||
3638 | } | |||
3639 | ||||
3640 | DeclarationName OpName = | |||
3641 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
3642 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
3643 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
3644 | ||||
3645 | SourceLocation TokLoc = Tok.getLocation(); | |||
3646 | ||||
3647 | // Perform literal operator lookup to determine if we're building a raw | |||
3648 | // literal or a cooked one. | |||
3649 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
3650 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | |||
3651 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | |||
3652 | /*AllowStringTemplatePack*/ false, | |||
3653 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | |||
3654 | case LOLR_ErrorNoDiagnostic: | |||
3655 | // Lookup failure for imaginary constants isn't fatal, there's still the | |||
3656 | // GNU extension producing _Complex types. | |||
3657 | break; | |||
3658 | case LOLR_Error: | |||
3659 | return ExprError(); | |||
3660 | case LOLR_Cooked: { | |||
3661 | Expr *Lit; | |||
3662 | if (Literal.isFloatingLiteral()) { | |||
3663 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | |||
3664 | } else { | |||
3665 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | |||
3666 | if (Literal.GetIntegerValue(ResultVal)) | |||
3667 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3668 | << /* Unsigned */ 1; | |||
3669 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | |||
3670 | Tok.getLocation()); | |||
3671 | } | |||
3672 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3673 | } | |||
3674 | ||||
3675 | case LOLR_Raw: { | |||
3676 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | |||
3677 | // literal is treated as a call of the form | |||
3678 | // operator "" X ("n") | |||
3679 | unsigned Length = Literal.getUDSuffixOffset(); | |||
3680 | QualType StrTy = Context.getConstantArrayType( | |||
3681 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | |||
3682 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | |||
3683 | Expr *Lit = StringLiteral::Create( | |||
3684 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | |||
3685 | /*Pascal*/false, StrTy, &TokLoc, 1); | |||
3686 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3687 | } | |||
3688 | ||||
3689 | case LOLR_Template: { | |||
3690 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | |||
3691 | // template), L is treated as a call fo the form | |||
3692 | // operator "" X <'c1', 'c2', ... 'ck'>() | |||
3693 | // where n is the source character sequence c1 c2 ... ck. | |||
3694 | TemplateArgumentListInfo ExplicitArgs; | |||
3695 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | |||
3696 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | |||
3697 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
3698 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | |||
3699 | Value = TokSpelling[I]; | |||
3700 | TemplateArgument Arg(Context, Value, Context.CharTy); | |||
3701 | TemplateArgumentLocInfo ArgInfo; | |||
3702 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
3703 | } | |||
3704 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | |||
3705 | &ExplicitArgs); | |||
3706 | } | |||
3707 | case LOLR_StringTemplatePack: | |||
3708 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3708); | |||
3709 | } | |||
3710 | } | |||
3711 | ||||
3712 | Expr *Res; | |||
3713 | ||||
3714 | if (Literal.isFixedPointLiteral()) { | |||
3715 | QualType Ty; | |||
3716 | ||||
3717 | if (Literal.isAccum) { | |||
3718 | if (Literal.isHalf) { | |||
3719 | Ty = Context.ShortAccumTy; | |||
3720 | } else if (Literal.isLong) { | |||
3721 | Ty = Context.LongAccumTy; | |||
3722 | } else { | |||
3723 | Ty = Context.AccumTy; | |||
3724 | } | |||
3725 | } else if (Literal.isFract) { | |||
3726 | if (Literal.isHalf) { | |||
3727 | Ty = Context.ShortFractTy; | |||
3728 | } else if (Literal.isLong) { | |||
3729 | Ty = Context.LongFractTy; | |||
3730 | } else { | |||
3731 | Ty = Context.FractTy; | |||
3732 | } | |||
3733 | } | |||
3734 | ||||
3735 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | |||
3736 | ||||
3737 | bool isSigned = !Literal.isUnsigned; | |||
3738 | unsigned scale = Context.getFixedPointScale(Ty); | |||
3739 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | |||
3740 | ||||
3741 | llvm::APInt Val(bit_width, 0, isSigned); | |||
3742 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | |||
3743 | bool ValIsZero = Val.isNullValue() && !Overflowed; | |||
3744 | ||||
3745 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | |||
3746 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | |||
3747 | // Clause 6.4.4 - The value of a constant shall be in the range of | |||
3748 | // representable values for its type, with exception for constants of a | |||
3749 | // fract type with a value of exactly 1; such a constant shall denote | |||
3750 | // the maximal value for the type. | |||
3751 | --Val; | |||
3752 | else if (Val.ugt(MaxVal) || Overflowed) | |||
3753 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | |||
3754 | ||||
3755 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | |||
3756 | Tok.getLocation(), scale); | |||
3757 | } else if (Literal.isFloatingLiteral()) { | |||
3758 | QualType Ty; | |||
3759 | if (Literal.isHalf){ | |||
3760 | if (getOpenCLOptions().isEnabled("cl_khr_fp16")) | |||
3761 | Ty = Context.HalfTy; | |||
3762 | else { | |||
3763 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | |||
3764 | return ExprError(); | |||
3765 | } | |||
3766 | } else if (Literal.isFloat) | |||
3767 | Ty = Context.FloatTy; | |||
3768 | else if (Literal.isLong) | |||
3769 | Ty = Context.LongDoubleTy; | |||
3770 | else if (Literal.isFloat16) | |||
3771 | Ty = Context.Float16Ty; | |||
3772 | else if (Literal.isFloat128) | |||
3773 | Ty = Context.Float128Ty; | |||
3774 | else | |||
3775 | Ty = Context.DoubleTy; | |||
3776 | ||||
3777 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | |||
3778 | ||||
3779 | if (Ty == Context.DoubleTy) { | |||
3780 | if (getLangOpts().SinglePrecisionConstants) { | |||
3781 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
3782 | if (BTy->getKind() != BuiltinType::Float) { | |||
3783 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3784 | } | |||
3785 | } else if (getLangOpts().OpenCL && | |||
3786 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | |||
3787 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | |||
3788 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | |||
3789 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3790 | } | |||
3791 | } | |||
3792 | } else if (!Literal.isIntegerLiteral()) { | |||
3793 | return ExprError(); | |||
3794 | } else { | |||
3795 | QualType Ty; | |||
3796 | ||||
3797 | // 'long long' is a C99 or C++11 feature. | |||
3798 | if (!getLangOpts().C99 && Literal.isLongLong) { | |||
3799 | if (getLangOpts().CPlusPlus) | |||
3800 | Diag(Tok.getLocation(), | |||
3801 | getLangOpts().CPlusPlus11 ? | |||
3802 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
3803 | else | |||
3804 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | |||
3805 | } | |||
3806 | ||||
3807 | // Get the value in the widest-possible width. | |||
3808 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | |||
3809 | llvm::APInt ResultVal(MaxWidth, 0); | |||
3810 | ||||
3811 | if (Literal.GetIntegerValue(ResultVal)) { | |||
3812 | // If this value didn't fit into uintmax_t, error and force to ull. | |||
3813 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3814 | << /* Unsigned */ 1; | |||
3815 | Ty = Context.UnsignedLongLongTy; | |||
3816 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3817, __PRETTY_FUNCTION__)) | |||
3817 | "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3817, __PRETTY_FUNCTION__)); | |||
3818 | } else { | |||
3819 | // If this value fits into a ULL, try to figure out what else it fits into | |||
3820 | // according to the rules of C99 6.4.4.1p5. | |||
3821 | ||||
3822 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | |||
3823 | // be an unsigned int. | |||
3824 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | |||
3825 | ||||
3826 | // Check from smallest to largest, picking the smallest type we can. | |||
3827 | unsigned Width = 0; | |||
3828 | ||||
3829 | // Microsoft specific integer suffixes are explicitly sized. | |||
3830 | if (Literal.MicrosoftInteger) { | |||
3831 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | |||
3832 | Width = 8; | |||
3833 | Ty = Context.CharTy; | |||
3834 | } else { | |||
3835 | Width = Literal.MicrosoftInteger; | |||
3836 | Ty = Context.getIntTypeForBitwidth(Width, | |||
3837 | /*Signed=*/!Literal.isUnsigned); | |||
3838 | } | |||
3839 | } | |||
3840 | ||||
3841 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { | |||
3842 | // Are int/unsigned possibilities? | |||
3843 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3844 | ||||
3845 | // Does it fit in a unsigned int? | |||
3846 | if (ResultVal.isIntN(IntSize)) { | |||
3847 | // Does it fit in a signed int? | |||
3848 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | |||
3849 | Ty = Context.IntTy; | |||
3850 | else if (AllowUnsigned) | |||
3851 | Ty = Context.UnsignedIntTy; | |||
3852 | Width = IntSize; | |||
3853 | } | |||
3854 | } | |||
3855 | ||||
3856 | // Are long/unsigned long possibilities? | |||
3857 | if (Ty.isNull() && !Literal.isLongLong) { | |||
3858 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | |||
3859 | ||||
3860 | // Does it fit in a unsigned long? | |||
3861 | if (ResultVal.isIntN(LongSize)) { | |||
3862 | // Does it fit in a signed long? | |||
3863 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | |||
3864 | Ty = Context.LongTy; | |||
3865 | else if (AllowUnsigned) | |||
3866 | Ty = Context.UnsignedLongTy; | |||
3867 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | |||
3868 | // is compatible. | |||
3869 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | |||
3870 | const unsigned LongLongSize = | |||
3871 | Context.getTargetInfo().getLongLongWidth(); | |||
3872 | Diag(Tok.getLocation(), | |||
3873 | getLangOpts().CPlusPlus | |||
3874 | ? Literal.isLong | |||
3875 | ? diag::warn_old_implicitly_unsigned_long_cxx | |||
3876 | : /*C++98 UB*/ diag:: | |||
3877 | ext_old_implicitly_unsigned_long_cxx | |||
3878 | : diag::warn_old_implicitly_unsigned_long) | |||
3879 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | |||
3880 | : /*will be ill-formed*/ 1); | |||
3881 | Ty = Context.UnsignedLongTy; | |||
3882 | } | |||
3883 | Width = LongSize; | |||
3884 | } | |||
3885 | } | |||
3886 | ||||
3887 | // Check long long if needed. | |||
3888 | if (Ty.isNull()) { | |||
3889 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | |||
3890 | ||||
3891 | // Does it fit in a unsigned long long? | |||
3892 | if (ResultVal.isIntN(LongLongSize)) { | |||
3893 | // Does it fit in a signed long long? | |||
3894 | // To be compatible with MSVC, hex integer literals ending with the | |||
3895 | // LL or i64 suffix are always signed in Microsoft mode. | |||
3896 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | |||
3897 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | |||
3898 | Ty = Context.LongLongTy; | |||
3899 | else if (AllowUnsigned) | |||
3900 | Ty = Context.UnsignedLongLongTy; | |||
3901 | Width = LongLongSize; | |||
3902 | } | |||
3903 | } | |||
3904 | ||||
3905 | // If we still couldn't decide a type, we probably have something that | |||
3906 | // does not fit in a signed long long, but has no U suffix. | |||
3907 | if (Ty.isNull()) { | |||
3908 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); | |||
3909 | Ty = Context.UnsignedLongLongTy; | |||
3910 | Width = Context.getTargetInfo().getLongLongWidth(); | |||
3911 | } | |||
3912 | ||||
3913 | if (ResultVal.getBitWidth() != Width) | |||
3914 | ResultVal = ResultVal.trunc(Width); | |||
3915 | } | |||
3916 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | |||
3917 | } | |||
3918 | ||||
3919 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | |||
3920 | if (Literal.isImaginary) { | |||
3921 | Res = new (Context) ImaginaryLiteral(Res, | |||
3922 | Context.getComplexType(Res->getType())); | |||
3923 | ||||
3924 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | |||
3925 | } | |||
3926 | return Res; | |||
3927 | } | |||
3928 | ||||
3929 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | |||
3930 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3930, __PRETTY_FUNCTION__)); | |||
3931 | return new (Context) ParenExpr(L, R, E); | |||
3932 | } | |||
3933 | ||||
3934 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | |||
3935 | SourceLocation Loc, | |||
3936 | SourceRange ArgRange) { | |||
3937 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | |||
3938 | // scalar or vector data type argument..." | |||
3939 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | |||
3940 | // type (C99 6.2.5p18) or void. | |||
3941 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | |||
3942 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | |||
3943 | << T << ArgRange; | |||
3944 | return true; | |||
3945 | } | |||
3946 | ||||
3947 | assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3948, __PRETTY_FUNCTION__)) | |||
3948 | "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 3948, __PRETTY_FUNCTION__)); | |||
3949 | return false; | |||
3950 | } | |||
3951 | ||||
3952 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | |||
3953 | SourceLocation Loc, | |||
3954 | SourceRange ArgRange, | |||
3955 | UnaryExprOrTypeTrait TraitKind) { | |||
3956 | // Invalid types must be hard errors for SFINAE in C++. | |||
3957 | if (S.LangOpts.CPlusPlus) | |||
3958 | return true; | |||
3959 | ||||
3960 | // C99 6.5.3.4p1: | |||
3961 | if (T->isFunctionType() && | |||
3962 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | |||
3963 | TraitKind == UETT_PreferredAlignOf)) { | |||
3964 | // sizeof(function)/alignof(function) is allowed as an extension. | |||
3965 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | |||
3966 | << getTraitSpelling(TraitKind) << ArgRange; | |||
3967 | return false; | |||
3968 | } | |||
3969 | ||||
3970 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | |||
3971 | // this is an error (OpenCL v1.1 s6.3.k) | |||
3972 | if (T->isVoidType()) { | |||
3973 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | |||
3974 | : diag::ext_sizeof_alignof_void_type; | |||
3975 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | |||
3976 | return false; | |||
3977 | } | |||
3978 | ||||
3979 | return true; | |||
3980 | } | |||
3981 | ||||
3982 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | |||
3983 | SourceLocation Loc, | |||
3984 | SourceRange ArgRange, | |||
3985 | UnaryExprOrTypeTrait TraitKind) { | |||
3986 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | |||
3987 | // runtime doesn't allow it. | |||
3988 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | |||
3989 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | |||
3990 | << T << (TraitKind == UETT_SizeOf) | |||
3991 | << ArgRange; | |||
3992 | return true; | |||
3993 | } | |||
3994 | ||||
3995 | return false; | |||
3996 | } | |||
3997 | ||||
3998 | /// Check whether E is a pointer from a decayed array type (the decayed | |||
3999 | /// pointer type is equal to T) and emit a warning if it is. | |||
4000 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | |||
4001 | Expr *E) { | |||
4002 | // Don't warn if the operation changed the type. | |||
4003 | if (T != E->getType()) | |||
4004 | return; | |||
4005 | ||||
4006 | // Now look for array decays. | |||
4007 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | |||
4008 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | |||
4009 | return; | |||
4010 | ||||
4011 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | |||
4012 | << ICE->getType() | |||
4013 | << ICE->getSubExpr()->getType(); | |||
4014 | } | |||
4015 | ||||
4016 | /// Check the constraints on expression operands to unary type expression | |||
4017 | /// and type traits. | |||
4018 | /// | |||
4019 | /// Completes any types necessary and validates the constraints on the operand | |||
4020 | /// expression. The logic mostly mirrors the type-based overload, but may modify | |||
4021 | /// the expression as it completes the type for that expression through template | |||
4022 | /// instantiation, etc. | |||
4023 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | |||
4024 | UnaryExprOrTypeTrait ExprKind) { | |||
4025 | QualType ExprTy = E->getType(); | |||
4026 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4026, __PRETTY_FUNCTION__)); | |||
4027 | ||||
4028 | bool IsUnevaluatedOperand = | |||
4029 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | |||
4030 | ExprKind == UETT_PreferredAlignOf); | |||
4031 | if (IsUnevaluatedOperand) { | |||
4032 | ExprResult Result = CheckUnevaluatedOperand(E); | |||
4033 | if (Result.isInvalid()) | |||
4034 | return true; | |||
4035 | E = Result.get(); | |||
4036 | } | |||
4037 | ||||
4038 | if (ExprKind == UETT_VecStep) | |||
4039 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
4040 | E->getSourceRange()); | |||
4041 | ||||
4042 | // Explicitly list some types as extensions. | |||
4043 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
4044 | E->getSourceRange(), ExprKind)) | |||
4045 | return false; | |||
4046 | ||||
4047 | // 'alignof' applied to an expression only requires the base element type of | |||
4048 | // the expression to be complete. 'sizeof' requires the expression's type to | |||
4049 | // be complete (and will attempt to complete it if it's an array of unknown | |||
4050 | // bound). | |||
4051 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | |||
4052 | if (RequireCompleteSizedType( | |||
4053 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | |||
4054 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | |||
4055 | getTraitSpelling(ExprKind), E->getSourceRange())) | |||
4056 | return true; | |||
4057 | } else { | |||
4058 | if (RequireCompleteSizedExprType( | |||
4059 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | |||
4060 | getTraitSpelling(ExprKind), E->getSourceRange())) | |||
4061 | return true; | |||
4062 | } | |||
4063 | ||||
4064 | // Completing the expression's type may have changed it. | |||
4065 | ExprTy = E->getType(); | |||
4066 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4066, __PRETTY_FUNCTION__)); | |||
4067 | ||||
4068 | if (ExprTy->isFunctionType()) { | |||
4069 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | |||
4070 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | |||
4071 | return true; | |||
4072 | } | |||
4073 | ||||
4074 | // The operand for sizeof and alignof is in an unevaluated expression context, | |||
4075 | // so side effects could result in unintended consequences. | |||
4076 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | |||
4077 | E->HasSideEffects(Context, false)) | |||
4078 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
4079 | ||||
4080 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | |||
4081 | E->getSourceRange(), ExprKind)) | |||
4082 | return true; | |||
4083 | ||||
4084 | if (ExprKind == UETT_SizeOf) { | |||
4085 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
4086 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | |||
4087 | QualType OType = PVD->getOriginalType(); | |||
4088 | QualType Type = PVD->getType(); | |||
4089 | if (Type->isPointerType() && OType->isArrayType()) { | |||
4090 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | |||
4091 | << Type << OType; | |||
4092 | Diag(PVD->getLocation(), diag::note_declared_at); | |||
4093 | } | |||
4094 | } | |||
4095 | } | |||
4096 | ||||
4097 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | |||
4098 | // decays into a pointer and returns an unintended result. This is most | |||
4099 | // likely a typo for "sizeof(array) op x". | |||
4100 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | |||
4101 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
4102 | BO->getLHS()); | |||
4103 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
4104 | BO->getRHS()); | |||
4105 | } | |||
4106 | } | |||
4107 | ||||
4108 | return false; | |||
4109 | } | |||
4110 | ||||
4111 | /// Check the constraints on operands to unary expression and type | |||
4112 | /// traits. | |||
4113 | /// | |||
4114 | /// This will complete any types necessary, and validate the various constraints | |||
4115 | /// on those operands. | |||
4116 | /// | |||
4117 | /// The UsualUnaryConversions() function is *not* called by this routine. | |||
4118 | /// C99 6.3.2.1p[2-4] all state: | |||
4119 | /// Except when it is the operand of the sizeof operator ... | |||
4120 | /// | |||
4121 | /// C++ [expr.sizeof]p4 | |||
4122 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | |||
4123 | /// standard conversions are not applied to the operand of sizeof. | |||
4124 | /// | |||
4125 | /// This policy is followed for all of the unary trait expressions. | |||
4126 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | |||
4127 | SourceLocation OpLoc, | |||
4128 | SourceRange ExprRange, | |||
4129 | UnaryExprOrTypeTrait ExprKind) { | |||
4130 | if (ExprType->isDependentType()) | |||
4131 | return false; | |||
4132 | ||||
4133 | // C++ [expr.sizeof]p2: | |||
4134 | // When applied to a reference or a reference type, the result | |||
4135 | // is the size of the referenced type. | |||
4136 | // C++11 [expr.alignof]p3: | |||
4137 | // When alignof is applied to a reference type, the result | |||
4138 | // shall be the alignment of the referenced type. | |||
4139 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | |||
4140 | ExprType = Ref->getPointeeType(); | |||
4141 | ||||
4142 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | |||
4143 | // When alignof or _Alignof is applied to an array type, the result | |||
4144 | // is the alignment of the element type. | |||
4145 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | |||
4146 | ExprKind == UETT_OpenMPRequiredSimdAlign) | |||
4147 | ExprType = Context.getBaseElementType(ExprType); | |||
4148 | ||||
4149 | if (ExprKind == UETT_VecStep) | |||
4150 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | |||
4151 | ||||
4152 | // Explicitly list some types as extensions. | |||
4153 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | |||
4154 | ExprKind)) | |||
4155 | return false; | |||
4156 | ||||
4157 | if (RequireCompleteSizedType( | |||
4158 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | |||
4159 | getTraitSpelling(ExprKind), ExprRange)) | |||
4160 | return true; | |||
4161 | ||||
4162 | if (ExprType->isFunctionType()) { | |||
4163 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | |||
4164 | << getTraitSpelling(ExprKind) << ExprRange; | |||
4165 | return true; | |||
4166 | } | |||
4167 | ||||
4168 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | |||
4169 | ExprKind)) | |||
4170 | return true; | |||
4171 | ||||
4172 | return false; | |||
4173 | } | |||
4174 | ||||
4175 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | |||
4176 | // Cannot know anything else if the expression is dependent. | |||
4177 | if (E->isTypeDependent()) | |||
4178 | return false; | |||
4179 | ||||
4180 | if (E->getObjectKind() == OK_BitField) { | |||
4181 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | |||
4182 | << 1 << E->getSourceRange(); | |||
4183 | return true; | |||
4184 | } | |||
4185 | ||||
4186 | ValueDecl *D = nullptr; | |||
4187 | Expr *Inner = E->IgnoreParens(); | |||
4188 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | |||
4189 | D = DRE->getDecl(); | |||
4190 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | |||
4191 | D = ME->getMemberDecl(); | |||
4192 | } | |||
4193 | ||||
4194 | // If it's a field, require the containing struct to have a | |||
4195 | // complete definition so that we can compute the layout. | |||
4196 | // | |||
4197 | // This can happen in C++11 onwards, either by naming the member | |||
4198 | // in a way that is not transformed into a member access expression | |||
4199 | // (in an unevaluated operand, for instance), or by naming the member | |||
4200 | // in a trailing-return-type. | |||
4201 | // | |||
4202 | // For the record, since __alignof__ on expressions is a GCC | |||
4203 | // extension, GCC seems to permit this but always gives the | |||
4204 | // nonsensical answer 0. | |||
4205 | // | |||
4206 | // We don't really need the layout here --- we could instead just | |||
4207 | // directly check for all the appropriate alignment-lowing | |||
4208 | // attributes --- but that would require duplicating a lot of | |||
4209 | // logic that just isn't worth duplicating for such a marginal | |||
4210 | // use-case. | |||
4211 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | |||
4212 | // Fast path this check, since we at least know the record has a | |||
4213 | // definition if we can find a member of it. | |||
4214 | if (!FD->getParent()->isCompleteDefinition()) { | |||
4215 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | |||
4216 | << E->getSourceRange(); | |||
4217 | return true; | |||
4218 | } | |||
4219 | ||||
4220 | // Otherwise, if it's a field, and the field doesn't have | |||
4221 | // reference type, then it must have a complete type (or be a | |||
4222 | // flexible array member, which we explicitly want to | |||
4223 | // white-list anyway), which makes the following checks trivial. | |||
4224 | if (!FD->getType()->isReferenceType()) | |||
4225 | return false; | |||
4226 | } | |||
4227 | ||||
4228 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | |||
4229 | } | |||
4230 | ||||
4231 | bool Sema::CheckVecStepExpr(Expr *E) { | |||
4232 | E = E->IgnoreParens(); | |||
4233 | ||||
4234 | // Cannot know anything else if the expression is dependent. | |||
4235 | if (E->isTypeDependent()) | |||
4236 | return false; | |||
4237 | ||||
4238 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | |||
4239 | } | |||
4240 | ||||
4241 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | |||
4242 | CapturingScopeInfo *CSI) { | |||
4243 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4243, __PRETTY_FUNCTION__)); | |||
4244 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4244, __PRETTY_FUNCTION__)); | |||
4245 | ||||
4246 | // We're going to walk down into the type and look for VLA expressions. | |||
4247 | do { | |||
4248 | const Type *Ty = T.getTypePtr(); | |||
4249 | switch (Ty->getTypeClass()) { | |||
4250 | #define TYPE(Class, Base) | |||
4251 | #define ABSTRACT_TYPE(Class, Base) | |||
4252 | #define NON_CANONICAL_TYPE(Class, Base) | |||
4253 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | |||
4254 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | |||
4255 | #include "clang/AST/TypeNodes.inc" | |||
4256 | T = QualType(); | |||
4257 | break; | |||
4258 | // These types are never variably-modified. | |||
4259 | case Type::Builtin: | |||
4260 | case Type::Complex: | |||
4261 | case Type::Vector: | |||
4262 | case Type::ExtVector: | |||
4263 | case Type::ConstantMatrix: | |||
4264 | case Type::Record: | |||
4265 | case Type::Enum: | |||
4266 | case Type::Elaborated: | |||
4267 | case Type::TemplateSpecialization: | |||
4268 | case Type::ObjCObject: | |||
4269 | case Type::ObjCInterface: | |||
4270 | case Type::ObjCObjectPointer: | |||
4271 | case Type::ObjCTypeParam: | |||
4272 | case Type::Pipe: | |||
4273 | case Type::ExtInt: | |||
4274 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4274); | |||
4275 | case Type::Adjusted: | |||
4276 | T = cast<AdjustedType>(Ty)->getOriginalType(); | |||
4277 | break; | |||
4278 | case Type::Decayed: | |||
4279 | T = cast<DecayedType>(Ty)->getPointeeType(); | |||
4280 | break; | |||
4281 | case Type::Pointer: | |||
4282 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
4283 | break; | |||
4284 | case Type::BlockPointer: | |||
4285 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
4286 | break; | |||
4287 | case Type::LValueReference: | |||
4288 | case Type::RValueReference: | |||
4289 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
4290 | break; | |||
4291 | case Type::MemberPointer: | |||
4292 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
4293 | break; | |||
4294 | case Type::ConstantArray: | |||
4295 | case Type::IncompleteArray: | |||
4296 | // Losing element qualification here is fine. | |||
4297 | T = cast<ArrayType>(Ty)->getElementType(); | |||
4298 | break; | |||
4299 | case Type::VariableArray: { | |||
4300 | // Losing element qualification here is fine. | |||
4301 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | |||
4302 | ||||
4303 | // Unknown size indication requires no size computation. | |||
4304 | // Otherwise, evaluate and record it. | |||
4305 | auto Size = VAT->getSizeExpr(); | |||
4306 | if (Size && !CSI->isVLATypeCaptured(VAT) && | |||
4307 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | |||
4308 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | |||
4309 | ||||
4310 | T = VAT->getElementType(); | |||
4311 | break; | |||
4312 | } | |||
4313 | case Type::FunctionProto: | |||
4314 | case Type::FunctionNoProto: | |||
4315 | T = cast<FunctionType>(Ty)->getReturnType(); | |||
4316 | break; | |||
4317 | case Type::Paren: | |||
4318 | case Type::TypeOf: | |||
4319 | case Type::UnaryTransform: | |||
4320 | case Type::Attributed: | |||
4321 | case Type::SubstTemplateTypeParm: | |||
4322 | case Type::MacroQualified: | |||
4323 | // Keep walking after single level desugaring. | |||
4324 | T = T.getSingleStepDesugaredType(Context); | |||
4325 | break; | |||
4326 | case Type::Typedef: | |||
4327 | T = cast<TypedefType>(Ty)->desugar(); | |||
4328 | break; | |||
4329 | case Type::Decltype: | |||
4330 | T = cast<DecltypeType>(Ty)->desugar(); | |||
4331 | break; | |||
4332 | case Type::Auto: | |||
4333 | case Type::DeducedTemplateSpecialization: | |||
4334 | T = cast<DeducedType>(Ty)->getDeducedType(); | |||
4335 | break; | |||
4336 | case Type::TypeOfExpr: | |||
4337 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | |||
4338 | break; | |||
4339 | case Type::Atomic: | |||
4340 | T = cast<AtomicType>(Ty)->getValueType(); | |||
4341 | break; | |||
4342 | } | |||
4343 | } while (!T.isNull() && T->isVariablyModifiedType()); | |||
4344 | } | |||
4345 | ||||
4346 | /// Build a sizeof or alignof expression given a type operand. | |||
4347 | ExprResult | |||
4348 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | |||
4349 | SourceLocation OpLoc, | |||
4350 | UnaryExprOrTypeTrait ExprKind, | |||
4351 | SourceRange R) { | |||
4352 | if (!TInfo) | |||
4353 | return ExprError(); | |||
4354 | ||||
4355 | QualType T = TInfo->getType(); | |||
4356 | ||||
4357 | if (!T->isDependentType() && | |||
4358 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | |||
4359 | return ExprError(); | |||
4360 | ||||
4361 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | |||
4362 | if (auto *TT = T->getAs<TypedefType>()) { | |||
4363 | for (auto I = FunctionScopes.rbegin(), | |||
4364 | E = std::prev(FunctionScopes.rend()); | |||
4365 | I != E; ++I) { | |||
4366 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
4367 | if (CSI == nullptr) | |||
4368 | break; | |||
4369 | DeclContext *DC = nullptr; | |||
4370 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
4371 | DC = LSI->CallOperator; | |||
4372 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
4373 | DC = CRSI->TheCapturedDecl; | |||
4374 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
4375 | DC = BSI->TheDecl; | |||
4376 | if (DC) { | |||
4377 | if (DC->containsDecl(TT->getDecl())) | |||
4378 | break; | |||
4379 | captureVariablyModifiedType(Context, T, CSI); | |||
4380 | } | |||
4381 | } | |||
4382 | } | |||
4383 | } | |||
4384 | ||||
4385 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4386 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4387 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | |||
4388 | } | |||
4389 | ||||
4390 | /// Build a sizeof or alignof expression given an expression | |||
4391 | /// operand. | |||
4392 | ExprResult | |||
4393 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | |||
4394 | UnaryExprOrTypeTrait ExprKind) { | |||
4395 | ExprResult PE = CheckPlaceholderExpr(E); | |||
4396 | if (PE.isInvalid()) | |||
4397 | return ExprError(); | |||
4398 | ||||
4399 | E = PE.get(); | |||
4400 | ||||
4401 | // Verify that the operand is valid. | |||
4402 | bool isInvalid = false; | |||
4403 | if (E->isTypeDependent()) { | |||
4404 | // Delay type-checking for type-dependent expressions. | |||
4405 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | |||
4406 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | |||
4407 | } else if (ExprKind == UETT_VecStep) { | |||
4408 | isInvalid = CheckVecStepExpr(E); | |||
4409 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | |||
4410 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | |||
4411 | isInvalid = true; | |||
4412 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | |||
4413 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | |||
4414 | isInvalid = true; | |||
4415 | } else { | |||
4416 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | |||
4417 | } | |||
4418 | ||||
4419 | if (isInvalid) | |||
4420 | return ExprError(); | |||
4421 | ||||
4422 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | |||
4423 | PE = TransformToPotentiallyEvaluated(E); | |||
4424 | if (PE.isInvalid()) return ExprError(); | |||
4425 | E = PE.get(); | |||
4426 | } | |||
4427 | ||||
4428 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4429 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4430 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | |||
4431 | } | |||
4432 | ||||
4433 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | |||
4434 | /// expr and the same for @c alignof and @c __alignof | |||
4435 | /// Note that the ArgRange is invalid if isType is false. | |||
4436 | ExprResult | |||
4437 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | |||
4438 | UnaryExprOrTypeTrait ExprKind, bool IsType, | |||
4439 | void *TyOrEx, SourceRange ArgRange) { | |||
4440 | // If error parsing type, ignore. | |||
4441 | if (!TyOrEx) return ExprError(); | |||
4442 | ||||
4443 | if (IsType) { | |||
4444 | TypeSourceInfo *TInfo; | |||
4445 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | |||
4446 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | |||
4447 | } | |||
4448 | ||||
4449 | Expr *ArgEx = (Expr *)TyOrEx; | |||
4450 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | |||
4451 | return Result; | |||
4452 | } | |||
4453 | ||||
4454 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | |||
4455 | bool IsReal) { | |||
4456 | if (V.get()->isTypeDependent()) | |||
4457 | return S.Context.DependentTy; | |||
4458 | ||||
4459 | // _Real and _Imag are only l-values for normal l-values. | |||
4460 | if (V.get()->getObjectKind() != OK_Ordinary) { | |||
4461 | V = S.DefaultLvalueConversion(V.get()); | |||
4462 | if (V.isInvalid()) | |||
4463 | return QualType(); | |||
4464 | } | |||
4465 | ||||
4466 | // These operators return the element type of a complex type. | |||
4467 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | |||
4468 | return CT->getElementType(); | |||
4469 | ||||
4470 | // Otherwise they pass through real integer and floating point types here. | |||
4471 | if (V.get()->getType()->isArithmeticType()) | |||
4472 | return V.get()->getType(); | |||
4473 | ||||
4474 | // Test for placeholders. | |||
4475 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | |||
4476 | if (PR.isInvalid()) return QualType(); | |||
4477 | if (PR.get() != V.get()) { | |||
4478 | V = PR; | |||
4479 | return CheckRealImagOperand(S, V, Loc, IsReal); | |||
4480 | } | |||
4481 | ||||
4482 | // Reject anything else. | |||
4483 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | |||
4484 | << (IsReal ? "__real" : "__imag"); | |||
4485 | return QualType(); | |||
4486 | } | |||
4487 | ||||
4488 | ||||
4489 | ||||
4490 | ExprResult | |||
4491 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4492 | tok::TokenKind Kind, Expr *Input) { | |||
4493 | UnaryOperatorKind Opc; | |||
4494 | switch (Kind) { | |||
4495 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4495); | |||
4496 | case tok::plusplus: Opc = UO_PostInc; break; | |||
4497 | case tok::minusminus: Opc = UO_PostDec; break; | |||
4498 | } | |||
4499 | ||||
4500 | // Since this might is a postfix expression, get rid of ParenListExprs. | |||
4501 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | |||
4502 | if (Result.isInvalid()) return ExprError(); | |||
4503 | Input = Result.get(); | |||
4504 | ||||
4505 | return BuildUnaryOp(S, OpLoc, Opc, Input); | |||
4506 | } | |||
4507 | ||||
4508 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | |||
4509 | /// | |||
4510 | /// \return true on error | |||
4511 | static bool checkArithmeticOnObjCPointer(Sema &S, | |||
4512 | SourceLocation opLoc, | |||
4513 | Expr *op) { | |||
4514 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4514, __PRETTY_FUNCTION__)); | |||
4515 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | |||
4516 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | |||
4517 | return false; | |||
4518 | ||||
4519 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | |||
4520 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | |||
4521 | << op->getSourceRange(); | |||
4522 | return true; | |||
4523 | } | |||
4524 | ||||
4525 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | |||
4526 | auto *BaseNoParens = Base->IgnoreParens(); | |||
4527 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | |||
4528 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | |||
4529 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | |||
4530 | } | |||
4531 | ||||
4532 | ExprResult | |||
4533 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | |||
4534 | Expr *idx, SourceLocation rbLoc) { | |||
4535 | if (base && !base->getType().isNull() && | |||
4536 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | |||
4537 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | |||
4538 | SourceLocation(), /*Length*/ nullptr, | |||
4539 | /*Stride=*/nullptr, rbLoc); | |||
4540 | ||||
4541 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
4542 | if (isa<ParenListExpr>(base)) { | |||
4543 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | |||
4544 | if (result.isInvalid()) return ExprError(); | |||
4545 | base = result.get(); | |||
4546 | } | |||
4547 | ||||
4548 | // Check if base and idx form a MatrixSubscriptExpr. | |||
4549 | // | |||
4550 | // Helper to check for comma expressions, which are not allowed as indices for | |||
4551 | // matrix subscript expressions. | |||
4552 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | |||
4553 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | |||
4554 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | |||
4555 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4556 | return true; | |||
4557 | } | |||
4558 | return false; | |||
4559 | }; | |||
4560 | // The matrix subscript operator ([][])is considered a single operator. | |||
4561 | // Separating the index expressions by parenthesis is not allowed. | |||
4562 | if (base->getType()->isSpecificPlaceholderType( | |||
4563 | BuiltinType::IncompleteMatrixIdx) && | |||
4564 | !isa<MatrixSubscriptExpr>(base)) { | |||
4565 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | |||
4566 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4567 | return ExprError(); | |||
4568 | } | |||
4569 | // If the base is a MatrixSubscriptExpr, try to create a new | |||
4570 | // MatrixSubscriptExpr. | |||
4571 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | |||
4572 | if (matSubscriptE) { | |||
4573 | if (CheckAndReportCommaError(idx)) | |||
4574 | return ExprError(); | |||
4575 | ||||
4576 | assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4577, __PRETTY_FUNCTION__)) | |||
4577 | "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4577, __PRETTY_FUNCTION__)); | |||
4578 | return CreateBuiltinMatrixSubscriptExpr( | |||
4579 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | |||
4580 | } | |||
4581 | ||||
4582 | // Handle any non-overload placeholder types in the base and index | |||
4583 | // expressions. We can't handle overloads here because the other | |||
4584 | // operand might be an overloadable type, in which case the overload | |||
4585 | // resolution for the operator overload should get the first crack | |||
4586 | // at the overload. | |||
4587 | bool IsMSPropertySubscript = false; | |||
4588 | if (base->getType()->isNonOverloadPlaceholderType()) { | |||
4589 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | |||
4590 | if (!IsMSPropertySubscript) { | |||
4591 | ExprResult result = CheckPlaceholderExpr(base); | |||
4592 | if (result.isInvalid()) | |||
4593 | return ExprError(); | |||
4594 | base = result.get(); | |||
4595 | } | |||
4596 | } | |||
4597 | ||||
4598 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | |||
4599 | if (base->getType()->isMatrixType()) { | |||
4600 | if (CheckAndReportCommaError(idx)) | |||
4601 | return ExprError(); | |||
4602 | ||||
4603 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | |||
4604 | } | |||
4605 | ||||
4606 | // A comma-expression as the index is deprecated in C++2a onwards. | |||
4607 | if (getLangOpts().CPlusPlus20 && | |||
4608 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | |||
4609 | (isa<CXXOperatorCallExpr>(idx) && | |||
4610 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | |||
4611 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | |||
4612 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4613 | } | |||
4614 | ||||
4615 | if (idx->getType()->isNonOverloadPlaceholderType()) { | |||
4616 | ExprResult result = CheckPlaceholderExpr(idx); | |||
4617 | if (result.isInvalid()) return ExprError(); | |||
4618 | idx = result.get(); | |||
4619 | } | |||
4620 | ||||
4621 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4622 | if (getLangOpts().CPlusPlus && | |||
4623 | (base->isTypeDependent() || idx->isTypeDependent())) { | |||
4624 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | |||
4625 | VK_LValue, OK_Ordinary, rbLoc); | |||
4626 | } | |||
4627 | ||||
4628 | // MSDN, property (C++) | |||
4629 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | |||
4630 | // This attribute can also be used in the declaration of an empty array in a | |||
4631 | // class or structure definition. For example: | |||
4632 | // __declspec(property(get=GetX, put=PutX)) int x[]; | |||
4633 | // The above statement indicates that x[] can be used with one or more array | |||
4634 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | |||
4635 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | |||
4636 | if (IsMSPropertySubscript) { | |||
4637 | // Build MS property subscript expression if base is MS property reference | |||
4638 | // or MS property subscript. | |||
4639 | return new (Context) MSPropertySubscriptExpr( | |||
4640 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | |||
4641 | } | |||
4642 | ||||
4643 | // Use C++ overloaded-operator rules if either operand has record | |||
4644 | // type. The spec says to do this if either type is *overloadable*, | |||
4645 | // but enum types can't declare subscript operators or conversion | |||
4646 | // operators, so there's nothing interesting for overload resolution | |||
4647 | // to do if there aren't any record types involved. | |||
4648 | // | |||
4649 | // ObjC pointers have their own subscripting logic that is not tied | |||
4650 | // to overload resolution and so should not take this path. | |||
4651 | if (getLangOpts().CPlusPlus && | |||
4652 | (base->getType()->isRecordType() || | |||
4653 | (!base->getType()->isObjCObjectPointerType() && | |||
4654 | idx->getType()->isRecordType()))) { | |||
4655 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | |||
4656 | } | |||
4657 | ||||
4658 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | |||
4659 | ||||
4660 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | |||
4661 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | |||
4662 | ||||
4663 | return Res; | |||
4664 | } | |||
4665 | ||||
4666 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | |||
4667 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | |||
4668 | InitializationKind Kind = | |||
4669 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | |||
4670 | InitializationSequence InitSeq(*this, Entity, Kind, E); | |||
4671 | return InitSeq.Perform(*this, Entity, Kind, E); | |||
4672 | } | |||
4673 | ||||
4674 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | |||
4675 | Expr *ColumnIdx, | |||
4676 | SourceLocation RBLoc) { | |||
4677 | ExprResult BaseR = CheckPlaceholderExpr(Base); | |||
4678 | if (BaseR.isInvalid()) | |||
4679 | return BaseR; | |||
4680 | Base = BaseR.get(); | |||
4681 | ||||
4682 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | |||
4683 | if (RowR.isInvalid()) | |||
4684 | return RowR; | |||
4685 | RowIdx = RowR.get(); | |||
4686 | ||||
4687 | if (!ColumnIdx) | |||
4688 | return new (Context) MatrixSubscriptExpr( | |||
4689 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | |||
4690 | ||||
4691 | // Build an unanalyzed expression if any of the operands is type-dependent. | |||
4692 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | |||
4693 | ColumnIdx->isTypeDependent()) | |||
4694 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | |||
4695 | Context.DependentTy, RBLoc); | |||
4696 | ||||
4697 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | |||
4698 | if (ColumnR.isInvalid()) | |||
4699 | return ColumnR; | |||
4700 | ColumnIdx = ColumnR.get(); | |||
4701 | ||||
4702 | // Check that IndexExpr is an integer expression. If it is a constant | |||
4703 | // expression, check that it is less than Dim (= the number of elements in the | |||
4704 | // corresponding dimension). | |||
4705 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | |||
4706 | bool IsColumnIdx) -> Expr * { | |||
4707 | if (!IndexExpr->getType()->isIntegerType() && | |||
4708 | !IndexExpr->isTypeDependent()) { | |||
4709 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | |||
4710 | << IsColumnIdx; | |||
4711 | return nullptr; | |||
4712 | } | |||
4713 | ||||
4714 | if (Optional<llvm::APSInt> Idx = | |||
4715 | IndexExpr->getIntegerConstantExpr(Context)) { | |||
4716 | if ((*Idx < 0 || *Idx >= Dim)) { | |||
4717 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | |||
4718 | << IsColumnIdx << Dim; | |||
4719 | return nullptr; | |||
4720 | } | |||
4721 | } | |||
4722 | ||||
4723 | ExprResult ConvExpr = | |||
4724 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | |||
4725 | assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4726, __PRETTY_FUNCTION__)) | |||
4726 | "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 4726, __PRETTY_FUNCTION__)); | |||
4727 | return ConvExpr.get(); | |||
4728 | }; | |||
4729 | ||||
4730 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | |||
4731 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | |||
4732 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | |||
4733 | if (!RowIdx || !ColumnIdx) | |||
4734 | return ExprError(); | |||
4735 | ||||
4736 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | |||
4737 | MTy->getElementType(), RBLoc); | |||
4738 | } | |||
4739 | ||||
4740 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | |||
4741 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | |||
4742 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | |||
4743 | ||||
4744 | // For expressions like `&(*s).b`, the base is recorded and what should be | |||
4745 | // checked. | |||
4746 | const MemberExpr *Member = nullptr; | |||
4747 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | |||
4748 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | |||
4749 | ||||
4750 | LastRecord.PossibleDerefs.erase(StrippedExpr); | |||
4751 | } | |||
4752 | ||||
4753 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | |||
4754 | if (isUnevaluatedContext()) | |||
4755 | return; | |||
4756 | ||||
4757 | QualType ResultTy = E->getType(); | |||
4758 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | |||
4759 | ||||
4760 | // Bail if the element is an array since it is not memory access. | |||
4761 | if (isa<ArrayType>(ResultTy)) | |||
4762 | return; | |||
4763 | ||||
4764 | if (ResultTy->hasAttr(attr::NoDeref)) { | |||
4765 | LastRecord.PossibleDerefs.insert(E); | |||
4766 | return; | |||
4767 | } | |||
4768 | ||||
4769 | // Check if the base type is a pointer to a member access of a struct | |||
4770 | // marked with noderef. | |||
4771 | const Expr *Base = E->getBase(); | |||
4772 | QualType BaseTy = Base->getType(); | |||
4773 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | |||
4774 | // Not a pointer access | |||
4775 | return; | |||
4776 | ||||
4777 | const MemberExpr *Member = nullptr; | |||
4778 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | |||
4779 | Member->isArrow()) | |||
4780 | Base = Member->getBase(); | |||
4781 | ||||
4782 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | |||
4783 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | |||
4784 | LastRecord.PossibleDerefs.insert(E); | |||
4785 | } | |||
4786 | } | |||
4787 | ||||
4788 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | |||
4789 | Expr *LowerBound, | |||
4790 | SourceLocation ColonLocFirst, | |||
4791 | SourceLocation ColonLocSecond, | |||
4792 | Expr *Length, Expr *Stride, | |||
4793 | SourceLocation RBLoc) { | |||
4794 | if (Base->getType()->isPlaceholderType() && | |||
4795 | !Base->getType()->isSpecificPlaceholderType( | |||
4796 | BuiltinType::OMPArraySection)) { | |||
4797 | ExprResult Result = CheckPlaceholderExpr(Base); | |||
4798 | if (Result.isInvalid()) | |||
4799 | return ExprError(); | |||
4800 | Base = Result.get(); | |||
4801 | } | |||
4802 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | |||
4803 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | |||
4804 | if (Result.isInvalid()) | |||
4805 | return ExprError(); | |||
4806 | Result = DefaultLvalueConversion(Result.get()); | |||
4807 | if (Result.isInvalid()) | |||
4808 | return ExprError(); | |||
4809 | LowerBound = Result.get(); | |||
4810 | } | |||
4811 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | |||
4812 | ExprResult Result = CheckPlaceholderExpr(Length); | |||
4813 | if (Result.isInvalid()) | |||
4814 | return ExprError(); | |||
4815 | Result = DefaultLvalueConversion(Result.get()); | |||
4816 | if (Result.isInvalid()) | |||
4817 | return ExprError(); | |||
4818 | Length = Result.get(); | |||
4819 | } | |||
4820 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | |||
4821 | ExprResult Result = CheckPlaceholderExpr(Stride); | |||
4822 | if (Result.isInvalid()) | |||
4823 | return ExprError(); | |||
4824 | Result = DefaultLvalueConversion(Result.get()); | |||
4825 | if (Result.isInvalid()) | |||
4826 | return ExprError(); | |||
4827 | Stride = Result.get(); | |||
4828 | } | |||
4829 | ||||
4830 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4831 | if (Base->isTypeDependent() || | |||
4832 | (LowerBound && | |||
4833 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | |||
4834 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | |||
4835 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | |||
4836 | return new (Context) OMPArraySectionExpr( | |||
4837 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | |||
4838 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | |||
4839 | } | |||
4840 | ||||
4841 | // Perform default conversions. | |||
4842 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | |||
4843 | QualType ResultTy; | |||
4844 | if (OriginalTy->isAnyPointerType()) { | |||
4845 | ResultTy = OriginalTy->getPointeeType(); | |||
4846 | } else if (OriginalTy->isArrayType()) { | |||
4847 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | |||
4848 | } else { | |||
4849 | return ExprError( | |||
4850 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | |||
4851 | << Base->getSourceRange()); | |||
4852 | } | |||
4853 | // C99 6.5.2.1p1 | |||
4854 | if (LowerBound) { | |||
4855 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | |||
4856 | LowerBound); | |||
4857 | if (Res.isInvalid()) | |||
4858 | return ExprError(Diag(LowerBound->getExprLoc(), | |||
4859 | diag::err_omp_typecheck_section_not_integer) | |||
4860 | << 0 << LowerBound->getSourceRange()); | |||
4861 | LowerBound = Res.get(); | |||
4862 | ||||
4863 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4864 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4865 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | |||
4866 | << 0 << LowerBound->getSourceRange(); | |||
4867 | } | |||
4868 | if (Length) { | |||
4869 | auto Res = | |||
4870 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | |||
4871 | if (Res.isInvalid()) | |||
4872 | return ExprError(Diag(Length->getExprLoc(), | |||
4873 | diag::err_omp_typecheck_section_not_integer) | |||
4874 | << 1 << Length->getSourceRange()); | |||
4875 | Length = Res.get(); | |||
4876 | ||||
4877 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4878 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4879 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | |||
4880 | << 1 << Length->getSourceRange(); | |||
4881 | } | |||
4882 | if (Stride) { | |||
4883 | ExprResult Res = | |||
4884 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | |||
4885 | if (Res.isInvalid()) | |||
4886 | return ExprError(Diag(Stride->getExprLoc(), | |||
4887 | diag::err_omp_typecheck_section_not_integer) | |||
4888 | << 1 << Stride->getSourceRange()); | |||
4889 | Stride = Res.get(); | |||
4890 | ||||
4891 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4892 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4893 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | |||
4894 | << 1 << Stride->getSourceRange(); | |||
4895 | } | |||
4896 | ||||
4897 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
4898 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
4899 | // type. Note that functions are not objects, and that (in C99 parlance) | |||
4900 | // incomplete types are not object types. | |||
4901 | if (ResultTy->isFunctionType()) { | |||
4902 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | |||
4903 | << ResultTy << Base->getSourceRange(); | |||
4904 | return ExprError(); | |||
4905 | } | |||
4906 | ||||
4907 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | |||
4908 | diag::err_omp_section_incomplete_type, Base)) | |||
4909 | return ExprError(); | |||
4910 | ||||
4911 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | |||
4912 | Expr::EvalResult Result; | |||
4913 | if (LowerBound->EvaluateAsInt(Result, Context)) { | |||
4914 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
4915 | // The array section must be a subset of the original array. | |||
4916 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | |||
4917 | if (LowerBoundValue.isNegative()) { | |||
4918 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | |||
4919 | << LowerBound->getSourceRange(); | |||
4920 | return ExprError(); | |||
4921 | } | |||
4922 | } | |||
4923 | } | |||
4924 | ||||
4925 | if (Length) { | |||
4926 | Expr::EvalResult Result; | |||
4927 | if (Length->EvaluateAsInt(Result, Context)) { | |||
4928 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
4929 | // The length must evaluate to non-negative integers. | |||
4930 | llvm::APSInt LengthValue = Result.Val.getInt(); | |||
4931 | if (LengthValue.isNegative()) { | |||
4932 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | |||
4933 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | |||
4934 | << Length->getSourceRange(); | |||
4935 | return ExprError(); | |||
4936 | } | |||
4937 | } | |||
4938 | } else if (ColonLocFirst.isValid() && | |||
4939 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | |||
4940 | !OriginalTy->isVariableArrayType()))) { | |||
4941 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
4942 | // When the size of the array dimension is not known, the length must be | |||
4943 | // specified explicitly. | |||
4944 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | |||
4945 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | |||
4946 | return ExprError(); | |||
4947 | } | |||
4948 | ||||
4949 | if (Stride) { | |||
4950 | Expr::EvalResult Result; | |||
4951 | if (Stride->EvaluateAsInt(Result, Context)) { | |||
4952 | // OpenMP 5.0, [2.1.5 Array Sections] | |||
4953 | // The stride must evaluate to a positive integer. | |||
4954 | llvm::APSInt StrideValue = Result.Val.getInt(); | |||
4955 | if (!StrideValue.isStrictlyPositive()) { | |||
4956 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | |||
4957 | << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) | |||
4958 | << Stride->getSourceRange(); | |||
4959 | return ExprError(); | |||
4960 | } | |||
4961 | } | |||
4962 | } | |||
4963 | ||||
4964 | if (!Base->getType()->isSpecificPlaceholderType( | |||
4965 | BuiltinType::OMPArraySection)) { | |||
4966 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | |||
4967 | if (Result.isInvalid()) | |||
4968 | return ExprError(); | |||
4969 | Base = Result.get(); | |||
4970 | } | |||
4971 | return new (Context) OMPArraySectionExpr( | |||
4972 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | |||
4973 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | |||
4974 | } | |||
4975 | ||||
4976 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | |||
4977 | SourceLocation RParenLoc, | |||
4978 | ArrayRef<Expr *> Dims, | |||
4979 | ArrayRef<SourceRange> Brackets) { | |||
4980 | if (Base->getType()->isPlaceholderType()) { | |||
4981 | ExprResult Result = CheckPlaceholderExpr(Base); | |||
4982 | if (Result.isInvalid()) | |||
4983 | return ExprError(); | |||
4984 | Result = DefaultLvalueConversion(Result.get()); | |||
4985 | if (Result.isInvalid()) | |||
4986 | return ExprError(); | |||
4987 | Base = Result.get(); | |||
4988 | } | |||
4989 | QualType BaseTy = Base->getType(); | |||
4990 | // Delay analysis of the types/expressions if instantiation/specialization is | |||
4991 | // required. | |||
4992 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | |||
4993 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | |||
4994 | LParenLoc, RParenLoc, Dims, Brackets); | |||
4995 | if (!BaseTy->isPointerType() || | |||
4996 | (!Base->isTypeDependent() && | |||
4997 | BaseTy->getPointeeType()->isIncompleteType())) | |||
4998 | return ExprError(Diag(Base->getExprLoc(), | |||
4999 | diag::err_omp_non_pointer_type_array_shaping_base) | |||
5000 | << Base->getSourceRange()); | |||
5001 | ||||
5002 | SmallVector<Expr *, 4> NewDims; | |||
5003 | bool ErrorFound = false; | |||
5004 | for (Expr *Dim : Dims) { | |||
5005 | if (Dim->getType()->isPlaceholderType()) { | |||
5006 | ExprResult Result = CheckPlaceholderExpr(Dim); | |||
5007 | if (Result.isInvalid()) { | |||
5008 | ErrorFound = true; | |||
5009 | continue; | |||
5010 | } | |||
5011 | Result = DefaultLvalueConversion(Result.get()); | |||
5012 | if (Result.isInvalid()) { | |||
5013 | ErrorFound = true; | |||
5014 | continue; | |||
5015 | } | |||
5016 | Dim = Result.get(); | |||
5017 | } | |||
5018 | if (!Dim->isTypeDependent()) { | |||
5019 | ExprResult Result = | |||
5020 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | |||
5021 | if (Result.isInvalid()) { | |||
5022 | ErrorFound = true; | |||
5023 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | |||
5024 | << Dim->getSourceRange(); | |||
5025 | continue; | |||
5026 | } | |||
5027 | Dim = Result.get(); | |||
5028 | Expr::EvalResult EvResult; | |||
5029 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | |||
5030 | // OpenMP 5.0, [2.1.4 Array Shaping] | |||
5031 | // Each si is an integral type expression that must evaluate to a | |||
5032 | // positive integer. | |||
5033 | llvm::APSInt Value = EvResult.Val.getInt(); | |||
5034 | if (!Value.isStrictlyPositive()) { | |||
5035 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | |||
5036 | << Value.toString(/*Radix=*/10, /*Signed=*/true) | |||
5037 | << Dim->getSourceRange(); | |||
5038 | ErrorFound = true; | |||
5039 | continue; | |||
5040 | } | |||
5041 | } | |||
5042 | } | |||
5043 | NewDims.push_back(Dim); | |||
5044 | } | |||
5045 | if (ErrorFound) | |||
5046 | return ExprError(); | |||
5047 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | |||
5048 | LParenLoc, RParenLoc, NewDims, Brackets); | |||
5049 | } | |||
5050 | ||||
5051 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | |||
5052 | SourceLocation LLoc, SourceLocation RLoc, | |||
5053 | ArrayRef<OMPIteratorData> Data) { | |||
5054 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | |||
5055 | bool IsCorrect = true; | |||
5056 | for (const OMPIteratorData &D : Data) { | |||
5057 | TypeSourceInfo *TInfo = nullptr; | |||
5058 | SourceLocation StartLoc; | |||
5059 | QualType DeclTy; | |||
5060 | if (!D.Type.getAsOpaquePtr()) { | |||
5061 | // OpenMP 5.0, 2.1.6 Iterators | |||
5062 | // In an iterator-specifier, if the iterator-type is not specified then | |||
5063 | // the type of that iterator is of int type. | |||
5064 | DeclTy = Context.IntTy; | |||
5065 | StartLoc = D.DeclIdentLoc; | |||
5066 | } else { | |||
5067 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | |||
5068 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
5069 | } | |||
5070 | ||||
5071 | bool IsDeclTyDependent = DeclTy->isDependentType() || | |||
5072 | DeclTy->containsUnexpandedParameterPack() || | |||
5073 | DeclTy->isInstantiationDependentType(); | |||
5074 | if (!IsDeclTyDependent) { | |||
5075 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | |||
5076 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | |||
5077 | // The iterator-type must be an integral or pointer type. | |||
5078 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | |||
5079 | << DeclTy; | |||
5080 | IsCorrect = false; | |||
5081 | continue; | |||
5082 | } | |||
5083 | if (DeclTy.isConstant(Context)) { | |||
5084 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | |||
5085 | // The iterator-type must not be const qualified. | |||
5086 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | |||
5087 | << DeclTy; | |||
5088 | IsCorrect = false; | |||
5089 | continue; | |||
5090 | } | |||
5091 | } | |||
5092 | ||||
5093 | // Iterator declaration. | |||
5094 | assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast <void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5094, __PRETTY_FUNCTION__)); | |||
5095 | // Always try to create iterator declarator to avoid extra error messages | |||
5096 | // about unknown declarations use. | |||
5097 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | |||
5098 | D.DeclIdent, DeclTy, TInfo, SC_None); | |||
5099 | VD->setImplicit(); | |||
5100 | if (S) { | |||
5101 | // Check for conflicting previous declaration. | |||
5102 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | |||
5103 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
5104 | ForVisibleRedeclaration); | |||
5105 | Previous.suppressDiagnostics(); | |||
5106 | LookupName(Previous, S); | |||
5107 | ||||
5108 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | |||
5109 | /*AllowInlineNamespace=*/false); | |||
5110 | if (!Previous.empty()) { | |||
5111 | NamedDecl *Old = Previous.getRepresentativeDecl(); | |||
5112 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | |||
5113 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
5114 | } else { | |||
5115 | PushOnScopeChains(VD, S); | |||
5116 | } | |||
5117 | } else { | |||
5118 | CurContext->addDecl(VD); | |||
5119 | } | |||
5120 | Expr *Begin = D.Range.Begin; | |||
5121 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | |||
5122 | ExprResult BeginRes = | |||
5123 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | |||
5124 | Begin = BeginRes.get(); | |||
5125 | } | |||
5126 | Expr *End = D.Range.End; | |||
5127 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | |||
5128 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | |||
5129 | End = EndRes.get(); | |||
5130 | } | |||
5131 | Expr *Step = D.Range.Step; | |||
5132 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | |||
5133 | if (!Step->getType()->isIntegralType(Context)) { | |||
5134 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | |||
5135 | << Step << Step->getSourceRange(); | |||
5136 | IsCorrect = false; | |||
5137 | continue; | |||
5138 | } | |||
5139 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | |||
5140 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | |||
5141 | // If the step expression of a range-specification equals zero, the | |||
5142 | // behavior is unspecified. | |||
5143 | if (Result && Result->isNullValue()) { | |||
5144 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | |||
5145 | << Step << Step->getSourceRange(); | |||
5146 | IsCorrect = false; | |||
5147 | continue; | |||
5148 | } | |||
5149 | } | |||
5150 | if (!Begin || !End || !IsCorrect) { | |||
5151 | IsCorrect = false; | |||
5152 | continue; | |||
5153 | } | |||
5154 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | |||
5155 | IDElem.IteratorDecl = VD; | |||
5156 | IDElem.AssignmentLoc = D.AssignLoc; | |||
5157 | IDElem.Range.Begin = Begin; | |||
5158 | IDElem.Range.End = End; | |||
5159 | IDElem.Range.Step = Step; | |||
5160 | IDElem.ColonLoc = D.ColonLoc; | |||
5161 | IDElem.SecondColonLoc = D.SecColonLoc; | |||
5162 | } | |||
5163 | if (!IsCorrect) { | |||
5164 | // Invalidate all created iterator declarations if error is found. | |||
5165 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | |||
5166 | if (Decl *ID = D.IteratorDecl) | |||
5167 | ID->setInvalidDecl(); | |||
5168 | } | |||
5169 | return ExprError(); | |||
5170 | } | |||
5171 | SmallVector<OMPIteratorHelperData, 4> Helpers; | |||
5172 | if (!CurContext->isDependentContext()) { | |||
5173 | // Build number of ityeration for each iteration range. | |||
5174 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | |||
5175 | // ((Begini-Stepi-1-Endi) / -Stepi); | |||
5176 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | |||
5177 | // (Endi - Begini) | |||
5178 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | |||
5179 | D.Range.Begin); | |||
5180 | if(!Res.isUsable()) { | |||
5181 | IsCorrect = false; | |||
5182 | continue; | |||
5183 | } | |||
5184 | ExprResult St, St1; | |||
5185 | if (D.Range.Step) { | |||
5186 | St = D.Range.Step; | |||
5187 | // (Endi - Begini) + Stepi | |||
5188 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | |||
5189 | if (!Res.isUsable()) { | |||
5190 | IsCorrect = false; | |||
5191 | continue; | |||
5192 | } | |||
5193 | // (Endi - Begini) + Stepi - 1 | |||
5194 | Res = | |||
5195 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | |||
5196 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | |||
5197 | if (!Res.isUsable()) { | |||
5198 | IsCorrect = false; | |||
5199 | continue; | |||
5200 | } | |||
5201 | // ((Endi - Begini) + Stepi - 1) / Stepi | |||
5202 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | |||
5203 | if (!Res.isUsable()) { | |||
5204 | IsCorrect = false; | |||
5205 | continue; | |||
5206 | } | |||
5207 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | |||
5208 | // (Begini - Endi) | |||
5209 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | |||
5210 | D.Range.Begin, D.Range.End); | |||
5211 | if (!Res1.isUsable()) { | |||
5212 | IsCorrect = false; | |||
5213 | continue; | |||
5214 | } | |||
5215 | // (Begini - Endi) - Stepi | |||
5216 | Res1 = | |||
5217 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | |||
5218 | if (!Res1.isUsable()) { | |||
5219 | IsCorrect = false; | |||
5220 | continue; | |||
5221 | } | |||
5222 | // (Begini - Endi) - Stepi - 1 | |||
5223 | Res1 = | |||
5224 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | |||
5225 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | |||
5226 | if (!Res1.isUsable()) { | |||
5227 | IsCorrect = false; | |||
5228 | continue; | |||
5229 | } | |||
5230 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | |||
5231 | Res1 = | |||
5232 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | |||
5233 | if (!Res1.isUsable()) { | |||
5234 | IsCorrect = false; | |||
5235 | continue; | |||
5236 | } | |||
5237 | // Stepi > 0. | |||
5238 | ExprResult CmpRes = | |||
5239 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | |||
5240 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | |||
5241 | if (!CmpRes.isUsable()) { | |||
5242 | IsCorrect = false; | |||
5243 | continue; | |||
5244 | } | |||
5245 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | |||
5246 | Res.get(), Res1.get()); | |||
5247 | if (!Res.isUsable()) { | |||
5248 | IsCorrect = false; | |||
5249 | continue; | |||
5250 | } | |||
5251 | } | |||
5252 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | |||
5253 | if (!Res.isUsable()) { | |||
5254 | IsCorrect = false; | |||
5255 | continue; | |||
5256 | } | |||
5257 | ||||
5258 | // Build counter update. | |||
5259 | // Build counter. | |||
5260 | auto *CounterVD = | |||
5261 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | |||
5262 | D.IteratorDecl->getBeginLoc(), nullptr, | |||
5263 | Res.get()->getType(), nullptr, SC_None); | |||
5264 | CounterVD->setImplicit(); | |||
5265 | ExprResult RefRes = | |||
5266 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | |||
5267 | D.IteratorDecl->getBeginLoc()); | |||
5268 | // Build counter update. | |||
5269 | // I = Begini + counter * Stepi; | |||
5270 | ExprResult UpdateRes; | |||
5271 | if (D.Range.Step) { | |||
5272 | UpdateRes = CreateBuiltinBinOp( | |||
5273 | D.AssignmentLoc, BO_Mul, | |||
5274 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | |||
5275 | } else { | |||
5276 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | |||
5277 | } | |||
5278 | if (!UpdateRes.isUsable()) { | |||
5279 | IsCorrect = false; | |||
5280 | continue; | |||
5281 | } | |||
5282 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | |||
5283 | UpdateRes.get()); | |||
5284 | if (!UpdateRes.isUsable()) { | |||
5285 | IsCorrect = false; | |||
5286 | continue; | |||
5287 | } | |||
5288 | ExprResult VDRes = | |||
5289 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | |||
5290 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | |||
5291 | D.IteratorDecl->getBeginLoc()); | |||
5292 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | |||
5293 | UpdateRes.get()); | |||
5294 | if (!UpdateRes.isUsable()) { | |||
5295 | IsCorrect = false; | |||
5296 | continue; | |||
5297 | } | |||
5298 | UpdateRes = | |||
5299 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | |||
5300 | if (!UpdateRes.isUsable()) { | |||
5301 | IsCorrect = false; | |||
5302 | continue; | |||
5303 | } | |||
5304 | ExprResult CounterUpdateRes = | |||
5305 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | |||
5306 | if (!CounterUpdateRes.isUsable()) { | |||
5307 | IsCorrect = false; | |||
5308 | continue; | |||
5309 | } | |||
5310 | CounterUpdateRes = | |||
5311 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | |||
5312 | if (!CounterUpdateRes.isUsable()) { | |||
5313 | IsCorrect = false; | |||
5314 | continue; | |||
5315 | } | |||
5316 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | |||
5317 | HD.CounterVD = CounterVD; | |||
5318 | HD.Upper = Res.get(); | |||
5319 | HD.Update = UpdateRes.get(); | |||
5320 | HD.CounterUpdate = CounterUpdateRes.get(); | |||
5321 | } | |||
5322 | } else { | |||
5323 | Helpers.assign(ID.size(), {}); | |||
5324 | } | |||
5325 | if (!IsCorrect) { | |||
5326 | // Invalidate all created iterator declarations if error is found. | |||
5327 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | |||
5328 | if (Decl *ID = D.IteratorDecl) | |||
5329 | ID->setInvalidDecl(); | |||
5330 | } | |||
5331 | return ExprError(); | |||
5332 | } | |||
5333 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | |||
5334 | LLoc, RLoc, ID, Helpers); | |||
5335 | } | |||
5336 | ||||
5337 | ExprResult | |||
5338 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | |||
5339 | Expr *Idx, SourceLocation RLoc) { | |||
5340 | Expr *LHSExp = Base; | |||
5341 | Expr *RHSExp = Idx; | |||
5342 | ||||
5343 | ExprValueKind VK = VK_LValue; | |||
5344 | ExprObjectKind OK = OK_Ordinary; | |||
5345 | ||||
5346 | // Per C++ core issue 1213, the result is an xvalue if either operand is | |||
5347 | // a non-lvalue array, and an lvalue otherwise. | |||
5348 | if (getLangOpts().CPlusPlus11) { | |||
5349 | for (auto *Op : {LHSExp, RHSExp}) { | |||
5350 | Op = Op->IgnoreImplicit(); | |||
5351 | if (Op->getType()->isArrayType() && !Op->isLValue()) | |||
5352 | VK = VK_XValue; | |||
5353 | } | |||
5354 | } | |||
5355 | ||||
5356 | // Perform default conversions. | |||
5357 | if (!LHSExp->getType()->getAs<VectorType>()) { | |||
5358 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | |||
5359 | if (Result.isInvalid()) | |||
5360 | return ExprError(); | |||
5361 | LHSExp = Result.get(); | |||
5362 | } | |||
5363 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | |||
5364 | if (Result.isInvalid()) | |||
5365 | return ExprError(); | |||
5366 | RHSExp = Result.get(); | |||
5367 | ||||
5368 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | |||
5369 | ||||
5370 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | |||
5371 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | |||
5372 | // in the subscript position. As a result, we need to derive the array base | |||
5373 | // and index from the expression types. | |||
5374 | Expr *BaseExpr, *IndexExpr; | |||
5375 | QualType ResultType; | |||
5376 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | |||
5377 | BaseExpr = LHSExp; | |||
5378 | IndexExpr = RHSExp; | |||
5379 | ResultType = Context.DependentTy; | |||
5380 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | |||
5381 | BaseExpr = LHSExp; | |||
5382 | IndexExpr = RHSExp; | |||
5383 | ResultType = PTy->getPointeeType(); | |||
5384 | } else if (const ObjCObjectPointerType *PTy = | |||
5385 | LHSTy->getAs<ObjCObjectPointerType>()) { | |||
5386 | BaseExpr = LHSExp; | |||
5387 | IndexExpr = RHSExp; | |||
5388 | ||||
5389 | // Use custom logic if this should be the pseudo-object subscript | |||
5390 | // expression. | |||
5391 | if (!LangOpts.isSubscriptPointerArithmetic()) | |||
5392 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | |||
5393 | nullptr); | |||
5394 | ||||
5395 | ResultType = PTy->getPointeeType(); | |||
5396 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | |||
5397 | // Handle the uncommon case of "123[Ptr]". | |||
5398 | BaseExpr = RHSExp; | |||
5399 | IndexExpr = LHSExp; | |||
5400 | ResultType = PTy->getPointeeType(); | |||
5401 | } else if (const ObjCObjectPointerType *PTy = | |||
5402 | RHSTy->getAs<ObjCObjectPointerType>()) { | |||
5403 | // Handle the uncommon case of "123[Ptr]". | |||
5404 | BaseExpr = RHSExp; | |||
5405 | IndexExpr = LHSExp; | |||
5406 | ResultType = PTy->getPointeeType(); | |||
5407 | if (!LangOpts.isSubscriptPointerArithmetic()) { | |||
5408 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | |||
5409 | << ResultType << BaseExpr->getSourceRange(); | |||
5410 | return ExprError(); | |||
5411 | } | |||
5412 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | |||
5413 | BaseExpr = LHSExp; // vectors: V[123] | |||
5414 | IndexExpr = RHSExp; | |||
5415 | // We apply C++ DR1213 to vector subscripting too. | |||
5416 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | |||
5417 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | |||
5418 | if (Materialized.isInvalid()) | |||
5419 | return ExprError(); | |||
5420 | LHSExp = Materialized.get(); | |||
5421 | } | |||
5422 | VK = LHSExp->getValueKind(); | |||
5423 | if (VK != VK_RValue) | |||
5424 | OK = OK_VectorComponent; | |||
5425 | ||||
5426 | ResultType = VTy->getElementType(); | |||
5427 | QualType BaseType = BaseExpr->getType(); | |||
5428 | Qualifiers BaseQuals = BaseType.getQualifiers(); | |||
5429 | Qualifiers MemberQuals = ResultType.getQualifiers(); | |||
5430 | Qualifiers Combined = BaseQuals + MemberQuals; | |||
5431 | if (Combined != MemberQuals) | |||
5432 | ResultType = Context.getQualifiedType(ResultType, Combined); | |||
5433 | } else if (LHSTy->isArrayType()) { | |||
5434 | // If we see an array that wasn't promoted by | |||
5435 | // DefaultFunctionArrayLvalueConversion, it must be an array that | |||
5436 | // wasn't promoted because of the C90 rule that doesn't | |||
5437 | // allow promoting non-lvalue arrays. Warn, then | |||
5438 | // force the promotion here. | |||
5439 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | |||
5440 | << LHSExp->getSourceRange(); | |||
5441 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | |||
5442 | CK_ArrayToPointerDecay).get(); | |||
5443 | LHSTy = LHSExp->getType(); | |||
5444 | ||||
5445 | BaseExpr = LHSExp; | |||
5446 | IndexExpr = RHSExp; | |||
5447 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | |||
5448 | } else if (RHSTy->isArrayType()) { | |||
5449 | // Same as previous, except for 123[f().a] case | |||
5450 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | |||
5451 | << RHSExp->getSourceRange(); | |||
5452 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | |||
5453 | CK_ArrayToPointerDecay).get(); | |||
5454 | RHSTy = RHSExp->getType(); | |||
5455 | ||||
5456 | BaseExpr = RHSExp; | |||
5457 | IndexExpr = LHSExp; | |||
5458 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | |||
5459 | } else { | |||
5460 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | |||
5461 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | |||
5462 | } | |||
5463 | // C99 6.5.2.1p1 | |||
5464 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | |||
5465 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | |||
5466 | << IndexExpr->getSourceRange()); | |||
5467 | ||||
5468 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
5469 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
5470 | && !IndexExpr->isTypeDependent()) | |||
5471 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | |||
5472 | ||||
5473 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
5474 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
5475 | // type. Note that Functions are not objects, and that (in C99 parlance) | |||
5476 | // incomplete types are not object types. | |||
5477 | if (ResultType->isFunctionType()) { | |||
5478 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | |||
5479 | << ResultType << BaseExpr->getSourceRange(); | |||
5480 | return ExprError(); | |||
5481 | } | |||
5482 | ||||
5483 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | |||
5484 | // GNU extension: subscripting on pointer to void | |||
5485 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | |||
5486 | << BaseExpr->getSourceRange(); | |||
5487 | ||||
5488 | // C forbids expressions of unqualified void type from being l-values. | |||
5489 | // See IsCForbiddenLValueType. | |||
5490 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | |||
5491 | } else if (!ResultType->isDependentType() && | |||
5492 | RequireCompleteSizedType( | |||
5493 | LLoc, ResultType, | |||
5494 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | |||
5495 | return ExprError(); | |||
5496 | ||||
5497 | assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5498, __PRETTY_FUNCTION__)) | |||
5498 | !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5498, __PRETTY_FUNCTION__)); | |||
5499 | ||||
5500 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | |||
5501 | FunctionScopes.size() > 1) { | |||
5502 | if (auto *TT = | |||
5503 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | |||
5504 | for (auto I = FunctionScopes.rbegin(), | |||
5505 | E = std::prev(FunctionScopes.rend()); | |||
5506 | I != E; ++I) { | |||
5507 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
5508 | if (CSI == nullptr) | |||
5509 | break; | |||
5510 | DeclContext *DC = nullptr; | |||
5511 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
5512 | DC = LSI->CallOperator; | |||
5513 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
5514 | DC = CRSI->TheCapturedDecl; | |||
5515 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
5516 | DC = BSI->TheDecl; | |||
5517 | if (DC) { | |||
5518 | if (DC->containsDecl(TT->getDecl())) | |||
5519 | break; | |||
5520 | captureVariablyModifiedType( | |||
5521 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | |||
5522 | } | |||
5523 | } | |||
5524 | } | |||
5525 | } | |||
5526 | ||||
5527 | return new (Context) | |||
5528 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | |||
5529 | } | |||
5530 | ||||
5531 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | |||
5532 | ParmVarDecl *Param) { | |||
5533 | if (Param->hasUnparsedDefaultArg()) { | |||
5534 | // If we've already cleared out the location for the default argument, | |||
5535 | // that means we're parsing it right now. | |||
5536 | if (!UnparsedDefaultArgLocs.count(Param)) { | |||
5537 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | |||
5538 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | |||
5539 | Param->setInvalidDecl(); | |||
5540 | return true; | |||
5541 | } | |||
5542 | ||||
5543 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | |||
5544 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | |||
5545 | Diag(UnparsedDefaultArgLocs[Param], | |||
5546 | diag::note_default_argument_declared_here); | |||
5547 | return true; | |||
5548 | } | |||
5549 | ||||
5550 | if (Param->hasUninstantiatedDefaultArg() && | |||
5551 | InstantiateDefaultArgument(CallLoc, FD, Param)) | |||
5552 | return true; | |||
5553 | ||||
5554 | assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?" ) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5554, __PRETTY_FUNCTION__)); | |||
5555 | ||||
5556 | // If the default expression creates temporaries, we need to | |||
5557 | // push them to the current stack of expression temporaries so they'll | |||
5558 | // be properly destroyed. | |||
5559 | // FIXME: We should really be rebuilding the default argument with new | |||
5560 | // bound temporaries; see the comment in PR5810. | |||
5561 | // We don't need to do that with block decls, though, because | |||
5562 | // blocks in default argument expression can never capture anything. | |||
5563 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | |||
5564 | // Set the "needs cleanups" bit regardless of whether there are | |||
5565 | // any explicit objects. | |||
5566 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | |||
5567 | ||||
5568 | // Append all the objects to the cleanup list. Right now, this | |||
5569 | // should always be a no-op, because blocks in default argument | |||
5570 | // expressions should never be able to capture anything. | |||
5571 | assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5572, __PRETTY_FUNCTION__)) | |||
5572 | "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5572, __PRETTY_FUNCTION__)); | |||
5573 | } | |||
5574 | ||||
5575 | // We already type-checked the argument, so we know it works. | |||
5576 | // Just mark all of the declarations in this potentially-evaluated expression | |||
5577 | // as being "referenced". | |||
5578 | EnterExpressionEvaluationContext EvalContext( | |||
5579 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | |||
5580 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | |||
5581 | /*SkipLocalVariables=*/true); | |||
5582 | return false; | |||
5583 | } | |||
5584 | ||||
5585 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | |||
5586 | FunctionDecl *FD, ParmVarDecl *Param) { | |||
5587 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg" ) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5587, __PRETTY_FUNCTION__)); | |||
5588 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | |||
5589 | return ExprError(); | |||
5590 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | |||
5591 | } | |||
5592 | ||||
5593 | Sema::VariadicCallType | |||
5594 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | |||
5595 | Expr *Fn) { | |||
5596 | if (Proto && Proto->isVariadic()) { | |||
5597 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | |||
5598 | return VariadicConstructor; | |||
5599 | else if (Fn && Fn->getType()->isBlockPointerType()) | |||
5600 | return VariadicBlock; | |||
5601 | else if (FDecl) { | |||
5602 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
5603 | if (Method->isInstance()) | |||
5604 | return VariadicMethod; | |||
5605 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | |||
5606 | return VariadicMethod; | |||
5607 | return VariadicFunction; | |||
5608 | } | |||
5609 | return VariadicDoesNotApply; | |||
5610 | } | |||
5611 | ||||
5612 | namespace { | |||
5613 | class FunctionCallCCC final : public FunctionCallFilterCCC { | |||
5614 | public: | |||
5615 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | |||
5616 | unsigned NumArgs, MemberExpr *ME) | |||
5617 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | |||
5618 | FunctionName(FuncName) {} | |||
5619 | ||||
5620 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
5621 | if (!candidate.getCorrectionSpecifier() || | |||
5622 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | |||
5623 | return false; | |||
5624 | } | |||
5625 | ||||
5626 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | |||
5627 | } | |||
5628 | ||||
5629 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
5630 | return std::make_unique<FunctionCallCCC>(*this); | |||
5631 | } | |||
5632 | ||||
5633 | private: | |||
5634 | const IdentifierInfo *const FunctionName; | |||
5635 | }; | |||
5636 | } | |||
5637 | ||||
5638 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | |||
5639 | FunctionDecl *FDecl, | |||
5640 | ArrayRef<Expr *> Args) { | |||
5641 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | |||
5642 | DeclarationName FuncName = FDecl->getDeclName(); | |||
5643 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | |||
5644 | ||||
5645 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | |||
5646 | if (TypoCorrection Corrected = S.CorrectTypo( | |||
5647 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | |||
5648 | S.getScopeForContext(S.CurContext), nullptr, CCC, | |||
5649 | Sema::CTK_ErrorRecovery)) { | |||
5650 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | |||
5651 | if (Corrected.isOverloaded()) { | |||
5652 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | |||
5653 | OverloadCandidateSet::iterator Best; | |||
5654 | for (NamedDecl *CD : Corrected) { | |||
5655 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
5656 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | |||
5657 | OCS); | |||
5658 | } | |||
5659 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | |||
5660 | case OR_Success: | |||
5661 | ND = Best->FoundDecl; | |||
5662 | Corrected.setCorrectionDecl(ND); | |||
5663 | break; | |||
5664 | default: | |||
5665 | break; | |||
5666 | } | |||
5667 | } | |||
5668 | ND = ND->getUnderlyingDecl(); | |||
5669 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | |||
5670 | return Corrected; | |||
5671 | } | |||
5672 | } | |||
5673 | return TypoCorrection(); | |||
5674 | } | |||
5675 | ||||
5676 | /// ConvertArgumentsForCall - Converts the arguments specified in | |||
5677 | /// Args/NumArgs to the parameter types of the function FDecl with | |||
5678 | /// function prototype Proto. Call is the call expression itself, and | |||
5679 | /// Fn is the function expression. For a C++ member function, this | |||
5680 | /// routine does not attempt to convert the object argument. Returns | |||
5681 | /// true if the call is ill-formed. | |||
5682 | bool | |||
5683 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | |||
5684 | FunctionDecl *FDecl, | |||
5685 | const FunctionProtoType *Proto, | |||
5686 | ArrayRef<Expr *> Args, | |||
5687 | SourceLocation RParenLoc, | |||
5688 | bool IsExecConfig) { | |||
5689 | // Bail out early if calling a builtin with custom typechecking. | |||
5690 | if (FDecl) | |||
5691 | if (unsigned ID = FDecl->getBuiltinID()) | |||
5692 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | |||
5693 | return false; | |||
5694 | ||||
5695 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | |||
5696 | // assignment, to the types of the corresponding parameter, ... | |||
5697 | unsigned NumParams = Proto->getNumParams(); | |||
5698 | bool Invalid = false; | |||
5699 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | |||
5700 | unsigned FnKind = Fn->getType()->isBlockPointerType() | |||
5701 | ? 1 /* block */ | |||
5702 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | |||
5703 | : 0 /* function */); | |||
5704 | ||||
5705 | // If too few arguments are available (and we don't have default | |||
5706 | // arguments for the remaining parameters), don't make the call. | |||
5707 | if (Args.size() < NumParams) { | |||
5708 | if (Args.size() < MinArgs) { | |||
5709 | TypoCorrection TC; | |||
5710 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
5711 | unsigned diag_id = | |||
5712 | MinArgs == NumParams && !Proto->isVariadic() | |||
5713 | ? diag::err_typecheck_call_too_few_args_suggest | |||
5714 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | |||
5715 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | |||
5716 | << static_cast<unsigned>(Args.size()) | |||
5717 | << TC.getCorrectionRange()); | |||
5718 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | |||
5719 | Diag(RParenLoc, | |||
5720 | MinArgs == NumParams && !Proto->isVariadic() | |||
5721 | ? diag::err_typecheck_call_too_few_args_one | |||
5722 | : diag::err_typecheck_call_too_few_args_at_least_one) | |||
5723 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | |||
5724 | else | |||
5725 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | |||
5726 | ? diag::err_typecheck_call_too_few_args | |||
5727 | : diag::err_typecheck_call_too_few_args_at_least) | |||
5728 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | |||
5729 | << Fn->getSourceRange(); | |||
5730 | ||||
5731 | // Emit the location of the prototype. | |||
5732 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
5733 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | |||
5734 | ||||
5735 | return true; | |||
5736 | } | |||
5737 | // We reserve space for the default arguments when we create | |||
5738 | // the call expression, before calling ConvertArgumentsForCall. | |||
5739 | assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5740, __PRETTY_FUNCTION__)) | |||
5740 | "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5740, __PRETTY_FUNCTION__)); | |||
5741 | } | |||
5742 | ||||
5743 | // If too many are passed and not variadic, error on the extras and drop | |||
5744 | // them. | |||
5745 | if (Args.size() > NumParams) { | |||
5746 | if (!Proto->isVariadic()) { | |||
5747 | TypoCorrection TC; | |||
5748 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
5749 | unsigned diag_id = | |||
5750 | MinArgs == NumParams && !Proto->isVariadic() | |||
5751 | ? diag::err_typecheck_call_too_many_args_suggest | |||
5752 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | |||
5753 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | |||
5754 | << static_cast<unsigned>(Args.size()) | |||
5755 | << TC.getCorrectionRange()); | |||
5756 | } else if (NumParams == 1 && FDecl && | |||
5757 | FDecl->getParamDecl(0)->getDeclName()) | |||
5758 | Diag(Args[NumParams]->getBeginLoc(), | |||
5759 | MinArgs == NumParams | |||
5760 | ? diag::err_typecheck_call_too_many_args_one | |||
5761 | : diag::err_typecheck_call_too_many_args_at_most_one) | |||
5762 | << FnKind << FDecl->getParamDecl(0) | |||
5763 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | |||
5764 | << SourceRange(Args[NumParams]->getBeginLoc(), | |||
5765 | Args.back()->getEndLoc()); | |||
5766 | else | |||
5767 | Diag(Args[NumParams]->getBeginLoc(), | |||
5768 | MinArgs == NumParams | |||
5769 | ? diag::err_typecheck_call_too_many_args | |||
5770 | : diag::err_typecheck_call_too_many_args_at_most) | |||
5771 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | |||
5772 | << Fn->getSourceRange() | |||
5773 | << SourceRange(Args[NumParams]->getBeginLoc(), | |||
5774 | Args.back()->getEndLoc()); | |||
5775 | ||||
5776 | // Emit the location of the prototype. | |||
5777 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
5778 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | |||
5779 | ||||
5780 | // This deletes the extra arguments. | |||
5781 | Call->shrinkNumArgs(NumParams); | |||
5782 | return true; | |||
5783 | } | |||
5784 | } | |||
5785 | SmallVector<Expr *, 8> AllArgs; | |||
5786 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | |||
5787 | ||||
5788 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | |||
5789 | AllArgs, CallType); | |||
5790 | if (Invalid) | |||
5791 | return true; | |||
5792 | unsigned TotalNumArgs = AllArgs.size(); | |||
5793 | for (unsigned i = 0; i < TotalNumArgs; ++i) | |||
5794 | Call->setArg(i, AllArgs[i]); | |||
5795 | ||||
5796 | return false; | |||
5797 | } | |||
5798 | ||||
5799 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | |||
5800 | const FunctionProtoType *Proto, | |||
5801 | unsigned FirstParam, ArrayRef<Expr *> Args, | |||
5802 | SmallVectorImpl<Expr *> &AllArgs, | |||
5803 | VariadicCallType CallType, bool AllowExplicit, | |||
5804 | bool IsListInitialization) { | |||
5805 | unsigned NumParams = Proto->getNumParams(); | |||
5806 | bool Invalid = false; | |||
5807 | size_t ArgIx = 0; | |||
5808 | // Continue to check argument types (even if we have too few/many args). | |||
5809 | for (unsigned i = FirstParam; i < NumParams; i++) { | |||
5810 | QualType ProtoArgType = Proto->getParamType(i); | |||
5811 | ||||
5812 | Expr *Arg; | |||
5813 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | |||
5814 | if (ArgIx < Args.size()) { | |||
5815 | Arg = Args[ArgIx++]; | |||
5816 | ||||
5817 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | |||
5818 | diag::err_call_incomplete_argument, Arg)) | |||
5819 | return true; | |||
5820 | ||||
5821 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
5822 | bool CFAudited = false; | |||
5823 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | |||
5824 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
5825 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
5826 | Arg = stripARCUnbridgedCast(Arg); | |||
5827 | else if (getLangOpts().ObjCAutoRefCount && | |||
5828 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
5829 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
5830 | CFAudited = true; | |||
5831 | ||||
5832 | if (Proto->getExtParameterInfo(i).isNoEscape()) | |||
5833 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | |||
5834 | BE->getBlockDecl()->setDoesNotEscape(); | |||
5835 | ||||
5836 | InitializedEntity Entity = | |||
5837 | Param ? InitializedEntity::InitializeParameter(Context, Param, | |||
5838 | ProtoArgType) | |||
5839 | : InitializedEntity::InitializeParameter( | |||
5840 | Context, ProtoArgType, Proto->isParamConsumed(i)); | |||
5841 | ||||
5842 | // Remember that parameter belongs to a CF audited API. | |||
5843 | if (CFAudited) | |||
5844 | Entity.setParameterCFAudited(); | |||
5845 | ||||
5846 | ExprResult ArgE = PerformCopyInitialization( | |||
5847 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | |||
5848 | if (ArgE.isInvalid()) | |||
5849 | return true; | |||
5850 | ||||
5851 | Arg = ArgE.getAs<Expr>(); | |||
5852 | } else { | |||
5853 | assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee" ) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 5853, __PRETTY_FUNCTION__)); | |||
5854 | ||||
5855 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | |||
5856 | if (ArgExpr.isInvalid()) | |||
5857 | return true; | |||
5858 | ||||
5859 | Arg = ArgExpr.getAs<Expr>(); | |||
5860 | } | |||
5861 | ||||
5862 | // Check for array bounds violations for each argument to the call. This | |||
5863 | // check only triggers warnings when the argument isn't a more complex Expr | |||
5864 | // with its own checking, such as a BinaryOperator. | |||
5865 | CheckArrayAccess(Arg); | |||
5866 | ||||
5867 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | |||
5868 | CheckStaticArrayArgument(CallLoc, Param, Arg); | |||
5869 | ||||
5870 | AllArgs.push_back(Arg); | |||
5871 | } | |||
5872 | ||||
5873 | // If this is a variadic call, handle args passed through "...". | |||
5874 | if (CallType != VariadicDoesNotApply) { | |||
5875 | // Assume that extern "C" functions with variadic arguments that | |||
5876 | // return __unknown_anytype aren't *really* variadic. | |||
5877 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | |||
5878 | FDecl->isExternC()) { | |||
5879 | for (Expr *A : Args.slice(ArgIx)) { | |||
5880 | QualType paramType; // ignored | |||
5881 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | |||
5882 | Invalid |= arg.isInvalid(); | |||
5883 | AllArgs.push_back(arg.get()); | |||
5884 | } | |||
5885 | ||||
5886 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | |||
5887 | } else { | |||
5888 | for (Expr *A : Args.slice(ArgIx)) { | |||
5889 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | |||
5890 | Invalid |= Arg.isInvalid(); | |||
5891 | AllArgs.push_back(Arg.get()); | |||
5892 | } | |||
5893 | } | |||
5894 | ||||
5895 | // Check for array bounds violations. | |||
5896 | for (Expr *A : Args.slice(ArgIx)) | |||
5897 | CheckArrayAccess(A); | |||
5898 | } | |||
5899 | return Invalid; | |||
5900 | } | |||
5901 | ||||
5902 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | |||
5903 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | |||
5904 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | |||
5905 | TL = DTL.getOriginalLoc(); | |||
5906 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | |||
5907 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | |||
5908 | << ATL.getLocalSourceRange(); | |||
5909 | } | |||
5910 | ||||
5911 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | |||
5912 | /// array parameter, check that it is non-null, and that if it is formed by | |||
5913 | /// array-to-pointer decay, the underlying array is sufficiently large. | |||
5914 | /// | |||
5915 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | |||
5916 | /// array type derivation, then for each call to the function, the value of the | |||
5917 | /// corresponding actual argument shall provide access to the first element of | |||
5918 | /// an array with at least as many elements as specified by the size expression. | |||
5919 | void | |||
5920 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | |||
5921 | ParmVarDecl *Param, | |||
5922 | const Expr *ArgExpr) { | |||
5923 | // Static array parameters are not supported in C++. | |||
5924 | if (!Param || getLangOpts().CPlusPlus) | |||
5925 | return; | |||
5926 | ||||
5927 | QualType OrigTy = Param->getOriginalType(); | |||
5928 | ||||
5929 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | |||
5930 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | |||
5931 | return; | |||
5932 | ||||
5933 | if (ArgExpr->isNullPointerConstant(Context, | |||
5934 | Expr::NPC_NeverValueDependent)) { | |||
5935 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | |||
5936 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
5937 | return; | |||
5938 | } | |||
5939 | ||||
5940 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | |||
5941 | if (!CAT) | |||
5942 | return; | |||
5943 | ||||
5944 | const ConstantArrayType *ArgCAT = | |||
5945 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | |||
5946 | if (!ArgCAT) | |||
5947 | return; | |||
5948 | ||||
5949 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | |||
5950 | ArgCAT->getElementType())) { | |||
5951 | if (ArgCAT->getSize().ult(CAT->getSize())) { | |||
5952 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
5953 | << ArgExpr->getSourceRange() | |||
5954 | << (unsigned)ArgCAT->getSize().getZExtValue() | |||
5955 | << (unsigned)CAT->getSize().getZExtValue() << 0; | |||
5956 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
5957 | } | |||
5958 | return; | |||
5959 | } | |||
5960 | ||||
5961 | Optional<CharUnits> ArgSize = | |||
5962 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | |||
5963 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | |||
5964 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | |||
5965 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
5966 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | |||
5967 | << (unsigned)ParmSize->getQuantity() << 1; | |||
5968 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
5969 | } | |||
5970 | } | |||
5971 | ||||
5972 | /// Given a function expression of unknown-any type, try to rebuild it | |||
5973 | /// to have a function type. | |||
5974 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | |||
5975 | ||||
5976 | /// Is the given type a placeholder that we need to lower out | |||
5977 | /// immediately during argument processing? | |||
5978 | static bool isPlaceholderToRemoveAsArg(QualType type) { | |||
5979 | // Placeholders are never sugared. | |||
5980 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | |||
5981 | if (!placeholder) return false; | |||
5982 | ||||
5983 | switch (placeholder->getKind()) { | |||
5984 | // Ignore all the non-placeholder types. | |||
5985 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
5986 | case BuiltinType::Id: | |||
5987 | #include "clang/Basic/OpenCLImageTypes.def" | |||
5988 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
5989 | case BuiltinType::Id: | |||
5990 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
5991 | // In practice we'll never use this, since all SVE types are sugared | |||
5992 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | |||
5993 | #define SVE_TYPE(Name, Id, SingletonId) \ | |||
5994 | case BuiltinType::Id: | |||
5995 | #include "clang/Basic/AArch64SVEACLETypes.def" | |||
5996 | #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ | |||
5997 | case BuiltinType::Id: | |||
5998 | #include "clang/Basic/PPCTypes.def" | |||
5999 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | |||
6000 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | |||
6001 | #include "clang/AST/BuiltinTypes.def" | |||
6002 | return false; | |||
6003 | ||||
6004 | // We cannot lower out overload sets; they might validly be resolved | |||
6005 | // by the call machinery. | |||
6006 | case BuiltinType::Overload: | |||
6007 | return false; | |||
6008 | ||||
6009 | // Unbridged casts in ARC can be handled in some call positions and | |||
6010 | // should be left in place. | |||
6011 | case BuiltinType::ARCUnbridgedCast: | |||
6012 | return false; | |||
6013 | ||||
6014 | // Pseudo-objects should be converted as soon as possible. | |||
6015 | case BuiltinType::PseudoObject: | |||
6016 | return true; | |||
6017 | ||||
6018 | // The debugger mode could theoretically but currently does not try | |||
6019 | // to resolve unknown-typed arguments based on known parameter types. | |||
6020 | case BuiltinType::UnknownAny: | |||
6021 | return true; | |||
6022 | ||||
6023 | // These are always invalid as call arguments and should be reported. | |||
6024 | case BuiltinType::BoundMember: | |||
6025 | case BuiltinType::BuiltinFn: | |||
6026 | case BuiltinType::IncompleteMatrixIdx: | |||
6027 | case BuiltinType::OMPArraySection: | |||
6028 | case BuiltinType::OMPArrayShaping: | |||
6029 | case BuiltinType::OMPIterator: | |||
6030 | return true; | |||
6031 | ||||
6032 | } | |||
6033 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6033); | |||
6034 | } | |||
6035 | ||||
6036 | /// Check an argument list for placeholders that we won't try to | |||
6037 | /// handle later. | |||
6038 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | |||
6039 | // Apply this processing to all the arguments at once instead of | |||
6040 | // dying at the first failure. | |||
6041 | bool hasInvalid = false; | |||
6042 | for (size_t i = 0, e = args.size(); i != e; i++) { | |||
6043 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | |||
6044 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | |||
6045 | if (result.isInvalid()) hasInvalid = true; | |||
6046 | else args[i] = result.get(); | |||
6047 | } | |||
6048 | } | |||
6049 | return hasInvalid; | |||
6050 | } | |||
6051 | ||||
6052 | /// If a builtin function has a pointer argument with no explicit address | |||
6053 | /// space, then it should be able to accept a pointer to any address | |||
6054 | /// space as input. In order to do this, we need to replace the | |||
6055 | /// standard builtin declaration with one that uses the same address space | |||
6056 | /// as the call. | |||
6057 | /// | |||
6058 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | |||
6059 | /// it does not contain any pointer arguments without | |||
6060 | /// an address space qualifer. Otherwise the rewritten | |||
6061 | /// FunctionDecl is returned. | |||
6062 | /// TODO: Handle pointer return types. | |||
6063 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | |||
6064 | FunctionDecl *FDecl, | |||
6065 | MultiExprArg ArgExprs) { | |||
6066 | ||||
6067 | QualType DeclType = FDecl->getType(); | |||
6068 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | |||
6069 | ||||
6070 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | |||
6071 | ArgExprs.size() < FT->getNumParams()) | |||
6072 | return nullptr; | |||
6073 | ||||
6074 | bool NeedsNewDecl = false; | |||
6075 | unsigned i = 0; | |||
6076 | SmallVector<QualType, 8> OverloadParams; | |||
6077 | ||||
6078 | for (QualType ParamType : FT->param_types()) { | |||
6079 | ||||
6080 | // Convert array arguments to pointer to simplify type lookup. | |||
6081 | ExprResult ArgRes = | |||
6082 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | |||
6083 | if (ArgRes.isInvalid()) | |||
6084 | return nullptr; | |||
6085 | Expr *Arg = ArgRes.get(); | |||
6086 | QualType ArgType = Arg->getType(); | |||
6087 | if (!ParamType->isPointerType() || | |||
6088 | ParamType.hasAddressSpace() || | |||
6089 | !ArgType->isPointerType() || | |||
6090 | !ArgType->getPointeeType().hasAddressSpace()) { | |||
6091 | OverloadParams.push_back(ParamType); | |||
6092 | continue; | |||
6093 | } | |||
6094 | ||||
6095 | QualType PointeeType = ParamType->getPointeeType(); | |||
6096 | if (PointeeType.hasAddressSpace()) | |||
6097 | continue; | |||
6098 | ||||
6099 | NeedsNewDecl = true; | |||
6100 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | |||
6101 | ||||
6102 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | |||
6103 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | |||
6104 | } | |||
6105 | ||||
6106 | if (!NeedsNewDecl) | |||
6107 | return nullptr; | |||
6108 | ||||
6109 | FunctionProtoType::ExtProtoInfo EPI; | |||
6110 | EPI.Variadic = FT->isVariadic(); | |||
6111 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | |||
6112 | OverloadParams, EPI); | |||
6113 | DeclContext *Parent = FDecl->getParent(); | |||
6114 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, | |||
6115 | FDecl->getLocation(), | |||
6116 | FDecl->getLocation(), | |||
6117 | FDecl->getIdentifier(), | |||
6118 | OverloadTy, | |||
6119 | /*TInfo=*/nullptr, | |||
6120 | SC_Extern, false, | |||
6121 | /*hasPrototype=*/true); | |||
6122 | SmallVector<ParmVarDecl*, 16> Params; | |||
6123 | FT = cast<FunctionProtoType>(OverloadTy); | |||
6124 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
6125 | QualType ParamType = FT->getParamType(i); | |||
6126 | ParmVarDecl *Parm = | |||
6127 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | |||
6128 | SourceLocation(), nullptr, ParamType, | |||
6129 | /*TInfo=*/nullptr, SC_None, nullptr); | |||
6130 | Parm->setScopeInfo(0, i); | |||
6131 | Params.push_back(Parm); | |||
6132 | } | |||
6133 | OverloadDecl->setParams(Params); | |||
6134 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | |||
6135 | return OverloadDecl; | |||
6136 | } | |||
6137 | ||||
6138 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | |||
6139 | FunctionDecl *Callee, | |||
6140 | MultiExprArg ArgExprs) { | |||
6141 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | |||
6142 | // similar attributes) really don't like it when functions are called with an | |||
6143 | // invalid number of args. | |||
6144 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | |||
6145 | /*PartialOverloading=*/false) && | |||
6146 | !Callee->isVariadic()) | |||
6147 | return; | |||
6148 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | |||
6149 | return; | |||
6150 | ||||
6151 | if (const EnableIfAttr *Attr = | |||
6152 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | |||
6153 | S.Diag(Fn->getBeginLoc(), | |||
6154 | isa<CXXMethodDecl>(Callee) | |||
6155 | ? diag::err_ovl_no_viable_member_function_in_call | |||
6156 | : diag::err_ovl_no_viable_function_in_call) | |||
6157 | << Callee << Callee->getSourceRange(); | |||
6158 | S.Diag(Callee->getLocation(), | |||
6159 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
6160 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
6161 | return; | |||
6162 | } | |||
6163 | } | |||
6164 | ||||
6165 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | |||
6166 | const UnresolvedMemberExpr *const UME, Sema &S) { | |||
6167 | ||||
6168 | const auto GetFunctionLevelDCIfCXXClass = | |||
6169 | [](Sema &S) -> const CXXRecordDecl * { | |||
6170 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | |||
6171 | if (!DC || !DC->getParent()) | |||
6172 | return nullptr; | |||
6173 | ||||
6174 | // If the call to some member function was made from within a member | |||
6175 | // function body 'M' return return 'M's parent. | |||
6176 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
6177 | return MD->getParent()->getCanonicalDecl(); | |||
6178 | // else the call was made from within a default member initializer of a | |||
6179 | // class, so return the class. | |||
6180 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
6181 | return RD->getCanonicalDecl(); | |||
6182 | return nullptr; | |||
6183 | }; | |||
6184 | // If our DeclContext is neither a member function nor a class (in the | |||
6185 | // case of a lambda in a default member initializer), we can't have an | |||
6186 | // enclosing 'this'. | |||
6187 | ||||
6188 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | |||
6189 | if (!CurParentClass) | |||
6190 | return false; | |||
6191 | ||||
6192 | // The naming class for implicit member functions call is the class in which | |||
6193 | // name lookup starts. | |||
6194 | const CXXRecordDecl *const NamingClass = | |||
6195 | UME->getNamingClass()->getCanonicalDecl(); | |||
6196 | assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access" ) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6196, __PRETTY_FUNCTION__)); | |||
6197 | ||||
6198 | // If the unresolved member functions were found in a 'naming class' that is | |||
6199 | // related (either the same or derived from) to the class that contains the | |||
6200 | // member function that itself contained the implicit member access. | |||
6201 | ||||
6202 | return CurParentClass == NamingClass || | |||
6203 | CurParentClass->isDerivedFrom(NamingClass); | |||
6204 | } | |||
6205 | ||||
6206 | static void | |||
6207 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
6208 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | |||
6209 | ||||
6210 | if (!UME) | |||
6211 | return; | |||
6212 | ||||
6213 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | |||
6214 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | |||
6215 | // already been captured, or if this is an implicit member function call (if | |||
6216 | // it isn't, an attempt to capture 'this' should already have been made). | |||
6217 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | |||
6218 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | |||
6219 | return; | |||
6220 | ||||
6221 | // Check if the naming class in which the unresolved members were found is | |||
6222 | // related (same as or is a base of) to the enclosing class. | |||
6223 | ||||
6224 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | |||
6225 | return; | |||
6226 | ||||
6227 | ||||
6228 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | |||
6229 | // If the enclosing function is not dependent, then this lambda is | |||
6230 | // capture ready, so if we can capture this, do so. | |||
6231 | if (!EnclosingFunctionCtx->isDependentContext()) { | |||
6232 | // If the current lambda and all enclosing lambdas can capture 'this' - | |||
6233 | // then go ahead and capture 'this' (since our unresolved overload set | |||
6234 | // contains at least one non-static member function). | |||
6235 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | |||
6236 | S.CheckCXXThisCapture(CallLoc); | |||
6237 | } else if (S.CurContext->isDependentContext()) { | |||
6238 | // ... since this is an implicit member reference, that might potentially | |||
6239 | // involve a 'this' capture, mark 'this' for potential capture in | |||
6240 | // enclosing lambdas. | |||
6241 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | |||
6242 | CurLSI->addPotentialThisCapture(CallLoc); | |||
6243 | } | |||
6244 | } | |||
6245 | ||||
6246 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
6247 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
6248 | Expr *ExecConfig) { | |||
6249 | ExprResult Call = | |||
6250 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); | |||
6251 | if (Call.isInvalid()) | |||
6252 | return Call; | |||
6253 | ||||
6254 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | |||
6255 | // language modes. | |||
6256 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | |||
6257 | if (ULE->hasExplicitTemplateArgs() && | |||
6258 | ULE->decls_begin() == ULE->decls_end()) { | |||
6259 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | |||
6260 | ? diag::warn_cxx17_compat_adl_only_template_id | |||
6261 | : diag::ext_adl_only_template_id) | |||
6262 | << ULE->getName(); | |||
6263 | } | |||
6264 | } | |||
6265 | ||||
6266 | if (LangOpts.OpenMP) | |||
6267 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | |||
6268 | ExecConfig); | |||
6269 | ||||
6270 | return Call; | |||
6271 | } | |||
6272 | ||||
6273 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | |||
6274 | /// This provides the location of the left/right parens and a list of comma | |||
6275 | /// locations. | |||
6276 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
6277 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
6278 | Expr *ExecConfig, bool IsExecConfig) { | |||
6279 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
6280 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | |||
6281 | if (Result.isInvalid()) return ExprError(); | |||
6282 | Fn = Result.get(); | |||
6283 | ||||
6284 | if (checkArgsForPlaceholders(*this, ArgExprs)) | |||
6285 | return ExprError(); | |||
6286 | ||||
6287 | if (getLangOpts().CPlusPlus) { | |||
6288 | // If this is a pseudo-destructor expression, build the call immediately. | |||
6289 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | |||
6290 | if (!ArgExprs.empty()) { | |||
6291 | // Pseudo-destructor calls should not have any arguments. | |||
6292 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | |||
6293 | << FixItHint::CreateRemoval( | |||
6294 | SourceRange(ArgExprs.front()->getBeginLoc(), | |||
6295 | ArgExprs.back()->getEndLoc())); | |||
6296 | } | |||
6297 | ||||
6298 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | |||
6299 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | |||
6300 | } | |||
6301 | if (Fn->getType() == Context.PseudoObjectTy) { | |||
6302 | ExprResult result = CheckPlaceholderExpr(Fn); | |||
6303 | if (result.isInvalid()) return ExprError(); | |||
6304 | Fn = result.get(); | |||
6305 | } | |||
6306 | ||||
6307 | // Determine whether this is a dependent call inside a C++ template, | |||
6308 | // in which case we won't do any semantic analysis now. | |||
6309 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | |||
6310 | if (ExecConfig) { | |||
6311 | return CUDAKernelCallExpr::Create( | |||
6312 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, | |||
6313 | Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); | |||
6314 | } else { | |||
6315 | ||||
6316 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
6317 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | |||
6318 | Fn->getBeginLoc()); | |||
6319 | ||||
6320 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | |||
6321 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | |||
6322 | } | |||
6323 | } | |||
6324 | ||||
6325 | // Determine whether this is a call to an object (C++ [over.call.object]). | |||
6326 | if (Fn->getType()->isRecordType()) | |||
6327 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | |||
6328 | RParenLoc); | |||
6329 | ||||
6330 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
6331 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
6332 | if (result.isInvalid()) return ExprError(); | |||
6333 | Fn = result.get(); | |||
6334 | } | |||
6335 | ||||
6336 | if (Fn->getType() == Context.BoundMemberTy) { | |||
6337 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
6338 | RParenLoc); | |||
6339 | } | |||
6340 | } | |||
6341 | ||||
6342 | // Check for overloaded calls. This can happen even in C due to extensions. | |||
6343 | if (Fn->getType() == Context.OverloadTy) { | |||
6344 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | |||
6345 | ||||
6346 | // We aren't supposed to apply this logic if there's an '&' involved. | |||
6347 | if (!find.HasFormOfMemberPointer) { | |||
6348 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | |||
6349 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | |||
6350 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | |||
6351 | OverloadExpr *ovl = find.Expression; | |||
6352 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | |||
6353 | return BuildOverloadedCallExpr( | |||
6354 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | |||
6355 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | |||
6356 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
6357 | RParenLoc); | |||
6358 | } | |||
6359 | } | |||
6360 | ||||
6361 | // If we're directly calling a function, get the appropriate declaration. | |||
6362 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
6363 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
6364 | if (result.isInvalid()) return ExprError(); | |||
6365 | Fn = result.get(); | |||
6366 | } | |||
6367 | ||||
6368 | Expr *NakedFn = Fn->IgnoreParens(); | |||
6369 | ||||
6370 | bool CallingNDeclIndirectly = false; | |||
6371 | NamedDecl *NDecl = nullptr; | |||
6372 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | |||
6373 | if (UnOp->getOpcode() == UO_AddrOf) { | |||
6374 | CallingNDeclIndirectly = true; | |||
6375 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | |||
6376 | } | |||
6377 | } | |||
6378 | ||||
6379 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | |||
6380 | NDecl = DRE->getDecl(); | |||
6381 | ||||
6382 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | |||
6383 | if (FDecl && FDecl->getBuiltinID()) { | |||
6384 | // Rewrite the function decl for this builtin by replacing parameters | |||
6385 | // with no explicit address space with the address space of the arguments | |||
6386 | // in ArgExprs. | |||
6387 | if ((FDecl = | |||
6388 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | |||
6389 | NDecl = FDecl; | |||
6390 | Fn = DeclRefExpr::Create( | |||
6391 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | |||
6392 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | |||
6393 | nullptr, DRE->isNonOdrUse()); | |||
6394 | } | |||
6395 | } | |||
6396 | } else if (isa<MemberExpr>(NakedFn)) | |||
6397 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | |||
6398 | ||||
6399 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | |||
6400 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | |||
6401 | FD, /*Complain=*/true, Fn->getBeginLoc())) | |||
6402 | return ExprError(); | |||
6403 | ||||
6404 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) | |||
6405 | return ExprError(); | |||
6406 | ||||
6407 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | |||
6408 | } | |||
6409 | ||||
6410 | if (Context.isDependenceAllowed() && | |||
6411 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | |||
6412 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6412, __PRETTY_FUNCTION__)); | |||
6413 | assert((Fn->containsErrors() ||(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6416, __PRETTY_FUNCTION__)) | |||
6414 | llvm::any_of(ArgExprs,(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6416, __PRETTY_FUNCTION__)) | |||
6415 | [](clang::Expr *E) { return E->containsErrors(); })) &&(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6416, __PRETTY_FUNCTION__)) | |||
6416 | "should only occur in error-recovery path.")(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6416, __PRETTY_FUNCTION__)); | |||
6417 | QualType ReturnType = | |||
6418 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | |||
6419 | ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType() | |||
6420 | : Context.DependentTy; | |||
6421 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | |||
6422 | Expr::getValueKindForType(ReturnType), RParenLoc, | |||
6423 | CurFPFeatureOverrides()); | |||
6424 | } | |||
6425 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | |||
6426 | ExecConfig, IsExecConfig); | |||
6427 | } | |||
6428 | ||||
6429 | /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. | |||
6430 | /// | |||
6431 | /// __builtin_astype( value, dst type ) | |||
6432 | /// | |||
6433 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | |||
6434 | SourceLocation BuiltinLoc, | |||
6435 | SourceLocation RParenLoc) { | |||
6436 | ExprValueKind VK = VK_RValue; | |||
6437 | ExprObjectKind OK = OK_Ordinary; | |||
6438 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | |||
6439 | QualType SrcTy = E->getType(); | |||
6440 | if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) | |||
6441 | return ExprError(Diag(BuiltinLoc, | |||
6442 | diag::err_invalid_astype_of_different_size) | |||
6443 | << DstTy | |||
6444 | << SrcTy | |||
6445 | << E->getSourceRange()); | |||
6446 | return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); | |||
6447 | } | |||
6448 | ||||
6449 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | |||
6450 | /// provided arguments. | |||
6451 | /// | |||
6452 | /// __builtin_convertvector( value, dst type ) | |||
6453 | /// | |||
6454 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | |||
6455 | SourceLocation BuiltinLoc, | |||
6456 | SourceLocation RParenLoc) { | |||
6457 | TypeSourceInfo *TInfo; | |||
6458 | GetTypeFromParser(ParsedDestTy, &TInfo); | |||
6459 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | |||
6460 | } | |||
6461 | ||||
6462 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | |||
6463 | /// i.e. an expression not of \p OverloadTy. The expression should | |||
6464 | /// unary-convert to an expression of function-pointer or | |||
6465 | /// block-pointer type. | |||
6466 | /// | |||
6467 | /// \param NDecl the declaration being called, if available | |||
6468 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | |||
6469 | SourceLocation LParenLoc, | |||
6470 | ArrayRef<Expr *> Args, | |||
6471 | SourceLocation RParenLoc, Expr *Config, | |||
6472 | bool IsExecConfig, ADLCallKind UsesADL) { | |||
6473 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | |||
6474 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | |||
6475 | ||||
6476 | // Functions with 'interrupt' attribute cannot be called directly. | |||
6477 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | |||
6478 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | |||
6479 | return ExprError(); | |||
6480 | } | |||
6481 | ||||
6482 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | |||
6483 | // so there's some risk when calling out to non-interrupt handler functions | |||
6484 | // that the callee might not preserve them. This is easy to diagnose here, | |||
6485 | // but can be very challenging to debug. | |||
6486 | if (auto *Caller = getCurFunctionDecl()) | |||
6487 | if (Caller->hasAttr<ARMInterruptAttr>()) { | |||
6488 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | |||
6489 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) | |||
6490 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | |||
6491 | } | |||
6492 | ||||
6493 | // Promote the function operand. | |||
6494 | // We special-case function promotion here because we only allow promoting | |||
6495 | // builtin functions to function pointers in the callee of a call. | |||
6496 | ExprResult Result; | |||
6497 | QualType ResultTy; | |||
6498 | if (BuiltinID && | |||
6499 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | |||
6500 | // Extract the return type from the (builtin) function pointer type. | |||
6501 | // FIXME Several builtins still have setType in | |||
6502 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | |||
6503 | // Builtins.def to ensure they are correct before removing setType calls. | |||
6504 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | |||
6505 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | |||
6506 | ResultTy = FDecl->getCallResultType(); | |||
6507 | } else { | |||
6508 | Result = CallExprUnaryConversions(Fn); | |||
6509 | ResultTy = Context.BoolTy; | |||
6510 | } | |||
6511 | if (Result.isInvalid()) | |||
6512 | return ExprError(); | |||
6513 | Fn = Result.get(); | |||
6514 | ||||
6515 | // Check for a valid function type, but only if it is not a builtin which | |||
6516 | // requires custom type checking. These will be handled by | |||
6517 | // CheckBuiltinFunctionCall below just after creation of the call expression. | |||
6518 | const FunctionType *FuncT = nullptr; | |||
6519 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | |||
6520 | retry: | |||
6521 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | |||
6522 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | |||
6523 | // have type pointer to function". | |||
6524 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | |||
6525 | if (!FuncT) | |||
6526 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
6527 | << Fn->getType() << Fn->getSourceRange()); | |||
6528 | } else if (const BlockPointerType *BPT = | |||
6529 | Fn->getType()->getAs<BlockPointerType>()) { | |||
6530 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | |||
6531 | } else { | |||
6532 | // Handle calls to expressions of unknown-any type. | |||
6533 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
6534 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | |||
6535 | if (rewrite.isInvalid()) | |||
6536 | return ExprError(); | |||
6537 | Fn = rewrite.get(); | |||
6538 | goto retry; | |||
6539 | } | |||
6540 | ||||
6541 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
6542 | << Fn->getType() << Fn->getSourceRange()); | |||
6543 | } | |||
6544 | } | |||
6545 | ||||
6546 | // Get the number of parameters in the function prototype, if any. | |||
6547 | // We will allocate space for max(Args.size(), NumParams) arguments | |||
6548 | // in the call expression. | |||
6549 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | |||
6550 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; | |||
6551 | ||||
6552 | CallExpr *TheCall; | |||
6553 | if (Config) { | |||
6554 | assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6555, __PRETTY_FUNCTION__)) | |||
6555 | "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6555, __PRETTY_FUNCTION__)); | |||
6556 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | |||
6557 | Args, ResultTy, VK_RValue, RParenLoc, | |||
6558 | CurFPFeatureOverrides(), NumParams); | |||
6559 | } else { | |||
6560 | TheCall = | |||
6561 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | |||
6562 | CurFPFeatureOverrides(), NumParams, UsesADL); | |||
6563 | } | |||
6564 | ||||
6565 | if (!Context.isDependenceAllowed()) { | |||
6566 | // Forget about the nulled arguments since typo correction | |||
6567 | // do not handle them well. | |||
6568 | TheCall->shrinkNumArgs(Args.size()); | |||
6569 | // C cannot always handle TypoExpr nodes in builtin calls and direct | |||
6570 | // function calls as their argument checking don't necessarily handle | |||
6571 | // dependent types properly, so make sure any TypoExprs have been | |||
6572 | // dealt with. | |||
6573 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | |||
6574 | if (!Result.isUsable()) return ExprError(); | |||
6575 | CallExpr *TheOldCall = TheCall; | |||
6576 | TheCall = dyn_cast<CallExpr>(Result.get()); | |||
6577 | bool CorrectedTypos = TheCall != TheOldCall; | |||
6578 | if (!TheCall) return Result; | |||
6579 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | |||
6580 | ||||
6581 | // A new call expression node was created if some typos were corrected. | |||
6582 | // However it may not have been constructed with enough storage. In this | |||
6583 | // case, rebuild the node with enough storage. The waste of space is | |||
6584 | // immaterial since this only happens when some typos were corrected. | |||
6585 | if (CorrectedTypos && Args.size() < NumParams) { | |||
6586 | if (Config) | |||
6587 | TheCall = CUDAKernelCallExpr::Create( | |||
6588 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, | |||
6589 | RParenLoc, CurFPFeatureOverrides(), NumParams); | |||
6590 | else | |||
6591 | TheCall = | |||
6592 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | |||
6593 | CurFPFeatureOverrides(), NumParams, UsesADL); | |||
6594 | } | |||
6595 | // We can now handle the nulled arguments for the default arguments. | |||
6596 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | |||
6597 | } | |||
6598 | ||||
6599 | // Bail out early if calling a builtin with custom type checking. | |||
6600 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | |||
6601 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
6602 | ||||
6603 | if (getLangOpts().CUDA) { | |||
6604 | if (Config) { | |||
6605 | // CUDA: Kernel calls must be to global functions | |||
6606 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | |||
6607 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | |||
6608 | << FDecl << Fn->getSourceRange()); | |||
6609 | ||||
6610 | // CUDA: Kernel function must have 'void' return type | |||
6611 | if (!FuncT->getReturnType()->isVoidType() && | |||
6612 | !FuncT->getReturnType()->getAs<AutoType>() && | |||
6613 | !FuncT->getReturnType()->isInstantiationDependentType()) | |||
6614 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | |||
6615 | << Fn->getType() << Fn->getSourceRange()); | |||
6616 | } else { | |||
6617 | // CUDA: Calls to global functions must be configured | |||
6618 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | |||
6619 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | |||
6620 | << FDecl << Fn->getSourceRange()); | |||
6621 | } | |||
6622 | } | |||
6623 | ||||
6624 | // Check for a valid return type | |||
6625 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | |||
6626 | FDecl)) | |||
6627 | return ExprError(); | |||
6628 | ||||
6629 | // We know the result type of the call, set it. | |||
6630 | TheCall->setType(FuncT->getCallResultType(Context)); | |||
6631 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | |||
6632 | ||||
6633 | if (Proto) { | |||
6634 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | |||
6635 | IsExecConfig)) | |||
6636 | return ExprError(); | |||
6637 | } else { | |||
6638 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6638, __PRETTY_FUNCTION__)); | |||
6639 | ||||
6640 | if (FDecl) { | |||
6641 | // Check if we have too few/too many template arguments, based | |||
6642 | // on our knowledge of the function definition. | |||
6643 | const FunctionDecl *Def = nullptr; | |||
6644 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | |||
6645 | Proto = Def->getType()->getAs<FunctionProtoType>(); | |||
6646 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | |||
6647 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | |||
6648 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | |||
6649 | } | |||
6650 | ||||
6651 | // If the function we're calling isn't a function prototype, but we have | |||
6652 | // a function prototype from a prior declaratiom, use that prototype. | |||
6653 | if (!FDecl->hasPrototype()) | |||
6654 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | |||
6655 | } | |||
6656 | ||||
6657 | // Promote the arguments (C99 6.5.2.2p6). | |||
6658 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | |||
6659 | Expr *Arg = Args[i]; | |||
6660 | ||||
6661 | if (Proto && i < Proto->getNumParams()) { | |||
6662 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
6663 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | |||
6664 | ExprResult ArgE = | |||
6665 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | |||
6666 | if (ArgE.isInvalid()) | |||
6667 | return true; | |||
6668 | ||||
6669 | Arg = ArgE.getAs<Expr>(); | |||
6670 | ||||
6671 | } else { | |||
6672 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | |||
6673 | ||||
6674 | if (ArgE.isInvalid()) | |||
6675 | return true; | |||
6676 | ||||
6677 | Arg = ArgE.getAs<Expr>(); | |||
6678 | } | |||
6679 | ||||
6680 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | |||
6681 | diag::err_call_incomplete_argument, Arg)) | |||
6682 | return ExprError(); | |||
6683 | ||||
6684 | TheCall->setArg(i, Arg); | |||
6685 | } | |||
6686 | } | |||
6687 | ||||
6688 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
6689 | if (!Method->isStatic()) | |||
6690 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | |||
6691 | << Fn->getSourceRange()); | |||
6692 | ||||
6693 | // Check for sentinels | |||
6694 | if (NDecl) | |||
6695 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | |||
6696 | ||||
6697 | // Warn for unions passing across security boundary (CMSE). | |||
6698 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | |||
6699 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | |||
6700 | if (const auto *RT = | |||
6701 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | |||
6702 | if (RT->getDecl()->isOrContainsUnion()) | |||
6703 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | |||
6704 | << 0 << i; | |||
6705 | } | |||
6706 | } | |||
6707 | } | |||
6708 | ||||
6709 | // Do special checking on direct calls to functions. | |||
6710 | if (FDecl) { | |||
6711 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | |||
6712 | return ExprError(); | |||
6713 | ||||
6714 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | |||
6715 | ||||
6716 | if (BuiltinID) | |||
6717 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
6718 | } else if (NDecl) { | |||
6719 | if (CheckPointerCall(NDecl, TheCall, Proto)) | |||
6720 | return ExprError(); | |||
6721 | } else { | |||
6722 | if (CheckOtherCall(TheCall, Proto)) | |||
6723 | return ExprError(); | |||
6724 | } | |||
6725 | ||||
6726 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | |||
6727 | } | |||
6728 | ||||
6729 | ExprResult | |||
6730 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | |||
6731 | SourceLocation RParenLoc, Expr *InitExpr) { | |||
6732 | assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast <void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6732, __PRETTY_FUNCTION__)); | |||
6733 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6733, __PRETTY_FUNCTION__)); | |||
6734 | ||||
6735 | TypeSourceInfo *TInfo; | |||
6736 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | |||
6737 | if (!TInfo) | |||
6738 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | |||
6739 | ||||
6740 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | |||
6741 | } | |||
6742 | ||||
6743 | ExprResult | |||
6744 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | |||
6745 | SourceLocation RParenLoc, Expr *LiteralExpr) { | |||
6746 | QualType literalType = TInfo->getType(); | |||
6747 | ||||
6748 | if (literalType->isArrayType()) { | |||
6749 | if (RequireCompleteSizedType( | |||
6750 | LParenLoc, Context.getBaseElementType(literalType), | |||
6751 | diag::err_array_incomplete_or_sizeless_type, | |||
6752 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | |||
6753 | return ExprError(); | |||
6754 | if (literalType->isVariableArrayType()) | |||
6755 | return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) | |||
6756 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); | |||
6757 | } else if (!literalType->isDependentType() && | |||
6758 | RequireCompleteType(LParenLoc, literalType, | |||
6759 | diag::err_typecheck_decl_incomplete_type, | |||
6760 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | |||
6761 | return ExprError(); | |||
6762 | ||||
6763 | InitializedEntity Entity | |||
6764 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | |||
6765 | InitializationKind Kind | |||
6766 | = InitializationKind::CreateCStyleCast(LParenLoc, | |||
6767 | SourceRange(LParenLoc, RParenLoc), | |||
6768 | /*InitList=*/true); | |||
6769 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | |||
6770 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | |||
6771 | &literalType); | |||
6772 | if (Result.isInvalid()) | |||
6773 | return ExprError(); | |||
6774 | LiteralExpr = Result.get(); | |||
6775 | ||||
6776 | bool isFileScope = !CurContext->isFunctionOrMethod(); | |||
6777 | ||||
6778 | // In C, compound literals are l-values for some reason. | |||
6779 | // For GCC compatibility, in C++, file-scope array compound literals with | |||
6780 | // constant initializers are also l-values, and compound literals are | |||
6781 | // otherwise prvalues. | |||
6782 | // | |||
6783 | // (GCC also treats C++ list-initialized file-scope array prvalues with | |||
6784 | // constant initializers as l-values, but that's non-conforming, so we don't | |||
6785 | // follow it there.) | |||
6786 | // | |||
6787 | // FIXME: It would be better to handle the lvalue cases as materializing and | |||
6788 | // lifetime-extending a temporary object, but our materialized temporaries | |||
6789 | // representation only supports lifetime extension from a variable, not "out | |||
6790 | // of thin air". | |||
6791 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | |||
6792 | // is bound to the result of applying array-to-pointer decay to the compound | |||
6793 | // literal. | |||
6794 | // FIXME: GCC supports compound literals of reference type, which should | |||
6795 | // obviously have a value kind derived from the kind of reference involved. | |||
6796 | ExprValueKind VK = | |||
6797 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | |||
6798 | ? VK_RValue | |||
6799 | : VK_LValue; | |||
6800 | ||||
6801 | if (isFileScope) | |||
6802 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | |||
6803 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | |||
6804 | Expr *Init = ILE->getInit(i); | |||
6805 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | |||
6806 | } | |||
6807 | ||||
6808 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | |||
6809 | VK, LiteralExpr, isFileScope); | |||
6810 | if (isFileScope) { | |||
6811 | if (!LiteralExpr->isTypeDependent() && | |||
6812 | !LiteralExpr->isValueDependent() && | |||
6813 | !literalType->isDependentType()) // C99 6.5.2.5p3 | |||
6814 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | |||
6815 | return ExprError(); | |||
6816 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | |||
6817 | literalType.getAddressSpace() != LangAS::Default) { | |||
6818 | // Embedded-C extensions to C99 6.5.2.5: | |||
6819 | // "If the compound literal occurs inside the body of a function, the | |||
6820 | // type name shall not be qualified by an address-space qualifier." | |||
6821 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | |||
6822 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | |||
6823 | return ExprError(); | |||
6824 | } | |||
6825 | ||||
6826 | if (!isFileScope && !getLangOpts().CPlusPlus) { | |||
6827 | // Compound literals that have automatic storage duration are destroyed at | |||
6828 | // the end of the scope in C; in C++, they're just temporaries. | |||
6829 | ||||
6830 | // Emit diagnostics if it is or contains a C union type that is non-trivial | |||
6831 | // to destruct. | |||
6832 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | |||
6833 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | |||
6834 | NTCUC_CompoundLiteral, NTCUK_Destruct); | |||
6835 | ||||
6836 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | |||
6837 | if (literalType.isDestructedType()) { | |||
6838 | Cleanup.setExprNeedsCleanups(true); | |||
6839 | ExprCleanupObjects.push_back(E); | |||
6840 | getCurFunction()->setHasBranchProtectedScope(); | |||
6841 | } | |||
6842 | } | |||
6843 | ||||
6844 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | |||
6845 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
6846 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | |||
6847 | E->getInitializer()->getExprLoc()); | |||
6848 | ||||
6849 | return MaybeBindToTemporary(E); | |||
6850 | } | |||
6851 | ||||
6852 | ExprResult | |||
6853 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | |||
6854 | SourceLocation RBraceLoc) { | |||
6855 | // Only produce each kind of designated initialization diagnostic once. | |||
6856 | SourceLocation FirstDesignator; | |||
6857 | bool DiagnosedArrayDesignator = false; | |||
6858 | bool DiagnosedNestedDesignator = false; | |||
6859 | bool DiagnosedMixedDesignator = false; | |||
6860 | ||||
6861 | // Check that any designated initializers are syntactically valid in the | |||
6862 | // current language mode. | |||
6863 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | |||
6864 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | |||
6865 | if (FirstDesignator.isInvalid()) | |||
6866 | FirstDesignator = DIE->getBeginLoc(); | |||
6867 | ||||
6868 | if (!getLangOpts().CPlusPlus) | |||
6869 | break; | |||
6870 | ||||
6871 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | |||
6872 | DiagnosedNestedDesignator = true; | |||
6873 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | |||
6874 | << DIE->getDesignatorsSourceRange(); | |||
6875 | } | |||
6876 | ||||
6877 | for (auto &Desig : DIE->designators()) { | |||
6878 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | |||
6879 | DiagnosedArrayDesignator = true; | |||
6880 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | |||
6881 | << Desig.getSourceRange(); | |||
6882 | } | |||
6883 | } | |||
6884 | ||||
6885 | if (!DiagnosedMixedDesignator && | |||
6886 | !isa<DesignatedInitExpr>(InitArgList[0])) { | |||
6887 | DiagnosedMixedDesignator = true; | |||
6888 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | |||
6889 | << DIE->getSourceRange(); | |||
6890 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | |||
6891 | << InitArgList[0]->getSourceRange(); | |||
6892 | } | |||
6893 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | |||
6894 | isa<DesignatedInitExpr>(InitArgList[0])) { | |||
6895 | DiagnosedMixedDesignator = true; | |||
6896 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | |||
6897 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | |||
6898 | << DIE->getSourceRange(); | |||
6899 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | |||
6900 | << InitArgList[I]->getSourceRange(); | |||
6901 | } | |||
6902 | } | |||
6903 | ||||
6904 | if (FirstDesignator.isValid()) { | |||
6905 | // Only diagnose designated initiaization as a C++20 extension if we didn't | |||
6906 | // already diagnose use of (non-C++20) C99 designator syntax. | |||
6907 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | |||
6908 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | |||
6909 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | |||
6910 | ? diag::warn_cxx17_compat_designated_init | |||
6911 | : diag::ext_cxx_designated_init); | |||
6912 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | |||
6913 | Diag(FirstDesignator, diag::ext_designated_init); | |||
6914 | } | |||
6915 | } | |||
6916 | ||||
6917 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | |||
6918 | } | |||
6919 | ||||
6920 | ExprResult | |||
6921 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | |||
6922 | SourceLocation RBraceLoc) { | |||
6923 | // Semantic analysis for initializers is done by ActOnDeclarator() and | |||
6924 | // CheckInitializer() - it requires knowledge of the object being initialized. | |||
6925 | ||||
6926 | // Immediately handle non-overload placeholders. Overloads can be | |||
6927 | // resolved contextually, but everything else here can't. | |||
6928 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | |||
6929 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | |||
6930 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | |||
6931 | ||||
6932 | // Ignore failures; dropping the entire initializer list because | |||
6933 | // of one failure would be terrible for indexing/etc. | |||
6934 | if (result.isInvalid()) continue; | |||
6935 | ||||
6936 | InitArgList[I] = result.get(); | |||
6937 | } | |||
6938 | } | |||
6939 | ||||
6940 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | |||
6941 | RBraceLoc); | |||
6942 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | |||
6943 | return E; | |||
6944 | } | |||
6945 | ||||
6946 | /// Do an explicit extend of the given block pointer if we're in ARC. | |||
6947 | void Sema::maybeExtendBlockObject(ExprResult &E) { | |||
6948 | assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast <void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6948, __PRETTY_FUNCTION__)); | |||
6949 | assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail ("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6949, __PRETTY_FUNCTION__)); | |||
6950 | ||||
6951 | // Only do this in an r-value context. | |||
6952 | if (!getLangOpts().ObjCAutoRefCount) return; | |||
6953 | ||||
6954 | E = ImplicitCastExpr::Create( | |||
6955 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | |||
6956 | /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); | |||
6957 | Cleanup.setExprNeedsCleanups(true); | |||
6958 | } | |||
6959 | ||||
6960 | /// Prepare a conversion of the given expression to an ObjC object | |||
6961 | /// pointer type. | |||
6962 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | |||
6963 | QualType type = E.get()->getType(); | |||
6964 | if (type->isObjCObjectPointerType()) { | |||
6965 | return CK_BitCast; | |||
6966 | } else if (type->isBlockPointerType()) { | |||
6967 | maybeExtendBlockObject(E); | |||
6968 | return CK_BlockPointerToObjCPointerCast; | |||
6969 | } else { | |||
6970 | assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail ("type->isPointerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6970, __PRETTY_FUNCTION__)); | |||
6971 | return CK_CPointerToObjCPointerCast; | |||
6972 | } | |||
6973 | } | |||
6974 | ||||
6975 | /// Prepares for a scalar cast, performing all the necessary stages | |||
6976 | /// except the final cast and returning the kind required. | |||
6977 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | |||
6978 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | |||
6979 | // Also, callers should have filtered out the invalid cases with | |||
6980 | // pointers. Everything else should be possible. | |||
6981 | ||||
6982 | QualType SrcTy = Src.get()->getType(); | |||
6983 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | |||
6984 | return CK_NoOp; | |||
6985 | ||||
6986 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | |||
6987 | case Type::STK_MemberPointer: | |||
6988 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 6988); | |||
6989 | ||||
6990 | case Type::STK_CPointer: | |||
6991 | case Type::STK_BlockPointer: | |||
6992 | case Type::STK_ObjCObjectPointer: | |||
6993 | switch (DestTy->getScalarTypeKind()) { | |||
6994 | case Type::STK_CPointer: { | |||
6995 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | |||
6996 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | |||
6997 | if (SrcAS != DestAS) | |||
6998 | return CK_AddressSpaceConversion; | |||
6999 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | |||
7000 | return CK_NoOp; | |||
7001 | return CK_BitCast; | |||
7002 | } | |||
7003 | case Type::STK_BlockPointer: | |||
7004 | return (SrcKind == Type::STK_BlockPointer | |||
7005 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | |||
7006 | case Type::STK_ObjCObjectPointer: | |||
7007 | if (SrcKind == Type::STK_ObjCObjectPointer) | |||
7008 | return CK_BitCast; | |||
7009 | if (SrcKind == Type::STK_CPointer) | |||
7010 | return CK_CPointerToObjCPointerCast; | |||
7011 | maybeExtendBlockObject(Src); | |||
7012 | return CK_BlockPointerToObjCPointerCast; | |||
7013 | case Type::STK_Bool: | |||
7014 | return CK_PointerToBoolean; | |||
7015 | case Type::STK_Integral: | |||
7016 | return CK_PointerToIntegral; | |||
7017 | case Type::STK_Floating: | |||
7018 | case Type::STK_FloatingComplex: | |||
7019 | case Type::STK_IntegralComplex: | |||
7020 | case Type::STK_MemberPointer: | |||
7021 | case Type::STK_FixedPoint: | |||
7022 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7022); | |||
7023 | } | |||
7024 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7024); | |||
7025 | ||||
7026 | case Type::STK_FixedPoint: | |||
7027 | switch (DestTy->getScalarTypeKind()) { | |||
7028 | case Type::STK_FixedPoint: | |||
7029 | return CK_FixedPointCast; | |||
7030 | case Type::STK_Bool: | |||
7031 | return CK_FixedPointToBoolean; | |||
7032 | case Type::STK_Integral: | |||
7033 | return CK_FixedPointToIntegral; | |||
7034 | case Type::STK_Floating: | |||
7035 | return CK_FixedPointToFloating; | |||
7036 | case Type::STK_IntegralComplex: | |||
7037 | case Type::STK_FloatingComplex: | |||
7038 | Diag(Src.get()->getExprLoc(), | |||
7039 | diag::err_unimplemented_conversion_with_fixed_point_type) | |||
7040 | << DestTy; | |||
7041 | return CK_IntegralCast; | |||
7042 | case Type::STK_CPointer: | |||
7043 | case Type::STK_ObjCObjectPointer: | |||
7044 | case Type::STK_BlockPointer: | |||
7045 | case Type::STK_MemberPointer: | |||
7046 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7046); | |||
7047 | } | |||
7048 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7048); | |||
7049 | ||||
7050 | case Type::STK_Bool: // casting from bool is like casting from an integer | |||
7051 | case Type::STK_Integral: | |||
7052 | switch (DestTy->getScalarTypeKind()) { | |||
7053 | case Type::STK_CPointer: | |||
7054 | case Type::STK_ObjCObjectPointer: | |||
7055 | case Type::STK_BlockPointer: | |||
7056 | if (Src.get()->isNullPointerConstant(Context, | |||
7057 | Expr::NPC_ValueDependentIsNull)) | |||
7058 | return CK_NullToPointer; | |||
7059 | return CK_IntegralToPointer; | |||
7060 | case Type::STK_Bool: | |||
7061 | return CK_IntegralToBoolean; | |||
7062 | case Type::STK_Integral: | |||
7063 | return CK_IntegralCast; | |||
7064 | case Type::STK_Floating: | |||
7065 | return CK_IntegralToFloating; | |||
7066 | case Type::STK_IntegralComplex: | |||
7067 | Src = ImpCastExprToType(Src.get(), | |||
7068 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7069 | CK_IntegralCast); | |||
7070 | return CK_IntegralRealToComplex; | |||
7071 | case Type::STK_FloatingComplex: | |||
7072 | Src = ImpCastExprToType(Src.get(), | |||
7073 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7074 | CK_IntegralToFloating); | |||
7075 | return CK_FloatingRealToComplex; | |||
7076 | case Type::STK_MemberPointer: | |||
7077 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7077); | |||
7078 | case Type::STK_FixedPoint: | |||
7079 | return CK_IntegralToFixedPoint; | |||
7080 | } | |||
7081 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7081); | |||
7082 | ||||
7083 | case Type::STK_Floating: | |||
7084 | switch (DestTy->getScalarTypeKind()) { | |||
7085 | case Type::STK_Floating: | |||
7086 | return CK_FloatingCast; | |||
7087 | case Type::STK_Bool: | |||
7088 | return CK_FloatingToBoolean; | |||
7089 | case Type::STK_Integral: | |||
7090 | return CK_FloatingToIntegral; | |||
7091 | case Type::STK_FloatingComplex: | |||
7092 | Src = ImpCastExprToType(Src.get(), | |||
7093 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7094 | CK_FloatingCast); | |||
7095 | return CK_FloatingRealToComplex; | |||
7096 | case Type::STK_IntegralComplex: | |||
7097 | Src = ImpCastExprToType(Src.get(), | |||
7098 | DestTy->castAs<ComplexType>()->getElementType(), | |||
7099 | CK_FloatingToIntegral); | |||
7100 | return CK_IntegralRealToComplex; | |||
7101 | case Type::STK_CPointer: | |||
7102 | case Type::STK_ObjCObjectPointer: | |||
7103 | case Type::STK_BlockPointer: | |||
7104 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7104); | |||
7105 | case Type::STK_MemberPointer: | |||
7106 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7106); | |||
7107 | case Type::STK_FixedPoint: | |||
7108 | return CK_FloatingToFixedPoint; | |||
7109 | } | |||
7110 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7110); | |||
7111 | ||||
7112 | case Type::STK_FloatingComplex: | |||
7113 | switch (DestTy->getScalarTypeKind()) { | |||
7114 | case Type::STK_FloatingComplex: | |||
7115 | return CK_FloatingComplexCast; | |||
7116 | case Type::STK_IntegralComplex: | |||
7117 | return CK_FloatingComplexToIntegralComplex; | |||
7118 | case Type::STK_Floating: { | |||
7119 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | |||
7120 | if (Context.hasSameType(ET, DestTy)) | |||
7121 | return CK_FloatingComplexToReal; | |||
7122 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | |||
7123 | return CK_FloatingCast; | |||
7124 | } | |||
7125 | case Type::STK_Bool: | |||
7126 | return CK_FloatingComplexToBoolean; | |||
7127 | case Type::STK_Integral: | |||
7128 | Src = ImpCastExprToType(Src.get(), | |||
7129 | SrcTy->castAs<ComplexType>()->getElementType(), | |||
7130 | CK_FloatingComplexToReal); | |||
7131 | return CK_FloatingToIntegral; | |||
7132 | case Type::STK_CPointer: | |||
7133 | case Type::STK_ObjCObjectPointer: | |||
7134 | case Type::STK_BlockPointer: | |||
7135 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7135); | |||
7136 | case Type::STK_MemberPointer: | |||
7137 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7137); | |||
7138 | case Type::STK_FixedPoint: | |||
7139 | Diag(Src.get()->getExprLoc(), | |||
7140 | diag::err_unimplemented_conversion_with_fixed_point_type) | |||
7141 | << SrcTy; | |||
7142 | return CK_IntegralCast; | |||
7143 | } | |||
7144 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7144); | |||
7145 | ||||
7146 | case Type::STK_IntegralComplex: | |||
7147 | switch (DestTy->getScalarTypeKind()) { | |||
7148 | case Type::STK_FloatingComplex: | |||
7149 | return CK_IntegralComplexToFloatingComplex; | |||
7150 | case Type::STK_IntegralComplex: | |||
7151 | return CK_IntegralComplexCast; | |||
7152 | case Type::STK_Integral: { | |||
7153 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | |||
7154 | if (Context.hasSameType(ET, DestTy)) | |||
7155 | return CK_IntegralComplexToReal; | |||
7156 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | |||
7157 | return CK_IntegralCast; | |||
7158 | } | |||
7159 | case Type::STK_Bool: | |||
7160 | return CK_IntegralComplexToBoolean; | |||
7161 | case Type::STK_Floating: | |||
7162 | Src = ImpCastExprToType(Src.get(), | |||
7163 | SrcTy->castAs<ComplexType>()->getElementType(), | |||
7164 | CK_IntegralComplexToReal); | |||
7165 | return CK_IntegralToFloating; | |||
7166 | case Type::STK_CPointer: | |||
7167 | case Type::STK_ObjCObjectPointer: | |||
7168 | case Type::STK_BlockPointer: | |||
7169 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7169); | |||
7170 | case Type::STK_MemberPointer: | |||
7171 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7171); | |||
7172 | case Type::STK_FixedPoint: | |||
7173 | Diag(Src.get()->getExprLoc(), | |||
7174 | diag::err_unimplemented_conversion_with_fixed_point_type) | |||
7175 | << SrcTy; | |||
7176 | return CK_IntegralCast; | |||
7177 | } | |||
7178 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7178); | |||
7179 | } | |||
7180 | ||||
7181 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7181); | |||
7182 | } | |||
7183 | ||||
7184 | static bool breakDownVectorType(QualType type, uint64_t &len, | |||
7185 | QualType &eltType) { | |||
7186 | // Vectors are simple. | |||
7187 | if (const VectorType *vecType = type->getAs<VectorType>()) { | |||
7188 | len = vecType->getNumElements(); | |||
7189 | eltType = vecType->getElementType(); | |||
7190 | assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) : __assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7190, __PRETTY_FUNCTION__)); | |||
7191 | return true; | |||
7192 | } | |||
7193 | ||||
7194 | // We allow lax conversion to and from non-vector types, but only if | |||
7195 | // they're real types (i.e. non-complex, non-pointer scalar types). | |||
7196 | if (!type->isRealType()) return false; | |||
7197 | ||||
7198 | len = 1; | |||
7199 | eltType = type; | |||
7200 | return true; | |||
7201 | } | |||
7202 | ||||
7203 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | |||
7204 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | |||
7205 | /// allowed? | |||
7206 | /// | |||
7207 | /// This will also return false if the two given types do not make sense from | |||
7208 | /// the perspective of SVE bitcasts. | |||
7209 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | |||
7210 | assert(srcTy->isVectorType() || destTy->isVectorType())((srcTy->isVectorType() || destTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7210, __PRETTY_FUNCTION__)); | |||
7211 | ||||
7212 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | |||
7213 | if (!FirstType->isSizelessBuiltinType()) | |||
7214 | return false; | |||
7215 | ||||
7216 | const auto *VecTy = SecondType->getAs<VectorType>(); | |||
7217 | return VecTy && | |||
7218 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | |||
7219 | }; | |||
7220 | ||||
7221 | return ValidScalableConversion(srcTy, destTy) || | |||
7222 | ValidScalableConversion(destTy, srcTy); | |||
7223 | } | |||
7224 | ||||
7225 | /// Are the two types lax-compatible vector types? That is, given | |||
7226 | /// that one of them is a vector, do they have equal storage sizes, | |||
7227 | /// where the storage size is the number of elements times the element | |||
7228 | /// size? | |||
7229 | /// | |||
7230 | /// This will also return false if either of the types is neither a | |||
7231 | /// vector nor a real type. | |||
7232 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | |||
7233 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7233, __PRETTY_FUNCTION__)); | |||
7234 | ||||
7235 | // Disallow lax conversions between scalars and ExtVectors (these | |||
7236 | // conversions are allowed for other vector types because common headers | |||
7237 | // depend on them). Most scalar OP ExtVector cases are handled by the | |||
7238 | // splat path anyway, which does what we want (convert, not bitcast). | |||
7239 | // What this rules out for ExtVectors is crazy things like char4*float. | |||
7240 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | |||
7241 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | |||
7242 | ||||
7243 | uint64_t srcLen, destLen; | |||
7244 | QualType srcEltTy, destEltTy; | |||
7245 | if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; | |||
7246 | if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; | |||
7247 | ||||
7248 | // ASTContext::getTypeSize will return the size rounded up to a | |||
7249 | // power of 2, so instead of using that, we need to use the raw | |||
7250 | // element size multiplied by the element count. | |||
7251 | uint64_t srcEltSize = Context.getTypeSize(srcEltTy); | |||
7252 | uint64_t destEltSize = Context.getTypeSize(destEltTy); | |||
7253 | ||||
7254 | return (srcLen * srcEltSize == destLen * destEltSize); | |||
7255 | } | |||
7256 | ||||
7257 | /// Is this a legal conversion between two types, one of which is | |||
7258 | /// known to be a vector type? | |||
7259 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | |||
7260 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7260, __PRETTY_FUNCTION__)); | |||
7261 | ||||
7262 | switch (Context.getLangOpts().getLaxVectorConversions()) { | |||
7263 | case LangOptions::LaxVectorConversionKind::None: | |||
7264 | return false; | |||
7265 | ||||
7266 | case LangOptions::LaxVectorConversionKind::Integer: | |||
7267 | if (!srcTy->isIntegralOrEnumerationType()) { | |||
7268 | auto *Vec = srcTy->getAs<VectorType>(); | |||
7269 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | |||
7270 | return false; | |||
7271 | } | |||
7272 | if (!destTy->isIntegralOrEnumerationType()) { | |||
7273 | auto *Vec = destTy->getAs<VectorType>(); | |||
7274 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | |||
7275 | return false; | |||
7276 | } | |||
7277 | // OK, integer (vector) -> integer (vector) bitcast. | |||
7278 | break; | |||
7279 | ||||
7280 | case LangOptions::LaxVectorConversionKind::All: | |||
7281 | break; | |||
7282 | } | |||
7283 | ||||
7284 | return areLaxCompatibleVectorTypes(srcTy, destTy); | |||
7285 | } | |||
7286 | ||||
7287 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | |||
7288 | CastKind &Kind) { | |||
7289 | assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!" ) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7289, __PRETTY_FUNCTION__)); | |||
7290 | ||||
7291 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | |||
7292 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | |||
7293 | return Diag(R.getBegin(), | |||
7294 | Ty->isVectorType() ? | |||
7295 | diag::err_invalid_conversion_between_vectors : | |||
7296 | diag::err_invalid_conversion_between_vector_and_integer) | |||
7297 | << VectorTy << Ty << R; | |||
7298 | } else | |||
7299 | return Diag(R.getBegin(), | |||
7300 | diag::err_invalid_conversion_between_vector_and_scalar) | |||
7301 | << VectorTy << Ty << R; | |||
7302 | ||||
7303 | Kind = CK_BitCast; | |||
7304 | return false; | |||
7305 | } | |||
7306 | ||||
7307 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | |||
7308 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | |||
7309 | ||||
7310 | if (DestElemTy == SplattedExpr->getType()) | |||
7311 | return SplattedExpr; | |||
7312 | ||||
7313 | assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7314, __PRETTY_FUNCTION__)) | |||
7314 | DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7314, __PRETTY_FUNCTION__)); | |||
7315 | ||||
7316 | CastKind CK; | |||
7317 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | |||
7318 | // OpenCL requires that we convert `true` boolean expressions to -1, but | |||
7319 | // only when splatting vectors. | |||
7320 | if (DestElemTy->isFloatingType()) { | |||
7321 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | |||
7322 | // in two steps: boolean to signed integral, then to floating. | |||
7323 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | |||
7324 | CK_BooleanToSignedIntegral); | |||
7325 | SplattedExpr = CastExprRes.get(); | |||
7326 | CK = CK_IntegralToFloating; | |||
7327 | } else { | |||
7328 | CK = CK_BooleanToSignedIntegral; | |||
7329 | } | |||
7330 | } else { | |||
7331 | ExprResult CastExprRes = SplattedExpr; | |||
7332 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | |||
7333 | if (CastExprRes.isInvalid()) | |||
7334 | return ExprError(); | |||
7335 | SplattedExpr = CastExprRes.get(); | |||
7336 | } | |||
7337 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | |||
7338 | } | |||
7339 | ||||
7340 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | |||
7341 | Expr *CastExpr, CastKind &Kind) { | |||
7342 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!" ) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7342, __PRETTY_FUNCTION__)); | |||
7343 | ||||
7344 | QualType SrcTy = CastExpr->getType(); | |||
7345 | ||||
7346 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | |||
7347 | // an ExtVectorType. | |||
7348 | // In OpenCL, casts between vectors of different types are not allowed. | |||
7349 | // (See OpenCL 6.2). | |||
7350 | if (SrcTy->isVectorType()) { | |||
7351 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | |||
7352 | (getLangOpts().OpenCL && | |||
7353 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | |||
7354 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | |||
7355 | << DestTy << SrcTy << R; | |||
7356 | return ExprError(); | |||
7357 | } | |||
7358 | Kind = CK_BitCast; | |||
7359 | return CastExpr; | |||
7360 | } | |||
7361 | ||||
7362 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | |||
7363 | // conversion will take place first from scalar to elt type, and then | |||
7364 | // splat from elt type to vector. | |||
7365 | if (SrcTy->isPointerType()) | |||
7366 | return Diag(R.getBegin(), | |||
7367 | diag::err_invalid_conversion_between_vector_and_scalar) | |||
7368 | << DestTy << SrcTy << R; | |||
7369 | ||||
7370 | Kind = CK_VectorSplat; | |||
7371 | return prepareVectorSplat(DestTy, CastExpr); | |||
7372 | } | |||
7373 | ||||
7374 | ExprResult | |||
7375 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | |||
7376 | Declarator &D, ParsedType &Ty, | |||
7377 | SourceLocation RParenLoc, Expr *CastExpr) { | |||
7378 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7379, __PRETTY_FUNCTION__)) | |||
7379 | "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7379, __PRETTY_FUNCTION__)); | |||
7380 | ||||
7381 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | |||
7382 | if (D.isInvalidType()) | |||
7383 | return ExprError(); | |||
7384 | ||||
7385 | if (getLangOpts().CPlusPlus) { | |||
7386 | // Check that there are no default arguments (C++ only). | |||
7387 | CheckExtraCXXDefaultArguments(D); | |||
7388 | } else { | |||
7389 | // Make sure any TypoExprs have been dealt with. | |||
7390 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | |||
7391 | if (!Res.isUsable()) | |||
7392 | return ExprError(); | |||
7393 | CastExpr = Res.get(); | |||
7394 | } | |||
7395 | ||||
7396 | checkUnusedDeclAttributes(D); | |||
7397 | ||||
7398 | QualType castType = castTInfo->getType(); | |||
7399 | Ty = CreateParsedType(castType, castTInfo); | |||
7400 | ||||
7401 | bool isVectorLiteral = false; | |||
7402 | ||||
7403 | // Check for an altivec or OpenCL literal, | |||
7404 | // i.e. all the elements are integer constants. | |||
7405 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | |||
7406 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | |||
7407 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | |||
7408 | && castType->isVectorType() && (PE || PLE)) { | |||
7409 | if (PLE && PLE->getNumExprs() == 0) { | |||
7410 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | |||
7411 | return ExprError(); | |||
7412 | } | |||
7413 | if (PE || PLE->getNumExprs() == 1) { | |||
7414 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | |||
7415 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | |||
7416 | isVectorLiteral = true; | |||
7417 | } | |||
7418 | else | |||
7419 | isVectorLiteral = true; | |||
7420 | } | |||
7421 | ||||
7422 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | |||
7423 | // then handle it as such. | |||
7424 | if (isVectorLiteral) | |||
7425 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | |||
7426 | ||||
7427 | // If the Expr being casted is a ParenListExpr, handle it specially. | |||
7428 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | |||
7429 | // sequence of BinOp comma operators. | |||
7430 | if (isa<ParenListExpr>(CastExpr)) { | |||
7431 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | |||
7432 | if (Result.isInvalid()) return ExprError(); | |||
7433 | CastExpr = Result.get(); | |||
7434 | } | |||
7435 | ||||
7436 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && | |||
7437 | !getSourceManager().isInSystemMacro(LParenLoc)) | |||
7438 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | |||
7439 | ||||
7440 | CheckTollFreeBridgeCast(castType, CastExpr); | |||
7441 | ||||
7442 | CheckObjCBridgeRelatedCast(castType, CastExpr); | |||
7443 | ||||
7444 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | |||
7445 | ||||
7446 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | |||
7447 | } | |||
7448 | ||||
7449 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | |||
7450 | SourceLocation RParenLoc, Expr *E, | |||
7451 | TypeSourceInfo *TInfo) { | |||
7452 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7453, __PRETTY_FUNCTION__)) | |||
7453 | "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7453, __PRETTY_FUNCTION__)); | |||
7454 | ||||
7455 | Expr **exprs; | |||
7456 | unsigned numExprs; | |||
7457 | Expr *subExpr; | |||
7458 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | |||
7459 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | |||
7460 | LiteralLParenLoc = PE->getLParenLoc(); | |||
7461 | LiteralRParenLoc = PE->getRParenLoc(); | |||
7462 | exprs = PE->getExprs(); | |||
7463 | numExprs = PE->getNumExprs(); | |||
7464 | } else { // isa<ParenExpr> by assertion at function entrance | |||
7465 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | |||
7466 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | |||
7467 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | |||
7468 | exprs = &subExpr; | |||
7469 | numExprs = 1; | |||
7470 | } | |||
7471 | ||||
7472 | QualType Ty = TInfo->getType(); | |||
7473 | assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast <void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7473, __PRETTY_FUNCTION__)); | |||
7474 | ||||
7475 | SmallVector<Expr *, 8> initExprs; | |||
7476 | const VectorType *VTy = Ty->castAs<VectorType>(); | |||
7477 | unsigned numElems = VTy->getNumElements(); | |||
7478 | ||||
7479 | // '(...)' form of vector initialization in AltiVec: the number of | |||
7480 | // initializers must be one or must match the size of the vector. | |||
7481 | // If a single value is specified in the initializer then it will be | |||
7482 | // replicated to all the components of the vector | |||
7483 | if (VTy->getVectorKind() == VectorType::AltiVecVector) { | |||
7484 | // The number of initializers must be one or must match the size of the | |||
7485 | // vector. If a single value is specified in the initializer then it will | |||
7486 | // be replicated to all the components of the vector | |||
7487 | if (numExprs == 1) { | |||
7488 | QualType ElemTy = VTy->getElementType(); | |||
7489 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | |||
7490 | if (Literal.isInvalid()) | |||
7491 | return ExprError(); | |||
7492 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | |||
7493 | PrepareScalarCast(Literal, ElemTy)); | |||
7494 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | |||
7495 | } | |||
7496 | else if (numExprs < numElems) { | |||
7497 | Diag(E->getExprLoc(), | |||
7498 | diag::err_incorrect_number_of_vector_initializers); | |||
7499 | return ExprError(); | |||
7500 | } | |||
7501 | else | |||
7502 | initExprs.append(exprs, exprs + numExprs); | |||
7503 | } | |||
7504 | else { | |||
7505 | // For OpenCL, when the number of initializers is a single value, | |||
7506 | // it will be replicated to all components of the vector. | |||
7507 | if (getLangOpts().OpenCL && | |||
7508 | VTy->getVectorKind() == VectorType::GenericVector && | |||
7509 | numExprs == 1) { | |||
7510 | QualType ElemTy = VTy->getElementType(); | |||
7511 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | |||
7512 | if (Literal.isInvalid()) | |||
7513 | return ExprError(); | |||
7514 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | |||
7515 | PrepareScalarCast(Literal, ElemTy)); | |||
7516 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | |||
7517 | } | |||
7518 | ||||
7519 | initExprs.append(exprs, exprs + numExprs); | |||
7520 | } | |||
7521 | // FIXME: This means that pretty-printing the final AST will produce curly | |||
7522 | // braces instead of the original commas. | |||
7523 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | |||
7524 | initExprs, LiteralRParenLoc); | |||
7525 | initE->setType(Ty); | |||
7526 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | |||
7527 | } | |||
7528 | ||||
7529 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | |||
7530 | /// the ParenListExpr into a sequence of comma binary operators. | |||
7531 | ExprResult | |||
7532 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | |||
7533 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | |||
7534 | if (!E) | |||
7535 | return OrigExpr; | |||
7536 | ||||
7537 | ExprResult Result(E->getExpr(0)); | |||
7538 | ||||
7539 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | |||
7540 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | |||
7541 | E->getExpr(i)); | |||
7542 | ||||
7543 | if (Result.isInvalid()) return ExprError(); | |||
7544 | ||||
7545 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | |||
7546 | } | |||
7547 | ||||
7548 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | |||
7549 | SourceLocation R, | |||
7550 | MultiExprArg Val) { | |||
7551 | return ParenListExpr::Create(Context, L, Val, R); | |||
7552 | } | |||
7553 | ||||
7554 | /// Emit a specialized diagnostic when one expression is a null pointer | |||
7555 | /// constant and the other is not a pointer. Returns true if a diagnostic is | |||
7556 | /// emitted. | |||
7557 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | |||
7558 | SourceLocation QuestionLoc) { | |||
7559 | Expr *NullExpr = LHSExpr; | |||
7560 | Expr *NonPointerExpr = RHSExpr; | |||
7561 | Expr::NullPointerConstantKind NullKind = | |||
7562 | NullExpr->isNullPointerConstant(Context, | |||
7563 | Expr::NPC_ValueDependentIsNotNull); | |||
7564 | ||||
7565 | if (NullKind == Expr::NPCK_NotNull) { | |||
7566 | NullExpr = RHSExpr; | |||
7567 | NonPointerExpr = LHSExpr; | |||
7568 | NullKind = | |||
7569 | NullExpr->isNullPointerConstant(Context, | |||
7570 | Expr::NPC_ValueDependentIsNotNull); | |||
7571 | } | |||
7572 | ||||
7573 | if (NullKind == Expr::NPCK_NotNull) | |||
7574 | return false; | |||
7575 | ||||
7576 | if (NullKind == Expr::NPCK_ZeroExpression) | |||
7577 | return false; | |||
7578 | ||||
7579 | if (NullKind == Expr::NPCK_ZeroLiteral) { | |||
7580 | // In this case, check to make sure that we got here from a "NULL" | |||
7581 | // string in the source code. | |||
7582 | NullExpr = NullExpr->IgnoreParenImpCasts(); | |||
7583 | SourceLocation loc = NullExpr->getExprLoc(); | |||
7584 | if (!findMacroSpelling(loc, "NULL")) | |||
7585 | return false; | |||
7586 | } | |||
7587 | ||||
7588 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | |||
7589 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | |||
7590 | << NonPointerExpr->getType() << DiagType | |||
7591 | << NonPointerExpr->getSourceRange(); | |||
7592 | return true; | |||
7593 | } | |||
7594 | ||||
7595 | /// Return false if the condition expression is valid, true otherwise. | |||
7596 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | |||
7597 | QualType CondTy = Cond->getType(); | |||
7598 | ||||
7599 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | |||
7600 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | |||
7601 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | |||
7602 | << CondTy << Cond->getSourceRange(); | |||
7603 | return true; | |||
7604 | } | |||
7605 | ||||
7606 | // C99 6.5.15p2 | |||
7607 | if (CondTy->isScalarType()) return false; | |||
7608 | ||||
7609 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | |||
7610 | << CondTy << Cond->getSourceRange(); | |||
7611 | return true; | |||
7612 | } | |||
7613 | ||||
7614 | /// Handle when one or both operands are void type. | |||
7615 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | |||
7616 | ExprResult &RHS) { | |||
7617 | Expr *LHSExpr = LHS.get(); | |||
7618 | Expr *RHSExpr = RHS.get(); | |||
7619 | ||||
7620 | if (!LHSExpr->getType()->isVoidType()) | |||
7621 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | |||
7622 | << RHSExpr->getSourceRange(); | |||
7623 | if (!RHSExpr->getType()->isVoidType()) | |||
7624 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | |||
7625 | << LHSExpr->getSourceRange(); | |||
7626 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | |||
7627 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | |||
7628 | return S.Context.VoidTy; | |||
7629 | } | |||
7630 | ||||
7631 | /// Return false if the NullExpr can be promoted to PointerTy, | |||
7632 | /// true otherwise. | |||
7633 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | |||
7634 | QualType PointerTy) { | |||
7635 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | |||
7636 | !NullExpr.get()->isNullPointerConstant(S.Context, | |||
7637 | Expr::NPC_ValueDependentIsNull)) | |||
7638 | return true; | |||
7639 | ||||
7640 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | |||
7641 | return false; | |||
7642 | } | |||
7643 | ||||
7644 | /// Checks compatibility between two pointers and return the resulting | |||
7645 | /// type. | |||
7646 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | |||
7647 | ExprResult &RHS, | |||
7648 | SourceLocation Loc) { | |||
7649 | QualType LHSTy = LHS.get()->getType(); | |||
7650 | QualType RHSTy = RHS.get()->getType(); | |||
7651 | ||||
7652 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | |||
7653 | // Two identical pointers types are always compatible. | |||
7654 | return LHSTy; | |||
7655 | } | |||
7656 | ||||
7657 | QualType lhptee, rhptee; | |||
7658 | ||||
7659 | // Get the pointee types. | |||
7660 | bool IsBlockPointer = false; | |||
7661 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | |||
7662 | lhptee = LHSBTy->getPointeeType(); | |||
7663 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | |||
7664 | IsBlockPointer = true; | |||
7665 | } else { | |||
7666 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
7667 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
7668 | } | |||
7669 | ||||
7670 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | |||
7671 | // differently qualified versions of compatible types, the result type is | |||
7672 | // a pointer to an appropriately qualified version of the composite | |||
7673 | // type. | |||
7674 | ||||
7675 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | |||
7676 | // clause doesn't make sense for our extensions. E.g. address space 2 should | |||
7677 | // be incompatible with address space 3: they may live on different devices or | |||
7678 | // anything. | |||
7679 | Qualifiers lhQual = lhptee.getQualifiers(); | |||
7680 | Qualifiers rhQual = rhptee.getQualifiers(); | |||
7681 | ||||
7682 | LangAS ResultAddrSpace = LangAS::Default; | |||
7683 | LangAS LAddrSpace = lhQual.getAddressSpace(); | |||
7684 | LangAS RAddrSpace = rhQual.getAddressSpace(); | |||
7685 | ||||
7686 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | |||
7687 | // spaces is disallowed. | |||
7688 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | |||
7689 | ResultAddrSpace = LAddrSpace; | |||
7690 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | |||
7691 | ResultAddrSpace = RAddrSpace; | |||
7692 | else { | |||
7693 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
7694 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | |||
7695 | << RHS.get()->getSourceRange(); | |||
7696 | return QualType(); | |||
7697 | } | |||
7698 | ||||
7699 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | |||
7700 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | |||
7701 | lhQual.removeCVRQualifiers(); | |||
7702 | rhQual.removeCVRQualifiers(); | |||
7703 | ||||
7704 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | |||
7705 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | |||
7706 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | |||
7707 | // qual types are compatible iff | |||
7708 | // * corresponded types are compatible | |||
7709 | // * CVR qualifiers are equal | |||
7710 | // * address spaces are equal | |||
7711 | // Thus for conditional operator we merge CVR and address space unqualified | |||
7712 | // pointees and if there is a composite type we return a pointer to it with | |||
7713 | // merged qualifiers. | |||
7714 | LHSCastKind = | |||
7715 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | |||
7716 | RHSCastKind = | |||
7717 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | |||
7718 | lhQual.removeAddressSpace(); | |||
7719 | rhQual.removeAddressSpace(); | |||
7720 | ||||
7721 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | |||
7722 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | |||
7723 | ||||
7724 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | |||
7725 | ||||
7726 | if (CompositeTy.isNull()) { | |||
7727 | // In this situation, we assume void* type. No especially good | |||
7728 | // reason, but this is what gcc does, and we do have to pick | |||
7729 | // to get a consistent AST. | |||
7730 | QualType incompatTy; | |||
7731 | incompatTy = S.Context.getPointerType( | |||
7732 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | |||
7733 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | |||
7734 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | |||
7735 | ||||
7736 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | |||
7737 | // for casts between types with incompatible address space qualifiers. | |||
7738 | // For the following code the compiler produces casts between global and | |||
7739 | // local address spaces of the corresponded innermost pointees: | |||
7740 | // local int *global *a; | |||
7741 | // global int *global *b; | |||
7742 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | |||
7743 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | |||
7744 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
7745 | << RHS.get()->getSourceRange(); | |||
7746 | ||||
7747 | return incompatTy; | |||
7748 | } | |||
7749 | ||||
7750 | // The pointer types are compatible. | |||
7751 | // In case of OpenCL ResultTy should have the address space qualifier | |||
7752 | // which is a superset of address spaces of both the 2nd and the 3rd | |||
7753 | // operands of the conditional operator. | |||
7754 | QualType ResultTy = [&, ResultAddrSpace]() { | |||
7755 | if (S.getLangOpts().OpenCL) { | |||
7756 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | |||
7757 | CompositeQuals.setAddressSpace(ResultAddrSpace); | |||
7758 | return S.Context | |||
7759 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | |||
7760 | .withCVRQualifiers(MergedCVRQual); | |||
7761 | } | |||
7762 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | |||
7763 | }(); | |||
7764 | if (IsBlockPointer) | |||
7765 | ResultTy = S.Context.getBlockPointerType(ResultTy); | |||
7766 | else | |||
7767 | ResultTy = S.Context.getPointerType(ResultTy); | |||
7768 | ||||
7769 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | |||
7770 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | |||
7771 | return ResultTy; | |||
7772 | } | |||
7773 | ||||
7774 | /// Return the resulting type when the operands are both block pointers. | |||
7775 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | |||
7776 | ExprResult &LHS, | |||
7777 | ExprResult &RHS, | |||
7778 | SourceLocation Loc) { | |||
7779 | QualType LHSTy = LHS.get()->getType(); | |||
7780 | QualType RHSTy = RHS.get()->getType(); | |||
7781 | ||||
7782 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | |||
7783 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | |||
7784 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | |||
7785 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
7786 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
7787 | return destType; | |||
7788 | } | |||
7789 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | |||
7790 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
7791 | << RHS.get()->getSourceRange(); | |||
7792 | return QualType(); | |||
7793 | } | |||
7794 | ||||
7795 | // We have 2 block pointer types. | |||
7796 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | |||
7797 | } | |||
7798 | ||||
7799 | /// Return the resulting type when the operands are both pointers. | |||
7800 | static QualType | |||
7801 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | |||
7802 | ExprResult &RHS, | |||
7803 | SourceLocation Loc) { | |||
7804 | // get the pointer types | |||
7805 | QualType LHSTy = LHS.get()->getType(); | |||
7806 | QualType RHSTy = RHS.get()->getType(); | |||
7807 | ||||
7808 | // get the "pointed to" types | |||
7809 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
7810 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
7811 | ||||
7812 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | |||
7813 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | |||
7814 | // Figure out necessary qualifiers (C99 6.5.15p6) | |||
7815 | QualType destPointee | |||
7816 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | |||
7817 | QualType destType = S.Context.getPointerType(destPointee); | |||
7818 | // Add qualifiers if necessary. | |||
7819 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | |||
7820 | // Promote to void*. | |||
7821 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
7822 | return destType; | |||
7823 | } | |||
7824 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | |||
7825 | QualType destPointee | |||
7826 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | |||
7827 | QualType destType = S.Context.getPointerType(destPointee); | |||
7828 | // Add qualifiers if necessary. | |||
7829 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | |||
7830 | // Promote to void*. | |||
7831 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
7832 | return destType; | |||
7833 | } | |||
7834 | ||||
7835 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | |||
7836 | } | |||
7837 | ||||
7838 | /// Return false if the first expression is not an integer and the second | |||
7839 | /// expression is not a pointer, true otherwise. | |||
7840 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | |||
7841 | Expr* PointerExpr, SourceLocation Loc, | |||
7842 | bool IsIntFirstExpr) { | |||
7843 | if (!PointerExpr->getType()->isPointerType() || | |||
7844 | !Int.get()->getType()->isIntegerType()) | |||
7845 | return false; | |||
7846 | ||||
7847 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | |||
7848 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | |||
7849 | ||||
7850 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | |||
7851 | << Expr1->getType() << Expr2->getType() | |||
7852 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | |||
7853 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | |||
7854 | CK_IntegralToPointer); | |||
7855 | return true; | |||
7856 | } | |||
7857 | ||||
7858 | /// Simple conversion between integer and floating point types. | |||
7859 | /// | |||
7860 | /// Used when handling the OpenCL conditional operator where the | |||
7861 | /// condition is a vector while the other operands are scalar. | |||
7862 | /// | |||
7863 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | |||
7864 | /// types are either integer or floating type. Between the two | |||
7865 | /// operands, the type with the higher rank is defined as the "result | |||
7866 | /// type". The other operand needs to be promoted to the same type. No | |||
7867 | /// other type promotion is allowed. We cannot use | |||
7868 | /// UsualArithmeticConversions() for this purpose, since it always | |||
7869 | /// promotes promotable types. | |||
7870 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | |||
7871 | ExprResult &RHS, | |||
7872 | SourceLocation QuestionLoc) { | |||
7873 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
7874 | if (LHS.isInvalid()) | |||
7875 | return QualType(); | |||
7876 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
7877 | if (RHS.isInvalid()) | |||
7878 | return QualType(); | |||
7879 | ||||
7880 | // For conversion purposes, we ignore any qualifiers. | |||
7881 | // For example, "const float" and "float" are equivalent. | |||
7882 | QualType LHSType = | |||
7883 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
7884 | QualType RHSType = | |||
7885 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
7886 | ||||
7887 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | |||
7888 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | |||
7889 | << LHSType << LHS.get()->getSourceRange(); | |||
7890 | return QualType(); | |||
7891 | } | |||
7892 | ||||
7893 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | |||
7894 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | |||
7895 | << RHSType << RHS.get()->getSourceRange(); | |||
7896 | return QualType(); | |||
7897 | } | |||
7898 | ||||
7899 | // If both types are identical, no conversion is needed. | |||
7900 | if (LHSType == RHSType) | |||
7901 | return LHSType; | |||
7902 | ||||
7903 | // Now handle "real" floating types (i.e. float, double, long double). | |||
7904 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
7905 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
7906 | /*IsCompAssign = */ false); | |||
7907 | ||||
7908 | // Finally, we have two differing integer types. | |||
7909 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
7910 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | |||
7911 | } | |||
7912 | ||||
7913 | /// Convert scalar operands to a vector that matches the | |||
7914 | /// condition in length. | |||
7915 | /// | |||
7916 | /// Used when handling the OpenCL conditional operator where the | |||
7917 | /// condition is a vector while the other operands are scalar. | |||
7918 | /// | |||
7919 | /// We first compute the "result type" for the scalar operands | |||
7920 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | |||
7921 | /// into a vector of that type where the length matches the condition | |||
7922 | /// vector type. s6.11.6 requires that the element types of the result | |||
7923 | /// and the condition must have the same number of bits. | |||
7924 | static QualType | |||
7925 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
7926 | QualType CondTy, SourceLocation QuestionLoc) { | |||
7927 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | |||
7928 | if (ResTy.isNull()) return QualType(); | |||
7929 | ||||
7930 | const VectorType *CV = CondTy->getAs<VectorType>(); | |||
7931 | assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7931, __PRETTY_FUNCTION__)); | |||
7932 | ||||
7933 | // Determine the vector result type | |||
7934 | unsigned NumElements = CV->getNumElements(); | |||
7935 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | |||
7936 | ||||
7937 | // Ensure that all types have the same number of bits | |||
7938 | if (S.Context.getTypeSize(CV->getElementType()) | |||
7939 | != S.Context.getTypeSize(ResTy)) { | |||
7940 | // Since VectorTy is created internally, it does not pretty print | |||
7941 | // with an OpenCL name. Instead, we just print a description. | |||
7942 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | |||
7943 | SmallString<64> Str; | |||
7944 | llvm::raw_svector_ostream OS(Str); | |||
7945 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | |||
7946 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
7947 | << CondTy << OS.str(); | |||
7948 | return QualType(); | |||
7949 | } | |||
7950 | ||||
7951 | // Convert operands to the vector result type | |||
7952 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | |||
7953 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | |||
7954 | ||||
7955 | return VectorTy; | |||
7956 | } | |||
7957 | ||||
7958 | /// Return false if this is a valid OpenCL condition vector | |||
7959 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | |||
7960 | SourceLocation QuestionLoc) { | |||
7961 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | |||
7962 | // integral type. | |||
7963 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | |||
7964 | assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7964, __PRETTY_FUNCTION__)); | |||
7965 | QualType EleTy = CondTy->getElementType(); | |||
7966 | if (EleTy->isIntegerType()) return false; | |||
7967 | ||||
7968 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | |||
7969 | << Cond->getType() << Cond->getSourceRange(); | |||
7970 | return true; | |||
7971 | } | |||
7972 | ||||
7973 | /// Return false if the vector condition type and the vector | |||
7974 | /// result type are compatible. | |||
7975 | /// | |||
7976 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | |||
7977 | /// number of elements, and their element types have the same number | |||
7978 | /// of bits. | |||
7979 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | |||
7980 | SourceLocation QuestionLoc) { | |||
7981 | const VectorType *CV = CondTy->getAs<VectorType>(); | |||
7982 | const VectorType *RV = VecResTy->getAs<VectorType>(); | |||
7983 | assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail ("CV && RV", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 7983, __PRETTY_FUNCTION__)); | |||
7984 | ||||
7985 | if (CV->getNumElements() != RV->getNumElements()) { | |||
7986 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | |||
7987 | << CondTy << VecResTy; | |||
7988 | return true; | |||
7989 | } | |||
7990 | ||||
7991 | QualType CVE = CV->getElementType(); | |||
7992 | QualType RVE = RV->getElementType(); | |||
7993 | ||||
7994 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | |||
7995 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
7996 | << CondTy << VecResTy; | |||
7997 | return true; | |||
7998 | } | |||
7999 | ||||
8000 | return false; | |||
8001 | } | |||
8002 | ||||
8003 | /// Return the resulting type for the conditional operator in | |||
8004 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | |||
8005 | /// s6.3.i) when the condition is a vector type. | |||
8006 | static QualType | |||
8007 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | |||
8008 | ExprResult &LHS, ExprResult &RHS, | |||
8009 | SourceLocation QuestionLoc) { | |||
8010 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | |||
8011 | if (Cond.isInvalid()) | |||
8012 | return QualType(); | |||
8013 | QualType CondTy = Cond.get()->getType(); | |||
8014 | ||||
8015 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | |||
8016 | return QualType(); | |||
8017 | ||||
8018 | // If either operand is a vector then find the vector type of the | |||
8019 | // result as specified in OpenCL v1.1 s6.3.i. | |||
8020 | if (LHS.get()->getType()->isVectorType() || | |||
8021 | RHS.get()->getType()->isVectorType()) { | |||
8022 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | |||
8023 | /*isCompAssign*/false, | |||
8024 | /*AllowBothBool*/true, | |||
8025 | /*AllowBoolConversions*/false); | |||
8026 | if (VecResTy.isNull()) return QualType(); | |||
8027 | // The result type must match the condition type as specified in | |||
8028 | // OpenCL v1.1 s6.11.6. | |||
8029 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | |||
8030 | return QualType(); | |||
8031 | return VecResTy; | |||
8032 | } | |||
8033 | ||||
8034 | // Both operands are scalar. | |||
8035 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | |||
8036 | } | |||
8037 | ||||
8038 | /// Return true if the Expr is block type | |||
8039 | static bool checkBlockType(Sema &S, const Expr *E) { | |||
8040 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
8041 | QualType Ty = CE->getCallee()->getType(); | |||
8042 | if (Ty->isBlockPointerType()) { | |||
8043 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | |||
8044 | return true; | |||
8045 | } | |||
8046 | } | |||
8047 | return false; | |||
8048 | } | |||
8049 | ||||
8050 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | |||
8051 | /// In that case, LHS = cond. | |||
8052 | /// C99 6.5.15 | |||
8053 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | |||
8054 | ExprResult &RHS, ExprValueKind &VK, | |||
8055 | ExprObjectKind &OK, | |||
8056 | SourceLocation QuestionLoc) { | |||
8057 | ||||
8058 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | |||
8059 | if (!LHSResult.isUsable()) return QualType(); | |||
8060 | LHS = LHSResult; | |||
8061 | ||||
8062 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | |||
8063 | if (!RHSResult.isUsable()) return QualType(); | |||
8064 | RHS = RHSResult; | |||
8065 | ||||
8066 | // C++ is sufficiently different to merit its own checker. | |||
8067 | if (getLangOpts().CPlusPlus) | |||
8068 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | |||
8069 | ||||
8070 | VK = VK_RValue; | |||
8071 | OK = OK_Ordinary; | |||
8072 | ||||
8073 | if (Context.isDependenceAllowed() && | |||
8074 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | |||
8075 | RHS.get()->isTypeDependent())) { | |||
8076 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8076, __PRETTY_FUNCTION__)); | |||
8077 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8079, __PRETTY_FUNCTION__)) | |||
8078 | RHS.get()->containsErrors()) &&(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8079, __PRETTY_FUNCTION__)) | |||
8079 | "should only occur in error-recovery path.")(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8079, __PRETTY_FUNCTION__)); | |||
8080 | return Context.DependentTy; | |||
8081 | } | |||
8082 | ||||
8083 | // The OpenCL operator with a vector condition is sufficiently | |||
8084 | // different to merit its own checker. | |||
8085 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | |||
8086 | Cond.get()->getType()->isExtVectorType()) | |||
8087 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | |||
8088 | ||||
8089 | // First, check the condition. | |||
8090 | Cond = UsualUnaryConversions(Cond.get()); | |||
8091 | if (Cond.isInvalid()) | |||
8092 | return QualType(); | |||
8093 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | |||
8094 | return QualType(); | |||
8095 | ||||
8096 | // Now check the two expressions. | |||
8097 | if (LHS.get()->getType()->isVectorType() || | |||
8098 | RHS.get()->getType()->isVectorType()) | |||
8099 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | |||
8100 | /*AllowBothBool*/true, | |||
8101 | /*AllowBoolConversions*/false); | |||
8102 | ||||
8103 | QualType ResTy = | |||
8104 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | |||
8105 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8106 | return QualType(); | |||
8107 | ||||
8108 | QualType LHSTy = LHS.get()->getType(); | |||
8109 | QualType RHSTy = RHS.get()->getType(); | |||
8110 | ||||
8111 | // Diagnose attempts to convert between __float128 and long double where | |||
8112 | // such conversions currently can't be handled. | |||
8113 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | |||
8114 | Diag(QuestionLoc, | |||
8115 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | |||
8116 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8117 | return QualType(); | |||
8118 | } | |||
8119 | ||||
8120 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | |||
8121 | // selection operator (?:). | |||
8122 | if (getLangOpts().OpenCL && | |||
8123 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { | |||
8124 | return QualType(); | |||
8125 | } | |||
8126 | ||||
8127 | // If both operands have arithmetic type, do the usual arithmetic conversions | |||
8128 | // to find a common type: C99 6.5.15p3,5. | |||
8129 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | |||
8130 | // Disallow invalid arithmetic conversions, such as those between ExtInts of | |||
8131 | // different sizes, or between ExtInts and other types. | |||
8132 | if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { | |||
8133 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
8134 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
8135 | << RHS.get()->getSourceRange(); | |||
8136 | return QualType(); | |||
8137 | } | |||
8138 | ||||
8139 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | |||
8140 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | |||
8141 | ||||
8142 | return ResTy; | |||
8143 | } | |||
8144 | ||||
8145 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | |||
8146 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | |||
8147 | return LHSTy; | |||
8148 | } | |||
8149 | ||||
8150 | // If both operands are the same structure or union type, the result is that | |||
8151 | // type. | |||
8152 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | |||
8153 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | |||
8154 | if (LHSRT->getDecl() == RHSRT->getDecl()) | |||
8155 | // "If both the operands have structure or union type, the result has | |||
8156 | // that type." This implies that CV qualifiers are dropped. | |||
8157 | return LHSTy.getUnqualifiedType(); | |||
8158 | // FIXME: Type of conditional expression must be complete in C mode. | |||
8159 | } | |||
8160 | ||||
8161 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | |||
8162 | // The following || allows only one side to be void (a GCC-ism). | |||
8163 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | |||
8164 | return checkConditionalVoidType(*this, LHS, RHS); | |||
8165 | } | |||
8166 | ||||
8167 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | |||
8168 | // the type of the other operand." | |||
8169 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | |||
8170 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | |||
8171 | ||||
8172 | // All objective-c pointer type analysis is done here. | |||
8173 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | |||
8174 | QuestionLoc); | |||
8175 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
8176 | return QualType(); | |||
8177 | if (!compositeType.isNull()) | |||
8178 | return compositeType; | |||
8179 | ||||
8180 | ||||
8181 | // Handle block pointer types. | |||
8182 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | |||
8183 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | |||
8184 | QuestionLoc); | |||
8185 | ||||
8186 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | |||
8187 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | |||
8188 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | |||
8189 | QuestionLoc); | |||
8190 | ||||
8191 | // GCC compatibility: soften pointer/integer mismatch. Note that | |||
8192 | // null pointers have been filtered out by this point. | |||
8193 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | |||
8194 | /*IsIntFirstExpr=*/true)) | |||
8195 | return RHSTy; | |||
8196 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | |||
8197 | /*IsIntFirstExpr=*/false)) | |||
8198 | return LHSTy; | |||
8199 | ||||
8200 | // Allow ?: operations in which both operands have the same | |||
8201 | // built-in sizeless type. | |||
8202 | if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) | |||
8203 | return LHSTy; | |||
8204 | ||||
8205 | // Emit a better diagnostic if one of the expressions is a null pointer | |||
8206 | // constant and the other is not a pointer type. In this case, the user most | |||
8207 | // likely forgot to take the address of the other expression. | |||
8208 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
8209 | return QualType(); | |||
8210 | ||||
8211 | // Otherwise, the operands are not compatible. | |||
8212 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
8213 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | |||
8214 | << RHS.get()->getSourceRange(); | |||
8215 | return QualType(); | |||
8216 | } | |||
8217 | ||||
8218 | /// FindCompositeObjCPointerType - Helper method to find composite type of | |||
8219 | /// two objective-c pointer types of the two input expressions. | |||
8220 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | |||
8221 | SourceLocation QuestionLoc) { | |||
8222 | QualType LHSTy = LHS.get()->getType(); | |||
8223 | QualType RHSTy = RHS.get()->getType(); | |||
8224 | ||||
8225 | // Handle things like Class and struct objc_class*. Here we case the result | |||
8226 | // to the pseudo-builtin, because that will be implicitly cast back to the | |||
8227 | // redefinition type if an attempt is made to access its fields. | |||
8228 | if (LHSTy->isObjCClassType() && | |||
8229 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | |||
8230 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | |||
8231 | return LHSTy; | |||
8232 | } | |||
8233 | if (RHSTy->isObjCClassType() && | |||
8234 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | |||
8235 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | |||
8236 | return RHSTy; | |||
8237 | } | |||
8238 | // And the same for struct objc_object* / id | |||
8239 | if (LHSTy->isObjCIdType() && | |||
8240 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | |||
8241 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | |||
8242 | return LHSTy; | |||
8243 | } | |||
8244 | if (RHSTy->isObjCIdType() && | |||
8245 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | |||
8246 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | |||
8247 | return RHSTy; | |||
8248 | } | |||
8249 | // And the same for struct objc_selector* / SEL | |||
8250 | if (Context.isObjCSelType(LHSTy) && | |||
8251 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | |||
8252 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | |||
8253 | return LHSTy; | |||
8254 | } | |||
8255 | if (Context.isObjCSelType(RHSTy) && | |||
8256 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | |||
8257 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | |||
8258 | return RHSTy; | |||
8259 | } | |||
8260 | // Check constraints for Objective-C object pointers types. | |||
8261 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | |||
8262 | ||||
8263 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | |||
8264 | // Two identical object pointer types are always compatible. | |||
8265 | return LHSTy; | |||
8266 | } | |||
8267 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | |||
8268 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | |||
8269 | QualType compositeType = LHSTy; | |||
8270 | ||||
8271 | // If both operands are interfaces and either operand can be | |||
8272 | // assigned to the other, use that type as the composite | |||
8273 | // type. This allows | |||
8274 | // xxx ? (A*) a : (B*) b | |||
8275 | // where B is a subclass of A. | |||
8276 | // | |||
8277 | // Additionally, as for assignment, if either type is 'id' | |||
8278 | // allow silent coercion. Finally, if the types are | |||
8279 | // incompatible then make sure to use 'id' as the composite | |||
8280 | // type so the result is acceptable for sending messages to. | |||
8281 | ||||
8282 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | |||
8283 | // It could return the composite type. | |||
8284 | if (!(compositeType = | |||
8285 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | |||
8286 | // Nothing more to do. | |||
8287 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | |||
8288 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | |||
8289 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | |||
8290 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | |||
8291 | } else if ((LHSOPT->isObjCQualifiedIdType() || | |||
8292 | RHSOPT->isObjCQualifiedIdType()) && | |||
8293 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | |||
8294 | true)) { | |||
8295 | // Need to handle "id<xx>" explicitly. | |||
8296 | // GCC allows qualified id and any Objective-C type to devolve to | |||
8297 | // id. Currently localizing to here until clear this should be | |||
8298 | // part of ObjCQualifiedIdTypesAreCompatible. | |||
8299 | compositeType = Context.getObjCIdType(); | |||
8300 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | |||
8301 | compositeType = Context.getObjCIdType(); | |||
8302 | } else { | |||
8303 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | |||
8304 | << LHSTy << RHSTy | |||
8305 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8306 | QualType incompatTy = Context.getObjCIdType(); | |||
8307 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | |||
8308 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | |||
8309 | return incompatTy; | |||
8310 | } | |||
8311 | // The object pointer types are compatible. | |||
8312 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | |||
8313 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | |||
8314 | return compositeType; | |||
8315 | } | |||
8316 | // Check Objective-C object pointer types and 'void *' | |||
8317 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | |||
8318 | if (getLangOpts().ObjCAutoRefCount) { | |||
8319 | // ARC forbids the implicit conversion of object pointers to 'void *', | |||
8320 | // so these types are not compatible. | |||
8321 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | |||
8322 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8323 | LHS = RHS = true; | |||
8324 | return QualType(); | |||
8325 | } | |||
8326 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | |||
8327 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
8328 | QualType destPointee | |||
8329 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | |||
8330 | QualType destType = Context.getPointerType(destPointee); | |||
8331 | // Add qualifiers if necessary. | |||
8332 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | |||
8333 | // Promote to void*. | |||
8334 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | |||
8335 | return destType; | |||
8336 | } | |||
8337 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | |||
8338 | if (getLangOpts().ObjCAutoRefCount) { | |||
8339 | // ARC forbids the implicit conversion of object pointers to 'void *', | |||
8340 | // so these types are not compatible. | |||
8341 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | |||
8342 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
8343 | LHS = RHS = true; | |||
8344 | return QualType(); | |||
8345 | } | |||
8346 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
8347 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | |||
8348 | QualType destPointee | |||
8349 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | |||
8350 | QualType destType = Context.getPointerType(destPointee); | |||
8351 | // Add qualifiers if necessary. | |||
8352 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | |||
8353 | // Promote to void*. | |||
8354 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | |||
8355 | return destType; | |||
8356 | } | |||
8357 | return QualType(); | |||
8358 | } | |||
8359 | ||||
8360 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | |||
8361 | /// ParenRange in parentheses. | |||
8362 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | |||
8363 | const PartialDiagnostic &Note, | |||
8364 | SourceRange ParenRange) { | |||
8365 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | |||
8366 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | |||
8367 | EndLoc.isValid()) { | |||
8368 | Self.Diag(Loc, Note) | |||
8369 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | |||
8370 | << FixItHint::CreateInsertion(EndLoc, ")"); | |||
8371 | } else { | |||
8372 | // We can't display the parentheses, so just show the bare note. | |||
8373 | Self.Diag(Loc, Note) << ParenRange; | |||
8374 | } | |||
8375 | } | |||
8376 | ||||
8377 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | |||
8378 | return BinaryOperator::isAdditiveOp(Opc) || | |||
8379 | BinaryOperator::isMultiplicativeOp(Opc) || | |||
8380 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | |||
8381 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | |||
8382 | // not any of the logical operators. Bitwise-xor is commonly used as a | |||
8383 | // logical-xor because there is no logical-xor operator. The logical | |||
8384 | // operators, including uses of xor, have a high false positive rate for | |||
8385 | // precedence warnings. | |||
8386 | } | |||
8387 | ||||
8388 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | |||
8389 | /// expression, either using a built-in or overloaded operator, | |||
8390 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | |||
8391 | /// expression. | |||
8392 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | |||
8393 | Expr **RHSExprs) { | |||
8394 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | |||
8395 | E = E->IgnoreImpCasts(); | |||
8396 | E = E->IgnoreConversionOperatorSingleStep(); | |||
8397 | E = E->IgnoreImpCasts(); | |||
8398 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | |||
8399 | E = MTE->getSubExpr(); | |||
8400 | E = E->IgnoreImpCasts(); | |||
8401 | } | |||
8402 | ||||
8403 | // Built-in binary operator. | |||
8404 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | |||
8405 | if (IsArithmeticOp(OP->getOpcode())) { | |||
8406 | *Opcode = OP->getOpcode(); | |||
8407 | *RHSExprs = OP->getRHS(); | |||
8408 | return true; | |||
8409 | } | |||
8410 | } | |||
8411 | ||||
8412 | // Overloaded operator. | |||
8413 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
8414 | if (Call->getNumArgs() != 2) | |||
8415 | return false; | |||
8416 | ||||
8417 | // Make sure this is really a binary operator that is safe to pass into | |||
8418 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | |||
8419 | OverloadedOperatorKind OO = Call->getOperator(); | |||
8420 | if (OO < OO_Plus || OO > OO_Arrow || | |||
8421 | OO == OO_PlusPlus || OO == OO_MinusMinus) | |||
8422 | return false; | |||
8423 | ||||
8424 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | |||
8425 | if (IsArithmeticOp(OpKind)) { | |||
8426 | *Opcode = OpKind; | |||
8427 | *RHSExprs = Call->getArg(1); | |||
8428 | return true; | |||
8429 | } | |||
8430 | } | |||
8431 | ||||
8432 | return false; | |||
8433 | } | |||
8434 | ||||
8435 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | |||
8436 | /// or is a logical expression such as (x==y) which has int type, but is | |||
8437 | /// commonly interpreted as boolean. | |||
8438 | static bool ExprLooksBoolean(Expr *E) { | |||
8439 | E = E->IgnoreParenImpCasts(); | |||
8440 | ||||
8441 | if (E->getType()->isBooleanType()) | |||
8442 | return true; | |||
8443 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | |||
8444 | return OP->isComparisonOp() || OP->isLogicalOp(); | |||
8445 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | |||
8446 | return OP->getOpcode() == UO_LNot; | |||
8447 | if (E->getType()->isPointerType()) | |||
8448 | return true; | |||
8449 | // FIXME: What about overloaded operator calls returning "unspecified boolean | |||
8450 | // type"s (commonly pointer-to-members)? | |||
8451 | ||||
8452 | return false; | |||
8453 | } | |||
8454 | ||||
8455 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | |||
8456 | /// and binary operator are mixed in a way that suggests the programmer assumed | |||
8457 | /// the conditional operator has higher precedence, for example: | |||
8458 | /// "int x = a + someBinaryCondition ? 1 : 2". | |||
8459 | static void DiagnoseConditionalPrecedence(Sema &Self, | |||
8460 | SourceLocation OpLoc, | |||
8461 | Expr *Condition, | |||
8462 | Expr *LHSExpr, | |||
8463 | Expr *RHSExpr) { | |||
8464 | BinaryOperatorKind CondOpcode; | |||
8465 | Expr *CondRHS; | |||
8466 | ||||
8467 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | |||
8468 | return; | |||
8469 | if (!ExprLooksBoolean(CondRHS)) | |||
8470 | return; | |||
8471 | ||||
8472 | // The condition is an arithmetic binary expression, with a right- | |||
8473 | // hand side that looks boolean, so warn. | |||
8474 | ||||
8475 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | |||
8476 | ? diag::warn_precedence_bitwise_conditional | |||
8477 | : diag::warn_precedence_conditional; | |||
8478 | ||||
8479 | Self.Diag(OpLoc, DiagID) | |||
8480 | << Condition->getSourceRange() | |||
8481 | << BinaryOperator::getOpcodeStr(CondOpcode); | |||
8482 | ||||
8483 | SuggestParentheses( | |||
8484 | Self, OpLoc, | |||
8485 | Self.PDiag(diag::note_precedence_silence) | |||
8486 | << BinaryOperator::getOpcodeStr(CondOpcode), | |||
8487 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | |||
8488 | ||||
8489 | SuggestParentheses(Self, OpLoc, | |||
8490 | Self.PDiag(diag::note_precedence_conditional_first), | |||
8491 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | |||
8492 | } | |||
8493 | ||||
8494 | /// Compute the nullability of a conditional expression. | |||
8495 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | |||
8496 | QualType LHSTy, QualType RHSTy, | |||
8497 | ASTContext &Ctx) { | |||
8498 | if (!ResTy->isAnyPointerType()) | |||
8499 | return ResTy; | |||
8500 | ||||
8501 | auto GetNullability = [&Ctx](QualType Ty) { | |||
8502 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | |||
8503 | if (Kind) | |||
8504 | return *Kind; | |||
8505 | return NullabilityKind::Unspecified; | |||
8506 | }; | |||
8507 | ||||
8508 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | |||
8509 | NullabilityKind MergedKind; | |||
8510 | ||||
8511 | // Compute nullability of a binary conditional expression. | |||
8512 | if (IsBin) { | |||
8513 | if (LHSKind == NullabilityKind::NonNull) | |||
8514 | MergedKind = NullabilityKind::NonNull; | |||
8515 | else | |||
8516 | MergedKind = RHSKind; | |||
8517 | // Compute nullability of a normal conditional expression. | |||
8518 | } else { | |||
8519 | if (LHSKind == NullabilityKind::Nullable || | |||
8520 | RHSKind == NullabilityKind::Nullable) | |||
8521 | MergedKind = NullabilityKind::Nullable; | |||
8522 | else if (LHSKind == NullabilityKind::NonNull) | |||
8523 | MergedKind = RHSKind; | |||
8524 | else if (RHSKind == NullabilityKind::NonNull) | |||
8525 | MergedKind = LHSKind; | |||
8526 | else | |||
8527 | MergedKind = NullabilityKind::Unspecified; | |||
8528 | } | |||
8529 | ||||
8530 | // Return if ResTy already has the correct nullability. | |||
8531 | if (GetNullability(ResTy) == MergedKind) | |||
8532 | return ResTy; | |||
8533 | ||||
8534 | // Strip all nullability from ResTy. | |||
8535 | while (ResTy->getNullability(Ctx)) | |||
8536 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | |||
8537 | ||||
8538 | // Create a new AttributedType with the new nullability kind. | |||
8539 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | |||
8540 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | |||
8541 | } | |||
8542 | ||||
8543 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | |||
8544 | /// in the case of a the GNU conditional expr extension. | |||
8545 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | |||
8546 | SourceLocation ColonLoc, | |||
8547 | Expr *CondExpr, Expr *LHSExpr, | |||
8548 | Expr *RHSExpr) { | |||
8549 | if (!Context.isDependenceAllowed()) { | |||
8550 | // C cannot handle TypoExpr nodes in the condition because it | |||
8551 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
8552 | // been dealt with before checking the operands. | |||
8553 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | |||
8554 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | |||
8555 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | |||
8556 | ||||
8557 | if (!CondResult.isUsable()) | |||
8558 | return ExprError(); | |||
8559 | ||||
8560 | if (LHSExpr) { | |||
8561 | if (!LHSResult.isUsable()) | |||
8562 | return ExprError(); | |||
8563 | } | |||
8564 | ||||
8565 | if (!RHSResult.isUsable()) | |||
8566 | return ExprError(); | |||
8567 | ||||
8568 | CondExpr = CondResult.get(); | |||
8569 | LHSExpr = LHSResult.get(); | |||
8570 | RHSExpr = RHSResult.get(); | |||
8571 | } | |||
8572 | ||||
8573 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | |||
8574 | // was the condition. | |||
8575 | OpaqueValueExpr *opaqueValue = nullptr; | |||
8576 | Expr *commonExpr = nullptr; | |||
8577 | if (!LHSExpr) { | |||
8578 | commonExpr = CondExpr; | |||
8579 | // Lower out placeholder types first. This is important so that we don't | |||
8580 | // try to capture a placeholder. This happens in few cases in C++; such | |||
8581 | // as Objective-C++'s dictionary subscripting syntax. | |||
8582 | if (commonExpr->hasPlaceholderType()) { | |||
8583 | ExprResult result = CheckPlaceholderExpr(commonExpr); | |||
8584 | if (!result.isUsable()) return ExprError(); | |||
8585 | commonExpr = result.get(); | |||
8586 | } | |||
8587 | // We usually want to apply unary conversions *before* saving, except | |||
8588 | // in the special case of a C++ l-value conditional. | |||
8589 | if (!(getLangOpts().CPlusPlus | |||
8590 | && !commonExpr->isTypeDependent() | |||
8591 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | |||
8592 | && commonExpr->isGLValue() | |||
8593 | && commonExpr->isOrdinaryOrBitFieldObject() | |||
8594 | && RHSExpr->isOrdinaryOrBitFieldObject() | |||
8595 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | |||
8596 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | |||
8597 | if (commonRes.isInvalid()) | |||
8598 | return ExprError(); | |||
8599 | commonExpr = commonRes.get(); | |||
8600 | } | |||
8601 | ||||
8602 | // If the common expression is a class or array prvalue, materialize it | |||
8603 | // so that we can safely refer to it multiple times. | |||
8604 | if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || | |||
8605 | commonExpr->getType()->isArrayType())) { | |||
8606 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | |||
8607 | if (MatExpr.isInvalid()) | |||
8608 | return ExprError(); | |||
8609 | commonExpr = MatExpr.get(); | |||
8610 | } | |||
8611 | ||||
8612 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | |||
8613 | commonExpr->getType(), | |||
8614 | commonExpr->getValueKind(), | |||
8615 | commonExpr->getObjectKind(), | |||
8616 | commonExpr); | |||
8617 | LHSExpr = CondExpr = opaqueValue; | |||
8618 | } | |||
8619 | ||||
8620 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | |||
8621 | ExprValueKind VK = VK_RValue; | |||
8622 | ExprObjectKind OK = OK_Ordinary; | |||
8623 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | |||
8624 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | |||
8625 | VK, OK, QuestionLoc); | |||
8626 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | |||
8627 | RHS.isInvalid()) | |||
8628 | return ExprError(); | |||
8629 | ||||
8630 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | |||
8631 | RHS.get()); | |||
8632 | ||||
8633 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | |||
8634 | ||||
8635 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | |||
8636 | Context); | |||
8637 | ||||
8638 | if (!commonExpr) | |||
8639 | return new (Context) | |||
8640 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | |||
8641 | RHS.get(), result, VK, OK); | |||
8642 | ||||
8643 | return new (Context) BinaryConditionalOperator( | |||
8644 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | |||
8645 | ColonLoc, result, VK, OK); | |||
8646 | } | |||
8647 | ||||
8648 | // Check if we have a conversion between incompatible cmse function pointer | |||
8649 | // types, that is, a conversion between a function pointer with the | |||
8650 | // cmse_nonsecure_call attribute and one without. | |||
8651 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | |||
8652 | QualType ToType) { | |||
8653 | if (const auto *ToFn = | |||
8654 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | |||
8655 | if (const auto *FromFn = | |||
8656 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | |||
8657 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | |||
8658 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | |||
8659 | ||||
8660 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | |||
8661 | } | |||
8662 | } | |||
8663 | return false; | |||
8664 | } | |||
8665 | ||||
8666 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | |||
8667 | // being closely modeled after the C99 spec:-). The odd characteristic of this | |||
8668 | // routine is it effectively iqnores the qualifiers on the top level pointee. | |||
8669 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | |||
8670 | // FIXME: add a couple examples in this comment. | |||
8671 | static Sema::AssignConvertType | |||
8672 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | |||
8673 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8673, __PRETTY_FUNCTION__)); | |||
8674 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8674, __PRETTY_FUNCTION__)); | |||
8675 | ||||
8676 | // get the "pointed to" type (ignoring qualifiers at the top level) | |||
8677 | const Type *lhptee, *rhptee; | |||
8678 | Qualifiers lhq, rhq; | |||
8679 | std::tie(lhptee, lhq) = | |||
8680 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | |||
8681 | std::tie(rhptee, rhq) = | |||
8682 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | |||
8683 | ||||
8684 | Sema::AssignConvertType ConvTy = Sema::Compatible; | |||
8685 | ||||
8686 | // C99 6.5.16.1p1: This following citation is common to constraints | |||
8687 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | |||
8688 | // qualifiers of the type *pointed to* by the right; | |||
8689 | ||||
8690 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | |||
8691 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | |||
8692 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | |||
8693 | // Ignore lifetime for further calculation. | |||
8694 | lhq.removeObjCLifetime(); | |||
8695 | rhq.removeObjCLifetime(); | |||
8696 | } | |||
8697 | ||||
8698 | if (!lhq.compatiblyIncludes(rhq)) { | |||
8699 | // Treat address-space mismatches as fatal. | |||
8700 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | |||
8701 | return Sema::IncompatiblePointerDiscardsQualifiers; | |||
8702 | ||||
8703 | // It's okay to add or remove GC or lifetime qualifiers when converting to | |||
8704 | // and from void*. | |||
8705 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | |||
8706 | .compatiblyIncludes( | |||
8707 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | |||
8708 | && (lhptee->isVoidType() || rhptee->isVoidType())) | |||
8709 | ; // keep old | |||
8710 | ||||
8711 | // Treat lifetime mismatches as fatal. | |||
8712 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | |||
8713 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | |||
8714 | ||||
8715 | // For GCC/MS compatibility, other qualifier mismatches are treated | |||
8716 | // as still compatible in C. | |||
8717 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | |||
8718 | } | |||
8719 | ||||
8720 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | |||
8721 | // incomplete type and the other is a pointer to a qualified or unqualified | |||
8722 | // version of void... | |||
8723 | if (lhptee->isVoidType()) { | |||
8724 | if (rhptee->isIncompleteOrObjectType()) | |||
8725 | return ConvTy; | |||
8726 | ||||
8727 | // As an extension, we allow cast to/from void* to function pointer. | |||
8728 | assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8728, __PRETTY_FUNCTION__)); | |||
8729 | return Sema::FunctionVoidPointer; | |||
8730 | } | |||
8731 | ||||
8732 | if (rhptee->isVoidType()) { | |||
8733 | if (lhptee->isIncompleteOrObjectType()) | |||
8734 | return ConvTy; | |||
8735 | ||||
8736 | // As an extension, we allow cast to/from void* to function pointer. | |||
8737 | assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8737, __PRETTY_FUNCTION__)); | |||
8738 | return Sema::FunctionVoidPointer; | |||
8739 | } | |||
8740 | ||||
8741 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | |||
8742 | // unqualified versions of compatible types, ... | |||
8743 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | |||
8744 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | |||
8745 | // Check if the pointee types are compatible ignoring the sign. | |||
8746 | // We explicitly check for char so that we catch "char" vs | |||
8747 | // "unsigned char" on systems where "char" is unsigned. | |||
8748 | if (lhptee->isCharType()) | |||
8749 | ltrans = S.Context.UnsignedCharTy; | |||
8750 | else if (lhptee->hasSignedIntegerRepresentation()) | |||
8751 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | |||
8752 | ||||
8753 | if (rhptee->isCharType()) | |||
8754 | rtrans = S.Context.UnsignedCharTy; | |||
8755 | else if (rhptee->hasSignedIntegerRepresentation()) | |||
8756 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | |||
8757 | ||||
8758 | if (ltrans == rtrans) { | |||
8759 | // Types are compatible ignoring the sign. Qualifier incompatibility | |||
8760 | // takes priority over sign incompatibility because the sign | |||
8761 | // warning can be disabled. | |||
8762 | if (ConvTy != Sema::Compatible) | |||
8763 | return ConvTy; | |||
8764 | ||||
8765 | return Sema::IncompatiblePointerSign; | |||
8766 | } | |||
8767 | ||||
8768 | // If we are a multi-level pointer, it's possible that our issue is simply | |||
8769 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | |||
8770 | // the eventual target type is the same and the pointers have the same | |||
8771 | // level of indirection, this must be the issue. | |||
8772 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | |||
8773 | do { | |||
8774 | std::tie(lhptee, lhq) = | |||
8775 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | |||
8776 | std::tie(rhptee, rhq) = | |||
8777 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | |||
8778 | ||||
8779 | // Inconsistent address spaces at this point is invalid, even if the | |||
8780 | // address spaces would be compatible. | |||
8781 | // FIXME: This doesn't catch address space mismatches for pointers of | |||
8782 | // different nesting levels, like: | |||
8783 | // __local int *** a; | |||
8784 | // int ** b = a; | |||
8785 | // It's not clear how to actually determine when such pointers are | |||
8786 | // invalidly incompatible. | |||
8787 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | |||
8788 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | |||
8789 | ||||
8790 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | |||
8791 | ||||
8792 | if (lhptee == rhptee) | |||
8793 | return Sema::IncompatibleNestedPointerQualifiers; | |||
8794 | } | |||
8795 | ||||
8796 | // General pointer incompatibility takes priority over qualifiers. | |||
8797 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | |||
8798 | return Sema::IncompatibleFunctionPointer; | |||
8799 | return Sema::IncompatiblePointer; | |||
8800 | } | |||
8801 | if (!S.getLangOpts().CPlusPlus && | |||
8802 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | |||
8803 | return Sema::IncompatibleFunctionPointer; | |||
8804 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | |||
8805 | return Sema::IncompatibleFunctionPointer; | |||
8806 | return ConvTy; | |||
8807 | } | |||
8808 | ||||
8809 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | |||
8810 | /// block pointer types are compatible or whether a block and normal pointer | |||
8811 | /// are compatible. It is more restrict than comparing two function pointer | |||
8812 | // types. | |||
8813 | static Sema::AssignConvertType | |||
8814 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | |||
8815 | QualType RHSType) { | |||
8816 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8816, __PRETTY_FUNCTION__)); | |||
8817 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8817, __PRETTY_FUNCTION__)); | |||
8818 | ||||
8819 | QualType lhptee, rhptee; | |||
8820 | ||||
8821 | // get the "pointed to" type (ignoring qualifiers at the top level) | |||
8822 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | |||
8823 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | |||
8824 | ||||
8825 | // In C++, the types have to match exactly. | |||
8826 | if (S.getLangOpts().CPlusPlus) | |||
8827 | return Sema::IncompatibleBlockPointer; | |||
8828 | ||||
8829 | Sema::AssignConvertType ConvTy = Sema::Compatible; | |||
8830 | ||||
8831 | // For blocks we enforce that qualifiers are identical. | |||
8832 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | |||
8833 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | |||
8834 | if (S.getLangOpts().OpenCL) { | |||
8835 | LQuals.removeAddressSpace(); | |||
8836 | RQuals.removeAddressSpace(); | |||
8837 | } | |||
8838 | if (LQuals != RQuals) | |||
8839 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | |||
8840 | ||||
8841 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | |||
8842 | // assignment. | |||
8843 | // The current behavior is similar to C++ lambdas. A block might be | |||
8844 | // assigned to a variable iff its return type and parameters are compatible | |||
8845 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | |||
8846 | // an assignment. Presumably it should behave in way that a function pointer | |||
8847 | // assignment does in C, so for each parameter and return type: | |||
8848 | // * CVR and address space of LHS should be a superset of CVR and address | |||
8849 | // space of RHS. | |||
8850 | // * unqualified types should be compatible. | |||
8851 | if (S.getLangOpts().OpenCL) { | |||
8852 | if (!S.Context.typesAreBlockPointerCompatible( | |||
8853 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | |||
8854 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | |||
8855 | return Sema::IncompatibleBlockPointer; | |||
8856 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | |||
8857 | return Sema::IncompatibleBlockPointer; | |||
8858 | ||||
8859 | return ConvTy; | |||
8860 | } | |||
8861 | ||||
8862 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | |||
8863 | /// for assignment compatibility. | |||
8864 | static Sema::AssignConvertType | |||
8865 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | |||
8866 | QualType RHSType) { | |||
8867 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8867, __PRETTY_FUNCTION__)); | |||
8868 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 8868, __PRETTY_FUNCTION__)); | |||
8869 | ||||
8870 | if (LHSType->isObjCBuiltinType()) { | |||
8871 | // Class is not compatible with ObjC object pointers. | |||
8872 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | |||
8873 | !RHSType->isObjCQualifiedClassType()) | |||
8874 | return Sema::IncompatiblePointer; | |||
8875 | return Sema::Compatible; | |||
8876 | } | |||
8877 | if (RHSType->isObjCBuiltinType()) { | |||
8878 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | |||
8879 | !LHSType->isObjCQualifiedClassType()) | |||
8880 | return Sema::IncompatiblePointer; | |||
8881 | return Sema::Compatible; | |||
8882 | } | |||
8883 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
8884 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | |||
8885 | ||||
8886 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | |||
8887 | // make an exception for id<P> | |||
8888 | !LHSType->isObjCQualifiedIdType()) | |||
8889 | return Sema::CompatiblePointerDiscardsQualifiers; | |||
8890 | ||||
8891 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | |||
8892 | return Sema::Compatible; | |||
8893 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | |||
8894 | return Sema::IncompatibleObjCQualifiedId; | |||
8895 | return Sema::IncompatiblePointer; | |||
8896 | } | |||
8897 | ||||
8898 | Sema::AssignConvertType | |||
8899 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | |||
8900 | QualType LHSType, QualType RHSType) { | |||
8901 | // Fake up an opaque expression. We don't actually care about what | |||
8902 | // cast operations are required, so if CheckAssignmentConstraints | |||
8903 | // adds casts to this they'll be wasted, but fortunately that doesn't | |||
8904 | // usually happen on valid code. | |||
8905 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); | |||
8906 | ExprResult RHSPtr = &RHSExpr; | |||
8907 | CastKind K; | |||
8908 | ||||
8909 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | |||
8910 | } | |||
8911 | ||||
8912 | /// This helper function returns true if QT is a vector type that has element | |||
8913 | /// type ElementType. | |||
8914 | static bool isVector(QualType QT, QualType ElementType) { | |||
8915 | if (const VectorType *VT = QT->getAs<VectorType>()) | |||
8916 | return VT->getElementType().getCanonicalType() == ElementType; | |||
8917 | return false; | |||
8918 | } | |||
8919 | ||||
8920 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | |||
8921 | /// has code to accommodate several GCC extensions when type checking | |||
8922 | /// pointers. Here are some objectionable examples that GCC considers warnings: | |||
8923 | /// | |||
8924 | /// int a, *pint; | |||
8925 | /// short *pshort; | |||
8926 | /// struct foo *pfoo; | |||
8927 | /// | |||
8928 | /// pint = pshort; // warning: assignment from incompatible pointer type | |||
8929 | /// a = pint; // warning: assignment makes integer from pointer without a cast | |||
8930 | /// pint = a; // warning: assignment makes pointer from integer without a cast | |||
8931 | /// pint = pfoo; // warning: assignment from incompatible pointer type | |||
8932 | /// | |||
8933 | /// As a result, the code for dealing with pointers is more complex than the | |||
8934 | /// C99 spec dictates. | |||
8935 | /// | |||
8936 | /// Sets 'Kind' for any result kind except Incompatible. | |||
8937 | Sema::AssignConvertType | |||
8938 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | |||
8939 | CastKind &Kind, bool ConvertRHS) { | |||
8940 | QualType RHSType = RHS.get()->getType(); | |||
8941 | QualType OrigLHSType = LHSType; | |||
8942 | ||||
8943 | // Get canonical types. We're not formatting these types, just comparing | |||
8944 | // them. | |||
8945 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | |||
8946 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | |||
8947 | ||||
8948 | // Common case: no conversion required. | |||
8949 | if (LHSType == RHSType) { | |||
8950 | Kind = CK_NoOp; | |||
8951 | return Compatible; | |||
8952 | } | |||
8953 | ||||
8954 | // If we have an atomic type, try a non-atomic assignment, then just add an | |||
8955 | // atomic qualification step. | |||
8956 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { | |||
8957 | Sema::AssignConvertType result = | |||
8958 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | |||
8959 | if (result != Compatible) | |||
8960 | return result; | |||
8961 | if (Kind != CK_NoOp && ConvertRHS) | |||
8962 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | |||
8963 | Kind = CK_NonAtomicToAtomic; | |||
8964 | return Compatible; | |||
8965 | } | |||
8966 | ||||
8967 | // If the left-hand side is a reference type, then we are in a | |||
8968 | // (rare!) case where we've allowed the use of references in C, | |||
8969 | // e.g., as a parameter type in a built-in function. In this case, | |||
8970 | // just make sure that the type referenced is compatible with the | |||
8971 | // right-hand side type. The caller is responsible for adjusting | |||
8972 | // LHSType so that the resulting expression does not have reference | |||
8973 | // type. | |||
8974 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { | |||
8975 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | |||
8976 | Kind = CK_LValueBitCast; | |||
8977 | return Compatible; | |||
8978 | } | |||
8979 | return Incompatible; | |||
8980 | } | |||
8981 | ||||
8982 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | |||
8983 | // to the same ExtVector type. | |||
8984 | if (LHSType->isExtVectorType()) { | |||
8985 | if (RHSType->isExtVectorType()) | |||
8986 | return Incompatible; | |||
8987 | if (RHSType->isArithmeticType()) { | |||
8988 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | |||
8989 | if (ConvertRHS) | |||
8990 | RHS = prepareVectorSplat(LHSType, RHS.get()); | |||
8991 | Kind = CK_VectorSplat; | |||
8992 | return Compatible; | |||
8993 | } | |||
8994 | } | |||
8995 | ||||
8996 | // Conversions to or from vector type. | |||
8997 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | |||
8998 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | |||
8999 | // Allow assignments of an AltiVec vector type to an equivalent GCC | |||
9000 | // vector type and vice versa | |||
9001 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | |||
9002 | Kind = CK_BitCast; | |||
9003 | return Compatible; | |||
9004 | } | |||
9005 | ||||
9006 | // If we are allowing lax vector conversions, and LHS and RHS are both | |||
9007 | // vectors, the total size only needs to be the same. This is a bitcast; | |||
9008 | // no bits are changed but the result type is different. | |||
9009 | if (isLaxVectorConversion(RHSType, LHSType)) { | |||
9010 | Kind = CK_BitCast; | |||
9011 | return IncompatibleVectors; | |||
9012 | } | |||
9013 | } | |||
9014 | ||||
9015 | // When the RHS comes from another lax conversion (e.g. binops between | |||
9016 | // scalars and vectors) the result is canonicalized as a vector. When the | |||
9017 | // LHS is also a vector, the lax is allowed by the condition above. Handle | |||
9018 | // the case where LHS is a scalar. | |||
9019 | if (LHSType->isScalarType()) { | |||
9020 | const VectorType *VecType = RHSType->getAs<VectorType>(); | |||
9021 | if (VecType && VecType->getNumElements() == 1 && | |||
9022 | isLaxVectorConversion(RHSType, LHSType)) { | |||
9023 | ExprResult *VecExpr = &RHS; | |||
9024 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | |||
9025 | Kind = CK_BitCast; | |||
9026 | return Compatible; | |||
9027 | } | |||
9028 | } | |||
9029 | ||||
9030 | // Allow assignments between fixed-length and sizeless SVE vectors. | |||
9031 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | |||
9032 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | |||
9033 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | |||
9034 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | |||
9035 | Kind = CK_BitCast; | |||
9036 | return Compatible; | |||
9037 | } | |||
9038 | ||||
9039 | return Incompatible; | |||
9040 | } | |||
9041 | ||||
9042 | // Diagnose attempts to convert between __float128 and long double where | |||
9043 | // such conversions currently can't be handled. | |||
9044 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
9045 | return Incompatible; | |||
9046 | ||||
9047 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | |||
9048 | // discards the imaginary part. | |||
9049 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | |||
9050 | !LHSType->getAs<ComplexType>()) | |||
9051 | return Incompatible; | |||
9052 | ||||
9053 | // Arithmetic conversions. | |||
9054 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | |||
9055 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | |||
9056 | if (ConvertRHS) | |||
9057 | Kind = PrepareScalarCast(RHS, LHSType); | |||
9058 | return Compatible; | |||
9059 | } | |||
9060 | ||||
9061 | // Conversions to normal pointers. | |||
9062 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { | |||
9063 | // U* -> T* | |||
9064 | if (isa<PointerType>(RHSType)) { | |||
9065 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | |||
9066 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | |||
9067 | if (AddrSpaceL != AddrSpaceR) | |||
9068 | Kind = CK_AddressSpaceConversion; | |||
9069 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | |||
9070 | Kind = CK_NoOp; | |||
9071 | else | |||
9072 | Kind = CK_BitCast; | |||
9073 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | |||
9074 | } | |||
9075 | ||||
9076 | // int -> T* | |||
9077 | if (RHSType->isIntegerType()) { | |||
9078 | Kind = CK_IntegralToPointer; // FIXME: null? | |||
9079 | return IntToPointer; | |||
9080 | } | |||
9081 | ||||
9082 | // C pointers are not compatible with ObjC object pointers, | |||
9083 | // with two exceptions: | |||
9084 | if (isa<ObjCObjectPointerType>(RHSType)) { | |||
9085 | // - conversions to void* | |||
9086 | if (LHSPointer->getPointeeType()->isVoidType()) { | |||
9087 | Kind = CK_BitCast; | |||
9088 | return Compatible; | |||
9089 | } | |||
9090 | ||||
9091 | // - conversions from 'Class' to the redefinition type | |||
9092 | if (RHSType->isObjCClassType() && | |||
9093 | Context.hasSameType(LHSType, | |||
9094 | Context.getObjCClassRedefinitionType())) { | |||
9095 | Kind = CK_BitCast; | |||
9096 | return Compatible; | |||
9097 | } | |||
9098 | ||||
9099 | Kind = CK_BitCast; | |||
9100 | return IncompatiblePointer; | |||
9101 | } | |||
9102 | ||||
9103 | // U^ -> void* | |||
9104 | if (RHSType->getAs<BlockPointerType>()) { | |||
9105 | if (LHSPointer->getPointeeType()->isVoidType()) { | |||
9106 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | |||
9107 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | |||
9108 | ->getPointeeType() | |||
9109 | .getAddressSpace(); | |||
9110 | Kind = | |||
9111 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
9112 | return Compatible; | |||
9113 | } | |||
9114 | } | |||
9115 | ||||
9116 | return Incompatible; | |||
9117 | } | |||
9118 | ||||
9119 | // Conversions to block pointers. | |||
9120 | if (isa<BlockPointerType>(LHSType)) { | |||
9121 | // U^ -> T^ | |||
9122 | if (RHSType->isBlockPointerType()) { | |||
9123 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | |||
9124 | ->getPointeeType() | |||
9125 | .getAddressSpace(); | |||
9126 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | |||
9127 | ->getPointeeType() | |||
9128 | .getAddressSpace(); | |||
9129 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
9130 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | |||
9131 | } | |||
9132 | ||||
9133 | // int or null -> T^ | |||
9134 | if (RHSType->isIntegerType()) { | |||
9135 | Kind = CK_IntegralToPointer; // FIXME: null | |||
9136 | return IntToBlockPointer; | |||
9137 | } | |||
9138 | ||||
9139 | // id -> T^ | |||
9140 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | |||
9141 | Kind = CK_AnyPointerToBlockPointerCast; | |||
9142 | return Compatible; | |||
9143 | } | |||
9144 | ||||
9145 | // void* -> T^ | |||
9146 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | |||
9147 | if (RHSPT->getPointeeType()->isVoidType()) { | |||
9148 | Kind = CK_AnyPointerToBlockPointerCast; | |||
9149 | return Compatible; | |||
9150 | } | |||
9151 | ||||
9152 | return Incompatible; | |||
9153 | } | |||
9154 | ||||
9155 | // Conversions to Objective-C pointers. | |||
9156 | if (isa<ObjCObjectPointerType>(LHSType)) { | |||
9157 | // A* -> B* | |||
9158 | if (RHSType->isObjCObjectPointerType()) { | |||
9159 | Kind = CK_BitCast; | |||
9160 | Sema::AssignConvertType result = | |||
9161 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | |||
9162 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
9163 | result == Compatible && | |||
9164 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | |||
9165 | result = IncompatibleObjCWeakRef; | |||
9166 | return result; | |||
9167 | } | |||
9168 | ||||
9169 | // int or null -> A* | |||
9170 | if (RHSType->isIntegerType()) { | |||
9171 | Kind = CK_IntegralToPointer; // FIXME: null | |||
9172 | return IntToPointer; | |||
9173 | } | |||
9174 | ||||
9175 | // In general, C pointers are not compatible with ObjC object pointers, | |||
9176 | // with two exceptions: | |||
9177 | if (isa<PointerType>(RHSType)) { | |||
9178 | Kind = CK_CPointerToObjCPointerCast; | |||
9179 | ||||
9180 | // - conversions from 'void*' | |||
9181 | if (RHSType->isVoidPointerType()) { | |||
9182 | return Compatible; | |||
9183 | } | |||
9184 | ||||
9185 | // - conversions to 'Class' from its redefinition type | |||
9186 | if (LHSType->isObjCClassType() && | |||
9187 | Context.hasSameType(RHSType, | |||
9188 | Context.getObjCClassRedefinitionType())) { | |||
9189 | return Compatible; | |||
9190 | } | |||
9191 | ||||
9192 | return IncompatiblePointer; | |||
9193 | } | |||
9194 | ||||
9195 | // Only under strict condition T^ is compatible with an Objective-C pointer. | |||
9196 | if (RHSType->isBlockPointerType() && | |||
9197 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | |||
9198 | if (ConvertRHS) | |||
9199 | maybeExtendBlockObject(RHS); | |||
9200 | Kind = CK_BlockPointerToObjCPointerCast; | |||
9201 | return Compatible; | |||
9202 | } | |||
9203 | ||||
9204 | return Incompatible; | |||
9205 | } | |||
9206 | ||||
9207 | // Conversions from pointers that are not covered by the above. | |||
9208 | if (isa<PointerType>(RHSType)) { | |||
9209 | // T* -> _Bool | |||
9210 | if (LHSType == Context.BoolTy) { | |||
9211 | Kind = CK_PointerToBoolean; | |||
9212 | return Compatible; | |||
9213 | } | |||
9214 | ||||
9215 | // T* -> int | |||
9216 | if (LHSType->isIntegerType()) { | |||
9217 | Kind = CK_PointerToIntegral; | |||
9218 | return PointerToInt; | |||
9219 | } | |||
9220 | ||||
9221 | return Incompatible; | |||
9222 | } | |||
9223 | ||||
9224 | // Conversions from Objective-C pointers that are not covered by the above. | |||
9225 | if (isa<ObjCObjectPointerType>(RHSType)) { | |||
9226 | // T* -> _Bool | |||
9227 | if (LHSType == Context.BoolTy) { | |||
9228 | Kind = CK_PointerToBoolean; | |||
9229 | return Compatible; | |||
9230 | } | |||
9231 | ||||
9232 | // T* -> int | |||
9233 | if (LHSType->isIntegerType()) { | |||
9234 | Kind = CK_PointerToIntegral; | |||
9235 | return PointerToInt; | |||
9236 | } | |||
9237 | ||||
9238 | return Incompatible; | |||
9239 | } | |||
9240 | ||||
9241 | // struct A -> struct B | |||
9242 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | |||
9243 | if (Context.typesAreCompatible(LHSType, RHSType)) { | |||
9244 | Kind = CK_NoOp; | |||
9245 | return Compatible; | |||
9246 | } | |||
9247 | } | |||
9248 | ||||
9249 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | |||
9250 | Kind = CK_IntToOCLSampler; | |||
9251 | return Compatible; | |||
9252 | } | |||
9253 | ||||
9254 | return Incompatible; | |||
9255 | } | |||
9256 | ||||
9257 | /// Constructs a transparent union from an expression that is | |||
9258 | /// used to initialize the transparent union. | |||
9259 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | |||
9260 | ExprResult &EResult, QualType UnionType, | |||
9261 | FieldDecl *Field) { | |||
9262 | // Build an initializer list that designates the appropriate member | |||
9263 | // of the transparent union. | |||
9264 | Expr *E = EResult.get(); | |||
9265 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | |||
9266 | E, SourceLocation()); | |||
9267 | Initializer->setType(UnionType); | |||
9268 | Initializer->setInitializedFieldInUnion(Field); | |||
9269 | ||||
9270 | // Build a compound literal constructing a value of the transparent | |||
9271 | // union type from this initializer list. | |||
9272 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | |||
9273 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | |||
9274 | VK_RValue, Initializer, false); | |||
9275 | } | |||
9276 | ||||
9277 | Sema::AssignConvertType | |||
9278 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | |||
9279 | ExprResult &RHS) { | |||
9280 | QualType RHSType = RHS.get()->getType(); | |||
9281 | ||||
9282 | // If the ArgType is a Union type, we want to handle a potential | |||
9283 | // transparent_union GCC extension. | |||
9284 | const RecordType *UT = ArgType->getAsUnionType(); | |||
9285 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | |||
9286 | return Incompatible; | |||
9287 | ||||
9288 | // The field to initialize within the transparent union. | |||
9289 | RecordDecl *UD = UT->getDecl(); | |||
9290 | FieldDecl *InitField = nullptr; | |||
9291 | // It's compatible if the expression matches any of the fields. | |||
9292 | for (auto *it : UD->fields()) { | |||
9293 | if (it->getType()->isPointerType()) { | |||
9294 | // If the transparent union contains a pointer type, we allow: | |||
9295 | // 1) void pointer | |||
9296 | // 2) null pointer constant | |||
9297 | if (RHSType->isPointerType()) | |||
9298 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | |||
9299 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | |||
9300 | InitField = it; | |||
9301 | break; | |||
9302 | } | |||
9303 | ||||
9304 | if (RHS.get()->isNullPointerConstant(Context, | |||
9305 | Expr::NPC_ValueDependentIsNull)) { | |||
9306 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | |||
9307 | CK_NullToPointer); | |||
9308 | InitField = it; | |||
9309 | break; | |||
9310 | } | |||
9311 | } | |||
9312 | ||||
9313 | CastKind Kind; | |||
9314 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | |||
9315 | == Compatible) { | |||
9316 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | |||
9317 | InitField = it; | |||
9318 | break; | |||
9319 | } | |||
9320 | } | |||
9321 | ||||
9322 | if (!InitField) | |||
9323 | return Incompatible; | |||
9324 | ||||
9325 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | |||
9326 | return Compatible; | |||
9327 | } | |||
9328 | ||||
9329 | Sema::AssignConvertType | |||
9330 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | |||
9331 | bool Diagnose, | |||
9332 | bool DiagnoseCFAudited, | |||
9333 | bool ConvertRHS) { | |||
9334 | // We need to be able to tell the caller whether we diagnosed a problem, if | |||
9335 | // they ask us to issue diagnostics. | |||
9336 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 9336, __PRETTY_FUNCTION__)); | |||
9337 | ||||
9338 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | |||
9339 | // we can't avoid *all* modifications at the moment, so we need some somewhere | |||
9340 | // to put the updated value. | |||
9341 | ExprResult LocalRHS = CallerRHS; | |||
9342 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | |||
9343 | ||||
9344 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | |||
9345 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | |||
9346 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | |||
9347 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | |||
9348 | Diag(RHS.get()->getExprLoc(), | |||
9349 | diag::warn_noderef_to_dereferenceable_pointer) | |||
9350 | << RHS.get()->getSourceRange(); | |||
9351 | } | |||
9352 | } | |||
9353 | } | |||
9354 | ||||
9355 | if (getLangOpts().CPlusPlus) { | |||
9356 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | |||
9357 | // C++ 5.17p3: If the left operand is not of class type, the | |||
9358 | // expression is implicitly converted (C++ 4) to the | |||
9359 | // cv-unqualified type of the left operand. | |||
9360 | QualType RHSType = RHS.get()->getType(); | |||
9361 | if (Diagnose) { | |||
9362 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
9363 | AA_Assigning); | |||
9364 | } else { | |||
9365 | ImplicitConversionSequence ICS = | |||
9366 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
9367 | /*SuppressUserConversions=*/false, | |||
9368 | AllowedExplicit::None, | |||
9369 | /*InOverloadResolution=*/false, | |||
9370 | /*CStyle=*/false, | |||
9371 | /*AllowObjCWritebackConversion=*/false); | |||
9372 | if (ICS.isFailure()) | |||
9373 | return Incompatible; | |||
9374 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | |||
9375 | ICS, AA_Assigning); | |||
9376 | } | |||
9377 | if (RHS.isInvalid()) | |||
9378 | return Incompatible; | |||
9379 | Sema::AssignConvertType result = Compatible; | |||
9380 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
9381 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | |||
9382 | result = IncompatibleObjCWeakRef; | |||
9383 | return result; | |||
9384 | } | |||
9385 | ||||
9386 | // FIXME: Currently, we fall through and treat C++ classes like C | |||
9387 | // structures. | |||
9388 | // FIXME: We also fall through for atomics; not sure what should | |||
9389 | // happen there, though. | |||
9390 | } else if (RHS.get()->getType() == Context.OverloadTy) { | |||
9391 | // As a set of extensions to C, we support overloading on functions. These | |||
9392 | // functions need to be resolved here. | |||
9393 | DeclAccessPair DAP; | |||
9394 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | |||
9395 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | |||
9396 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | |||
9397 | else | |||
9398 | return Incompatible; | |||
9399 | } | |||
9400 | ||||
9401 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | |||
9402 | // a null pointer constant. | |||
9403 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | |||
9404 | LHSType->isBlockPointerType()) && | |||
9405 | RHS.get()->isNullPointerConstant(Context, | |||
9406 | Expr::NPC_ValueDependentIsNull)) { | |||
9407 | if (Diagnose || ConvertRHS) { | |||
9408 | CastKind Kind; | |||
9409 | CXXCastPath Path; | |||
9410 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | |||
9411 | /*IgnoreBaseAccess=*/false, Diagnose); | |||
9412 | if (ConvertRHS) | |||
9413 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); | |||
9414 | } | |||
9415 | return Compatible; | |||
9416 | } | |||
9417 | ||||
9418 | // OpenCL queue_t type assignment. | |||
9419 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | |||
9420 | Context, Expr::NPC_ValueDependentIsNull)) { | |||
9421 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
9422 | return Compatible; | |||
9423 | } | |||
9424 | ||||
9425 | // This check seems unnatural, however it is necessary to ensure the proper | |||
9426 | // conversion of functions/arrays. If the conversion were done for all | |||
9427 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | |||
9428 | // expressions that suppress this implicit conversion (&, sizeof). | |||
9429 | // | |||
9430 | // Suppress this for references: C++ 8.5.3p5. | |||
9431 | if (!LHSType->isReferenceType()) { | |||
9432 | // FIXME: We potentially allocate here even if ConvertRHS is false. | |||
9433 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | |||
9434 | if (RHS.isInvalid()) | |||
9435 | return Incompatible; | |||
9436 | } | |||
9437 | CastKind Kind; | |||
9438 | Sema::AssignConvertType result = | |||
9439 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | |||
9440 | ||||
9441 | // C99 6.5.16.1p2: The value of the right operand is converted to the | |||
9442 | // type of the assignment expression. | |||
9443 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | |||
9444 | // so that we can use references in built-in functions even in C. | |||
9445 | // The getNonReferenceType() call makes sure that the resulting expression | |||
9446 | // does not have reference type. | |||
9447 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | |||
9448 | QualType Ty = LHSType.getNonLValueExprType(Context); | |||
9449 | Expr *E = RHS.get(); | |||
9450 | ||||
9451 | // Check for various Objective-C errors. If we are not reporting | |||
9452 | // diagnostics and just checking for errors, e.g., during overload | |||
9453 | // resolution, return Incompatible to indicate the failure. | |||
9454 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
9455 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | |||
9456 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | |||
9457 | if (!Diagnose) | |||
9458 | return Incompatible; | |||
9459 | } | |||
9460 | if (getLangOpts().ObjC && | |||
9461 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | |||
9462 | E->getType(), E, Diagnose) || | |||
9463 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | |||
9464 | if (!Diagnose) | |||
9465 | return Incompatible; | |||
9466 | // Replace the expression with a corrected version and continue so we | |||
9467 | // can find further errors. | |||
9468 | RHS = E; | |||
9469 | return Compatible; | |||
9470 | } | |||
9471 | ||||
9472 | if (ConvertRHS) | |||
9473 | RHS = ImpCastExprToType(E, Ty, Kind); | |||
9474 | } | |||
9475 | ||||
9476 | return result; | |||
9477 | } | |||
9478 | ||||
9479 | namespace { | |||
9480 | /// The original operand to an operator, prior to the application of the usual | |||
9481 | /// arithmetic conversions and converting the arguments of a builtin operator | |||
9482 | /// candidate. | |||
9483 | struct OriginalOperand { | |||
9484 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | |||
9485 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | |||
9486 | Op = MTE->getSubExpr(); | |||
9487 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | |||
9488 | Op = BTE->getSubExpr(); | |||
9489 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | |||
9490 | Orig = ICE->getSubExprAsWritten(); | |||
9491 | Conversion = ICE->getConversionFunction(); | |||
9492 | } | |||
9493 | } | |||
9494 | ||||
9495 | QualType getType() const { return Orig->getType(); } | |||
9496 | ||||
9497 | Expr *Orig; | |||
9498 | NamedDecl *Conversion; | |||
9499 | }; | |||
9500 | } | |||
9501 | ||||
9502 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | |||
9503 | ExprResult &RHS) { | |||
9504 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | |||
9505 | ||||
9506 | Diag(Loc, diag::err_typecheck_invalid_operands) | |||
9507 | << OrigLHS.getType() << OrigRHS.getType() | |||
9508 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9509 | ||||
9510 | // If a user-defined conversion was applied to either of the operands prior | |||
9511 | // to applying the built-in operator rules, tell the user about it. | |||
9512 | if (OrigLHS.Conversion) { | |||
9513 | Diag(OrigLHS.Conversion->getLocation(), | |||
9514 | diag::note_typecheck_invalid_operands_converted) | |||
9515 | << 0 << LHS.get()->getType(); | |||
9516 | } | |||
9517 | if (OrigRHS.Conversion) { | |||
9518 | Diag(OrigRHS.Conversion->getLocation(), | |||
9519 | diag::note_typecheck_invalid_operands_converted) | |||
9520 | << 1 << RHS.get()->getType(); | |||
9521 | } | |||
9522 | ||||
9523 | return QualType(); | |||
9524 | } | |||
9525 | ||||
9526 | // Diagnose cases where a scalar was implicitly converted to a vector and | |||
9527 | // diagnose the underlying types. Otherwise, diagnose the error | |||
9528 | // as invalid vector logical operands for non-C++ cases. | |||
9529 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | |||
9530 | ExprResult &RHS) { | |||
9531 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | |||
9532 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | |||
9533 | ||||
9534 | bool LHSNatVec = LHSType->isVectorType(); | |||
9535 | bool RHSNatVec = RHSType->isVectorType(); | |||
9536 | ||||
9537 | if (!(LHSNatVec && RHSNatVec)) { | |||
9538 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | |||
9539 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | |||
9540 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | |||
9541 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | |||
9542 | << Vector->getSourceRange(); | |||
9543 | return QualType(); | |||
9544 | } | |||
9545 | ||||
9546 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | |||
9547 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | |||
9548 | << RHS.get()->getSourceRange(); | |||
9549 | ||||
9550 | return QualType(); | |||
9551 | } | |||
9552 | ||||
9553 | /// Try to convert a value of non-vector type to a vector type by converting | |||
9554 | /// the type to the element type of the vector and then performing a splat. | |||
9555 | /// If the language is OpenCL, we only use conversions that promote scalar | |||
9556 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | |||
9557 | /// for float->int. | |||
9558 | /// | |||
9559 | /// OpenCL V2.0 6.2.6.p2: | |||
9560 | /// An error shall occur if any scalar operand type has greater rank | |||
9561 | /// than the type of the vector element. | |||
9562 | /// | |||
9563 | /// \param scalar - if non-null, actually perform the conversions | |||
9564 | /// \return true if the operation fails (but without diagnosing the failure) | |||
9565 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | |||
9566 | QualType scalarTy, | |||
9567 | QualType vectorEltTy, | |||
9568 | QualType vectorTy, | |||
9569 | unsigned &DiagID) { | |||
9570 | // The conversion to apply to the scalar before splatting it, | |||
9571 | // if necessary. | |||
9572 | CastKind scalarCast = CK_NoOp; | |||
9573 | ||||
9574 | if (vectorEltTy->isIntegralType(S.Context)) { | |||
9575 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | |||
9576 | (scalarTy->isIntegerType() && | |||
9577 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | |||
9578 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | |||
9579 | return true; | |||
9580 | } | |||
9581 | if (!scalarTy->isIntegralType(S.Context)) | |||
9582 | return true; | |||
9583 | scalarCast = CK_IntegralCast; | |||
9584 | } else if (vectorEltTy->isRealFloatingType()) { | |||
9585 | if (scalarTy->isRealFloatingType()) { | |||
9586 | if (S.getLangOpts().OpenCL && | |||
9587 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | |||
9588 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | |||
9589 | return true; | |||
9590 | } | |||
9591 | scalarCast = CK_FloatingCast; | |||
9592 | } | |||
9593 | else if (scalarTy->isIntegralType(S.Context)) | |||
9594 | scalarCast = CK_IntegralToFloating; | |||
9595 | else | |||
9596 | return true; | |||
9597 | } else { | |||
9598 | return true; | |||
9599 | } | |||
9600 | ||||
9601 | // Adjust scalar if desired. | |||
9602 | if (scalar) { | |||
9603 | if (scalarCast != CK_NoOp) | |||
9604 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | |||
9605 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | |||
9606 | } | |||
9607 | return false; | |||
9608 | } | |||
9609 | ||||
9610 | /// Convert vector E to a vector with the same number of elements but different | |||
9611 | /// element type. | |||
9612 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | |||
9613 | const auto *VecTy = E->getType()->getAs<VectorType>(); | |||
9614 | assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast <void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 9614, __PRETTY_FUNCTION__)); | |||
9615 | QualType NewVecTy = S.Context.getVectorType(ElementType, | |||
9616 | VecTy->getNumElements(), | |||
9617 | VecTy->getVectorKind()); | |||
9618 | ||||
9619 | // Look through the implicit cast. Return the subexpression if its type is | |||
9620 | // NewVecTy. | |||
9621 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
9622 | if (ICE->getSubExpr()->getType() == NewVecTy) | |||
9623 | return ICE->getSubExpr(); | |||
9624 | ||||
9625 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | |||
9626 | return S.ImpCastExprToType(E, NewVecTy, Cast); | |||
9627 | } | |||
9628 | ||||
9629 | /// Test if a (constant) integer Int can be casted to another integer type | |||
9630 | /// IntTy without losing precision. | |||
9631 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | |||
9632 | QualType OtherIntTy) { | |||
9633 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | |||
9634 | ||||
9635 | // Reject cases where the value of the Int is unknown as that would | |||
9636 | // possibly cause truncation, but accept cases where the scalar can be | |||
9637 | // demoted without loss of precision. | |||
9638 | Expr::EvalResult EVResult; | |||
9639 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | |||
9640 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | |||
9641 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | |||
9642 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | |||
9643 | ||||
9644 | if (CstInt) { | |||
9645 | // If the scalar is constant and is of a higher order and has more active | |||
9646 | // bits that the vector element type, reject it. | |||
9647 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
9648 | unsigned NumBits = IntSigned | |||
9649 | ? (Result.isNegative() ? Result.getMinSignedBits() | |||
9650 | : Result.getActiveBits()) | |||
9651 | : Result.getActiveBits(); | |||
9652 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | |||
9653 | return true; | |||
9654 | ||||
9655 | // If the signedness of the scalar type and the vector element type | |||
9656 | // differs and the number of bits is greater than that of the vector | |||
9657 | // element reject it. | |||
9658 | return (IntSigned != OtherIntSigned && | |||
9659 | NumBits > S.Context.getIntWidth(OtherIntTy)); | |||
9660 | } | |||
9661 | ||||
9662 | // Reject cases where the value of the scalar is not constant and it's | |||
9663 | // order is greater than that of the vector element type. | |||
9664 | return (Order < 0); | |||
9665 | } | |||
9666 | ||||
9667 | /// Test if a (constant) integer Int can be casted to floating point type | |||
9668 | /// FloatTy without losing precision. | |||
9669 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | |||
9670 | QualType FloatTy) { | |||
9671 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | |||
9672 | ||||
9673 | // Determine if the integer constant can be expressed as a floating point | |||
9674 | // number of the appropriate type. | |||
9675 | Expr::EvalResult EVResult; | |||
9676 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | |||
9677 | ||||
9678 | uint64_t Bits = 0; | |||
9679 | if (CstInt) { | |||
9680 | // Reject constants that would be truncated if they were converted to | |||
9681 | // the floating point type. Test by simple to/from conversion. | |||
9682 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | |||
9683 | // could be avoided if there was a convertFromAPInt method | |||
9684 | // which could signal back if implicit truncation occurred. | |||
9685 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
9686 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | |||
9687 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | |||
9688 | llvm::APFloat::rmTowardZero); | |||
9689 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | |||
9690 | !IntTy->hasSignedIntegerRepresentation()); | |||
9691 | bool Ignored = false; | |||
9692 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | |||
9693 | &Ignored); | |||
9694 | if (Result != ConvertBack) | |||
9695 | return true; | |||
9696 | } else { | |||
9697 | // Reject types that cannot be fully encoded into the mantissa of | |||
9698 | // the float. | |||
9699 | Bits = S.Context.getTypeSize(IntTy); | |||
9700 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | |||
9701 | S.Context.getFloatTypeSemantics(FloatTy)); | |||
9702 | if (Bits > FloatPrec) | |||
9703 | return true; | |||
9704 | } | |||
9705 | ||||
9706 | return false; | |||
9707 | } | |||
9708 | ||||
9709 | /// Attempt to convert and splat Scalar into a vector whose types matches | |||
9710 | /// Vector following GCC conversion rules. The rule is that implicit | |||
9711 | /// conversion can occur when Scalar can be casted to match Vector's element | |||
9712 | /// type without causing truncation of Scalar. | |||
9713 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | |||
9714 | ExprResult *Vector) { | |||
9715 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | |||
9716 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | |||
9717 | const VectorType *VT = VectorTy->getAs<VectorType>(); | |||
9718 | ||||
9719 | assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 9720, __PRETTY_FUNCTION__)) | |||
9720 | "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 9720, __PRETTY_FUNCTION__)); | |||
9721 | ||||
9722 | QualType VectorEltTy = VT->getElementType(); | |||
9723 | ||||
9724 | // Reject cases where the vector element type or the scalar element type are | |||
9725 | // not integral or floating point types. | |||
9726 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | |||
9727 | return true; | |||
9728 | ||||
9729 | // The conversion to apply to the scalar before splatting it, | |||
9730 | // if necessary. | |||
9731 | CastKind ScalarCast = CK_NoOp; | |||
9732 | ||||
9733 | // Accept cases where the vector elements are integers and the scalar is | |||
9734 | // an integer. | |||
9735 | // FIXME: Notionally if the scalar was a floating point value with a precise | |||
9736 | // integral representation, we could cast it to an appropriate integer | |||
9737 | // type and then perform the rest of the checks here. GCC will perform | |||
9738 | // this conversion in some cases as determined by the input language. | |||
9739 | // We should accept it on a language independent basis. | |||
9740 | if (VectorEltTy->isIntegralType(S.Context) && | |||
9741 | ScalarTy->isIntegralType(S.Context) && | |||
9742 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | |||
9743 | ||||
9744 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | |||
9745 | return true; | |||
9746 | ||||
9747 | ScalarCast = CK_IntegralCast; | |||
9748 | } else if (VectorEltTy->isIntegralType(S.Context) && | |||
9749 | ScalarTy->isRealFloatingType()) { | |||
9750 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | |||
9751 | ScalarCast = CK_FloatingToIntegral; | |||
9752 | else | |||
9753 | return true; | |||
9754 | } else if (VectorEltTy->isRealFloatingType()) { | |||
9755 | if (ScalarTy->isRealFloatingType()) { | |||
9756 | ||||
9757 | // Reject cases where the scalar type is not a constant and has a higher | |||
9758 | // Order than the vector element type. | |||
9759 | llvm::APFloat Result(0.0); | |||
9760 | ||||
9761 | // Determine whether this is a constant scalar. In the event that the | |||
9762 | // value is dependent (and thus cannot be evaluated by the constant | |||
9763 | // evaluator), skip the evaluation. This will then diagnose once the | |||
9764 | // expression is instantiated. | |||
9765 | bool CstScalar = Scalar->get()->isValueDependent() || | |||
9766 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | |||
9767 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | |||
9768 | if (!CstScalar && Order < 0) | |||
9769 | return true; | |||
9770 | ||||
9771 | // If the scalar cannot be safely casted to the vector element type, | |||
9772 | // reject it. | |||
9773 | if (CstScalar) { | |||
9774 | bool Truncated = false; | |||
9775 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | |||
9776 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | |||
9777 | if (Truncated) | |||
9778 | return true; | |||
9779 | } | |||
9780 | ||||
9781 | ScalarCast = CK_FloatingCast; | |||
9782 | } else if (ScalarTy->isIntegralType(S.Context)) { | |||
9783 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | |||
9784 | return true; | |||
9785 | ||||
9786 | ScalarCast = CK_IntegralToFloating; | |||
9787 | } else | |||
9788 | return true; | |||
9789 | } else if (ScalarTy->isEnumeralType()) | |||
9790 | return true; | |||
9791 | ||||
9792 | // Adjust scalar if desired. | |||
9793 | if (Scalar) { | |||
9794 | if (ScalarCast != CK_NoOp) | |||
9795 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | |||
9796 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | |||
9797 | } | |||
9798 | return false; | |||
9799 | } | |||
9800 | ||||
9801 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | |||
9802 | SourceLocation Loc, bool IsCompAssign, | |||
9803 | bool AllowBothBool, | |||
9804 | bool AllowBoolConversions) { | |||
9805 | if (!IsCompAssign) { | |||
9806 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
9807 | if (LHS.isInvalid()) | |||
9808 | return QualType(); | |||
9809 | } | |||
9810 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
9811 | if (RHS.isInvalid()) | |||
9812 | return QualType(); | |||
9813 | ||||
9814 | // For conversion purposes, we ignore any qualifiers. | |||
9815 | // For example, "const float" and "float" are equivalent. | |||
9816 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | |||
9817 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | |||
9818 | ||||
9819 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | |||
9820 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | |||
9821 | assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail ("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 9821, __PRETTY_FUNCTION__)); | |||
9822 | ||||
9823 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | |||
9824 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | |||
9825 | return InvalidOperands(Loc, LHS, RHS); | |||
9826 | ||||
9827 | // AltiVec-style "vector bool op vector bool" combinations are allowed | |||
9828 | // for some operators but not others. | |||
9829 | if (!AllowBothBool && | |||
9830 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | |||
9831 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
9832 | return InvalidOperands(Loc, LHS, RHS); | |||
9833 | ||||
9834 | // If the vector types are identical, return. | |||
9835 | if (Context.hasSameType(LHSType, RHSType)) | |||
9836 | return LHSType; | |||
9837 | ||||
9838 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | |||
9839 | if (LHSVecType && RHSVecType && | |||
9840 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | |||
9841 | if (isa<ExtVectorType>(LHSVecType)) { | |||
9842 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
9843 | return LHSType; | |||
9844 | } | |||
9845 | ||||
9846 | if (!IsCompAssign) | |||
9847 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
9848 | return RHSType; | |||
9849 | } | |||
9850 | ||||
9851 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | |||
9852 | // can be mixed, with the result being the non-bool type. The non-bool | |||
9853 | // operand must have integer element type. | |||
9854 | if (AllowBoolConversions && LHSVecType && RHSVecType && | |||
9855 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | |||
9856 | (Context.getTypeSize(LHSVecType->getElementType()) == | |||
9857 | Context.getTypeSize(RHSVecType->getElementType()))) { | |||
9858 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | |||
9859 | LHSVecType->getElementType()->isIntegerType() && | |||
9860 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | |||
9861 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
9862 | return LHSType; | |||
9863 | } | |||
9864 | if (!IsCompAssign && | |||
9865 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | |||
9866 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | |||
9867 | RHSVecType->getElementType()->isIntegerType()) { | |||
9868 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
9869 | return RHSType; | |||
9870 | } | |||
9871 | } | |||
9872 | ||||
9873 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | |||
9874 | // since the ambiguity can affect the ABI. | |||
9875 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | |||
9876 | const VectorType *VecType = SecondType->getAs<VectorType>(); | |||
9877 | return FirstType->isSizelessBuiltinType() && VecType && | |||
9878 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | |||
9879 | VecType->getVectorKind() == | |||
9880 | VectorType::SveFixedLengthPredicateVector); | |||
9881 | }; | |||
9882 | ||||
9883 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | |||
9884 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | |||
9885 | return QualType(); | |||
9886 | } | |||
9887 | ||||
9888 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | |||
9889 | // since the ambiguity can affect the ABI. | |||
9890 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | |||
9891 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | |||
9892 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | |||
9893 | ||||
9894 | if (FirstVecType && SecondVecType) | |||
9895 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | |||
9896 | (SecondVecType->getVectorKind() == | |||
9897 | VectorType::SveFixedLengthDataVector || | |||
9898 | SecondVecType->getVectorKind() == | |||
9899 | VectorType::SveFixedLengthPredicateVector); | |||
9900 | ||||
9901 | return FirstType->isSizelessBuiltinType() && SecondVecType && | |||
9902 | SecondVecType->getVectorKind() == VectorType::GenericVector; | |||
9903 | }; | |||
9904 | ||||
9905 | if (IsSveGnuConversion(LHSType, RHSType) || | |||
9906 | IsSveGnuConversion(RHSType, LHSType)) { | |||
9907 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | |||
9908 | return QualType(); | |||
9909 | } | |||
9910 | ||||
9911 | // If there's a vector type and a scalar, try to convert the scalar to | |||
9912 | // the vector element type and splat. | |||
9913 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | |||
9914 | if (!RHSVecType) { | |||
9915 | if (isa<ExtVectorType>(LHSVecType)) { | |||
9916 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | |||
9917 | LHSVecType->getElementType(), LHSType, | |||
9918 | DiagID)) | |||
9919 | return LHSType; | |||
9920 | } else { | |||
9921 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | |||
9922 | return LHSType; | |||
9923 | } | |||
9924 | } | |||
9925 | if (!LHSVecType) { | |||
9926 | if (isa<ExtVectorType>(RHSVecType)) { | |||
9927 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | |||
9928 | LHSType, RHSVecType->getElementType(), | |||
9929 | RHSType, DiagID)) | |||
9930 | return RHSType; | |||
9931 | } else { | |||
9932 | if (LHS.get()->getValueKind() == VK_LValue || | |||
9933 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | |||
9934 | return RHSType; | |||
9935 | } | |||
9936 | } | |||
9937 | ||||
9938 | // FIXME: The code below also handles conversion between vectors and | |||
9939 | // non-scalars, we should break this down into fine grained specific checks | |||
9940 | // and emit proper diagnostics. | |||
9941 | QualType VecType = LHSVecType ? LHSType : RHSType; | |||
9942 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | |||
9943 | QualType OtherType = LHSVecType ? RHSType : LHSType; | |||
9944 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | |||
9945 | if (isLaxVectorConversion(OtherType, VecType)) { | |||
9946 | // If we're allowing lax vector conversions, only the total (data) size | |||
9947 | // needs to be the same. For non compound assignment, if one of the types is | |||
9948 | // scalar, the result is always the vector type. | |||
9949 | if (!IsCompAssign) { | |||
9950 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | |||
9951 | return VecType; | |||
9952 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | |||
9953 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | |||
9954 | // type. Note that this is already done by non-compound assignments in | |||
9955 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | |||
9956 | // <1 x T> -> T. The result is also a vector type. | |||
9957 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | |||
9958 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | |||
9959 | ExprResult *RHSExpr = &RHS; | |||
9960 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | |||
9961 | return VecType; | |||
9962 | } | |||
9963 | } | |||
9964 | ||||
9965 | // Okay, the expression is invalid. | |||
9966 | ||||
9967 | // If there's a non-vector, non-real operand, diagnose that. | |||
9968 | if ((!RHSVecType && !RHSType->isRealType()) || | |||
9969 | (!LHSVecType && !LHSType->isRealType())) { | |||
9970 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | |||
9971 | << LHSType << RHSType | |||
9972 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
9973 | return QualType(); | |||
9974 | } | |||
9975 | ||||
9976 | // OpenCL V1.1 6.2.6.p1: | |||
9977 | // If the operands are of more than one vector type, then an error shall | |||
9978 | // occur. Implicit conversions between vector types are not permitted, per | |||
9979 | // section 6.2.1. | |||
9980 | if (getLangOpts().OpenCL && | |||
9981 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | |||
9982 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | |||
9983 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | |||
9984 | << RHSType; | |||
9985 | return QualType(); | |||
9986 | } | |||
9987 | ||||
9988 | ||||
9989 | // If there is a vector type that is not a ExtVector and a scalar, we reach | |||
9990 | // this point if scalar could not be converted to the vector's element type | |||
9991 | // without truncation. | |||
9992 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | |||
9993 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | |||
9994 | QualType Scalar = LHSVecType ? RHSType : LHSType; | |||
9995 | QualType Vector = LHSVecType ? LHSType : RHSType; | |||
9996 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | |||
9997 | Diag(Loc, | |||
9998 | diag::err_typecheck_vector_not_convertable_implict_truncation) | |||
9999 | << ScalarOrVector << Scalar << Vector; | |||
10000 | ||||
10001 | return QualType(); | |||
10002 | } | |||
10003 | ||||
10004 | // Otherwise, use the generic diagnostic. | |||
10005 | Diag(Loc, DiagID) | |||
10006 | << LHSType << RHSType | |||
10007 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10008 | return QualType(); | |||
10009 | } | |||
10010 | ||||
10011 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | |||
10012 | // expression. These are mainly cases where the null pointer is used as an | |||
10013 | // integer instead of a pointer. | |||
10014 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
10015 | SourceLocation Loc, bool IsCompare) { | |||
10016 | // The canonical way to check for a GNU null is with isNullPointerConstant, | |||
10017 | // but we use a bit of a hack here for speed; this is a relatively | |||
10018 | // hot path, and isNullPointerConstant is slow. | |||
10019 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | |||
10020 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | |||
10021 | ||||
10022 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | |||
10023 | ||||
10024 | // Avoid analyzing cases where the result will either be invalid (and | |||
10025 | // diagnosed as such) or entirely valid and not something to warn about. | |||
10026 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | |||
10027 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | |||
10028 | return; | |||
10029 | ||||
10030 | // Comparison operations would not make sense with a null pointer no matter | |||
10031 | // what the other expression is. | |||
10032 | if (!IsCompare) { | |||
10033 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | |||
10034 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | |||
10035 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | |||
10036 | return; | |||
10037 | } | |||
10038 | ||||
10039 | // The rest of the operations only make sense with a null pointer | |||
10040 | // if the other expression is a pointer. | |||
10041 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | |||
10042 | NonNullType->canDecayToPointerType()) | |||
10043 | return; | |||
10044 | ||||
10045 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | |||
10046 | << LHSNull /* LHS is NULL */ << NonNullType | |||
10047 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10048 | } | |||
10049 | ||||
10050 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | |||
10051 | SourceLocation Loc) { | |||
10052 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | |||
10053 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | |||
10054 | if (!LUE || !RUE) | |||
10055 | return; | |||
10056 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | |||
10057 | RUE->getKind() != UETT_SizeOf) | |||
10058 | return; | |||
10059 | ||||
10060 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | |||
10061 | QualType LHSTy = LHSArg->getType(); | |||
10062 | QualType RHSTy; | |||
10063 | ||||
10064 | if (RUE->isArgumentType()) | |||
10065 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | |||
10066 | else | |||
10067 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | |||
10068 | ||||
10069 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | |||
10070 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | |||
10071 | return; | |||
10072 | ||||
10073 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | |||
10074 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | |||
10075 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | |||
10076 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | |||
10077 | << LHSArgDecl; | |||
10078 | } | |||
10079 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | |||
10080 | QualType ArrayElemTy = ArrayTy->getElementType(); | |||
10081 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | |||
10082 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | |||
10083 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | |||
10084 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | |||
10085 | return; | |||
10086 | S.Diag(Loc, diag::warn_division_sizeof_array) | |||
10087 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | |||
10088 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | |||
10089 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | |||
10090 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | |||
10091 | << LHSArgDecl; | |||
10092 | } | |||
10093 | ||||
10094 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | |||
10095 | } | |||
10096 | } | |||
10097 | ||||
10098 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | |||
10099 | ExprResult &RHS, | |||
10100 | SourceLocation Loc, bool IsDiv) { | |||
10101 | // Check for division/remainder by zero. | |||
10102 | Expr::EvalResult RHSValue; | |||
10103 | if (!RHS.get()->isValueDependent() && | |||
10104 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | |||
10105 | RHSValue.Val.getInt() == 0) | |||
10106 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
10107 | S.PDiag(diag::warn_remainder_division_by_zero) | |||
10108 | << IsDiv << RHS.get()->getSourceRange()); | |||
10109 | } | |||
10110 | ||||
10111 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | |||
10112 | SourceLocation Loc, | |||
10113 | bool IsCompAssign, bool IsDiv) { | |||
10114 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10115 | ||||
10116 | if (LHS.get()->getType()->isVectorType() || | |||
10117 | RHS.get()->getType()->isVectorType()) | |||
10118 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
10119 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10120 | /*AllowBoolConversions*/false); | |||
10121 | if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || | |||
10122 | RHS.get()->getType()->isConstantMatrixType())) | |||
10123 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | |||
10124 | ||||
10125 | QualType compType = UsualArithmeticConversions( | |||
10126 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | |||
10127 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10128 | return QualType(); | |||
10129 | ||||
10130 | ||||
10131 | if (compType.isNull() || !compType->isArithmeticType()) | |||
10132 | return InvalidOperands(Loc, LHS, RHS); | |||
10133 | if (IsDiv) { | |||
10134 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | |||
10135 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | |||
10136 | } | |||
10137 | return compType; | |||
10138 | } | |||
10139 | ||||
10140 | QualType Sema::CheckRemainderOperands( | |||
10141 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | |||
10142 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10143 | ||||
10144 | if (LHS.get()->getType()->isVectorType() || | |||
10145 | RHS.get()->getType()->isVectorType()) { | |||
10146 | if (LHS.get()->getType()->hasIntegerRepresentation() && | |||
10147 | RHS.get()->getType()->hasIntegerRepresentation()) | |||
10148 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
10149 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10150 | /*AllowBoolConversions*/false); | |||
10151 | return InvalidOperands(Loc, LHS, RHS); | |||
10152 | } | |||
10153 | ||||
10154 | QualType compType = UsualArithmeticConversions( | |||
10155 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | |||
10156 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10157 | return QualType(); | |||
10158 | ||||
10159 | if (compType.isNull() || !compType->isIntegerType()) | |||
10160 | return InvalidOperands(Loc, LHS, RHS); | |||
10161 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | |||
10162 | return compType; | |||
10163 | } | |||
10164 | ||||
10165 | /// Diagnose invalid arithmetic on two void pointers. | |||
10166 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | |||
10167 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10168 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10169 | ? diag::err_typecheck_pointer_arith_void_type | |||
10170 | : diag::ext_gnu_void_ptr) | |||
10171 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | |||
10172 | << RHSExpr->getSourceRange(); | |||
10173 | } | |||
10174 | ||||
10175 | /// Diagnose invalid arithmetic on a void pointer. | |||
10176 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | |||
10177 | Expr *Pointer) { | |||
10178 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10179 | ? diag::err_typecheck_pointer_arith_void_type | |||
10180 | : diag::ext_gnu_void_ptr) | |||
10181 | << 0 /* one pointer */ << Pointer->getSourceRange(); | |||
10182 | } | |||
10183 | ||||
10184 | /// Diagnose invalid arithmetic on a null pointer. | |||
10185 | /// | |||
10186 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | |||
10187 | /// idiom, which we recognize as a GNU extension. | |||
10188 | /// | |||
10189 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | |||
10190 | Expr *Pointer, bool IsGNUIdiom) { | |||
10191 | if (IsGNUIdiom) | |||
10192 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | |||
10193 | << Pointer->getSourceRange(); | |||
10194 | else | |||
10195 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | |||
10196 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | |||
10197 | } | |||
10198 | ||||
10199 | /// Diagnose invalid arithmetic on two function pointers. | |||
10200 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | |||
10201 | Expr *LHS, Expr *RHS) { | |||
10202 | assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10202, __PRETTY_FUNCTION__)); | |||
10203 | assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10203, __PRETTY_FUNCTION__)); | |||
10204 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10205 | ? diag::err_typecheck_pointer_arith_function_type | |||
10206 | : diag::ext_gnu_ptr_func_arith) | |||
10207 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | |||
10208 | // We only show the second type if it differs from the first. | |||
10209 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | |||
10210 | RHS->getType()) | |||
10211 | << RHS->getType()->getPointeeType() | |||
10212 | << LHS->getSourceRange() << RHS->getSourceRange(); | |||
10213 | } | |||
10214 | ||||
10215 | /// Diagnose invalid arithmetic on a function pointer. | |||
10216 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | |||
10217 | Expr *Pointer) { | |||
10218 | assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10218, __PRETTY_FUNCTION__)); | |||
10219 | S.Diag(Loc, S.getLangOpts().CPlusPlus | |||
10220 | ? diag::err_typecheck_pointer_arith_function_type | |||
10221 | : diag::ext_gnu_ptr_func_arith) | |||
10222 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | |||
10223 | << 0 /* one pointer, so only one type */ | |||
10224 | << Pointer->getSourceRange(); | |||
10225 | } | |||
10226 | ||||
10227 | /// Emit error if Operand is incomplete pointer type | |||
10228 | /// | |||
10229 | /// \returns True if pointer has incomplete type | |||
10230 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | |||
10231 | Expr *Operand) { | |||
10232 | QualType ResType = Operand->getType(); | |||
10233 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
10234 | ResType = ResAtomicType->getValueType(); | |||
10235 | ||||
10236 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType ()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10236, __PRETTY_FUNCTION__)); | |||
10237 | QualType PointeeTy = ResType->getPointeeType(); | |||
10238 | return S.RequireCompleteSizedType( | |||
10239 | Loc, PointeeTy, | |||
10240 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | |||
10241 | Operand->getSourceRange()); | |||
10242 | } | |||
10243 | ||||
10244 | /// Check the validity of an arithmetic pointer operand. | |||
10245 | /// | |||
10246 | /// If the operand has pointer type, this code will check for pointer types | |||
10247 | /// which are invalid in arithmetic operations. These will be diagnosed | |||
10248 | /// appropriately, including whether or not the use is supported as an | |||
10249 | /// extension. | |||
10250 | /// | |||
10251 | /// \returns True when the operand is valid to use (even if as an extension). | |||
10252 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | |||
10253 | Expr *Operand) { | |||
10254 | QualType ResType = Operand->getType(); | |||
10255 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
10256 | ResType = ResAtomicType->getValueType(); | |||
10257 | ||||
10258 | if (!ResType->isAnyPointerType()) return true; | |||
10259 | ||||
10260 | QualType PointeeTy = ResType->getPointeeType(); | |||
10261 | if (PointeeTy->isVoidType()) { | |||
10262 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | |||
10263 | return !S.getLangOpts().CPlusPlus; | |||
10264 | } | |||
10265 | if (PointeeTy->isFunctionType()) { | |||
10266 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | |||
10267 | return !S.getLangOpts().CPlusPlus; | |||
10268 | } | |||
10269 | ||||
10270 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | |||
10271 | ||||
10272 | return true; | |||
10273 | } | |||
10274 | ||||
10275 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | |||
10276 | /// operands. | |||
10277 | /// | |||
10278 | /// This routine will diagnose any invalid arithmetic on pointer operands much | |||
10279 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | |||
10280 | /// for emitting a single diagnostic even for operations where both LHS and RHS | |||
10281 | /// are (potentially problematic) pointers. | |||
10282 | /// | |||
10283 | /// \returns True when the operand is valid to use (even if as an extension). | |||
10284 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | |||
10285 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10286 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | |||
10287 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | |||
10288 | if (!isLHSPointer && !isRHSPointer) return true; | |||
10289 | ||||
10290 | QualType LHSPointeeTy, RHSPointeeTy; | |||
10291 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | |||
10292 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | |||
10293 | ||||
10294 | // if both are pointers check if operation is valid wrt address spaces | |||
10295 | if (isLHSPointer && isRHSPointer) { | |||
10296 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | |||
10297 | S.Diag(Loc, | |||
10298 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
10299 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | |||
10300 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | |||
10301 | return false; | |||
10302 | } | |||
10303 | } | |||
10304 | ||||
10305 | // Check for arithmetic on pointers to incomplete types. | |||
10306 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | |||
10307 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | |||
10308 | if (isLHSVoidPtr || isRHSVoidPtr) { | |||
10309 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | |||
10310 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | |||
10311 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | |||
10312 | ||||
10313 | return !S.getLangOpts().CPlusPlus; | |||
10314 | } | |||
10315 | ||||
10316 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | |||
10317 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | |||
10318 | if (isLHSFuncPtr || isRHSFuncPtr) { | |||
10319 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | |||
10320 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | |||
10321 | RHSExpr); | |||
10322 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | |||
10323 | ||||
10324 | return !S.getLangOpts().CPlusPlus; | |||
10325 | } | |||
10326 | ||||
10327 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | |||
10328 | return false; | |||
10329 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | |||
10330 | return false; | |||
10331 | ||||
10332 | return true; | |||
10333 | } | |||
10334 | ||||
10335 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | |||
10336 | /// literal. | |||
10337 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | |||
10338 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10339 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | |||
10340 | Expr* IndexExpr = RHSExpr; | |||
10341 | if (!StrExpr) { | |||
10342 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | |||
10343 | IndexExpr = LHSExpr; | |||
10344 | } | |||
10345 | ||||
10346 | bool IsStringPlusInt = StrExpr && | |||
10347 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | |||
10348 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | |||
10349 | return; | |||
10350 | ||||
10351 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
10352 | Self.Diag(OpLoc, diag::warn_string_plus_int) | |||
10353 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | |||
10354 | ||||
10355 | // Only print a fixit for "str" + int, not for int + "str". | |||
10356 | if (IndexExpr == RHSExpr) { | |||
10357 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | |||
10358 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | |||
10359 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | |||
10360 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | |||
10361 | << FixItHint::CreateInsertion(EndLoc, "]"); | |||
10362 | } else | |||
10363 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | |||
10364 | } | |||
10365 | ||||
10366 | /// Emit a warning when adding a char literal to a string. | |||
10367 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | |||
10368 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10369 | const Expr *StringRefExpr = LHSExpr; | |||
10370 | const CharacterLiteral *CharExpr = | |||
10371 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | |||
10372 | ||||
10373 | if (!CharExpr) { | |||
10374 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | |||
10375 | StringRefExpr = RHSExpr; | |||
10376 | } | |||
10377 | ||||
10378 | if (!CharExpr || !StringRefExpr) | |||
10379 | return; | |||
10380 | ||||
10381 | const QualType StringType = StringRefExpr->getType(); | |||
10382 | ||||
10383 | // Return if not a PointerType. | |||
10384 | if (!StringType->isAnyPointerType()) | |||
10385 | return; | |||
10386 | ||||
10387 | // Return if not a CharacterType. | |||
10388 | if (!StringType->getPointeeType()->isAnyCharacterType()) | |||
10389 | return; | |||
10390 | ||||
10391 | ASTContext &Ctx = Self.getASTContext(); | |||
10392 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
10393 | ||||
10394 | const QualType CharType = CharExpr->getType(); | |||
10395 | if (!CharType->isAnyCharacterType() && | |||
10396 | CharType->isIntegerType() && | |||
10397 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | |||
10398 | Self.Diag(OpLoc, diag::warn_string_plus_char) | |||
10399 | << DiagRange << Ctx.CharTy; | |||
10400 | } else { | |||
10401 | Self.Diag(OpLoc, diag::warn_string_plus_char) | |||
10402 | << DiagRange << CharExpr->getType(); | |||
10403 | } | |||
10404 | ||||
10405 | // Only print a fixit for str + char, not for char + str. | |||
10406 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | |||
10407 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | |||
10408 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | |||
10409 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | |||
10410 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | |||
10411 | << FixItHint::CreateInsertion(EndLoc, "]"); | |||
10412 | } else { | |||
10413 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | |||
10414 | } | |||
10415 | } | |||
10416 | ||||
10417 | /// Emit error when two pointers are incompatible. | |||
10418 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | |||
10419 | Expr *LHSExpr, Expr *RHSExpr) { | |||
10420 | assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10420, __PRETTY_FUNCTION__)); | |||
10421 | assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10421, __PRETTY_FUNCTION__)); | |||
10422 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | |||
10423 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | |||
10424 | << RHSExpr->getSourceRange(); | |||
10425 | } | |||
10426 | ||||
10427 | // C99 6.5.6 | |||
10428 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | |||
10429 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
10430 | QualType* CompLHSTy) { | |||
10431 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10432 | ||||
10433 | if (LHS.get()->getType()->isVectorType() || | |||
10434 | RHS.get()->getType()->isVectorType()) { | |||
10435 | QualType compType = CheckVectorOperands( | |||
10436 | LHS, RHS, Loc, CompLHSTy, | |||
10437 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10438 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
10439 | if (CompLHSTy) *CompLHSTy = compType; | |||
10440 | return compType; | |||
10441 | } | |||
10442 | ||||
10443 | if (LHS.get()->getType()->isConstantMatrixType() || | |||
10444 | RHS.get()->getType()->isConstantMatrixType()) { | |||
10445 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | |||
10446 | } | |||
10447 | ||||
10448 | QualType compType = UsualArithmeticConversions( | |||
10449 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | |||
10450 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10451 | return QualType(); | |||
10452 | ||||
10453 | // Diagnose "string literal" '+' int and string '+' "char literal". | |||
10454 | if (Opc == BO_Add) { | |||
10455 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | |||
10456 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | |||
10457 | } | |||
10458 | ||||
10459 | // handle the common case first (both operands are arithmetic). | |||
10460 | if (!compType.isNull() && compType->isArithmeticType()) { | |||
10461 | if (CompLHSTy) *CompLHSTy = compType; | |||
10462 | return compType; | |||
10463 | } | |||
10464 | ||||
10465 | // Type-checking. Ultimately the pointer's going to be in PExp; | |||
10466 | // note that we bias towards the LHS being the pointer. | |||
10467 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | |||
10468 | ||||
10469 | bool isObjCPointer; | |||
10470 | if (PExp->getType()->isPointerType()) { | |||
10471 | isObjCPointer = false; | |||
10472 | } else if (PExp->getType()->isObjCObjectPointerType()) { | |||
10473 | isObjCPointer = true; | |||
10474 | } else { | |||
10475 | std::swap(PExp, IExp); | |||
10476 | if (PExp->getType()->isPointerType()) { | |||
10477 | isObjCPointer = false; | |||
10478 | } else if (PExp->getType()->isObjCObjectPointerType()) { | |||
10479 | isObjCPointer = true; | |||
10480 | } else { | |||
10481 | return InvalidOperands(Loc, LHS, RHS); | |||
10482 | } | |||
10483 | } | |||
10484 | assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10484, __PRETTY_FUNCTION__)); | |||
10485 | ||||
10486 | if (!IExp->getType()->isIntegerType()) | |||
10487 | return InvalidOperands(Loc, LHS, RHS); | |||
10488 | ||||
10489 | // Adding to a null pointer results in undefined behavior. | |||
10490 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | |||
10491 | Context, Expr::NPC_ValueDependentIsNotNull)) { | |||
10492 | // In C++ adding zero to a null pointer is defined. | |||
10493 | Expr::EvalResult KnownVal; | |||
10494 | if (!getLangOpts().CPlusPlus || | |||
10495 | (!IExp->isValueDependent() && | |||
10496 | (!IExp->EvaluateAsInt(KnownVal, Context) || | |||
10497 | KnownVal.Val.getInt() != 0))) { | |||
10498 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | |||
10499 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | |||
10500 | Context, BO_Add, PExp, IExp); | |||
10501 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | |||
10502 | } | |||
10503 | } | |||
10504 | ||||
10505 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | |||
10506 | return QualType(); | |||
10507 | ||||
10508 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | |||
10509 | return QualType(); | |||
10510 | ||||
10511 | // Check array bounds for pointer arithemtic | |||
10512 | CheckArrayAccess(PExp, IExp); | |||
10513 | ||||
10514 | if (CompLHSTy) { | |||
10515 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | |||
10516 | if (LHSTy.isNull()) { | |||
10517 | LHSTy = LHS.get()->getType(); | |||
10518 | if (LHSTy->isPromotableIntegerType()) | |||
10519 | LHSTy = Context.getPromotedIntegerType(LHSTy); | |||
10520 | } | |||
10521 | *CompLHSTy = LHSTy; | |||
10522 | } | |||
10523 | ||||
10524 | return PExp->getType(); | |||
10525 | } | |||
10526 | ||||
10527 | // C99 6.5.6 | |||
10528 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | |||
10529 | SourceLocation Loc, | |||
10530 | QualType* CompLHSTy) { | |||
10531 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10532 | ||||
10533 | if (LHS.get()->getType()->isVectorType() || | |||
10534 | RHS.get()->getType()->isVectorType()) { | |||
10535 | QualType compType = CheckVectorOperands( | |||
10536 | LHS, RHS, Loc, CompLHSTy, | |||
10537 | /*AllowBothBool*/getLangOpts().AltiVec, | |||
10538 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
10539 | if (CompLHSTy) *CompLHSTy = compType; | |||
10540 | return compType; | |||
10541 | } | |||
10542 | ||||
10543 | if (LHS.get()->getType()->isConstantMatrixType() || | |||
10544 | RHS.get()->getType()->isConstantMatrixType()) { | |||
10545 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | |||
10546 | } | |||
10547 | ||||
10548 | QualType compType = UsualArithmeticConversions( | |||
10549 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | |||
10550 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
10551 | return QualType(); | |||
10552 | ||||
10553 | // Enforce type constraints: C99 6.5.6p3. | |||
10554 | ||||
10555 | // Handle the common case first (both operands are arithmetic). | |||
10556 | if (!compType.isNull() && compType->isArithmeticType()) { | |||
10557 | if (CompLHSTy) *CompLHSTy = compType; | |||
10558 | return compType; | |||
10559 | } | |||
10560 | ||||
10561 | // Either ptr - int or ptr - ptr. | |||
10562 | if (LHS.get()->getType()->isAnyPointerType()) { | |||
10563 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | |||
10564 | ||||
10565 | // Diagnose bad cases where we step over interface counts. | |||
10566 | if (LHS.get()->getType()->isObjCObjectPointerType() && | |||
10567 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | |||
10568 | return QualType(); | |||
10569 | ||||
10570 | // The result type of a pointer-int computation is the pointer type. | |||
10571 | if (RHS.get()->getType()->isIntegerType()) { | |||
10572 | // Subtracting from a null pointer should produce a warning. | |||
10573 | // The last argument to the diagnose call says this doesn't match the | |||
10574 | // GNU int-to-pointer idiom. | |||
10575 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | |||
10576 | Expr::NPC_ValueDependentIsNotNull)) { | |||
10577 | // In C++ adding zero to a null pointer is defined. | |||
10578 | Expr::EvalResult KnownVal; | |||
10579 | if (!getLangOpts().CPlusPlus || | |||
10580 | (!RHS.get()->isValueDependent() && | |||
10581 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | |||
10582 | KnownVal.Val.getInt() != 0))) { | |||
10583 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | |||
10584 | } | |||
10585 | } | |||
10586 | ||||
10587 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | |||
10588 | return QualType(); | |||
10589 | ||||
10590 | // Check array bounds for pointer arithemtic | |||
10591 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | |||
10592 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | |||
10593 | ||||
10594 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | |||
10595 | return LHS.get()->getType(); | |||
10596 | } | |||
10597 | ||||
10598 | // Handle pointer-pointer subtractions. | |||
10599 | if (const PointerType *RHSPTy | |||
10600 | = RHS.get()->getType()->getAs<PointerType>()) { | |||
10601 | QualType rpointee = RHSPTy->getPointeeType(); | |||
10602 | ||||
10603 | if (getLangOpts().CPlusPlus) { | |||
10604 | // Pointee types must be the same: C++ [expr.add] | |||
10605 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | |||
10606 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | |||
10607 | } | |||
10608 | } else { | |||
10609 | // Pointee types must be compatible C99 6.5.6p3 | |||
10610 | if (!Context.typesAreCompatible( | |||
10611 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | |||
10612 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | |||
10613 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | |||
10614 | return QualType(); | |||
10615 | } | |||
10616 | } | |||
10617 | ||||
10618 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | |||
10619 | LHS.get(), RHS.get())) | |||
10620 | return QualType(); | |||
10621 | ||||
10622 | // FIXME: Add warnings for nullptr - ptr. | |||
10623 | ||||
10624 | // The pointee type may have zero size. As an extension, a structure or | |||
10625 | // union may have zero size or an array may have zero length. In this | |||
10626 | // case subtraction does not make sense. | |||
10627 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | |||
10628 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | |||
10629 | if (ElementSize.isZero()) { | |||
10630 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | |||
10631 | << rpointee.getUnqualifiedType() | |||
10632 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10633 | } | |||
10634 | } | |||
10635 | ||||
10636 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | |||
10637 | return Context.getPointerDiffType(); | |||
10638 | } | |||
10639 | } | |||
10640 | ||||
10641 | return InvalidOperands(Loc, LHS, RHS); | |||
10642 | } | |||
10643 | ||||
10644 | static bool isScopedEnumerationType(QualType T) { | |||
10645 | if (const EnumType *ET = T->getAs<EnumType>()) | |||
10646 | return ET->getDecl()->isScoped(); | |||
10647 | return false; | |||
10648 | } | |||
10649 | ||||
10650 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | |||
10651 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
10652 | QualType LHSType) { | |||
10653 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | |||
10654 | // so skip remaining warnings as we don't want to modify values within Sema. | |||
10655 | if (S.getLangOpts().OpenCL) | |||
10656 | return; | |||
10657 | ||||
10658 | // Check right/shifter operand | |||
10659 | Expr::EvalResult RHSResult; | |||
10660 | if (RHS.get()->isValueDependent() || | |||
10661 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | |||
10662 | return; | |||
10663 | llvm::APSInt Right = RHSResult.Val.getInt(); | |||
10664 | ||||
10665 | if (Right.isNegative()) { | |||
10666 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
10667 | S.PDiag(diag::warn_shift_negative) | |||
10668 | << RHS.get()->getSourceRange()); | |||
10669 | return; | |||
10670 | } | |||
10671 | ||||
10672 | QualType LHSExprType = LHS.get()->getType(); | |||
10673 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | |||
10674 | if (LHSExprType->isExtIntType()) | |||
10675 | LeftSize = S.Context.getIntWidth(LHSExprType); | |||
10676 | else if (LHSExprType->isFixedPointType()) { | |||
10677 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | |||
10678 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | |||
10679 | } | |||
10680 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | |||
10681 | if (Right.uge(LeftBits)) { | |||
10682 | S.DiagRuntimeBehavior(Loc, RHS.get(), | |||
10683 | S.PDiag(diag::warn_shift_gt_typewidth) | |||
10684 | << RHS.get()->getSourceRange()); | |||
10685 | return; | |||
10686 | } | |||
10687 | ||||
10688 | // FIXME: We probably need to handle fixed point types specially here. | |||
10689 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | |||
10690 | return; | |||
10691 | ||||
10692 | // When left shifting an ICE which is signed, we can check for overflow which | |||
10693 | // according to C++ standards prior to C++2a has undefined behavior | |||
10694 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | |||
10695 | // more than the maximum value representable in the result type, so never | |||
10696 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | |||
10697 | // expression is still probably a bug.) | |||
10698 | Expr::EvalResult LHSResult; | |||
10699 | if (LHS.get()->isValueDependent() || | |||
10700 | LHSType->hasUnsignedIntegerRepresentation() || | |||
10701 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | |||
10702 | return; | |||
10703 | llvm::APSInt Left = LHSResult.Val.getInt(); | |||
10704 | ||||
10705 | // If LHS does not have a signed type and non-negative value | |||
10706 | // then, the behavior is undefined before C++2a. Warn about it. | |||
10707 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && | |||
10708 | !S.getLangOpts().CPlusPlus20) { | |||
10709 | S.DiagRuntimeBehavior(Loc, LHS.get(), | |||
10710 | S.PDiag(diag::warn_shift_lhs_negative) | |||
10711 | << LHS.get()->getSourceRange()); | |||
10712 | return; | |||
10713 | } | |||
10714 | ||||
10715 | llvm::APInt ResultBits = | |||
10716 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | |||
10717 | if (LeftBits.uge(ResultBits)) | |||
10718 | return; | |||
10719 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | |||
10720 | Result = Result.shl(Right); | |||
10721 | ||||
10722 | // Print the bit representation of the signed integer as an unsigned | |||
10723 | // hexadecimal number. | |||
10724 | SmallString<40> HexResult; | |||
10725 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | |||
10726 | ||||
10727 | // If we are only missing a sign bit, this is less likely to result in actual | |||
10728 | // bugs -- if the result is cast back to an unsigned type, it will have the | |||
10729 | // expected value. Thus we place this behind a different warning that can be | |||
10730 | // turned off separately if needed. | |||
10731 | if (LeftBits == ResultBits - 1) { | |||
10732 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | |||
10733 | << HexResult << LHSType | |||
10734 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10735 | return; | |||
10736 | } | |||
10737 | ||||
10738 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | |||
10739 | << HexResult.str() << Result.getMinSignedBits() << LHSType | |||
10740 | << Left.getBitWidth() << LHS.get()->getSourceRange() | |||
10741 | << RHS.get()->getSourceRange(); | |||
10742 | } | |||
10743 | ||||
10744 | /// Return the resulting type when a vector is shifted | |||
10745 | /// by a scalar or vector shift amount. | |||
10746 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
10747 | SourceLocation Loc, bool IsCompAssign) { | |||
10748 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | |||
10749 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | |||
10750 | !LHS.get()->getType()->isVectorType()) { | |||
10751 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | |||
10752 | << RHS.get()->getType() << LHS.get()->getType() | |||
10753 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10754 | return QualType(); | |||
10755 | } | |||
10756 | ||||
10757 | if (!IsCompAssign) { | |||
10758 | LHS = S.UsualUnaryConversions(LHS.get()); | |||
10759 | if (LHS.isInvalid()) return QualType(); | |||
10760 | } | |||
10761 | ||||
10762 | RHS = S.UsualUnaryConversions(RHS.get()); | |||
10763 | if (RHS.isInvalid()) return QualType(); | |||
10764 | ||||
10765 | QualType LHSType = LHS.get()->getType(); | |||
10766 | // Note that LHS might be a scalar because the routine calls not only in | |||
10767 | // OpenCL case. | |||
10768 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | |||
10769 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | |||
10770 | ||||
10771 | // Note that RHS might not be a vector. | |||
10772 | QualType RHSType = RHS.get()->getType(); | |||
10773 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | |||
10774 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | |||
10775 | ||||
10776 | // The operands need to be integers. | |||
10777 | if (!LHSEleType->isIntegerType()) { | |||
10778 | S.Diag(Loc, diag::err_typecheck_expect_int) | |||
10779 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | |||
10780 | return QualType(); | |||
10781 | } | |||
10782 | ||||
10783 | if (!RHSEleType->isIntegerType()) { | |||
10784 | S.Diag(Loc, diag::err_typecheck_expect_int) | |||
10785 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | |||
10786 | return QualType(); | |||
10787 | } | |||
10788 | ||||
10789 | if (!LHSVecTy) { | |||
10790 | assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10790, __PRETTY_FUNCTION__)); | |||
10791 | if (IsCompAssign) | |||
10792 | return RHSType; | |||
10793 | if (LHSEleType != RHSEleType) { | |||
10794 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | |||
10795 | LHSEleType = RHSEleType; | |||
10796 | } | |||
10797 | QualType VecTy = | |||
10798 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | |||
10799 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | |||
10800 | LHSType = VecTy; | |||
10801 | } else if (RHSVecTy) { | |||
10802 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | |||
10803 | // are applied component-wise. So if RHS is a vector, then ensure | |||
10804 | // that the number of elements is the same as LHS... | |||
10805 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | |||
10806 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | |||
10807 | << LHS.get()->getType() << RHS.get()->getType() | |||
10808 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10809 | return QualType(); | |||
10810 | } | |||
10811 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | |||
10812 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | |||
10813 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | |||
10814 | if (LHSBT != RHSBT && | |||
10815 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | |||
10816 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | |||
10817 | << LHS.get()->getType() << RHS.get()->getType() | |||
10818 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10819 | } | |||
10820 | } | |||
10821 | } else { | |||
10822 | // ...else expand RHS to match the number of elements in LHS. | |||
10823 | QualType VecTy = | |||
10824 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | |||
10825 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | |||
10826 | } | |||
10827 | ||||
10828 | return LHSType; | |||
10829 | } | |||
10830 | ||||
10831 | // C99 6.5.7 | |||
10832 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | |||
10833 | SourceLocation Loc, BinaryOperatorKind Opc, | |||
10834 | bool IsCompAssign) { | |||
10835 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
10836 | ||||
10837 | // Vector shifts promote their scalar inputs to vector type. | |||
10838 | if (LHS.get()->getType()->isVectorType() || | |||
10839 | RHS.get()->getType()->isVectorType()) { | |||
10840 | if (LangOpts.ZVector) { | |||
10841 | // The shift operators for the z vector extensions work basically | |||
10842 | // like general shifts, except that neither the LHS nor the RHS is | |||
10843 | // allowed to be a "vector bool". | |||
10844 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | |||
10845 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
10846 | return InvalidOperands(Loc, LHS, RHS); | |||
10847 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | |||
10848 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | |||
10849 | return InvalidOperands(Loc, LHS, RHS); | |||
10850 | } | |||
10851 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | |||
10852 | } | |||
10853 | ||||
10854 | // Shifts don't perform usual arithmetic conversions, they just do integer | |||
10855 | // promotions on each operand. C99 6.5.7p3 | |||
10856 | ||||
10857 | // For the LHS, do usual unary conversions, but then reset them away | |||
10858 | // if this is a compound assignment. | |||
10859 | ExprResult OldLHS = LHS; | |||
10860 | LHS = UsualUnaryConversions(LHS.get()); | |||
10861 | if (LHS.isInvalid()) | |||
10862 | return QualType(); | |||
10863 | QualType LHSType = LHS.get()->getType(); | |||
10864 | if (IsCompAssign) LHS = OldLHS; | |||
10865 | ||||
10866 | // The RHS is simpler. | |||
10867 | RHS = UsualUnaryConversions(RHS.get()); | |||
10868 | if (RHS.isInvalid()) | |||
10869 | return QualType(); | |||
10870 | QualType RHSType = RHS.get()->getType(); | |||
10871 | ||||
10872 | // C99 6.5.7p2: Each of the operands shall have integer type. | |||
10873 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | |||
10874 | if ((!LHSType->isFixedPointOrIntegerType() && | |||
10875 | !LHSType->hasIntegerRepresentation()) || | |||
10876 | !RHSType->hasIntegerRepresentation()) | |||
10877 | return InvalidOperands(Loc, LHS, RHS); | |||
10878 | ||||
10879 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | |||
10880 | // hasIntegerRepresentation() above instead of this. | |||
10881 | if (isScopedEnumerationType(LHSType) || | |||
10882 | isScopedEnumerationType(RHSType)) { | |||
10883 | return InvalidOperands(Loc, LHS, RHS); | |||
10884 | } | |||
10885 | // Sanity-check shift operands | |||
10886 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | |||
10887 | ||||
10888 | // "The type of the result is that of the promoted left operand." | |||
10889 | return LHSType; | |||
10890 | } | |||
10891 | ||||
10892 | /// Diagnose bad pointer comparisons. | |||
10893 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | |||
10894 | ExprResult &LHS, ExprResult &RHS, | |||
10895 | bool IsError) { | |||
10896 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | |||
10897 | : diag::ext_typecheck_comparison_of_distinct_pointers) | |||
10898 | << LHS.get()->getType() << RHS.get()->getType() | |||
10899 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10900 | } | |||
10901 | ||||
10902 | /// Returns false if the pointers are converted to a composite type, | |||
10903 | /// true otherwise. | |||
10904 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | |||
10905 | ExprResult &LHS, ExprResult &RHS) { | |||
10906 | // C++ [expr.rel]p2: | |||
10907 | // [...] Pointer conversions (4.10) and qualification | |||
10908 | // conversions (4.4) are performed on pointer operands (or on | |||
10909 | // a pointer operand and a null pointer constant) to bring | |||
10910 | // them to their composite pointer type. [...] | |||
10911 | // | |||
10912 | // C++ [expr.eq]p1 uses the same notion for (in)equality | |||
10913 | // comparisons of pointers. | |||
10914 | ||||
10915 | QualType LHSType = LHS.get()->getType(); | |||
10916 | QualType RHSType = RHS.get()->getType(); | |||
10917 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10918, __PRETTY_FUNCTION__)) | |||
10918 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 10918, __PRETTY_FUNCTION__)); | |||
10919 | ||||
10920 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | |||
10921 | if (T.isNull()) { | |||
10922 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | |||
10923 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | |||
10924 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | |||
10925 | else | |||
10926 | S.InvalidOperands(Loc, LHS, RHS); | |||
10927 | return true; | |||
10928 | } | |||
10929 | ||||
10930 | return false; | |||
10931 | } | |||
10932 | ||||
10933 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | |||
10934 | ExprResult &LHS, | |||
10935 | ExprResult &RHS, | |||
10936 | bool IsError) { | |||
10937 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | |||
10938 | : diag::ext_typecheck_comparison_of_fptr_to_void) | |||
10939 | << LHS.get()->getType() << RHS.get()->getType() | |||
10940 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
10941 | } | |||
10942 | ||||
10943 | static bool isObjCObjectLiteral(ExprResult &E) { | |||
10944 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | |||
10945 | case Stmt::ObjCArrayLiteralClass: | |||
10946 | case Stmt::ObjCDictionaryLiteralClass: | |||
10947 | case Stmt::ObjCStringLiteralClass: | |||
10948 | case Stmt::ObjCBoxedExprClass: | |||
10949 | return true; | |||
10950 | default: | |||
10951 | // Note that ObjCBoolLiteral is NOT an object literal! | |||
10952 | return false; | |||
10953 | } | |||
10954 | } | |||
10955 | ||||
10956 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | |||
10957 | const ObjCObjectPointerType *Type = | |||
10958 | LHS->getType()->getAs<ObjCObjectPointerType>(); | |||
10959 | ||||
10960 | // If this is not actually an Objective-C object, bail out. | |||
10961 | if (!Type) | |||
10962 | return false; | |||
10963 | ||||
10964 | // Get the LHS object's interface type. | |||
10965 | QualType InterfaceType = Type->getPointeeType(); | |||
10966 | ||||
10967 | // If the RHS isn't an Objective-C object, bail out. | |||
10968 | if (!RHS->getType()->isObjCObjectPointerType()) | |||
10969 | return false; | |||
10970 | ||||
10971 | // Try to find the -isEqual: method. | |||
10972 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | |||
10973 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | |||
10974 | InterfaceType, | |||
10975 | /*IsInstance=*/true); | |||
10976 | if (!Method) { | |||
10977 | if (Type->isObjCIdType()) { | |||
10978 | // For 'id', just check the global pool. | |||
10979 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | |||
10980 | /*receiverId=*/true); | |||
10981 | } else { | |||
10982 | // Check protocols. | |||
10983 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | |||
10984 | /*IsInstance=*/true); | |||
10985 | } | |||
10986 | } | |||
10987 | ||||
10988 | if (!Method) | |||
10989 | return false; | |||
10990 | ||||
10991 | QualType T = Method->parameters()[0]->getType(); | |||
10992 | if (!T->isObjCObjectPointerType()) | |||
10993 | return false; | |||
10994 | ||||
10995 | QualType R = Method->getReturnType(); | |||
10996 | if (!R->isScalarType()) | |||
10997 | return false; | |||
10998 | ||||
10999 | return true; | |||
11000 | } | |||
11001 | ||||
11002 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | |||
11003 | FromE = FromE->IgnoreParenImpCasts(); | |||
11004 | switch (FromE->getStmtClass()) { | |||
11005 | default: | |||
11006 | break; | |||
11007 | case Stmt::ObjCStringLiteralClass: | |||
11008 | // "string literal" | |||
11009 | return LK_String; | |||
11010 | case Stmt::ObjCArrayLiteralClass: | |||
11011 | // "array literal" | |||
11012 | return LK_Array; | |||
11013 | case Stmt::ObjCDictionaryLiteralClass: | |||
11014 | // "dictionary literal" | |||
11015 | return LK_Dictionary; | |||
11016 | case Stmt::BlockExprClass: | |||
11017 | return LK_Block; | |||
11018 | case Stmt::ObjCBoxedExprClass: { | |||
11019 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | |||
11020 | switch (Inner->getStmtClass()) { | |||
11021 | case Stmt::IntegerLiteralClass: | |||
11022 | case Stmt::FloatingLiteralClass: | |||
11023 | case Stmt::CharacterLiteralClass: | |||
11024 | case Stmt::ObjCBoolLiteralExprClass: | |||
11025 | case Stmt::CXXBoolLiteralExprClass: | |||
11026 | // "numeric literal" | |||
11027 | return LK_Numeric; | |||
11028 | case Stmt::ImplicitCastExprClass: { | |||
11029 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | |||
11030 | // Boolean literals can be represented by implicit casts. | |||
11031 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | |||
11032 | return LK_Numeric; | |||
11033 | break; | |||
11034 | } | |||
11035 | default: | |||
11036 | break; | |||
11037 | } | |||
11038 | return LK_Boxed; | |||
11039 | } | |||
11040 | } | |||
11041 | return LK_None; | |||
11042 | } | |||
11043 | ||||
11044 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | |||
11045 | ExprResult &LHS, ExprResult &RHS, | |||
11046 | BinaryOperator::Opcode Opc){ | |||
11047 | Expr *Literal; | |||
11048 | Expr *Other; | |||
11049 | if (isObjCObjectLiteral(LHS)) { | |||
11050 | Literal = LHS.get(); | |||
11051 | Other = RHS.get(); | |||
11052 | } else { | |||
11053 | Literal = RHS.get(); | |||
11054 | Other = LHS.get(); | |||
11055 | } | |||
11056 | ||||
11057 | // Don't warn on comparisons against nil. | |||
11058 | Other = Other->IgnoreParenCasts(); | |||
11059 | if (Other->isNullPointerConstant(S.getASTContext(), | |||
11060 | Expr::NPC_ValueDependentIsNotNull)) | |||
11061 | return; | |||
11062 | ||||
11063 | // This should be kept in sync with warn_objc_literal_comparison. | |||
11064 | // LK_String should always be after the other literals, since it has its own | |||
11065 | // warning flag. | |||
11066 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | |||
11067 | assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0 ) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11067, __PRETTY_FUNCTION__)); | |||
11068 | if (LiteralKind == Sema::LK_None) { | |||
11069 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11069); | |||
11070 | } | |||
11071 | ||||
11072 | if (LiteralKind == Sema::LK_String) | |||
11073 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | |||
11074 | << Literal->getSourceRange(); | |||
11075 | else | |||
11076 | S.Diag(Loc, diag::warn_objc_literal_comparison) | |||
11077 | << LiteralKind << Literal->getSourceRange(); | |||
11078 | ||||
11079 | if (BinaryOperator::isEqualityOp(Opc) && | |||
11080 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | |||
11081 | SourceLocation Start = LHS.get()->getBeginLoc(); | |||
11082 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | |||
11083 | CharSourceRange OpRange = | |||
11084 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | |||
11085 | ||||
11086 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | |||
11087 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | |||
11088 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | |||
11089 | << FixItHint::CreateInsertion(End, "]"); | |||
11090 | } | |||
11091 | } | |||
11092 | ||||
11093 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | |||
11094 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | |||
11095 | ExprResult &RHS, SourceLocation Loc, | |||
11096 | BinaryOperatorKind Opc) { | |||
11097 | // Check that left hand side is !something. | |||
11098 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | |||
11099 | if (!UO || UO->getOpcode() != UO_LNot) return; | |||
11100 | ||||
11101 | // Only check if the right hand side is non-bool arithmetic type. | |||
11102 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | |||
11103 | ||||
11104 | // Make sure that the something in !something is not bool. | |||
11105 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | |||
11106 | if (SubExpr->isKnownToHaveBooleanValue()) return; | |||
11107 | ||||
11108 | // Emit warning. | |||
11109 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | |||
11110 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | |||
11111 | << Loc << IsBitwiseOp; | |||
11112 | ||||
11113 | // First note suggest !(x < y) | |||
11114 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | |||
11115 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | |||
11116 | FirstClose = S.getLocForEndOfToken(FirstClose); | |||
11117 | if (FirstClose.isInvalid()) | |||
11118 | FirstOpen = SourceLocation(); | |||
11119 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | |||
11120 | << IsBitwiseOp | |||
11121 | << FixItHint::CreateInsertion(FirstOpen, "(") | |||
11122 | << FixItHint::CreateInsertion(FirstClose, ")"); | |||
11123 | ||||
11124 | // Second note suggests (!x) < y | |||
11125 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | |||
11126 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | |||
11127 | SecondClose = S.getLocForEndOfToken(SecondClose); | |||
11128 | if (SecondClose.isInvalid()) | |||
11129 | SecondOpen = SourceLocation(); | |||
11130 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | |||
11131 | << FixItHint::CreateInsertion(SecondOpen, "(") | |||
11132 | << FixItHint::CreateInsertion(SecondClose, ")"); | |||
11133 | } | |||
11134 | ||||
11135 | // Returns true if E refers to a non-weak array. | |||
11136 | static bool checkForArray(const Expr *E) { | |||
11137 | const ValueDecl *D = nullptr; | |||
11138 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | |||
11139 | D = DR->getDecl(); | |||
11140 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | |||
11141 | if (Mem->isImplicitAccess()) | |||
11142 | D = Mem->getMemberDecl(); | |||
11143 | } | |||
11144 | if (!D) | |||
11145 | return false; | |||
11146 | return D->getType()->isArrayType() && !D->isWeak(); | |||
11147 | } | |||
11148 | ||||
11149 | /// Diagnose some forms of syntactically-obvious tautological comparison. | |||
11150 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | |||
11151 | Expr *LHS, Expr *RHS, | |||
11152 | BinaryOperatorKind Opc) { | |||
11153 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | |||
11154 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | |||
11155 | ||||
11156 | QualType LHSType = LHS->getType(); | |||
11157 | QualType RHSType = RHS->getType(); | |||
11158 | if (LHSType->hasFloatingRepresentation() || | |||
11159 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | |||
11160 | S.inTemplateInstantiation()) | |||
11161 | return; | |||
11162 | ||||
11163 | // Comparisons between two array types are ill-formed for operator<=>, so | |||
11164 | // we shouldn't emit any additional warnings about it. | |||
11165 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | |||
11166 | return; | |||
11167 | ||||
11168 | // For non-floating point types, check for self-comparisons of the form | |||
11169 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | |||
11170 | // often indicate logic errors in the program. | |||
11171 | // | |||
11172 | // NOTE: Don't warn about comparison expressions resulting from macro | |||
11173 | // expansion. Also don't warn about comparisons which are only self | |||
11174 | // comparisons within a template instantiation. The warnings should catch | |||
11175 | // obvious cases in the definition of the template anyways. The idea is to | |||
11176 | // warn when the typed comparison operator will always evaluate to the same | |||
11177 | // result. | |||
11178 | ||||
11179 | // Used for indexing into %select in warn_comparison_always | |||
11180 | enum { | |||
11181 | AlwaysConstant, | |||
11182 | AlwaysTrue, | |||
11183 | AlwaysFalse, | |||
11184 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | |||
11185 | }; | |||
11186 | ||||
11187 | // C++2a [depr.array.comp]: | |||
11188 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | |||
11189 | // operands of array type are deprecated. | |||
11190 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | |||
11191 | RHSStripped->getType()->isArrayType()) { | |||
11192 | S.Diag(Loc, diag::warn_depr_array_comparison) | |||
11193 | << LHS->getSourceRange() << RHS->getSourceRange() | |||
11194 | << LHSStripped->getType() << RHSStripped->getType(); | |||
11195 | // Carry on to produce the tautological comparison warning, if this | |||
11196 | // expression is potentially-evaluated, we can resolve the array to a | |||
11197 | // non-weak declaration, and so on. | |||
11198 | } | |||
11199 | ||||
11200 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | |||
11201 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | |||
11202 | unsigned Result; | |||
11203 | switch (Opc) { | |||
11204 | case BO_EQ: | |||
11205 | case BO_LE: | |||
11206 | case BO_GE: | |||
11207 | Result = AlwaysTrue; | |||
11208 | break; | |||
11209 | case BO_NE: | |||
11210 | case BO_LT: | |||
11211 | case BO_GT: | |||
11212 | Result = AlwaysFalse; | |||
11213 | break; | |||
11214 | case BO_Cmp: | |||
11215 | Result = AlwaysEqual; | |||
11216 | break; | |||
11217 | default: | |||
11218 | Result = AlwaysConstant; | |||
11219 | break; | |||
11220 | } | |||
11221 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
11222 | S.PDiag(diag::warn_comparison_always) | |||
11223 | << 0 /*self-comparison*/ | |||
11224 | << Result); | |||
11225 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | |||
11226 | // What is it always going to evaluate to? | |||
11227 | unsigned Result; | |||
11228 | switch (Opc) { | |||
11229 | case BO_EQ: // e.g. array1 == array2 | |||
11230 | Result = AlwaysFalse; | |||
11231 | break; | |||
11232 | case BO_NE: // e.g. array1 != array2 | |||
11233 | Result = AlwaysTrue; | |||
11234 | break; | |||
11235 | default: // e.g. array1 <= array2 | |||
11236 | // The best we can say is 'a constant' | |||
11237 | Result = AlwaysConstant; | |||
11238 | break; | |||
11239 | } | |||
11240 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
11241 | S.PDiag(diag::warn_comparison_always) | |||
11242 | << 1 /*array comparison*/ | |||
11243 | << Result); | |||
11244 | } | |||
11245 | } | |||
11246 | ||||
11247 | if (isa<CastExpr>(LHSStripped)) | |||
11248 | LHSStripped = LHSStripped->IgnoreParenCasts(); | |||
11249 | if (isa<CastExpr>(RHSStripped)) | |||
11250 | RHSStripped = RHSStripped->IgnoreParenCasts(); | |||
11251 | ||||
11252 | // Warn about comparisons against a string constant (unless the other | |||
11253 | // operand is null); the user probably wants string comparison function. | |||
11254 | Expr *LiteralString = nullptr; | |||
11255 | Expr *LiteralStringStripped = nullptr; | |||
11256 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | |||
11257 | !RHSStripped->isNullPointerConstant(S.Context, | |||
11258 | Expr::NPC_ValueDependentIsNull)) { | |||
11259 | LiteralString = LHS; | |||
11260 | LiteralStringStripped = LHSStripped; | |||
11261 | } else if ((isa<StringLiteral>(RHSStripped) || | |||
11262 | isa<ObjCEncodeExpr>(RHSStripped)) && | |||
11263 | !LHSStripped->isNullPointerConstant(S.Context, | |||
11264 | Expr::NPC_ValueDependentIsNull)) { | |||
11265 | LiteralString = RHS; | |||
11266 | LiteralStringStripped = RHSStripped; | |||
11267 | } | |||
11268 | ||||
11269 | if (LiteralString) { | |||
11270 | S.DiagRuntimeBehavior(Loc, nullptr, | |||
11271 | S.PDiag(diag::warn_stringcompare) | |||
11272 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | |||
11273 | << LiteralString->getSourceRange()); | |||
11274 | } | |||
11275 | } | |||
11276 | ||||
11277 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | |||
11278 | switch (CK) { | |||
11279 | default: { | |||
11280 | #ifndef NDEBUG | |||
11281 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | |||
11282 | << "\n"; | |||
11283 | #endif | |||
11284 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11284); | |||
11285 | } | |||
11286 | case CK_UserDefinedConversion: | |||
11287 | return ICK_Identity; | |||
11288 | case CK_LValueToRValue: | |||
11289 | return ICK_Lvalue_To_Rvalue; | |||
11290 | case CK_ArrayToPointerDecay: | |||
11291 | return ICK_Array_To_Pointer; | |||
11292 | case CK_FunctionToPointerDecay: | |||
11293 | return ICK_Function_To_Pointer; | |||
11294 | case CK_IntegralCast: | |||
11295 | return ICK_Integral_Conversion; | |||
11296 | case CK_FloatingCast: | |||
11297 | return ICK_Floating_Conversion; | |||
11298 | case CK_IntegralToFloating: | |||
11299 | case CK_FloatingToIntegral: | |||
11300 | return ICK_Floating_Integral; | |||
11301 | case CK_IntegralComplexCast: | |||
11302 | case CK_FloatingComplexCast: | |||
11303 | case CK_FloatingComplexToIntegralComplex: | |||
11304 | case CK_IntegralComplexToFloatingComplex: | |||
11305 | return ICK_Complex_Conversion; | |||
11306 | case CK_FloatingComplexToReal: | |||
11307 | case CK_FloatingRealToComplex: | |||
11308 | case CK_IntegralComplexToReal: | |||
11309 | case CK_IntegralRealToComplex: | |||
11310 | return ICK_Complex_Real; | |||
11311 | } | |||
11312 | } | |||
11313 | ||||
11314 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | |||
11315 | QualType FromType, | |||
11316 | SourceLocation Loc) { | |||
11317 | // Check for a narrowing implicit conversion. | |||
11318 | StandardConversionSequence SCS; | |||
11319 | SCS.setAsIdentityConversion(); | |||
11320 | SCS.setToType(0, FromType); | |||
11321 | SCS.setToType(1, ToType); | |||
11322 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
11323 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | |||
11324 | ||||
11325 | APValue PreNarrowingValue; | |||
11326 | QualType PreNarrowingType; | |||
11327 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | |||
11328 | PreNarrowingType, | |||
11329 | /*IgnoreFloatToIntegralConversion*/ true)) { | |||
11330 | case NK_Dependent_Narrowing: | |||
11331 | // Implicit conversion to a narrower type, but the expression is | |||
11332 | // value-dependent so we can't tell whether it's actually narrowing. | |||
11333 | case NK_Not_Narrowing: | |||
11334 | return false; | |||
11335 | ||||
11336 | case NK_Constant_Narrowing: | |||
11337 | // Implicit conversion to a narrower type, and the value is not a constant | |||
11338 | // expression. | |||
11339 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | |||
11340 | << /*Constant*/ 1 | |||
11341 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | |||
11342 | return true; | |||
11343 | ||||
11344 | case NK_Variable_Narrowing: | |||
11345 | // Implicit conversion to a narrower type, and the value is not a constant | |||
11346 | // expression. | |||
11347 | case NK_Type_Narrowing: | |||
11348 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | |||
11349 | << /*Constant*/ 0 << FromType << ToType; | |||
11350 | // TODO: It's not a constant expression, but what if the user intended it | |||
11351 | // to be? Can we produce notes to help them figure out why it isn't? | |||
11352 | return true; | |||
11353 | } | |||
11354 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11354); | |||
11355 | } | |||
11356 | ||||
11357 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | |||
11358 | ExprResult &LHS, | |||
11359 | ExprResult &RHS, | |||
11360 | SourceLocation Loc) { | |||
11361 | QualType LHSType = LHS.get()->getType(); | |||
11362 | QualType RHSType = RHS.get()->getType(); | |||
11363 | // Dig out the original argument type and expression before implicit casts | |||
11364 | // were applied. These are the types/expressions we need to check the | |||
11365 | // [expr.spaceship] requirements against. | |||
11366 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | |||
11367 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | |||
11368 | QualType LHSStrippedType = LHSStripped.get()->getType(); | |||
11369 | QualType RHSStrippedType = RHSStripped.get()->getType(); | |||
11370 | ||||
11371 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | |||
11372 | // other is not, the program is ill-formed. | |||
11373 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | |||
11374 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | |||
11375 | return QualType(); | |||
11376 | } | |||
11377 | ||||
11378 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | |||
11379 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | |||
11380 | RHSStrippedType->isEnumeralType(); | |||
11381 | if (NumEnumArgs == 1) { | |||
11382 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | |||
11383 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | |||
11384 | if (OtherTy->hasFloatingRepresentation()) { | |||
11385 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | |||
11386 | return QualType(); | |||
11387 | } | |||
11388 | } | |||
11389 | if (NumEnumArgs == 2) { | |||
11390 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | |||
11391 | // type E, the operator yields the result of converting the operands | |||
11392 | // to the underlying type of E and applying <=> to the converted operands. | |||
11393 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | |||
11394 | S.InvalidOperands(Loc, LHS, RHS); | |||
11395 | return QualType(); | |||
11396 | } | |||
11397 | QualType IntType = | |||
11398 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | |||
11399 | assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> ( 0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11399, __PRETTY_FUNCTION__)); | |||
11400 | ||||
11401 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | |||
11402 | // promote the boolean type, and all other promotable integer types, to | |||
11403 | // avoid this. | |||
11404 | if (IntType->isPromotableIntegerType()) | |||
11405 | IntType = S.Context.getPromotedIntegerType(IntType); | |||
11406 | ||||
11407 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | |||
11408 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | |||
11409 | LHSType = RHSType = IntType; | |||
11410 | } | |||
11411 | ||||
11412 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | |||
11413 | // usual arithmetic conversions are applied to the operands. | |||
11414 | QualType Type = | |||
11415 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | |||
11416 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
11417 | return QualType(); | |||
11418 | if (Type.isNull()) | |||
11419 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11420 | ||||
11421 | Optional<ComparisonCategoryType> CCT = | |||
11422 | getComparisonCategoryForBuiltinCmp(Type); | |||
11423 | if (!CCT) | |||
11424 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11425 | ||||
11426 | bool HasNarrowing = checkThreeWayNarrowingConversion( | |||
11427 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | |||
11428 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | |||
11429 | RHS.get()->getBeginLoc()); | |||
11430 | if (HasNarrowing) | |||
11431 | return QualType(); | |||
11432 | ||||
11433 | assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set" ) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11433, __PRETTY_FUNCTION__)); | |||
11434 | ||||
11435 | return S.CheckComparisonCategoryType( | |||
11436 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | |||
11437 | } | |||
11438 | ||||
11439 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | |||
11440 | ExprResult &RHS, | |||
11441 | SourceLocation Loc, | |||
11442 | BinaryOperatorKind Opc) { | |||
11443 | if (Opc == BO_Cmp) | |||
11444 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | |||
11445 | ||||
11446 | // C99 6.5.8p3 / C99 6.5.9p4 | |||
11447 | QualType Type = | |||
11448 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | |||
11449 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
11450 | return QualType(); | |||
11451 | if (Type.isNull()) | |||
11452 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11453 | assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ? static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11453, __PRETTY_FUNCTION__)); | |||
11454 | ||||
11455 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | |||
11456 | return S.InvalidOperands(Loc, LHS, RHS); | |||
11457 | ||||
11458 | // Check for comparisons of floating point operands using != and ==. | |||
11459 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | |||
11460 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | |||
11461 | ||||
11462 | // The result of comparisons is 'bool' in C++, 'int' in C. | |||
11463 | return S.Context.getLogicalOperationType(); | |||
11464 | } | |||
11465 | ||||
11466 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | |||
11467 | if (!NullE.get()->getType()->isAnyPointerType()) | |||
11468 | return; | |||
11469 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | |||
11470 | if (!E.get()->getType()->isAnyPointerType() && | |||
11471 | E.get()->isNullPointerConstant(Context, | |||
11472 | Expr::NPC_ValueDependentIsNotNull) == | |||
11473 | Expr::NPCK_ZeroExpression) { | |||
11474 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | |||
11475 | if (CL->getValue() == 0) | |||
11476 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | |||
11477 | << NullValue | |||
11478 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | |||
11479 | NullValue ? "NULL" : "(void *)0"); | |||
11480 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | |||
11481 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | |||
11482 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | |||
11483 | if (T == Context.CharTy) | |||
11484 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | |||
11485 | << NullValue | |||
11486 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | |||
11487 | NullValue ? "NULL" : "(void *)0"); | |||
11488 | } | |||
11489 | } | |||
11490 | } | |||
11491 | ||||
11492 | // C99 6.5.8, C++ [expr.rel] | |||
11493 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
11494 | SourceLocation Loc, | |||
11495 | BinaryOperatorKind Opc) { | |||
11496 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | |||
11497 | bool IsThreeWay = Opc == BO_Cmp; | |||
11498 | bool IsOrdered = IsRelational || IsThreeWay; | |||
11499 | auto IsAnyPointerType = [](ExprResult E) { | |||
11500 | QualType Ty = E.get()->getType(); | |||
11501 | return Ty->isPointerType() || Ty->isMemberPointerType(); | |||
11502 | }; | |||
11503 | ||||
11504 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | |||
11505 | // type, array-to-pointer, ..., conversions are performed on both operands to | |||
11506 | // bring them to their composite type. | |||
11507 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | |||
11508 | // any type-related checks. | |||
11509 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | |||
11510 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
11511 | if (LHS.isInvalid()) | |||
11512 | return QualType(); | |||
11513 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
11514 | if (RHS.isInvalid()) | |||
11515 | return QualType(); | |||
11516 | } else { | |||
11517 | LHS = DefaultLvalueConversion(LHS.get()); | |||
11518 | if (LHS.isInvalid()) | |||
11519 | return QualType(); | |||
11520 | RHS = DefaultLvalueConversion(RHS.get()); | |||
11521 | if (RHS.isInvalid()) | |||
11522 | return QualType(); | |||
11523 | } | |||
11524 | ||||
11525 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | |||
11526 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | |||
11527 | CheckPtrComparisonWithNullChar(LHS, RHS); | |||
11528 | CheckPtrComparisonWithNullChar(RHS, LHS); | |||
11529 | } | |||
11530 | ||||
11531 | // Handle vector comparisons separately. | |||
11532 | if (LHS.get()->getType()->isVectorType() || | |||
11533 | RHS.get()->getType()->isVectorType()) | |||
11534 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | |||
11535 | ||||
11536 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | |||
11537 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | |||
11538 | ||||
11539 | QualType LHSType = LHS.get()->getType(); | |||
11540 | QualType RHSType = RHS.get()->getType(); | |||
11541 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | |||
11542 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | |||
11543 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | |||
11544 | ||||
11545 | const Expr::NullPointerConstantKind LHSNullKind = | |||
11546 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | |||
11547 | const Expr::NullPointerConstantKind RHSNullKind = | |||
11548 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | |||
11549 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | |||
11550 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | |||
11551 | ||||
11552 | auto computeResultTy = [&]() { | |||
11553 | if (Opc != BO_Cmp) | |||
11554 | return Context.getLogicalOperationType(); | |||
11555 | assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11555, __PRETTY_FUNCTION__)); | |||
11556 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()-> getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11556, __PRETTY_FUNCTION__)); | |||
11557 | ||||
11558 | QualType CompositeTy = LHS.get()->getType(); | |||
11559 | assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void> (0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11559, __PRETTY_FUNCTION__)); | |||
11560 | ||||
11561 | Optional<ComparisonCategoryType> CCT = | |||
11562 | getComparisonCategoryForBuiltinCmp(CompositeTy); | |||
11563 | if (!CCT) | |||
11564 | return InvalidOperands(Loc, LHS, RHS); | |||
11565 | ||||
11566 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | |||
11567 | // P0946R0: Comparisons between a null pointer constant and an object | |||
11568 | // pointer result in std::strong_equality, which is ill-formed under | |||
11569 | // P1959R0. | |||
11570 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | |||
11571 | << (LHSIsNull ? LHS.get()->getSourceRange() | |||
11572 | : RHS.get()->getSourceRange()); | |||
11573 | return QualType(); | |||
11574 | } | |||
11575 | ||||
11576 | return CheckComparisonCategoryType( | |||
11577 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | |||
11578 | }; | |||
11579 | ||||
11580 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | |||
11581 | bool IsEquality = Opc == BO_EQ; | |||
11582 | if (RHSIsNull) | |||
11583 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | |||
11584 | RHS.get()->getSourceRange()); | |||
11585 | else | |||
11586 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | |||
11587 | LHS.get()->getSourceRange()); | |||
11588 | } | |||
11589 | ||||
11590 | if ((LHSType->isIntegerType() && !LHSIsNull) || | |||
11591 | (RHSType->isIntegerType() && !RHSIsNull)) { | |||
11592 | // Skip normal pointer conversion checks in this case; we have better | |||
11593 | // diagnostics for this below. | |||
11594 | } else if (getLangOpts().CPlusPlus) { | |||
11595 | // Equality comparison of a function pointer to a void pointer is invalid, | |||
11596 | // but we allow it as an extension. | |||
11597 | // FIXME: If we really want to allow this, should it be part of composite | |||
11598 | // pointer type computation so it works in conditionals too? | |||
11599 | if (!IsOrdered && | |||
11600 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | |||
11601 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | |||
11602 | // This is a gcc extension compatibility comparison. | |||
11603 | // In a SFINAE context, we treat this as a hard error to maintain | |||
11604 | // conformance with the C++ standard. | |||
11605 | diagnoseFunctionPointerToVoidComparison( | |||
11606 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | |||
11607 | ||||
11608 | if (isSFINAEContext()) | |||
11609 | return QualType(); | |||
11610 | ||||
11611 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
11612 | return computeResultTy(); | |||
11613 | } | |||
11614 | ||||
11615 | // C++ [expr.eq]p2: | |||
11616 | // If at least one operand is a pointer [...] bring them to their | |||
11617 | // composite pointer type. | |||
11618 | // C++ [expr.spaceship]p6 | |||
11619 | // If at least one of the operands is of pointer type, [...] bring them | |||
11620 | // to their composite pointer type. | |||
11621 | // C++ [expr.rel]p2: | |||
11622 | // If both operands are pointers, [...] bring them to their composite | |||
11623 | // pointer type. | |||
11624 | // For <=>, the only valid non-pointer types are arrays and functions, and | |||
11625 | // we already decayed those, so this is really the same as the relational | |||
11626 | // comparison rule. | |||
11627 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | |||
11628 | (IsOrdered ? 2 : 1) && | |||
11629 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | |||
11630 | RHSType->isObjCObjectPointerType()))) { | |||
11631 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | |||
11632 | return QualType(); | |||
11633 | return computeResultTy(); | |||
11634 | } | |||
11635 | } else if (LHSType->isPointerType() && | |||
11636 | RHSType->isPointerType()) { // C99 6.5.8p2 | |||
11637 | // All of the following pointer-related warnings are GCC extensions, except | |||
11638 | // when handling null pointer constants. | |||
11639 | QualType LCanPointeeTy = | |||
11640 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | |||
11641 | QualType RCanPointeeTy = | |||
11642 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | |||
11643 | ||||
11644 | // C99 6.5.9p2 and C99 6.5.8p2 | |||
11645 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | |||
11646 | RCanPointeeTy.getUnqualifiedType())) { | |||
11647 | if (IsRelational) { | |||
11648 | // Pointers both need to point to complete or incomplete types | |||
11649 | if ((LCanPointeeTy->isIncompleteType() != | |||
11650 | RCanPointeeTy->isIncompleteType()) && | |||
11651 | !getLangOpts().C11) { | |||
11652 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | |||
11653 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | |||
11654 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | |||
11655 | << RCanPointeeTy->isIncompleteType(); | |||
11656 | } | |||
11657 | if (LCanPointeeTy->isFunctionType()) { | |||
11658 | // Valid unless a relational comparison of function pointers | |||
11659 | Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) | |||
11660 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
11661 | << RHS.get()->getSourceRange(); | |||
11662 | } | |||
11663 | } | |||
11664 | } else if (!IsRelational && | |||
11665 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | |||
11666 | // Valid unless comparison between non-null pointer and function pointer | |||
11667 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | |||
11668 | && !LHSIsNull && !RHSIsNull) | |||
11669 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | |||
11670 | /*isError*/false); | |||
11671 | } else { | |||
11672 | // Invalid | |||
11673 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | |||
11674 | } | |||
11675 | if (LCanPointeeTy != RCanPointeeTy) { | |||
11676 | // Treat NULL constant as a special case in OpenCL. | |||
11677 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | |||
11678 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | |||
11679 | Diag(Loc, | |||
11680 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | |||
11681 | << LHSType << RHSType << 0 /* comparison */ | |||
11682 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
11683 | } | |||
11684 | } | |||
11685 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | |||
11686 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | |||
11687 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | |||
11688 | : CK_BitCast; | |||
11689 | if (LHSIsNull && !RHSIsNull) | |||
11690 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | |||
11691 | else | |||
11692 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | |||
11693 | } | |||
11694 | return computeResultTy(); | |||
11695 | } | |||
11696 | ||||
11697 | if (getLangOpts().CPlusPlus) { | |||
11698 | // C++ [expr.eq]p4: | |||
11699 | // Two operands of type std::nullptr_t or one operand of type | |||
11700 | // std::nullptr_t and the other a null pointer constant compare equal. | |||
11701 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | |||
11702 | if (LHSType->isNullPtrType()) { | |||
11703 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
11704 | return computeResultTy(); | |||
11705 | } | |||
11706 | if (RHSType->isNullPtrType()) { | |||
11707 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
11708 | return computeResultTy(); | |||
11709 | } | |||
11710 | } | |||
11711 | ||||
11712 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | |||
11713 | // These aren't covered by the composite pointer type rules. | |||
11714 | if (!IsOrdered && RHSType->isNullPtrType() && | |||
11715 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | |||
11716 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
11717 | return computeResultTy(); | |||
11718 | } | |||
11719 | if (!IsOrdered && LHSType->isNullPtrType() && | |||
11720 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | |||
11721 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
11722 | return computeResultTy(); | |||
11723 | } | |||
11724 | ||||
11725 | if (IsRelational && | |||
11726 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | |||
11727 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | |||
11728 | // HACK: Relational comparison of nullptr_t against a pointer type is | |||
11729 | // invalid per DR583, but we allow it within std::less<> and friends, | |||
11730 | // since otherwise common uses of it break. | |||
11731 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | |||
11732 | // friends to have std::nullptr_t overload candidates. | |||
11733 | DeclContext *DC = CurContext; | |||
11734 | if (isa<FunctionDecl>(DC)) | |||
11735 | DC = DC->getParent(); | |||
11736 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | |||
11737 | if (CTSD->isInStdNamespace() && | |||
11738 | llvm::StringSwitch<bool>(CTSD->getName()) | |||
11739 | .Cases("less", "less_equal", "greater", "greater_equal", true) | |||
11740 | .Default(false)) { | |||
11741 | if (RHSType->isNullPtrType()) | |||
11742 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
11743 | else | |||
11744 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
11745 | return computeResultTy(); | |||
11746 | } | |||
11747 | } | |||
11748 | } | |||
11749 | ||||
11750 | // C++ [expr.eq]p2: | |||
11751 | // If at least one operand is a pointer to member, [...] bring them to | |||
11752 | // their composite pointer type. | |||
11753 | if (!IsOrdered && | |||
11754 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | |||
11755 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | |||
11756 | return QualType(); | |||
11757 | else | |||
11758 | return computeResultTy(); | |||
11759 | } | |||
11760 | } | |||
11761 | ||||
11762 | // Handle block pointer types. | |||
11763 | if (!IsOrdered && LHSType->isBlockPointerType() && | |||
11764 | RHSType->isBlockPointerType()) { | |||
11765 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | |||
11766 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | |||
11767 | ||||
11768 | if (!LHSIsNull && !RHSIsNull && | |||
11769 | !Context.typesAreCompatible(lpointee, rpointee)) { | |||
11770 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | |||
11771 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
11772 | << RHS.get()->getSourceRange(); | |||
11773 | } | |||
11774 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
11775 | return computeResultTy(); | |||
11776 | } | |||
11777 | ||||
11778 | // Allow block pointers to be compared with null pointer constants. | |||
11779 | if (!IsOrdered | |||
11780 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | |||
11781 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | |||
11782 | if (!LHSIsNull && !RHSIsNull) { | |||
11783 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | |||
11784 | ->getPointeeType()->isVoidType()) | |||
11785 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | |||
11786 | ->getPointeeType()->isVoidType()))) | |||
11787 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | |||
11788 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
11789 | << RHS.get()->getSourceRange(); | |||
11790 | } | |||
11791 | if (LHSIsNull && !RHSIsNull) | |||
11792 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
11793 | RHSType->isPointerType() ? CK_BitCast | |||
11794 | : CK_AnyPointerToBlockPointerCast); | |||
11795 | else | |||
11796 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
11797 | LHSType->isPointerType() ? CK_BitCast | |||
11798 | : CK_AnyPointerToBlockPointerCast); | |||
11799 | return computeResultTy(); | |||
11800 | } | |||
11801 | ||||
11802 | if (LHSType->isObjCObjectPointerType() || | |||
11803 | RHSType->isObjCObjectPointerType()) { | |||
11804 | const PointerType *LPT = LHSType->getAs<PointerType>(); | |||
11805 | const PointerType *RPT = RHSType->getAs<PointerType>(); | |||
11806 | if (LPT || RPT) { | |||
11807 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | |||
11808 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | |||
11809 | ||||
11810 | if (!LPtrToVoid && !RPtrToVoid && | |||
11811 | !Context.typesAreCompatible(LHSType, RHSType)) { | |||
11812 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | |||
11813 | /*isError*/false); | |||
11814 | } | |||
11815 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | |||
11816 | // the RHS, but we have test coverage for this behavior. | |||
11817 | // FIXME: Consider using convertPointersToCompositeType in C++. | |||
11818 | if (LHSIsNull && !RHSIsNull) { | |||
11819 | Expr *E = LHS.get(); | |||
11820 | if (getLangOpts().ObjCAutoRefCount) | |||
11821 | CheckObjCConversion(SourceRange(), RHSType, E, | |||
11822 | CCK_ImplicitConversion); | |||
11823 | LHS = ImpCastExprToType(E, RHSType, | |||
11824 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | |||
11825 | } | |||
11826 | else { | |||
11827 | Expr *E = RHS.get(); | |||
11828 | if (getLangOpts().ObjCAutoRefCount) | |||
11829 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | |||
11830 | /*Diagnose=*/true, | |||
11831 | /*DiagnoseCFAudited=*/false, Opc); | |||
11832 | RHS = ImpCastExprToType(E, LHSType, | |||
11833 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | |||
11834 | } | |||
11835 | return computeResultTy(); | |||
11836 | } | |||
11837 | if (LHSType->isObjCObjectPointerType() && | |||
11838 | RHSType->isObjCObjectPointerType()) { | |||
11839 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | |||
11840 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | |||
11841 | /*isError*/false); | |||
11842 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | |||
11843 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | |||
11844 | ||||
11845 | if (LHSIsNull && !RHSIsNull) | |||
11846 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | |||
11847 | else | |||
11848 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | |||
11849 | return computeResultTy(); | |||
11850 | } | |||
11851 | ||||
11852 | if (!IsOrdered && LHSType->isBlockPointerType() && | |||
11853 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | |||
11854 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
11855 | CK_BlockPointerToObjCPointerCast); | |||
11856 | return computeResultTy(); | |||
11857 | } else if (!IsOrdered && | |||
11858 | LHSType->isBlockCompatibleObjCPointerType(Context) && | |||
11859 | RHSType->isBlockPointerType()) { | |||
11860 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
11861 | CK_BlockPointerToObjCPointerCast); | |||
11862 | return computeResultTy(); | |||
11863 | } | |||
11864 | } | |||
11865 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | |||
11866 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | |||
11867 | unsigned DiagID = 0; | |||
11868 | bool isError = false; | |||
11869 | if (LangOpts.DebuggerSupport) { | |||
11870 | // Under a debugger, allow the comparison of pointers to integers, | |||
11871 | // since users tend to want to compare addresses. | |||
11872 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | |||
11873 | (RHSIsNull && RHSType->isIntegerType())) { | |||
11874 | if (IsOrdered) { | |||
11875 | isError = getLangOpts().CPlusPlus; | |||
11876 | DiagID = | |||
11877 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | |||
11878 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | |||
11879 | } | |||
11880 | } else if (getLangOpts().CPlusPlus) { | |||
11881 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | |||
11882 | isError = true; | |||
11883 | } else if (IsOrdered) | |||
11884 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | |||
11885 | else | |||
11886 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | |||
11887 | ||||
11888 | if (DiagID) { | |||
11889 | Diag(Loc, DiagID) | |||
11890 | << LHSType << RHSType << LHS.get()->getSourceRange() | |||
11891 | << RHS.get()->getSourceRange(); | |||
11892 | if (isError) | |||
11893 | return QualType(); | |||
11894 | } | |||
11895 | ||||
11896 | if (LHSType->isIntegerType()) | |||
11897 | LHS = ImpCastExprToType(LHS.get(), RHSType, | |||
11898 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | |||
11899 | else | |||
11900 | RHS = ImpCastExprToType(RHS.get(), LHSType, | |||
11901 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | |||
11902 | return computeResultTy(); | |||
11903 | } | |||
11904 | ||||
11905 | // Handle block pointers. | |||
11906 | if (!IsOrdered && RHSIsNull | |||
11907 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | |||
11908 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
11909 | return computeResultTy(); | |||
11910 | } | |||
11911 | if (!IsOrdered && LHSIsNull | |||
11912 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | |||
11913 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
11914 | return computeResultTy(); | |||
11915 | } | |||
11916 | ||||
11917 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | |||
11918 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | |||
11919 | return computeResultTy(); | |||
11920 | } | |||
11921 | ||||
11922 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | |||
11923 | return computeResultTy(); | |||
11924 | } | |||
11925 | ||||
11926 | if (LHSIsNull && RHSType->isQueueT()) { | |||
11927 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | |||
11928 | return computeResultTy(); | |||
11929 | } | |||
11930 | ||||
11931 | if (LHSType->isQueueT() && RHSIsNull) { | |||
11932 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | |||
11933 | return computeResultTy(); | |||
11934 | } | |||
11935 | } | |||
11936 | ||||
11937 | return InvalidOperands(Loc, LHS, RHS); | |||
11938 | } | |||
11939 | ||||
11940 | // Return a signed ext_vector_type that is of identical size and number of | |||
11941 | // elements. For floating point vectors, return an integer type of identical | |||
11942 | // size and number of elements. In the non ext_vector_type case, search from | |||
11943 | // the largest type to the smallest type to avoid cases where long long == long, | |||
11944 | // where long gets picked over long long. | |||
11945 | QualType Sema::GetSignedVectorType(QualType V) { | |||
11946 | const VectorType *VTy = V->castAs<VectorType>(); | |||
11947 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | |||
11948 | ||||
11949 | if (isa<ExtVectorType>(VTy)) { | |||
11950 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | |||
11951 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | |||
11952 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | |||
11953 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | |||
11954 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | |||
11955 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | |||
11956 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | |||
11957 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | |||
11958 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11959, __PRETTY_FUNCTION__)) | |||
11959 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11959, __PRETTY_FUNCTION__)); | |||
11960 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | |||
11961 | } | |||
11962 | ||||
11963 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | |||
11964 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | |||
11965 | VectorType::GenericVector); | |||
11966 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | |||
11967 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | |||
11968 | VectorType::GenericVector); | |||
11969 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | |||
11970 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | |||
11971 | VectorType::GenericVector); | |||
11972 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | |||
11973 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | |||
11974 | VectorType::GenericVector); | |||
11975 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11976, __PRETTY_FUNCTION__)) | |||
11976 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 11976, __PRETTY_FUNCTION__)); | |||
11977 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | |||
11978 | VectorType::GenericVector); | |||
11979 | } | |||
11980 | ||||
11981 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | |||
11982 | /// operates on extended vector types. Instead of producing an IntTy result, | |||
11983 | /// like a scalar comparison, a vector comparison produces a vector of integer | |||
11984 | /// types. | |||
11985 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
11986 | SourceLocation Loc, | |||
11987 | BinaryOperatorKind Opc) { | |||
11988 | if (Opc == BO_Cmp) { | |||
11989 | Diag(Loc, diag::err_three_way_vector_comparison); | |||
11990 | return QualType(); | |||
11991 | } | |||
11992 | ||||
11993 | // Check to make sure we're operating on vectors of the same type and width, | |||
11994 | // Allowing one side to be a scalar of element type. | |||
11995 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | |||
11996 | /*AllowBothBool*/true, | |||
11997 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
11998 | if (vType.isNull()) | |||
11999 | return vType; | |||
12000 | ||||
12001 | QualType LHSType = LHS.get()->getType(); | |||
12002 | ||||
12003 | // If AltiVec, the comparison results in a numeric type, i.e. | |||
12004 | // bool for C++, int for C | |||
12005 | if (getLangOpts().AltiVec && | |||
12006 | vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) | |||
12007 | return Context.getLogicalOperationType(); | |||
12008 | ||||
12009 | // For non-floating point types, check for self-comparisons of the form | |||
12010 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | |||
12011 | // often indicate logic errors in the program. | |||
12012 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | |||
12013 | ||||
12014 | // Check for comparisons of floating point operands using != and ==. | |||
12015 | if (BinaryOperator::isEqualityOp(Opc) && | |||
12016 | LHSType->hasFloatingRepresentation()) { | |||
12017 | assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast <void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12017, __PRETTY_FUNCTION__)); | |||
12018 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | |||
12019 | } | |||
12020 | ||||
12021 | // Return a signed type for the vector. | |||
12022 | return GetSignedVectorType(vType); | |||
12023 | } | |||
12024 | ||||
12025 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | |||
12026 | const ExprResult &XorRHS, | |||
12027 | const SourceLocation Loc) { | |||
12028 | // Do not diagnose macros. | |||
12029 | if (Loc.isMacroID()) | |||
12030 | return; | |||
12031 | ||||
12032 | bool Negative = false; | |||
12033 | bool ExplicitPlus = false; | |||
12034 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | |||
12035 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | |||
12036 | ||||
12037 | if (!LHSInt) | |||
12038 | return; | |||
12039 | if (!RHSInt) { | |||
12040 | // Check negative literals. | |||
12041 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | |||
12042 | UnaryOperatorKind Opc = UO->getOpcode(); | |||
12043 | if (Opc != UO_Minus && Opc != UO_Plus) | |||
12044 | return; | |||
12045 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | |||
12046 | if (!RHSInt) | |||
12047 | return; | |||
12048 | Negative = (Opc == UO_Minus); | |||
12049 | ExplicitPlus = !Negative; | |||
12050 | } else { | |||
12051 | return; | |||
12052 | } | |||
12053 | } | |||
12054 | ||||
12055 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | |||
12056 | llvm::APInt RightSideValue = RHSInt->getValue(); | |||
12057 | if (LeftSideValue != 2 && LeftSideValue != 10) | |||
12058 | return; | |||
12059 | ||||
12060 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | |||
12061 | return; | |||
12062 | ||||
12063 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | |||
12064 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | |||
12065 | llvm::StringRef ExprStr = | |||
12066 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | |||
12067 | ||||
12068 | CharSourceRange XorRange = | |||
12069 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | |||
12070 | llvm::StringRef XorStr = | |||
12071 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | |||
12072 | // Do not diagnose if xor keyword/macro is used. | |||
12073 | if (XorStr == "xor") | |||
12074 | return; | |||
12075 | ||||
12076 | std::string LHSStr = std::string(Lexer::getSourceText( | |||
12077 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | |||
12078 | S.getSourceManager(), S.getLangOpts())); | |||
12079 | std::string RHSStr = std::string(Lexer::getSourceText( | |||
12080 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | |||
12081 | S.getSourceManager(), S.getLangOpts())); | |||
12082 | ||||
12083 | if (Negative) { | |||
12084 | RightSideValue = -RightSideValue; | |||
12085 | RHSStr = "-" + RHSStr; | |||
12086 | } else if (ExplicitPlus) { | |||
12087 | RHSStr = "+" + RHSStr; | |||
12088 | } | |||
12089 | ||||
12090 | StringRef LHSStrRef = LHSStr; | |||
12091 | StringRef RHSStrRef = RHSStr; | |||
12092 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | |||
12093 | // literals. | |||
12094 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | |||
12095 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | |||
12096 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | |||
12097 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | |||
12098 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | |||
12099 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | |||
12100 | LHSStrRef.find('\'') != StringRef::npos || | |||
12101 | RHSStrRef.find('\'') != StringRef::npos) | |||
12102 | return; | |||
12103 | ||||
12104 | bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | |||
12105 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | |||
12106 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | |||
12107 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | |||
12108 | std::string SuggestedExpr = "1 << " + RHSStr; | |||
12109 | bool Overflow = false; | |||
12110 | llvm::APInt One = (LeftSideValue - 1); | |||
12111 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | |||
12112 | if (Overflow) { | |||
12113 | if (RightSideIntValue < 64) | |||
12114 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | |||
12115 | << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) | |||
12116 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | |||
12117 | else if (RightSideIntValue == 64) | |||
12118 | S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); | |||
12119 | else | |||
12120 | return; | |||
12121 | } else { | |||
12122 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | |||
12123 | << ExprStr << XorValue.toString(10, true) << SuggestedExpr | |||
12124 | << PowValue.toString(10, true) | |||
12125 | << FixItHint::CreateReplacement( | |||
12126 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | |||
12127 | } | |||
12128 | ||||
12129 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; | |||
12130 | } else if (LeftSideValue == 10) { | |||
12131 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | |||
12132 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | |||
12133 | << ExprStr << XorValue.toString(10, true) << SuggestedValue | |||
12134 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | |||
12135 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; | |||
12136 | } | |||
12137 | } | |||
12138 | ||||
12139 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
12140 | SourceLocation Loc) { | |||
12141 | // Ensure that either both operands are of the same vector type, or | |||
12142 | // one operand is of a vector type and the other is of its element type. | |||
12143 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | |||
12144 | /*AllowBothBool*/true, | |||
12145 | /*AllowBoolConversions*/false); | |||
12146 | if (vType.isNull()) | |||
12147 | return InvalidOperands(Loc, LHS, RHS); | |||
12148 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && | |||
12149 | !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) | |||
12150 | return InvalidOperands(Loc, LHS, RHS); | |||
12151 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | |||
12152 | // usage of the logical operators && and || with vectors in C. This | |||
12153 | // check could be notionally dropped. | |||
12154 | if (!getLangOpts().CPlusPlus && | |||
12155 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | |||
12156 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | |||
12157 | ||||
12158 | return GetSignedVectorType(LHS.get()->getType()); | |||
12159 | } | |||
12160 | ||||
12161 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | |||
12162 | SourceLocation Loc, | |||
12163 | bool IsCompAssign) { | |||
12164 | if (!IsCompAssign) { | |||
12165 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
12166 | if (LHS.isInvalid()) | |||
12167 | return QualType(); | |||
12168 | } | |||
12169 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
12170 | if (RHS.isInvalid()) | |||
12171 | return QualType(); | |||
12172 | ||||
12173 | // For conversion purposes, we ignore any qualifiers. | |||
12174 | // For example, "const float" and "float" are equivalent. | |||
12175 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | |||
12176 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | |||
12177 | ||||
12178 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | |||
12179 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | |||
12180 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12180, __PRETTY_FUNCTION__)); | |||
12181 | ||||
12182 | if (Context.hasSameType(LHSType, RHSType)) | |||
12183 | return LHSType; | |||
12184 | ||||
12185 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | |||
12186 | // case we have to return InvalidOperands. | |||
12187 | ExprResult OriginalLHS = LHS; | |||
12188 | ExprResult OriginalRHS = RHS; | |||
12189 | if (LHSMatType && !RHSMatType) { | |||
12190 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | |||
12191 | if (!RHS.isInvalid()) | |||
12192 | return LHSType; | |||
12193 | ||||
12194 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | |||
12195 | } | |||
12196 | ||||
12197 | if (!LHSMatType && RHSMatType) { | |||
12198 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | |||
12199 | if (!LHS.isInvalid()) | |||
12200 | return RHSType; | |||
12201 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | |||
12202 | } | |||
12203 | ||||
12204 | return InvalidOperands(Loc, LHS, RHS); | |||
12205 | } | |||
12206 | ||||
12207 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | |||
12208 | SourceLocation Loc, | |||
12209 | bool IsCompAssign) { | |||
12210 | if (!IsCompAssign) { | |||
12211 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
12212 | if (LHS.isInvalid()) | |||
12213 | return QualType(); | |||
12214 | } | |||
12215 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
12216 | if (RHS.isInvalid()) | |||
12217 | return QualType(); | |||
12218 | ||||
12219 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | |||
12220 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | |||
12221 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12221, __PRETTY_FUNCTION__)); | |||
12222 | ||||
12223 | if (LHSMatType && RHSMatType) { | |||
12224 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | |||
12225 | return InvalidOperands(Loc, LHS, RHS); | |||
12226 | ||||
12227 | if (!Context.hasSameType(LHSMatType->getElementType(), | |||
12228 | RHSMatType->getElementType())) | |||
12229 | return InvalidOperands(Loc, LHS, RHS); | |||
12230 | ||||
12231 | return Context.getConstantMatrixType(LHSMatType->getElementType(), | |||
12232 | LHSMatType->getNumRows(), | |||
12233 | RHSMatType->getNumColumns()); | |||
12234 | } | |||
12235 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | |||
12236 | } | |||
12237 | ||||
12238 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | |||
12239 | SourceLocation Loc, | |||
12240 | BinaryOperatorKind Opc) { | |||
12241 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | |||
12242 | ||||
12243 | bool IsCompAssign = | |||
12244 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | |||
12245 | ||||
12246 | if (LHS.get()->getType()->isVectorType() || | |||
12247 | RHS.get()->getType()->isVectorType()) { | |||
12248 | if (LHS.get()->getType()->hasIntegerRepresentation() && | |||
12249 | RHS.get()->getType()->hasIntegerRepresentation()) | |||
12250 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | |||
12251 | /*AllowBothBool*/true, | |||
12252 | /*AllowBoolConversions*/getLangOpts().ZVector); | |||
12253 | return InvalidOperands(Loc, LHS, RHS); | |||
12254 | } | |||
12255 | ||||
12256 | if (Opc == BO_And) | |||
12257 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | |||
12258 | ||||
12259 | if (LHS.get()->getType()->hasFloatingRepresentation() || | |||
12260 | RHS.get()->getType()->hasFloatingRepresentation()) | |||
12261 | return InvalidOperands(Loc, LHS, RHS); | |||
12262 | ||||
12263 | ExprResult LHSResult = LHS, RHSResult = RHS; | |||
12264 | QualType compType = UsualArithmeticConversions( | |||
12265 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | |||
12266 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | |||
12267 | return QualType(); | |||
12268 | LHS = LHSResult.get(); | |||
12269 | RHS = RHSResult.get(); | |||
12270 | ||||
12271 | if (Opc == BO_Xor) | |||
12272 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | |||
12273 | ||||
12274 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | |||
12275 | return compType; | |||
12276 | return InvalidOperands(Loc, LHS, RHS); | |||
12277 | } | |||
12278 | ||||
12279 | // C99 6.5.[13,14] | |||
12280 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
12281 | SourceLocation Loc, | |||
12282 | BinaryOperatorKind Opc) { | |||
12283 | // Check vector operands differently. | |||
12284 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | |||
12285 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | |||
12286 | ||||
12287 | bool EnumConstantInBoolContext = false; | |||
12288 | for (const ExprResult &HS : {LHS, RHS}) { | |||
12289 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | |||
12290 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | |||
12291 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | |||
12292 | EnumConstantInBoolContext = true; | |||
12293 | } | |||
12294 | } | |||
12295 | ||||
12296 | if (EnumConstantInBoolContext) | |||
12297 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | |||
12298 | ||||
12299 | // Diagnose cases where the user write a logical and/or but probably meant a | |||
12300 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | |||
12301 | // is a constant. | |||
12302 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | |||
12303 | !LHS.get()->getType()->isBooleanType() && | |||
12304 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | |||
12305 | // Don't warn in macros or template instantiations. | |||
12306 | !Loc.isMacroID() && !inTemplateInstantiation()) { | |||
12307 | // If the RHS can be constant folded, and if it constant folds to something | |||
12308 | // that isn't 0 or 1 (which indicate a potential logical operation that | |||
12309 | // happened to fold to true/false) then warn. | |||
12310 | // Parens on the RHS are ignored. | |||
12311 | Expr::EvalResult EVResult; | |||
12312 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | |||
12313 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
12314 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | |||
12315 | !RHS.get()->getExprLoc().isMacroID()) || | |||
12316 | (Result != 0 && Result != 1)) { | |||
12317 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | |||
12318 | << RHS.get()->getSourceRange() | |||
12319 | << (Opc == BO_LAnd ? "&&" : "||"); | |||
12320 | // Suggest replacing the logical operator with the bitwise version | |||
12321 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | |||
12322 | << (Opc == BO_LAnd ? "&" : "|") | |||
12323 | << FixItHint::CreateReplacement(SourceRange( | |||
12324 | Loc, getLocForEndOfToken(Loc)), | |||
12325 | Opc == BO_LAnd ? "&" : "|"); | |||
12326 | if (Opc == BO_LAnd) | |||
12327 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | |||
12328 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | |||
12329 | << FixItHint::CreateRemoval( | |||
12330 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | |||
12331 | RHS.get()->getEndLoc())); | |||
12332 | } | |||
12333 | } | |||
12334 | } | |||
12335 | ||||
12336 | if (!Context.getLangOpts().CPlusPlus) { | |||
12337 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | |||
12338 | // not operate on the built-in scalar and vector float types. | |||
12339 | if (Context.getLangOpts().OpenCL && | |||
12340 | Context.getLangOpts().OpenCLVersion < 120) { | |||
12341 | if (LHS.get()->getType()->isFloatingType() || | |||
12342 | RHS.get()->getType()->isFloatingType()) | |||
12343 | return InvalidOperands(Loc, LHS, RHS); | |||
12344 | } | |||
12345 | ||||
12346 | LHS = UsualUnaryConversions(LHS.get()); | |||
12347 | if (LHS.isInvalid()) | |||
12348 | return QualType(); | |||
12349 | ||||
12350 | RHS = UsualUnaryConversions(RHS.get()); | |||
12351 | if (RHS.isInvalid()) | |||
12352 | return QualType(); | |||
12353 | ||||
12354 | if (!LHS.get()->getType()->isScalarType() || | |||
12355 | !RHS.get()->getType()->isScalarType()) | |||
12356 | return InvalidOperands(Loc, LHS, RHS); | |||
12357 | ||||
12358 | return Context.IntTy; | |||
12359 | } | |||
12360 | ||||
12361 | // The following is safe because we only use this method for | |||
12362 | // non-overloadable operands. | |||
12363 | ||||
12364 | // C++ [expr.log.and]p1 | |||
12365 | // C++ [expr.log.or]p1 | |||
12366 | // The operands are both contextually converted to type bool. | |||
12367 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | |||
12368 | if (LHSRes.isInvalid()) | |||
12369 | return InvalidOperands(Loc, LHS, RHS); | |||
12370 | LHS = LHSRes; | |||
12371 | ||||
12372 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | |||
12373 | if (RHSRes.isInvalid()) | |||
12374 | return InvalidOperands(Loc, LHS, RHS); | |||
12375 | RHS = RHSRes; | |||
12376 | ||||
12377 | // C++ [expr.log.and]p2 | |||
12378 | // C++ [expr.log.or]p2 | |||
12379 | // The result is a bool. | |||
12380 | return Context.BoolTy; | |||
12381 | } | |||
12382 | ||||
12383 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | |||
12384 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | |||
12385 | if (!ME) return false; | |||
12386 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | |||
12387 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | |||
12388 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | |||
12389 | if (!Base) return false; | |||
12390 | return Base->getMethodDecl() != nullptr; | |||
12391 | } | |||
12392 | ||||
12393 | /// Is the given expression (which must be 'const') a reference to a | |||
12394 | /// variable which was originally non-const, but which has become | |||
12395 | /// 'const' due to being captured within a block? | |||
12396 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | |||
12397 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | |||
12398 | assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified ()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12398, __PRETTY_FUNCTION__)); | |||
12399 | E = E->IgnoreParens(); | |||
12400 | ||||
12401 | // Must be a reference to a declaration from an enclosing scope. | |||
12402 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | |||
12403 | if (!DRE) return NCCK_None; | |||
12404 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | |||
12405 | ||||
12406 | // The declaration must be a variable which is not declared 'const'. | |||
12407 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | |||
12408 | if (!var) return NCCK_None; | |||
12409 | if (var->getType().isConstQualified()) return NCCK_None; | |||
12410 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?" ) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12410, __PRETTY_FUNCTION__)); | |||
12411 | ||||
12412 | // Decide whether the first capture was for a block or a lambda. | |||
12413 | DeclContext *DC = S.CurContext, *Prev = nullptr; | |||
12414 | // Decide whether the first capture was for a block or a lambda. | |||
12415 | while (DC) { | |||
12416 | // For init-capture, it is possible that the variable belongs to the | |||
12417 | // template pattern of the current context. | |||
12418 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | |||
12419 | if (var->isInitCapture() && | |||
12420 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | |||
12421 | break; | |||
12422 | if (DC == var->getDeclContext()) | |||
12423 | break; | |||
12424 | Prev = DC; | |||
12425 | DC = DC->getParent(); | |||
12426 | } | |||
12427 | // Unless we have an init-capture, we've gone one step too far. | |||
12428 | if (!var->isInitCapture()) | |||
12429 | DC = Prev; | |||
12430 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | |||
12431 | } | |||
12432 | ||||
12433 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | |||
12434 | Ty = Ty.getNonReferenceType(); | |||
12435 | if (IsDereference && Ty->isPointerType()) | |||
12436 | Ty = Ty->getPointeeType(); | |||
12437 | return !Ty.isConstQualified(); | |||
12438 | } | |||
12439 | ||||
12440 | // Update err_typecheck_assign_const and note_typecheck_assign_const | |||
12441 | // when this enum is changed. | |||
12442 | enum { | |||
12443 | ConstFunction, | |||
12444 | ConstVariable, | |||
12445 | ConstMember, | |||
12446 | ConstMethod, | |||
12447 | NestedConstMember, | |||
12448 | ConstUnknown, // Keep as last element | |||
12449 | }; | |||
12450 | ||||
12451 | /// Emit the "read-only variable not assignable" error and print notes to give | |||
12452 | /// more information about why the variable is not assignable, such as pointing | |||
12453 | /// to the declaration of a const variable, showing that a method is const, or | |||
12454 | /// that the function is returning a const reference. | |||
12455 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | |||
12456 | SourceLocation Loc) { | |||
12457 | SourceRange ExprRange = E->getSourceRange(); | |||
12458 | ||||
12459 | // Only emit one error on the first const found. All other consts will emit | |||
12460 | // a note to the error. | |||
12461 | bool DiagnosticEmitted = false; | |||
12462 | ||||
12463 | // Track if the current expression is the result of a dereference, and if the | |||
12464 | // next checked expression is the result of a dereference. | |||
12465 | bool IsDereference = false; | |||
12466 | bool NextIsDereference = false; | |||
12467 | ||||
12468 | // Loop to process MemberExpr chains. | |||
12469 | while (true) { | |||
12470 | IsDereference = NextIsDereference; | |||
12471 | ||||
12472 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | |||
12473 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
12474 | NextIsDereference = ME->isArrow(); | |||
12475 | const ValueDecl *VD = ME->getMemberDecl(); | |||
12476 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | |||
12477 | // Mutable fields can be modified even if the class is const. | |||
12478 | if (Field->isMutable()) { | |||
12479 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted." ) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12479, __PRETTY_FUNCTION__)); | |||
12480 | break; | |||
12481 | } | |||
12482 | ||||
12483 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | |||
12484 | if (!DiagnosticEmitted) { | |||
12485 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12486 | << ExprRange << ConstMember << false /*static*/ << Field | |||
12487 | << Field->getType(); | |||
12488 | DiagnosticEmitted = true; | |||
12489 | } | |||
12490 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
12491 | << ConstMember << false /*static*/ << Field << Field->getType() | |||
12492 | << Field->getSourceRange(); | |||
12493 | } | |||
12494 | E = ME->getBase(); | |||
12495 | continue; | |||
12496 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | |||
12497 | if (VDecl->getType().isConstQualified()) { | |||
12498 | if (!DiagnosticEmitted) { | |||
12499 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12500 | << ExprRange << ConstMember << true /*static*/ << VDecl | |||
12501 | << VDecl->getType(); | |||
12502 | DiagnosticEmitted = true; | |||
12503 | } | |||
12504 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
12505 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | |||
12506 | << VDecl->getSourceRange(); | |||
12507 | } | |||
12508 | // Static fields do not inherit constness from parents. | |||
12509 | break; | |||
12510 | } | |||
12511 | break; // End MemberExpr | |||
12512 | } else if (const ArraySubscriptExpr *ASE = | |||
12513 | dyn_cast<ArraySubscriptExpr>(E)) { | |||
12514 | E = ASE->getBase()->IgnoreParenImpCasts(); | |||
12515 | continue; | |||
12516 | } else if (const ExtVectorElementExpr *EVE = | |||
12517 | dyn_cast<ExtVectorElementExpr>(E)) { | |||
12518 | E = EVE->getBase()->IgnoreParenImpCasts(); | |||
12519 | continue; | |||
12520 | } | |||
12521 | break; | |||
12522 | } | |||
12523 | ||||
12524 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | |||
12525 | // Function calls | |||
12526 | const FunctionDecl *FD = CE->getDirectCallee(); | |||
12527 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | |||
12528 | if (!DiagnosticEmitted) { | |||
12529 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | |||
12530 | << ConstFunction << FD; | |||
12531 | DiagnosticEmitted = true; | |||
12532 | } | |||
12533 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | |||
12534 | diag::note_typecheck_assign_const) | |||
12535 | << ConstFunction << FD << FD->getReturnType() | |||
12536 | << FD->getReturnTypeSourceRange(); | |||
12537 | } | |||
12538 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
12539 | // Point to variable declaration. | |||
12540 | if (const ValueDecl *VD = DRE->getDecl()) { | |||
12541 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | |||
12542 | if (!DiagnosticEmitted) { | |||
12543 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12544 | << ExprRange << ConstVariable << VD << VD->getType(); | |||
12545 | DiagnosticEmitted = true; | |||
12546 | } | |||
12547 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | |||
12548 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | |||
12549 | } | |||
12550 | } | |||
12551 | } else if (isa<CXXThisExpr>(E)) { | |||
12552 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | |||
12553 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | |||
12554 | if (MD->isConst()) { | |||
12555 | if (!DiagnosticEmitted) { | |||
12556 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | |||
12557 | << ConstMethod << MD; | |||
12558 | DiagnosticEmitted = true; | |||
12559 | } | |||
12560 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | |||
12561 | << ConstMethod << MD << MD->getSourceRange(); | |||
12562 | } | |||
12563 | } | |||
12564 | } | |||
12565 | } | |||
12566 | ||||
12567 | if (DiagnosticEmitted) | |||
12568 | return; | |||
12569 | ||||
12570 | // Can't determine a more specific message, so display the generic error. | |||
12571 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | |||
12572 | } | |||
12573 | ||||
12574 | enum OriginalExprKind { | |||
12575 | OEK_Variable, | |||
12576 | OEK_Member, | |||
12577 | OEK_LValue | |||
12578 | }; | |||
12579 | ||||
12580 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | |||
12581 | const RecordType *Ty, | |||
12582 | SourceLocation Loc, SourceRange Range, | |||
12583 | OriginalExprKind OEK, | |||
12584 | bool &DiagnosticEmitted) { | |||
12585 | std::vector<const RecordType *> RecordTypeList; | |||
12586 | RecordTypeList.push_back(Ty); | |||
12587 | unsigned NextToCheckIndex = 0; | |||
12588 | // We walk the record hierarchy breadth-first to ensure that we print | |||
12589 | // diagnostics in field nesting order. | |||
12590 | while (RecordTypeList.size() > NextToCheckIndex) { | |||
12591 | bool IsNested = NextToCheckIndex > 0; | |||
12592 | for (const FieldDecl *Field : | |||
12593 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | |||
12594 | // First, check every field for constness. | |||
12595 | QualType FieldTy = Field->getType(); | |||
12596 | if (FieldTy.isConstQualified()) { | |||
12597 | if (!DiagnosticEmitted) { | |||
12598 | S.Diag(Loc, diag::err_typecheck_assign_const) | |||
12599 | << Range << NestedConstMember << OEK << VD | |||
12600 | << IsNested << Field; | |||
12601 | DiagnosticEmitted = true; | |||
12602 | } | |||
12603 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | |||
12604 | << NestedConstMember << IsNested << Field | |||
12605 | << FieldTy << Field->getSourceRange(); | |||
12606 | } | |||
12607 | ||||
12608 | // Then we append it to the list to check next in order. | |||
12609 | FieldTy = FieldTy.getCanonicalType(); | |||
12610 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | |||
12611 | if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) | |||
12612 | RecordTypeList.push_back(FieldRecTy); | |||
12613 | } | |||
12614 | } | |||
12615 | ++NextToCheckIndex; | |||
12616 | } | |||
12617 | } | |||
12618 | ||||
12619 | /// Emit an error for the case where a record we are trying to assign to has a | |||
12620 | /// const-qualified field somewhere in its hierarchy. | |||
12621 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | |||
12622 | SourceLocation Loc) { | |||
12623 | QualType Ty = E->getType(); | |||
12624 | assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ? static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12624, __PRETTY_FUNCTION__)); | |||
12625 | SourceRange Range = E->getSourceRange(); | |||
12626 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | |||
12627 | bool DiagEmitted = false; | |||
12628 | ||||
12629 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | |||
12630 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | |||
12631 | Range, OEK_Member, DiagEmitted); | |||
12632 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | |||
12633 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | |||
12634 | Range, OEK_Variable, DiagEmitted); | |||
12635 | else | |||
12636 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | |||
12637 | Range, OEK_LValue, DiagEmitted); | |||
12638 | if (!DiagEmitted) | |||
12639 | DiagnoseConstAssignment(S, E, Loc); | |||
12640 | } | |||
12641 | ||||
12642 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | |||
12643 | /// emit an error and return true. If so, return false. | |||
12644 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | |||
12645 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast <void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12645, __PRETTY_FUNCTION__)); | |||
12646 | ||||
12647 | S.CheckShadowingDeclModification(E, Loc); | |||
12648 | ||||
12649 | SourceLocation OrigLoc = Loc; | |||
12650 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | |||
12651 | &Loc); | |||
12652 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | |||
12653 | IsLV = Expr::MLV_InvalidMessageExpression; | |||
12654 | if (IsLV == Expr::MLV_Valid) | |||
12655 | return false; | |||
12656 | ||||
12657 | unsigned DiagID = 0; | |||
12658 | bool NeedType = false; | |||
12659 | switch (IsLV) { // C99 6.5.16p2 | |||
12660 | case Expr::MLV_ConstQualified: | |||
12661 | // Use a specialized diagnostic when we're assigning to an object | |||
12662 | // from an enclosing function or block. | |||
12663 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | |||
12664 | if (NCCK == NCCK_Block) | |||
12665 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | |||
12666 | else | |||
12667 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | |||
12668 | break; | |||
12669 | } | |||
12670 | ||||
12671 | // In ARC, use some specialized diagnostics for occasions where we | |||
12672 | // infer 'const'. These are always pseudo-strong variables. | |||
12673 | if (S.getLangOpts().ObjCAutoRefCount) { | |||
12674 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | |||
12675 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | |||
12676 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | |||
12677 | ||||
12678 | // Use the normal diagnostic if it's pseudo-__strong but the | |||
12679 | // user actually wrote 'const'. | |||
12680 | if (var->isARCPseudoStrong() && | |||
12681 | (!var->getTypeSourceInfo() || | |||
12682 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | |||
12683 | // There are three pseudo-strong cases: | |||
12684 | // - self | |||
12685 | ObjCMethodDecl *method = S.getCurMethodDecl(); | |||
12686 | if (method && var == method->getSelfDecl()) { | |||
12687 | DiagID = method->isClassMethod() | |||
12688 | ? diag::err_typecheck_arc_assign_self_class_method | |||
12689 | : diag::err_typecheck_arc_assign_self; | |||
12690 | ||||
12691 | // - Objective-C externally_retained attribute. | |||
12692 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | |||
12693 | isa<ParmVarDecl>(var)) { | |||
12694 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | |||
12695 | ||||
12696 | // - fast enumeration variables | |||
12697 | } else { | |||
12698 | DiagID = diag::err_typecheck_arr_assign_enumeration; | |||
12699 | } | |||
12700 | ||||
12701 | SourceRange Assign; | |||
12702 | if (Loc != OrigLoc) | |||
12703 | Assign = SourceRange(OrigLoc, OrigLoc); | |||
12704 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | |||
12705 | // We need to preserve the AST regardless, so migration tool | |||
12706 | // can do its job. | |||
12707 | return false; | |||
12708 | } | |||
12709 | } | |||
12710 | } | |||
12711 | ||||
12712 | // If none of the special cases above are triggered, then this is a | |||
12713 | // simple const assignment. | |||
12714 | if (DiagID == 0) { | |||
12715 | DiagnoseConstAssignment(S, E, Loc); | |||
12716 | return true; | |||
12717 | } | |||
12718 | ||||
12719 | break; | |||
12720 | case Expr::MLV_ConstAddrSpace: | |||
12721 | DiagnoseConstAssignment(S, E, Loc); | |||
12722 | return true; | |||
12723 | case Expr::MLV_ConstQualifiedField: | |||
12724 | DiagnoseRecursiveConstFields(S, E, Loc); | |||
12725 | return true; | |||
12726 | case Expr::MLV_ArrayType: | |||
12727 | case Expr::MLV_ArrayTemporary: | |||
12728 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | |||
12729 | NeedType = true; | |||
12730 | break; | |||
12731 | case Expr::MLV_NotObjectType: | |||
12732 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | |||
12733 | NeedType = true; | |||
12734 | break; | |||
12735 | case Expr::MLV_LValueCast: | |||
12736 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | |||
12737 | break; | |||
12738 | case Expr::MLV_Valid: | |||
12739 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12739); | |||
12740 | case Expr::MLV_InvalidExpression: | |||
12741 | case Expr::MLV_MemberFunction: | |||
12742 | case Expr::MLV_ClassTemporary: | |||
12743 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | |||
12744 | break; | |||
12745 | case Expr::MLV_IncompleteType: | |||
12746 | case Expr::MLV_IncompleteVoidType: | |||
12747 | return S.RequireCompleteType(Loc, E->getType(), | |||
12748 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | |||
12749 | case Expr::MLV_DuplicateVectorComponents: | |||
12750 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | |||
12751 | break; | |||
12752 | case Expr::MLV_NoSetterProperty: | |||
12753 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12753); | |||
12754 | case Expr::MLV_InvalidMessageExpression: | |||
12755 | DiagID = diag::err_readonly_message_assignment; | |||
12756 | break; | |||
12757 | case Expr::MLV_SubObjCPropertySetting: | |||
12758 | DiagID = diag::err_no_subobject_property_setting; | |||
12759 | break; | |||
12760 | } | |||
12761 | ||||
12762 | SourceRange Assign; | |||
12763 | if (Loc != OrigLoc) | |||
12764 | Assign = SourceRange(OrigLoc, OrigLoc); | |||
12765 | if (NeedType) | |||
12766 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | |||
12767 | else | |||
12768 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | |||
12769 | return true; | |||
12770 | } | |||
12771 | ||||
12772 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | |||
12773 | SourceLocation Loc, | |||
12774 | Sema &Sema) { | |||
12775 | if (Sema.inTemplateInstantiation()) | |||
12776 | return; | |||
12777 | if (Sema.isUnevaluatedContext()) | |||
12778 | return; | |||
12779 | if (Loc.isInvalid() || Loc.isMacroID()) | |||
12780 | return; | |||
12781 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | |||
12782 | return; | |||
12783 | ||||
12784 | // C / C++ fields | |||
12785 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | |||
12786 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | |||
12787 | if (ML && MR) { | |||
12788 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | |||
12789 | return; | |||
12790 | const ValueDecl *LHSDecl = | |||
12791 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | |||
12792 | const ValueDecl *RHSDecl = | |||
12793 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | |||
12794 | if (LHSDecl != RHSDecl) | |||
12795 | return; | |||
12796 | if (LHSDecl->getType().isVolatileQualified()) | |||
12797 | return; | |||
12798 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | |||
12799 | if (RefTy->getPointeeType().isVolatileQualified()) | |||
12800 | return; | |||
12801 | ||||
12802 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | |||
12803 | } | |||
12804 | ||||
12805 | // Objective-C instance variables | |||
12806 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | |||
12807 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | |||
12808 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | |||
12809 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | |||
12810 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | |||
12811 | if (RL && RR && RL->getDecl() == RR->getDecl()) | |||
12812 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | |||
12813 | } | |||
12814 | } | |||
12815 | ||||
12816 | // C99 6.5.16.1 | |||
12817 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | |||
12818 | SourceLocation Loc, | |||
12819 | QualType CompoundType) { | |||
12820 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 12820, __PRETTY_FUNCTION__)); | |||
12821 | ||||
12822 | // Verify that LHS is a modifiable lvalue, and emit error if not. | |||
12823 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | |||
12824 | return QualType(); | |||
12825 | ||||
12826 | QualType LHSType = LHSExpr->getType(); | |||
12827 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | |||
12828 | CompoundType; | |||
12829 | // OpenCL v1.2 s6.1.1.1 p2: | |||
12830 | // The half data type can only be used to declare a pointer to a buffer that | |||
12831 | // contains half values | |||
12832 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | |||
12833 | LHSType->isHalfType()) { | |||
12834 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | |||
12835 | << LHSType.getUnqualifiedType(); | |||
12836 | return QualType(); | |||
12837 | } | |||
12838 | ||||
12839 | AssignConvertType ConvTy; | |||
12840 | if (CompoundType.isNull()) { | |||
12841 | Expr *RHSCheck = RHS.get(); | |||
12842 | ||||
12843 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | |||
12844 | ||||
12845 | QualType LHSTy(LHSType); | |||
12846 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | |||
12847 | if (RHS.isInvalid()) | |||
12848 | return QualType(); | |||
12849 | // Special case of NSObject attributes on c-style pointer types. | |||
12850 | if (ConvTy == IncompatiblePointer && | |||
12851 | ((Context.isObjCNSObjectType(LHSType) && | |||
12852 | RHSType->isObjCObjectPointerType()) || | |||
12853 | (Context.isObjCNSObjectType(RHSType) && | |||
12854 | LHSType->isObjCObjectPointerType()))) | |||
12855 | ConvTy = Compatible; | |||
12856 | ||||
12857 | if (ConvTy == Compatible && | |||
12858 | LHSType->isObjCObjectType()) | |||
12859 | Diag(Loc, diag::err_objc_object_assignment) | |||
12860 | << LHSType; | |||
12861 | ||||
12862 | // If the RHS is a unary plus or minus, check to see if they = and + are | |||
12863 | // right next to each other. If so, the user may have typo'd "x =+ 4" | |||
12864 | // instead of "x += 4". | |||
12865 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | |||
12866 | RHSCheck = ICE->getSubExpr(); | |||
12867 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | |||
12868 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | |||
12869 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | |||
12870 | // Only if the two operators are exactly adjacent. | |||
12871 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | |||
12872 | // And there is a space or other character before the subexpr of the | |||
12873 | // unary +/-. We don't want to warn on "x=-1". | |||
12874 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | |||
12875 | UO->getSubExpr()->getBeginLoc().isFileID()) { | |||
12876 | Diag(Loc, diag::warn_not_compound_assign) | |||
12877 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | |||
12878 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | |||
12879 | } | |||
12880 | } | |||
12881 | ||||
12882 | if (ConvTy == Compatible) { | |||
12883 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | |||
12884 | // Warn about retain cycles where a block captures the LHS, but | |||
12885 | // not if the LHS is a simple variable into which the block is | |||
12886 | // being stored...unless that variable can be captured by reference! | |||
12887 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | |||
12888 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | |||
12889 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | |||
12890 | checkRetainCycles(LHSExpr, RHS.get()); | |||
12891 | } | |||
12892 | ||||
12893 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | |||
12894 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | |||
12895 | // It is safe to assign a weak reference into a strong variable. | |||
12896 | // Although this code can still have problems: | |||
12897 | // id x = self.weakProp; | |||
12898 | // id y = self.weakProp; | |||
12899 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | |||
12900 | // paths through the function. This should be revisited if | |||
12901 | // -Wrepeated-use-of-weak is made flow-sensitive. | |||
12902 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | |||
12903 | // variable, which will be valid for the current autorelease scope. | |||
12904 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | |||
12905 | RHS.get()->getBeginLoc())) | |||
12906 | getCurFunction()->markSafeWeakUse(RHS.get()); | |||
12907 | ||||
12908 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | |||
12909 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | |||
12910 | } | |||
12911 | } | |||
12912 | } else { | |||
12913 | // Compound assignment "x += y" | |||
12914 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | |||
12915 | } | |||
12916 | ||||
12917 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | |||
12918 | RHS.get(), AA_Assigning)) | |||
12919 | return QualType(); | |||
12920 | ||||
12921 | CheckForNullPointerDereference(*this, LHSExpr); | |||
12922 | ||||
12923 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | |||
12924 | if (CompoundType.isNull()) { | |||
12925 | // C++2a [expr.ass]p5: | |||
12926 | // A simple-assignment whose left operand is of a volatile-qualified | |||
12927 | // type is deprecated unless the assignment is either a discarded-value | |||
12928 | // expression or an unevaluated operand | |||
12929 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | |||
12930 | } else { | |||
12931 | // C++2a [expr.ass]p6: | |||
12932 | // [Compound-assignment] expressions are deprecated if E1 has | |||
12933 | // volatile-qualified type | |||
12934 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | |||
12935 | } | |||
12936 | } | |||
12937 | ||||
12938 | // C99 6.5.16p3: The type of an assignment expression is the type of the | |||
12939 | // left operand unless the left operand has qualified type, in which case | |||
12940 | // it is the unqualified version of the type of the left operand. | |||
12941 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | |||
12942 | // is converted to the type of the assignment expression (above). | |||
12943 | // C++ 5.17p1: the type of the assignment expression is that of its left | |||
12944 | // operand. | |||
12945 | return (getLangOpts().CPlusPlus | |||
12946 | ? LHSType : LHSType.getUnqualifiedType()); | |||
12947 | } | |||
12948 | ||||
12949 | // Only ignore explicit casts to void. | |||
12950 | static bool IgnoreCommaOperand(const Expr *E) { | |||
12951 | E = E->IgnoreParens(); | |||
12952 | ||||
12953 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | |||
12954 | if (CE->getCastKind() == CK_ToVoid) { | |||
12955 | return true; | |||
12956 | } | |||
12957 | ||||
12958 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | |||
12959 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | |||
12960 | CE->getSubExpr()->getType()->isDependentType()) { | |||
12961 | return true; | |||
12962 | } | |||
12963 | } | |||
12964 | ||||
12965 | return false; | |||
12966 | } | |||
12967 | ||||
12968 | // Look for instances where it is likely the comma operator is confused with | |||
12969 | // another operator. There is an explicit list of acceptable expressions for | |||
12970 | // the left hand side of the comma operator, otherwise emit a warning. | |||
12971 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | |||
12972 | // No warnings in macros | |||
12973 | if (Loc.isMacroID()) | |||
12974 | return; | |||
12975 | ||||
12976 | // Don't warn in template instantiations. | |||
12977 | if (inTemplateInstantiation()) | |||
12978 | return; | |||
12979 | ||||
12980 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | |||
12981 | // instead, skip more than needed, then call back into here with the | |||
12982 | // CommaVisitor in SemaStmt.cpp. | |||
12983 | // The listed locations are the initialization and increment portions | |||
12984 | // of a for loop. The additional checks are on the condition of | |||
12985 | // if statements, do/while loops, and for loops. | |||
12986 | // Differences in scope flags for C89 mode requires the extra logic. | |||
12987 | const unsigned ForIncrementFlags = | |||
12988 | getLangOpts().C99 || getLangOpts().CPlusPlus | |||
12989 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | |||
12990 | : Scope::ContinueScope | Scope::BreakScope; | |||
12991 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | |||
12992 | const unsigned ScopeFlags = getCurScope()->getFlags(); | |||
12993 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | |||
12994 | (ScopeFlags & ForInitFlags) == ForInitFlags) | |||
12995 | return; | |||
12996 | ||||
12997 | // If there are multiple comma operators used together, get the RHS of the | |||
12998 | // of the comma operator as the LHS. | |||
12999 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | |||
13000 | if (BO->getOpcode() != BO_Comma) | |||
13001 | break; | |||
13002 | LHS = BO->getRHS(); | |||
13003 | } | |||
13004 | ||||
13005 | // Only allow some expressions on LHS to not warn. | |||
13006 | if (IgnoreCommaOperand(LHS)) | |||
13007 | return; | |||
13008 | ||||
13009 | Diag(Loc, diag::warn_comma_operator); | |||
13010 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | |||
13011 | << LHS->getSourceRange() | |||
13012 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | |||
13013 | LangOpts.CPlusPlus ? "static_cast<void>(" | |||
13014 | : "(void)(") | |||
13015 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | |||
13016 | ")"); | |||
13017 | } | |||
13018 | ||||
13019 | // C99 6.5.17 | |||
13020 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | |||
13021 | SourceLocation Loc) { | |||
13022 | LHS = S.CheckPlaceholderExpr(LHS.get()); | |||
13023 | RHS = S.CheckPlaceholderExpr(RHS.get()); | |||
13024 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
13025 | return QualType(); | |||
13026 | ||||
13027 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | |||
13028 | // operands, but not unary promotions. | |||
13029 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | |||
13030 | ||||
13031 | // So we treat the LHS as a ignored value, and in C++ we allow the | |||
13032 | // containing site to determine what should be done with the RHS. | |||
13033 | LHS = S.IgnoredValueConversions(LHS.get()); | |||
13034 | if (LHS.isInvalid()) | |||
13035 | return QualType(); | |||
13036 | ||||
13037 | S.DiagnoseUnusedExprResult(LHS.get()); | |||
13038 | ||||
13039 | if (!S.getLangOpts().CPlusPlus) { | |||
13040 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
13041 | if (RHS.isInvalid()) | |||
13042 | return QualType(); | |||
13043 | if (!RHS.get()->getType()->isVoidType()) | |||
13044 | S.RequireCompleteType(Loc, RHS.get()->getType(), | |||
13045 | diag::err_incomplete_type); | |||
13046 | } | |||
13047 | ||||
13048 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | |||
13049 | S.DiagnoseCommaOperator(LHS.get(), Loc); | |||
13050 | ||||
13051 | return RHS.get()->getType(); | |||
13052 | } | |||
13053 | ||||
13054 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | |||
13055 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | |||
13056 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | |||
13057 | ExprValueKind &VK, | |||
13058 | ExprObjectKind &OK, | |||
13059 | SourceLocation OpLoc, | |||
13060 | bool IsInc, bool IsPrefix) { | |||
13061 | if (Op->isTypeDependent()) | |||
13062 | return S.Context.DependentTy; | |||
13063 | ||||
13064 | QualType ResType = Op->getType(); | |||
13065 | // Atomic types can be used for increment / decrement where the non-atomic | |||
13066 | // versions can, so ignore the _Atomic() specifier for the purpose of | |||
13067 | // checking. | |||
13068 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | |||
13069 | ResType = ResAtomicType->getValueType(); | |||
13070 | ||||
13071 | assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression" ) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13071, __PRETTY_FUNCTION__)); | |||
13072 | ||||
13073 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | |||
13074 | // Decrement of bool is not allowed. | |||
13075 | if (!IsInc) { | |||
13076 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | |||
13077 | return QualType(); | |||
13078 | } | |||
13079 | // Increment of bool sets it to true, but is deprecated. | |||
13080 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | |||
13081 | : diag::warn_increment_bool) | |||
13082 | << Op->getSourceRange(); | |||
13083 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | |||
13084 | // Error on enum increments and decrements in C++ mode | |||
13085 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | |||
13086 | return QualType(); | |||
13087 | } else if (ResType->isRealType()) { | |||
13088 | // OK! | |||
13089 | } else if (ResType->isPointerType()) { | |||
13090 | // C99 6.5.2.4p2, 6.5.6p2 | |||
13091 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | |||
13092 | return QualType(); | |||
13093 | } else if (ResType->isObjCObjectPointerType()) { | |||
13094 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | |||
13095 | // Otherwise, we just need a complete type. | |||
13096 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | |||
13097 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | |||
13098 | return QualType(); | |||
13099 | } else if (ResType->isAnyComplexType()) { | |||
13100 | // C99 does not support ++/-- on complex types, we allow as an extension. | |||
13101 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | |||
13102 | << ResType << Op->getSourceRange(); | |||
13103 | } else if (ResType->isPlaceholderType()) { | |||
13104 | ExprResult PR = S.CheckPlaceholderExpr(Op); | |||
13105 | if (PR.isInvalid()) return QualType(); | |||
13106 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | |||
13107 | IsInc, IsPrefix); | |||
13108 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | |||
13109 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | |||
13110 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | |||
13111 | (ResType->castAs<VectorType>()->getVectorKind() != | |||
13112 | VectorType::AltiVecBool)) { | |||
13113 | // The z vector extensions allow ++ and -- for non-bool vectors. | |||
13114 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | |||
13115 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | |||
13116 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | |||
13117 | } else { | |||
13118 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | |||
13119 | << ResType << int(IsInc) << Op->getSourceRange(); | |||
13120 | return QualType(); | |||
13121 | } | |||
13122 | // At this point, we know we have a real, complex or pointer type. | |||
13123 | // Now make sure the operand is a modifiable lvalue. | |||
13124 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | |||
13125 | return QualType(); | |||
13126 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | |||
13127 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | |||
13128 | // An operand with volatile-qualified type is deprecated | |||
13129 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | |||
13130 | << IsInc << ResType; | |||
13131 | } | |||
13132 | // In C++, a prefix increment is the same type as the operand. Otherwise | |||
13133 | // (in C or with postfix), the increment is the unqualified type of the | |||
13134 | // operand. | |||
13135 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | |||
13136 | VK = VK_LValue; | |||
13137 | OK = Op->getObjectKind(); | |||
13138 | return ResType; | |||
13139 | } else { | |||
13140 | VK = VK_RValue; | |||
13141 | return ResType.getUnqualifiedType(); | |||
13142 | } | |||
13143 | } | |||
13144 | ||||
13145 | ||||
13146 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | |||
13147 | /// This routine allows us to typecheck complex/recursive expressions | |||
13148 | /// where the declaration is needed for type checking. We only need to | |||
13149 | /// handle cases when the expression references a function designator | |||
13150 | /// or is an lvalue. Here are some examples: | |||
13151 | /// - &(x) => x | |||
13152 | /// - &*****f => f for f a function designator. | |||
13153 | /// - &s.xx => s | |||
13154 | /// - &s.zz[1].yy -> s, if zz is an array | |||
13155 | /// - *(x + 1) -> x, if x is an array | |||
13156 | /// - &"123"[2] -> 0 | |||
13157 | /// - & __real__ x -> x | |||
13158 | /// | |||
13159 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | |||
13160 | /// members. | |||
13161 | static ValueDecl *getPrimaryDecl(Expr *E) { | |||
13162 | switch (E->getStmtClass()) { | |||
13163 | case Stmt::DeclRefExprClass: | |||
13164 | return cast<DeclRefExpr>(E)->getDecl(); | |||
13165 | case Stmt::MemberExprClass: | |||
13166 | // If this is an arrow operator, the address is an offset from | |||
13167 | // the base's value, so the object the base refers to is | |||
13168 | // irrelevant. | |||
13169 | if (cast<MemberExpr>(E)->isArrow()) | |||
13170 | return nullptr; | |||
13171 | // Otherwise, the expression refers to a part of the base | |||
13172 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | |||
13173 | case Stmt::ArraySubscriptExprClass: { | |||
13174 | // FIXME: This code shouldn't be necessary! We should catch the implicit | |||
13175 | // promotion of register arrays earlier. | |||
13176 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | |||
13177 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | |||
13178 | if (ICE->getSubExpr()->getType()->isArrayType()) | |||
13179 | return getPrimaryDecl(ICE->getSubExpr()); | |||
13180 | } | |||
13181 | return nullptr; | |||
13182 | } | |||
13183 | case Stmt::UnaryOperatorClass: { | |||
13184 | UnaryOperator *UO = cast<UnaryOperator>(E); | |||
13185 | ||||
13186 | switch(UO->getOpcode()) { | |||
13187 | case UO_Real: | |||
13188 | case UO_Imag: | |||
13189 | case UO_Extension: | |||
13190 | return getPrimaryDecl(UO->getSubExpr()); | |||
13191 | default: | |||
13192 | return nullptr; | |||
13193 | } | |||
13194 | } | |||
13195 | case Stmt::ParenExprClass: | |||
13196 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | |||
13197 | case Stmt::ImplicitCastExprClass: | |||
13198 | // If the result of an implicit cast is an l-value, we care about | |||
13199 | // the sub-expression; otherwise, the result here doesn't matter. | |||
13200 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | |||
13201 | case Stmt::CXXUuidofExprClass: | |||
13202 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | |||
13203 | default: | |||
13204 | return nullptr; | |||
13205 | } | |||
13206 | } | |||
13207 | ||||
13208 | namespace { | |||
13209 | enum { | |||
13210 | AO_Bit_Field = 0, | |||
13211 | AO_Vector_Element = 1, | |||
13212 | AO_Property_Expansion = 2, | |||
13213 | AO_Register_Variable = 3, | |||
13214 | AO_Matrix_Element = 4, | |||
13215 | AO_No_Error = 5 | |||
13216 | }; | |||
13217 | } | |||
13218 | /// Diagnose invalid operand for address of operations. | |||
13219 | /// | |||
13220 | /// \param Type The type of operand which cannot have its address taken. | |||
13221 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | |||
13222 | Expr *E, unsigned Type) { | |||
13223 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | |||
13224 | } | |||
13225 | ||||
13226 | /// CheckAddressOfOperand - The operand of & must be either a function | |||
13227 | /// designator or an lvalue designating an object. If it is an lvalue, the | |||
13228 | /// object cannot be declared with storage class register or be a bit field. | |||
13229 | /// Note: The usual conversions are *not* applied to the operand of the & | |||
13230 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | |||
13231 | /// In C++, the operand might be an overloaded function name, in which case | |||
13232 | /// we allow the '&' but retain the overloaded-function type. | |||
13233 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | |||
13234 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | |||
13235 | if (PTy->getKind() == BuiltinType::Overload) { | |||
13236 | Expr *E = OrigOp.get()->IgnoreParens(); | |||
13237 | if (!isa<OverloadExpr>(E)) { | |||
13238 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13238, __PRETTY_FUNCTION__)); | |||
13239 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | |||
13240 | << OrigOp.get()->getSourceRange(); | |||
13241 | return QualType(); | |||
13242 | } | |||
13243 | ||||
13244 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | |||
13245 | if (isa<UnresolvedMemberExpr>(Ovl)) | |||
13246 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | |||
13247 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
13248 | << OrigOp.get()->getSourceRange(); | |||
13249 | return QualType(); | |||
13250 | } | |||
13251 | ||||
13252 | return Context.OverloadTy; | |||
13253 | } | |||
13254 | ||||
13255 | if (PTy->getKind() == BuiltinType::UnknownAny) | |||
13256 | return Context.UnknownAnyTy; | |||
13257 | ||||
13258 | if (PTy->getKind() == BuiltinType::BoundMember) { | |||
13259 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
13260 | << OrigOp.get()->getSourceRange(); | |||
13261 | return QualType(); | |||
13262 | } | |||
13263 | ||||
13264 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | |||
13265 | if (OrigOp.isInvalid()) return QualType(); | |||
13266 | } | |||
13267 | ||||
13268 | if (OrigOp.get()->isTypeDependent()) | |||
13269 | return Context.DependentTy; | |||
13270 | ||||
13271 | assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast <void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13271, __PRETTY_FUNCTION__)); | |||
13272 | ||||
13273 | // Make sure to ignore parentheses in subsequent checks | |||
13274 | Expr *op = OrigOp.get()->IgnoreParens(); | |||
13275 | ||||
13276 | // In OpenCL captures for blocks called as lambda functions | |||
13277 | // are located in the private address space. Blocks used in | |||
13278 | // enqueue_kernel can be located in a different address space | |||
13279 | // depending on a vendor implementation. Thus preventing | |||
13280 | // taking an address of the capture to avoid invalid AS casts. | |||
13281 | if (LangOpts.OpenCL) { | |||
13282 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | |||
13283 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | |||
13284 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | |||
13285 | return QualType(); | |||
13286 | } | |||
13287 | } | |||
13288 | ||||
13289 | if (getLangOpts().C99) { | |||
13290 | // Implement C99-only parts of addressof rules. | |||
13291 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | |||
13292 | if (uOp->getOpcode() == UO_Deref) | |||
13293 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | |||
13294 | // (assuming the deref expression is valid). | |||
13295 | return uOp->getSubExpr()->getType(); | |||
13296 | } | |||
13297 | // Technically, there should be a check for array subscript | |||
13298 | // expressions here, but the result of one is always an lvalue anyway. | |||
13299 | } | |||
13300 | ValueDecl *dcl = getPrimaryDecl(op); | |||
13301 | ||||
13302 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | |||
13303 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
13304 | op->getBeginLoc())) | |||
13305 | return QualType(); | |||
13306 | ||||
13307 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | |||
13308 | unsigned AddressOfError = AO_No_Error; | |||
13309 | ||||
13310 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | |||
13311 | bool sfinae = (bool)isSFINAEContext(); | |||
13312 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | |||
13313 | : diag::ext_typecheck_addrof_temporary) | |||
13314 | << op->getType() << op->getSourceRange(); | |||
13315 | if (sfinae) | |||
13316 | return QualType(); | |||
13317 | // Materialize the temporary as an lvalue so that we can take its address. | |||
13318 | OrigOp = op = | |||
13319 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | |||
13320 | } else if (isa<ObjCSelectorExpr>(op)) { | |||
13321 | return Context.getPointerType(op->getType()); | |||
13322 | } else if (lval == Expr::LV_MemberFunction) { | |||
13323 | // If it's an instance method, make a member pointer. | |||
13324 | // The expression must have exactly the form &A::foo. | |||
13325 | ||||
13326 | // If the underlying expression isn't a decl ref, give up. | |||
13327 | if (!isa<DeclRefExpr>(op)) { | |||
13328 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | |||
13329 | << OrigOp.get()->getSourceRange(); | |||
13330 | return QualType(); | |||
13331 | } | |||
13332 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | |||
13333 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | |||
13334 | ||||
13335 | // The id-expression was parenthesized. | |||
13336 | if (OrigOp.get() != DRE) { | |||
13337 | Diag(OpLoc, diag::err_parens_pointer_member_function) | |||
13338 | << OrigOp.get()->getSourceRange(); | |||
13339 | ||||
13340 | // The method was named without a qualifier. | |||
13341 | } else if (!DRE->getQualifier()) { | |||
13342 | if (MD->getParent()->getName().empty()) | |||
13343 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | |||
13344 | << op->getSourceRange(); | |||
13345 | else { | |||
13346 | SmallString<32> Str; | |||
13347 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | |||
13348 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | |||
13349 | << op->getSourceRange() | |||
13350 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | |||
13351 | } | |||
13352 | } | |||
13353 | ||||
13354 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | |||
13355 | if (isa<CXXDestructorDecl>(MD)) | |||
13356 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | |||
13357 | ||||
13358 | QualType MPTy = Context.getMemberPointerType( | |||
13359 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | |||
13360 | // Under the MS ABI, lock down the inheritance model now. | |||
13361 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
13362 | (void)isCompleteType(OpLoc, MPTy); | |||
13363 | return MPTy; | |||
13364 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | |||
13365 | // C99 6.5.3.2p1 | |||
13366 | // The operand must be either an l-value or a function designator | |||
13367 | if (!op->getType()->isFunctionType()) { | |||
13368 | // Use a special diagnostic for loads from property references. | |||
13369 | if (isa<PseudoObjectExpr>(op)) { | |||
13370 | AddressOfError = AO_Property_Expansion; | |||
13371 | } else { | |||
13372 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | |||
13373 | << op->getType() << op->getSourceRange(); | |||
13374 | return QualType(); | |||
13375 | } | |||
13376 | } | |||
13377 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | |||
13378 | // The operand cannot be a bit-field | |||
13379 | AddressOfError = AO_Bit_Field; | |||
13380 | } else if (op->getObjectKind() == OK_VectorComponent) { | |||
13381 | // The operand cannot be an element of a vector | |||
13382 | AddressOfError = AO_Vector_Element; | |||
13383 | } else if (op->getObjectKind() == OK_MatrixComponent) { | |||
13384 | // The operand cannot be an element of a matrix. | |||
13385 | AddressOfError = AO_Matrix_Element; | |||
13386 | } else if (dcl) { // C99 6.5.3.2p1 | |||
13387 | // We have an lvalue with a decl. Make sure the decl is not declared | |||
13388 | // with the register storage-class specifier. | |||
13389 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | |||
13390 | // in C++ it is not error to take address of a register | |||
13391 | // variable (c++03 7.1.1P3) | |||
13392 | if (vd->getStorageClass() == SC_Register && | |||
13393 | !getLangOpts().CPlusPlus) { | |||
13394 | AddressOfError = AO_Register_Variable; | |||
13395 | } | |||
13396 | } else if (isa<MSPropertyDecl>(dcl)) { | |||
13397 | AddressOfError = AO_Property_Expansion; | |||
13398 | } else if (isa<FunctionTemplateDecl>(dcl)) { | |||
13399 | return Context.OverloadTy; | |||
13400 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | |||
13401 | // Okay: we can take the address of a field. | |||
13402 | // Could be a pointer to member, though, if there is an explicit | |||
13403 | // scope qualifier for the class. | |||
13404 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | |||
13405 | DeclContext *Ctx = dcl->getDeclContext(); | |||
13406 | if (Ctx && Ctx->isRecord()) { | |||
13407 | if (dcl->getType()->isReferenceType()) { | |||
13408 | Diag(OpLoc, | |||
13409 | diag::err_cannot_form_pointer_to_member_of_reference_type) | |||
13410 | << dcl->getDeclName() << dcl->getType(); | |||
13411 | return QualType(); | |||
13412 | } | |||
13413 | ||||
13414 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | |||
13415 | Ctx = Ctx->getParent(); | |||
13416 | ||||
13417 | QualType MPTy = Context.getMemberPointerType( | |||
13418 | op->getType(), | |||
13419 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | |||
13420 | // Under the MS ABI, lock down the inheritance model now. | |||
13421 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
13422 | (void)isCompleteType(OpLoc, MPTy); | |||
13423 | return MPTy; | |||
13424 | } | |||
13425 | } | |||
13426 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | |||
13427 | !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) | |||
13428 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13428); | |||
13429 | } | |||
13430 | ||||
13431 | if (AddressOfError != AO_No_Error) { | |||
13432 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | |||
13433 | return QualType(); | |||
13434 | } | |||
13435 | ||||
13436 | if (lval == Expr::LV_IncompleteVoidType) { | |||
13437 | // Taking the address of a void variable is technically illegal, but we | |||
13438 | // allow it in cases which are otherwise valid. | |||
13439 | // Example: "extern void x; void* y = &x;". | |||
13440 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | |||
13441 | } | |||
13442 | ||||
13443 | // If the operand has type "type", the result has type "pointer to type". | |||
13444 | if (op->getType()->isObjCObjectType()) | |||
13445 | return Context.getObjCObjectPointerType(op->getType()); | |||
13446 | ||||
13447 | CheckAddressOfPackedMember(op); | |||
13448 | ||||
13449 | return Context.getPointerType(op->getType()); | |||
13450 | } | |||
13451 | ||||
13452 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | |||
13453 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | |||
13454 | if (!DRE) | |||
13455 | return; | |||
13456 | const Decl *D = DRE->getDecl(); | |||
13457 | if (!D) | |||
13458 | return; | |||
13459 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | |||
13460 | if (!Param) | |||
13461 | return; | |||
13462 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | |||
13463 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | |||
13464 | return; | |||
13465 | if (FunctionScopeInfo *FD = S.getCurFunction()) | |||
13466 | if (!FD->ModifiedNonNullParams.count(Param)) | |||
13467 | FD->ModifiedNonNullParams.insert(Param); | |||
13468 | } | |||
13469 | ||||
13470 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | |||
13471 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | |||
13472 | SourceLocation OpLoc) { | |||
13473 | if (Op->isTypeDependent()) | |||
13474 | return S.Context.DependentTy; | |||
13475 | ||||
13476 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | |||
13477 | if (ConvResult.isInvalid()) | |||
13478 | return QualType(); | |||
13479 | Op = ConvResult.get(); | |||
13480 | QualType OpTy = Op->getType(); | |||
13481 | QualType Result; | |||
13482 | ||||
13483 | if (isa<CXXReinterpretCastExpr>(Op)) { | |||
13484 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | |||
13485 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | |||
13486 | Op->getSourceRange()); | |||
13487 | } | |||
13488 | ||||
13489 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | |||
13490 | { | |||
13491 | Result = PT->getPointeeType(); | |||
13492 | } | |||
13493 | else if (const ObjCObjectPointerType *OPT = | |||
13494 | OpTy->getAs<ObjCObjectPointerType>()) | |||
13495 | Result = OPT->getPointeeType(); | |||
13496 | else { | |||
13497 | ExprResult PR = S.CheckPlaceholderExpr(Op); | |||
13498 | if (PR.isInvalid()) return QualType(); | |||
13499 | if (PR.get() != Op) | |||
13500 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | |||
13501 | } | |||
13502 | ||||
13503 | if (Result.isNull()) { | |||
13504 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | |||
13505 | << OpTy << Op->getSourceRange(); | |||
13506 | return QualType(); | |||
13507 | } | |||
13508 | ||||
13509 | // Note that per both C89 and C99, indirection is always legal, even if Result | |||
13510 | // is an incomplete type or void. It would be possible to warn about | |||
13511 | // dereferencing a void pointer, but it's completely well-defined, and such a | |||
13512 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | |||
13513 | // for pointers to 'void' but is fine for any other pointer type: | |||
13514 | // | |||
13515 | // C++ [expr.unary.op]p1: | |||
13516 | // [...] the expression to which [the unary * operator] is applied shall | |||
13517 | // be a pointer to an object type, or a pointer to a function type | |||
13518 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | |||
13519 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | |||
13520 | << OpTy << Op->getSourceRange(); | |||
13521 | ||||
13522 | // Dereferences are usually l-values... | |||
13523 | VK = VK_LValue; | |||
13524 | ||||
13525 | // ...except that certain expressions are never l-values in C. | |||
13526 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | |||
13527 | VK = VK_RValue; | |||
13528 | ||||
13529 | return Result; | |||
13530 | } | |||
13531 | ||||
13532 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | |||
13533 | BinaryOperatorKind Opc; | |||
13534 | switch (Kind) { | |||
13535 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13535); | |||
13536 | case tok::periodstar: Opc = BO_PtrMemD; break; | |||
13537 | case tok::arrowstar: Opc = BO_PtrMemI; break; | |||
13538 | case tok::star: Opc = BO_Mul; break; | |||
13539 | case tok::slash: Opc = BO_Div; break; | |||
13540 | case tok::percent: Opc = BO_Rem; break; | |||
13541 | case tok::plus: Opc = BO_Add; break; | |||
13542 | case tok::minus: Opc = BO_Sub; break; | |||
13543 | case tok::lessless: Opc = BO_Shl; break; | |||
13544 | case tok::greatergreater: Opc = BO_Shr; break; | |||
13545 | case tok::lessequal: Opc = BO_LE; break; | |||
13546 | case tok::less: Opc = BO_LT; break; | |||
13547 | case tok::greaterequal: Opc = BO_GE; break; | |||
13548 | case tok::greater: Opc = BO_GT; break; | |||
13549 | case tok::exclaimequal: Opc = BO_NE; break; | |||
13550 | case tok::equalequal: Opc = BO_EQ; break; | |||
13551 | case tok::spaceship: Opc = BO_Cmp; break; | |||
13552 | case tok::amp: Opc = BO_And; break; | |||
13553 | case tok::caret: Opc = BO_Xor; break; | |||
13554 | case tok::pipe: Opc = BO_Or; break; | |||
13555 | case tok::ampamp: Opc = BO_LAnd; break; | |||
13556 | case tok::pipepipe: Opc = BO_LOr; break; | |||
13557 | case tok::equal: Opc = BO_Assign; break; | |||
13558 | case tok::starequal: Opc = BO_MulAssign; break; | |||
13559 | case tok::slashequal: Opc = BO_DivAssign; break; | |||
13560 | case tok::percentequal: Opc = BO_RemAssign; break; | |||
13561 | case tok::plusequal: Opc = BO_AddAssign; break; | |||
13562 | case tok::minusequal: Opc = BO_SubAssign; break; | |||
13563 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | |||
13564 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | |||
13565 | case tok::ampequal: Opc = BO_AndAssign; break; | |||
13566 | case tok::caretequal: Opc = BO_XorAssign; break; | |||
13567 | case tok::pipeequal: Opc = BO_OrAssign; break; | |||
13568 | case tok::comma: Opc = BO_Comma; break; | |||
13569 | } | |||
13570 | return Opc; | |||
13571 | } | |||
13572 | ||||
13573 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | |||
13574 | tok::TokenKind Kind) { | |||
13575 | UnaryOperatorKind Opc; | |||
13576 | switch (Kind) { | |||
13577 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13577); | |||
13578 | case tok::plusplus: Opc = UO_PreInc; break; | |||
13579 | case tok::minusminus: Opc = UO_PreDec; break; | |||
13580 | case tok::amp: Opc = UO_AddrOf; break; | |||
13581 | case tok::star: Opc = UO_Deref; break; | |||
13582 | case tok::plus: Opc = UO_Plus; break; | |||
13583 | case tok::minus: Opc = UO_Minus; break; | |||
13584 | case tok::tilde: Opc = UO_Not; break; | |||
13585 | case tok::exclaim: Opc = UO_LNot; break; | |||
13586 | case tok::kw___real: Opc = UO_Real; break; | |||
13587 | case tok::kw___imag: Opc = UO_Imag; break; | |||
13588 | case tok::kw___extension__: Opc = UO_Extension; break; | |||
13589 | } | |||
13590 | return Opc; | |||
13591 | } | |||
13592 | ||||
13593 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | |||
13594 | /// This warning suppressed in the event of macro expansions. | |||
13595 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | |||
13596 | SourceLocation OpLoc, bool IsBuiltin) { | |||
13597 | if (S.inTemplateInstantiation()) | |||
13598 | return; | |||
13599 | if (S.isUnevaluatedContext()) | |||
13600 | return; | |||
13601 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | |||
13602 | return; | |||
13603 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | |||
13604 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | |||
13605 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | |||
13606 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | |||
13607 | if (!LHSDeclRef || !RHSDeclRef || | |||
13608 | LHSDeclRef->getLocation().isMacroID() || | |||
13609 | RHSDeclRef->getLocation().isMacroID()) | |||
13610 | return; | |||
13611 | const ValueDecl *LHSDecl = | |||
13612 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | |||
13613 | const ValueDecl *RHSDecl = | |||
13614 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | |||
13615 | if (LHSDecl != RHSDecl) | |||
13616 | return; | |||
13617 | if (LHSDecl->getType().isVolatileQualified()) | |||
13618 | return; | |||
13619 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | |||
13620 | if (RefTy->getPointeeType().isVolatileQualified()) | |||
13621 | return; | |||
13622 | ||||
13623 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | |||
13624 | : diag::warn_self_assignment_overloaded) | |||
13625 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | |||
13626 | << RHSExpr->getSourceRange(); | |||
13627 | } | |||
13628 | ||||
13629 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | |||
13630 | /// is usually indicative of introspection within the Objective-C pointer. | |||
13631 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | |||
13632 | SourceLocation OpLoc) { | |||
13633 | if (!S.getLangOpts().ObjC) | |||
13634 | return; | |||
13635 | ||||
13636 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | |||
13637 | const Expr *LHS = L.get(); | |||
13638 | const Expr *RHS = R.get(); | |||
13639 | ||||
13640 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | |||
13641 | ObjCPointerExpr = LHS; | |||
13642 | OtherExpr = RHS; | |||
13643 | } | |||
13644 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | |||
13645 | ObjCPointerExpr = RHS; | |||
13646 | OtherExpr = LHS; | |||
13647 | } | |||
13648 | ||||
13649 | // This warning is deliberately made very specific to reduce false | |||
13650 | // positives with logic that uses '&' for hashing. This logic mainly | |||
13651 | // looks for code trying to introspect into tagged pointers, which | |||
13652 | // code should generally never do. | |||
13653 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | |||
13654 | unsigned Diag = diag::warn_objc_pointer_masking; | |||
13655 | // Determine if we are introspecting the result of performSelectorXXX. | |||
13656 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | |||
13657 | // Special case messages to -performSelector and friends, which | |||
13658 | // can return non-pointer values boxed in a pointer value. | |||
13659 | // Some clients may wish to silence warnings in this subcase. | |||
13660 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | |||
13661 | Selector S = ME->getSelector(); | |||
13662 | StringRef SelArg0 = S.getNameForSlot(0); | |||
13663 | if (SelArg0.startswith("performSelector")) | |||
13664 | Diag = diag::warn_objc_pointer_masking_performSelector; | |||
13665 | } | |||
13666 | ||||
13667 | S.Diag(OpLoc, Diag) | |||
13668 | << ObjCPointerExpr->getSourceRange(); | |||
13669 | } | |||
13670 | } | |||
13671 | ||||
13672 | static NamedDecl *getDeclFromExpr(Expr *E) { | |||
13673 | if (!E) | |||
13674 | return nullptr; | |||
13675 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
13676 | return DRE->getDecl(); | |||
13677 | if (auto *ME = dyn_cast<MemberExpr>(E)) | |||
13678 | return ME->getMemberDecl(); | |||
13679 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | |||
13680 | return IRE->getDecl(); | |||
13681 | return nullptr; | |||
13682 | } | |||
13683 | ||||
13684 | // This helper function promotes a binary operator's operands (which are of a | |||
13685 | // half vector type) to a vector of floats and then truncates the result to | |||
13686 | // a vector of either half or short. | |||
13687 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | |||
13688 | BinaryOperatorKind Opc, QualType ResultTy, | |||
13689 | ExprValueKind VK, ExprObjectKind OK, | |||
13690 | bool IsCompAssign, SourceLocation OpLoc, | |||
13691 | FPOptionsOverride FPFeatures) { | |||
13692 | auto &Context = S.getASTContext(); | |||
13693 | assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13695, __PRETTY_FUNCTION__)) | |||
13694 | isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13695, __PRETTY_FUNCTION__)) | |||
13695 | "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13695, __PRETTY_FUNCTION__)); | |||
13696 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13698, __PRETTY_FUNCTION__)) | |||
13697 | isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13698, __PRETTY_FUNCTION__)) | |||
13698 | "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13698, __PRETTY_FUNCTION__)); | |||
13699 | ||||
13700 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | |||
13701 | QualType BinOpResTy = RHS.get()->getType(); | |||
13702 | ||||
13703 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | |||
13704 | // change BinOpResTy to a vector of ints. | |||
13705 | if (isVector(ResultTy, Context.ShortTy)) | |||
13706 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | |||
13707 | ||||
13708 | if (IsCompAssign) | |||
13709 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | |||
13710 | ResultTy, VK, OK, OpLoc, FPFeatures, | |||
13711 | BinOpResTy, BinOpResTy); | |||
13712 | ||||
13713 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | |||
13714 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | |||
13715 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | |||
13716 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | |||
13717 | } | |||
13718 | ||||
13719 | static std::pair<ExprResult, ExprResult> | |||
13720 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | |||
13721 | Expr *RHSExpr) { | |||
13722 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | |||
13723 | if (!S.Context.isDependenceAllowed()) { | |||
13724 | // C cannot handle TypoExpr nodes on either side of a binop because it | |||
13725 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
13726 | // been dealt with before checking the operands. | |||
13727 | LHS = S.CorrectDelayedTyposInExpr(LHS); | |||
13728 | RHS = S.CorrectDelayedTyposInExpr( | |||
13729 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | |||
13730 | [Opc, LHS](Expr *E) { | |||
13731 | if (Opc != BO_Assign) | |||
13732 | return ExprResult(E); | |||
13733 | // Avoid correcting the RHS to the same Expr as the LHS. | |||
13734 | Decl *D = getDeclFromExpr(E); | |||
13735 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | |||
13736 | }); | |||
13737 | } | |||
13738 | return std::make_pair(LHS, RHS); | |||
13739 | } | |||
13740 | ||||
13741 | /// Returns true if conversion between vectors of halfs and vectors of floats | |||
13742 | /// is needed. | |||
13743 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | |||
13744 | Expr *E0, Expr *E1 = nullptr) { | |||
13745 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | |||
13746 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | |||
13747 | return false; | |||
13748 | ||||
13749 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | |||
13750 | QualType Ty = E->IgnoreImplicit()->getType(); | |||
13751 | ||||
13752 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | |||
13753 | // to vectors of floats. Although the element type of the vectors is __fp16, | |||
13754 | // the vectors shouldn't be treated as storage-only types. See the | |||
13755 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | |||
13756 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | |||
13757 | if (VT->getVectorKind() == VectorType::NeonVector) | |||
13758 | return false; | |||
13759 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | |||
13760 | } | |||
13761 | return false; | |||
13762 | }; | |||
13763 | ||||
13764 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | |||
13765 | } | |||
13766 | ||||
13767 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | |||
13768 | /// operator @p Opc at location @c TokLoc. This routine only supports | |||
13769 | /// built-in operations; ActOnBinOp handles overloaded operators. | |||
13770 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | |||
13771 | BinaryOperatorKind Opc, | |||
13772 | Expr *LHSExpr, Expr *RHSExpr) { | |||
13773 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | |||
13774 | // The syntax only allows initializer lists on the RHS of assignment, | |||
13775 | // so we don't need to worry about accepting invalid code for | |||
13776 | // non-assignment operators. | |||
13777 | // C++11 5.17p9: | |||
13778 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | |||
13779 | // of x = {} is x = T(). | |||
13780 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
13781 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
13782 | InitializedEntity Entity = | |||
13783 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | |||
13784 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | |||
13785 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | |||
13786 | if (Init.isInvalid()) | |||
13787 | return Init; | |||
13788 | RHSExpr = Init.get(); | |||
13789 | } | |||
13790 | ||||
13791 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | |||
13792 | QualType ResultTy; // Result type of the binary operator. | |||
13793 | // The following two variables are used for compound assignment operators | |||
13794 | QualType CompLHSTy; // Type of LHS after promotions for computation | |||
13795 | QualType CompResultTy; // Type of computation result | |||
13796 | ExprValueKind VK = VK_RValue; | |||
13797 | ExprObjectKind OK = OK_Ordinary; | |||
13798 | bool ConvertHalfVec = false; | |||
13799 | ||||
13800 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | |||
13801 | if (!LHS.isUsable() || !RHS.isUsable()) | |||
13802 | return ExprError(); | |||
13803 | ||||
13804 | if (getLangOpts().OpenCL) { | |||
13805 | QualType LHSTy = LHSExpr->getType(); | |||
13806 | QualType RHSTy = RHSExpr->getType(); | |||
13807 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | |||
13808 | // the ATOMIC_VAR_INIT macro. | |||
13809 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | |||
13810 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | |||
13811 | if (BO_Assign == Opc) | |||
13812 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | |||
13813 | else | |||
13814 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | |||
13815 | return ExprError(); | |||
13816 | } | |||
13817 | ||||
13818 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | |||
13819 | // only with a builtin functions and therefore should be disallowed here. | |||
13820 | if (LHSTy->isImageType() || RHSTy->isImageType() || | |||
13821 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | |||
13822 | LHSTy->isPipeType() || RHSTy->isPipeType() || | |||
13823 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | |||
13824 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | |||
13825 | return ExprError(); | |||
13826 | } | |||
13827 | } | |||
13828 | ||||
13829 | switch (Opc) { | |||
13830 | case BO_Assign: | |||
13831 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | |||
13832 | if (getLangOpts().CPlusPlus && | |||
13833 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | |||
13834 | VK = LHS.get()->getValueKind(); | |||
13835 | OK = LHS.get()->getObjectKind(); | |||
13836 | } | |||
13837 | if (!ResultTy.isNull()) { | |||
13838 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | |||
13839 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | |||
13840 | ||||
13841 | // Avoid copying a block to the heap if the block is assigned to a local | |||
13842 | // auto variable that is declared in the same scope as the block. This | |||
13843 | // optimization is unsafe if the local variable is declared in an outer | |||
13844 | // scope. For example: | |||
13845 | // | |||
13846 | // BlockTy b; | |||
13847 | // { | |||
13848 | // b = ^{...}; | |||
13849 | // } | |||
13850 | // // It is unsafe to invoke the block here if it wasn't copied to the | |||
13851 | // // heap. | |||
13852 | // b(); | |||
13853 | ||||
13854 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | |||
13855 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | |||
13856 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | |||
13857 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | |||
13858 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | |||
13859 | ||||
13860 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
13861 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | |||
13862 | NTCUC_Assignment, NTCUK_Copy); | |||
13863 | } | |||
13864 | RecordModifiableNonNullParam(*this, LHS.get()); | |||
13865 | break; | |||
13866 | case BO_PtrMemD: | |||
13867 | case BO_PtrMemI: | |||
13868 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | |||
13869 | Opc == BO_PtrMemI); | |||
13870 | break; | |||
13871 | case BO_Mul: | |||
13872 | case BO_Div: | |||
13873 | ConvertHalfVec = true; | |||
13874 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | |||
13875 | Opc == BO_Div); | |||
13876 | break; | |||
13877 | case BO_Rem: | |||
13878 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | |||
13879 | break; | |||
13880 | case BO_Add: | |||
13881 | ConvertHalfVec = true; | |||
13882 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | |||
13883 | break; | |||
13884 | case BO_Sub: | |||
13885 | ConvertHalfVec = true; | |||
13886 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | |||
13887 | break; | |||
13888 | case BO_Shl: | |||
13889 | case BO_Shr: | |||
13890 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | |||
13891 | break; | |||
13892 | case BO_LE: | |||
13893 | case BO_LT: | |||
13894 | case BO_GE: | |||
13895 | case BO_GT: | |||
13896 | ConvertHalfVec = true; | |||
13897 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | |||
13898 | break; | |||
13899 | case BO_EQ: | |||
13900 | case BO_NE: | |||
13901 | ConvertHalfVec = true; | |||
13902 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | |||
13903 | break; | |||
13904 | case BO_Cmp: | |||
13905 | ConvertHalfVec = true; | |||
13906 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | |||
13907 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast <void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13907, __PRETTY_FUNCTION__)); | |||
13908 | break; | |||
13909 | case BO_And: | |||
13910 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | |||
13911 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
13912 | case BO_Xor: | |||
13913 | case BO_Or: | |||
13914 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | |||
13915 | break; | |||
13916 | case BO_LAnd: | |||
13917 | case BO_LOr: | |||
13918 | ConvertHalfVec = true; | |||
13919 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | |||
13920 | break; | |||
13921 | case BO_MulAssign: | |||
13922 | case BO_DivAssign: | |||
13923 | ConvertHalfVec = true; | |||
13924 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | |||
13925 | Opc == BO_DivAssign); | |||
13926 | CompLHSTy = CompResultTy; | |||
13927 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
13928 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
13929 | break; | |||
13930 | case BO_RemAssign: | |||
13931 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | |||
13932 | CompLHSTy = CompResultTy; | |||
13933 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
13934 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
13935 | break; | |||
13936 | case BO_AddAssign: | |||
13937 | ConvertHalfVec = true; | |||
13938 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | |||
13939 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
13940 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
13941 | break; | |||
13942 | case BO_SubAssign: | |||
13943 | ConvertHalfVec = true; | |||
13944 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | |||
13945 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
13946 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
13947 | break; | |||
13948 | case BO_ShlAssign: | |||
13949 | case BO_ShrAssign: | |||
13950 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | |||
13951 | CompLHSTy = CompResultTy; | |||
13952 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
13953 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
13954 | break; | |||
13955 | case BO_AndAssign: | |||
13956 | case BO_OrAssign: // fallthrough | |||
13957 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | |||
13958 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
13959 | case BO_XorAssign: | |||
13960 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | |||
13961 | CompLHSTy = CompResultTy; | |||
13962 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | |||
13963 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | |||
13964 | break; | |||
13965 | case BO_Comma: | |||
13966 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | |||
13967 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | |||
13968 | VK = RHS.get()->getValueKind(); | |||
13969 | OK = RHS.get()->getObjectKind(); | |||
13970 | } | |||
13971 | break; | |||
13972 | } | |||
13973 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | |||
13974 | return ExprError(); | |||
13975 | ||||
13976 | // Some of the binary operations require promoting operands of half vector to | |||
13977 | // float vectors and truncating the result back to half vector. For now, we do | |||
13978 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | |||
13979 | // arm64). | |||
13980 | assert((((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13983, __PRETTY_FUNCTION__)) | |||
13981 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13983, __PRETTY_FUNCTION__)) | |||
13982 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13983, __PRETTY_FUNCTION__)) | |||
13983 | "both sides are half vectors or neither sides are")(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 13983, __PRETTY_FUNCTION__)); | |||
13984 | ConvertHalfVec = | |||
13985 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | |||
13986 | ||||
13987 | // Check for array bounds violations for both sides of the BinaryOperator | |||
13988 | CheckArrayAccess(LHS.get()); | |||
13989 | CheckArrayAccess(RHS.get()); | |||
13990 | ||||
13991 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | |||
13992 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | |||
13993 | &Context.Idents.get("object_setClass"), | |||
13994 | SourceLocation(), LookupOrdinaryName); | |||
13995 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | |||
13996 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | |||
13997 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | |||
13998 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | |||
13999 | "object_setClass(") | |||
14000 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | |||
14001 | ",") | |||
14002 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
14003 | } | |||
14004 | else | |||
14005 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | |||
14006 | } | |||
14007 | else if (const ObjCIvarRefExpr *OIRE = | |||
14008 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | |||
14009 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | |||
14010 | ||||
14011 | // Opc is not a compound assignment if CompResultTy is null. | |||
14012 | if (CompResultTy.isNull()) { | |||
14013 | if (ConvertHalfVec) | |||
14014 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | |||
14015 | OpLoc, CurFPFeatureOverrides()); | |||
14016 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | |||
14017 | VK, OK, OpLoc, CurFPFeatureOverrides()); | |||
14018 | } | |||
14019 | ||||
14020 | // Handle compound assignments. | |||
14021 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | |||
14022 | OK_ObjCProperty) { | |||
14023 | VK = VK_LValue; | |||
14024 | OK = LHS.get()->getObjectKind(); | |||
14025 | } | |||
14026 | ||||
14027 | // The LHS is not converted to the result type for fixed-point compound | |||
14028 | // assignment as the common type is computed on demand. Reset the CompLHSTy | |||
14029 | // to the LHS type we would have gotten after unary conversions. | |||
14030 | if (CompResultTy->isFixedPointType()) | |||
14031 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | |||
14032 | ||||
14033 | if (ConvertHalfVec) | |||
14034 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | |||
14035 | OpLoc, CurFPFeatureOverrides()); | |||
14036 | ||||
14037 | return CompoundAssignOperator::Create( | |||
14038 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | |||
14039 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | |||
14040 | } | |||
14041 | ||||
14042 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | |||
14043 | /// operators are mixed in a way that suggests that the programmer forgot that | |||
14044 | /// comparison operators have higher precedence. The most typical example of | |||
14045 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | |||
14046 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | |||
14047 | SourceLocation OpLoc, Expr *LHSExpr, | |||
14048 | Expr *RHSExpr) { | |||
14049 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | |||
14050 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | |||
14051 | ||||
14052 | // Check that one of the sides is a comparison operator and the other isn't. | |||
14053 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | |||
14054 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | |||
14055 | if (isLeftComp == isRightComp) | |||
14056 | return; | |||
14057 | ||||
14058 | // Bitwise operations are sometimes used as eager logical ops. | |||
14059 | // Don't diagnose this. | |||
14060 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | |||
14061 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | |||
14062 | if (isLeftBitwise || isRightBitwise) | |||
14063 | return; | |||
14064 | ||||
14065 | SourceRange DiagRange = isLeftComp | |||
14066 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | |||
14067 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | |||
14068 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | |||
14069 | SourceRange ParensRange = | |||
14070 | isLeftComp | |||
14071 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | |||
14072 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | |||
14073 | ||||
14074 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | |||
14075 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | |||
14076 | SuggestParentheses(Self, OpLoc, | |||
14077 | Self.PDiag(diag::note_precedence_silence) << OpStr, | |||
14078 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | |||
14079 | SuggestParentheses(Self, OpLoc, | |||
14080 | Self.PDiag(diag::note_precedence_bitwise_first) | |||
14081 | << BinaryOperator::getOpcodeStr(Opc), | |||
14082 | ParensRange); | |||
14083 | } | |||
14084 | ||||
14085 | /// It accepts a '&&' expr that is inside a '||' one. | |||
14086 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | |||
14087 | /// in parentheses. | |||
14088 | static void | |||
14089 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | |||
14090 | BinaryOperator *Bop) { | |||
14091 | assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> ( 0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14091, __PRETTY_FUNCTION__)); | |||
14092 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | |||
14093 | << Bop->getSourceRange() << OpLoc; | |||
14094 | SuggestParentheses(Self, Bop->getOperatorLoc(), | |||
14095 | Self.PDiag(diag::note_precedence_silence) | |||
14096 | << Bop->getOpcodeStr(), | |||
14097 | Bop->getSourceRange()); | |||
14098 | } | |||
14099 | ||||
14100 | /// Returns true if the given expression can be evaluated as a constant | |||
14101 | /// 'true'. | |||
14102 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | |||
14103 | bool Res; | |||
14104 | return !E->isValueDependent() && | |||
14105 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | |||
14106 | } | |||
14107 | ||||
14108 | /// Returns true if the given expression can be evaluated as a constant | |||
14109 | /// 'false'. | |||
14110 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | |||
14111 | bool Res; | |||
14112 | return !E->isValueDependent() && | |||
14113 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | |||
14114 | } | |||
14115 | ||||
14116 | /// Look for '&&' in the left hand of a '||' expr. | |||
14117 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | |||
14118 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14119 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | |||
14120 | if (Bop->getOpcode() == BO_LAnd) { | |||
14121 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | |||
14122 | if (EvaluatesAsFalse(S, RHSExpr)) | |||
14123 | return; | |||
14124 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | |||
14125 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | |||
14126 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | |||
14127 | } else if (Bop->getOpcode() == BO_LOr) { | |||
14128 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | |||
14129 | // If it's "a || b && 1 || c" we didn't warn earlier for | |||
14130 | // "a || b && 1", but warn now. | |||
14131 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | |||
14132 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | |||
14133 | } | |||
14134 | } | |||
14135 | } | |||
14136 | } | |||
14137 | ||||
14138 | /// Look for '&&' in the right hand of a '||' expr. | |||
14139 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | |||
14140 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14141 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | |||
14142 | if (Bop->getOpcode() == BO_LAnd) { | |||
14143 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | |||
14144 | if (EvaluatesAsFalse(S, LHSExpr)) | |||
14145 | return; | |||
14146 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | |||
14147 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | |||
14148 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | |||
14149 | } | |||
14150 | } | |||
14151 | } | |||
14152 | ||||
14153 | /// Look for bitwise op in the left or right hand of a bitwise op with | |||
14154 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | |||
14155 | /// the '&' expression in parentheses. | |||
14156 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | |||
14157 | SourceLocation OpLoc, Expr *SubExpr) { | |||
14158 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | |||
14159 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | |||
14160 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | |||
14161 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | |||
14162 | << Bop->getSourceRange() << OpLoc; | |||
14163 | SuggestParentheses(S, Bop->getOperatorLoc(), | |||
14164 | S.PDiag(diag::note_precedence_silence) | |||
14165 | << Bop->getOpcodeStr(), | |||
14166 | Bop->getSourceRange()); | |||
14167 | } | |||
14168 | } | |||
14169 | } | |||
14170 | ||||
14171 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | |||
14172 | Expr *SubExpr, StringRef Shift) { | |||
14173 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | |||
14174 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | |||
14175 | StringRef Op = Bop->getOpcodeStr(); | |||
14176 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | |||
14177 | << Bop->getSourceRange() << OpLoc << Shift << Op; | |||
14178 | SuggestParentheses(S, Bop->getOperatorLoc(), | |||
14179 | S.PDiag(diag::note_precedence_silence) << Op, | |||
14180 | Bop->getSourceRange()); | |||
14181 | } | |||
14182 | } | |||
14183 | } | |||
14184 | ||||
14185 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | |||
14186 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14187 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | |||
14188 | if (!OCE) | |||
14189 | return; | |||
14190 | ||||
14191 | FunctionDecl *FD = OCE->getDirectCallee(); | |||
14192 | if (!FD || !FD->isOverloadedOperator()) | |||
14193 | return; | |||
14194 | ||||
14195 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | |||
14196 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | |||
14197 | return; | |||
14198 | ||||
14199 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | |||
14200 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | |||
14201 | << (Kind == OO_LessLess); | |||
14202 | SuggestParentheses(S, OCE->getOperatorLoc(), | |||
14203 | S.PDiag(diag::note_precedence_silence) | |||
14204 | << (Kind == OO_LessLess ? "<<" : ">>"), | |||
14205 | OCE->getSourceRange()); | |||
14206 | SuggestParentheses( | |||
14207 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | |||
14208 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | |||
14209 | } | |||
14210 | ||||
14211 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | |||
14212 | /// precedence. | |||
14213 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | |||
14214 | SourceLocation OpLoc, Expr *LHSExpr, | |||
14215 | Expr *RHSExpr){ | |||
14216 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | |||
14217 | if (BinaryOperator::isBitwiseOp(Opc)) | |||
14218 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | |||
14219 | ||||
14220 | // Diagnose "arg1 & arg2 | arg3" | |||
14221 | if ((Opc == BO_Or || Opc == BO_Xor) && | |||
14222 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | |||
14223 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | |||
14224 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | |||
14225 | } | |||
14226 | ||||
14227 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | |||
14228 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | |||
14229 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | |||
14230 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | |||
14231 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | |||
14232 | } | |||
14233 | ||||
14234 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | |||
14235 | || Opc == BO_Shr) { | |||
14236 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | |||
14237 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | |||
14238 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | |||
14239 | } | |||
14240 | ||||
14241 | // Warn on overloaded shift operators and comparisons, such as: | |||
14242 | // cout << 5 == 4; | |||
14243 | if (BinaryOperator::isComparisonOp(Opc)) | |||
14244 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | |||
14245 | } | |||
14246 | ||||
14247 | // Binary Operators. 'Tok' is the token for the operator. | |||
14248 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | |||
14249 | tok::TokenKind Kind, | |||
14250 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14251 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | |||
14252 | assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression") ? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14252, __PRETTY_FUNCTION__)); | |||
14253 | assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression" ) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14253, __PRETTY_FUNCTION__)); | |||
14254 | ||||
14255 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | |||
14256 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | |||
14257 | ||||
14258 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | |||
14259 | } | |||
14260 | ||||
14261 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | |||
14262 | UnresolvedSetImpl &Functions) { | |||
14263 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | |||
14264 | if (OverOp != OO_None && OverOp != OO_Equal) | |||
14265 | LookupOverloadedOperatorName(OverOp, S, Functions); | |||
14266 | ||||
14267 | // In C++20 onwards, we may have a second operator to look up. | |||
14268 | if (getLangOpts().CPlusPlus20) { | |||
14269 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | |||
14270 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | |||
14271 | } | |||
14272 | } | |||
14273 | ||||
14274 | /// Build an overloaded binary operator expression in the given scope. | |||
14275 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | |||
14276 | BinaryOperatorKind Opc, | |||
14277 | Expr *LHS, Expr *RHS) { | |||
14278 | switch (Opc) { | |||
14279 | case BO_Assign: | |||
14280 | case BO_DivAssign: | |||
14281 | case BO_RemAssign: | |||
14282 | case BO_SubAssign: | |||
14283 | case BO_AndAssign: | |||
14284 | case BO_OrAssign: | |||
14285 | case BO_XorAssign: | |||
14286 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | |||
14287 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | |||
14288 | break; | |||
14289 | default: | |||
14290 | break; | |||
14291 | } | |||
14292 | ||||
14293 | // Find all of the overloaded operators visible from this point. | |||
14294 | UnresolvedSet<16> Functions; | |||
14295 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | |||
14296 | ||||
14297 | // Build the (potentially-overloaded, potentially-dependent) | |||
14298 | // binary operation. | |||
14299 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | |||
14300 | } | |||
14301 | ||||
14302 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | |||
14303 | BinaryOperatorKind Opc, | |||
14304 | Expr *LHSExpr, Expr *RHSExpr) { | |||
14305 | ExprResult LHS, RHS; | |||
14306 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | |||
14307 | if (!LHS.isUsable() || !RHS.isUsable()) | |||
14308 | return ExprError(); | |||
14309 | LHSExpr = LHS.get(); | |||
14310 | RHSExpr = RHS.get(); | |||
14311 | ||||
14312 | // We want to end up calling one of checkPseudoObjectAssignment | |||
14313 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | |||
14314 | // both expressions are overloadable or either is type-dependent), | |||
14315 | // or CreateBuiltinBinOp (in any other case). We also want to get | |||
14316 | // any placeholder types out of the way. | |||
14317 | ||||
14318 | // Handle pseudo-objects in the LHS. | |||
14319 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | |||
14320 | // Assignments with a pseudo-object l-value need special analysis. | |||
14321 | if (pty->getKind() == BuiltinType::PseudoObject && | |||
14322 | BinaryOperator::isAssignmentOp(Opc)) | |||
14323 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14324 | ||||
14325 | // Don't resolve overloads if the other type is overloadable. | |||
14326 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | |||
14327 | // We can't actually test that if we still have a placeholder, | |||
14328 | // though. Fortunately, none of the exceptions we see in that | |||
14329 | // code below are valid when the LHS is an overload set. Note | |||
14330 | // that an overload set can be dependently-typed, but it never | |||
14331 | // instantiates to having an overloadable type. | |||
14332 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | |||
14333 | if (resolvedRHS.isInvalid()) return ExprError(); | |||
14334 | RHSExpr = resolvedRHS.get(); | |||
14335 | ||||
14336 | if (RHSExpr->isTypeDependent() || | |||
14337 | RHSExpr->getType()->isOverloadableType()) | |||
14338 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14339 | } | |||
14340 | ||||
14341 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | |||
14342 | // template, diagnose the missing 'template' keyword instead of diagnosing | |||
14343 | // an invalid use of a bound member function. | |||
14344 | // | |||
14345 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | |||
14346 | // to C++1z [over.over]/1.4, but we already checked for that case above. | |||
14347 | if (Opc == BO_LT && inTemplateInstantiation() && | |||
14348 | (pty->getKind() == BuiltinType::BoundMember || | |||
14349 | pty->getKind() == BuiltinType::Overload)) { | |||
14350 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | |||
14351 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | |||
14352 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | |||
14353 | return isa<FunctionTemplateDecl>(ND); | |||
14354 | })) { | |||
14355 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | |||
14356 | : OE->getNameLoc(), | |||
14357 | diag::err_template_kw_missing) | |||
14358 | << OE->getName().getAsString() << ""; | |||
14359 | return ExprError(); | |||
14360 | } | |||
14361 | } | |||
14362 | ||||
14363 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | |||
14364 | if (LHS.isInvalid()) return ExprError(); | |||
14365 | LHSExpr = LHS.get(); | |||
14366 | } | |||
14367 | ||||
14368 | // Handle pseudo-objects in the RHS. | |||
14369 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | |||
14370 | // An overload in the RHS can potentially be resolved by the type | |||
14371 | // being assigned to. | |||
14372 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | |||
14373 | if (getLangOpts().CPlusPlus && | |||
14374 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | |||
14375 | LHSExpr->getType()->isOverloadableType())) | |||
14376 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14377 | ||||
14378 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | |||
14379 | } | |||
14380 | ||||
14381 | // Don't resolve overloads if the other type is overloadable. | |||
14382 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | |||
14383 | LHSExpr->getType()->isOverloadableType()) | |||
14384 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14385 | ||||
14386 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | |||
14387 | if (!resolvedRHS.isUsable()) return ExprError(); | |||
14388 | RHSExpr = resolvedRHS.get(); | |||
14389 | } | |||
14390 | ||||
14391 | if (getLangOpts().CPlusPlus) { | |||
14392 | // If either expression is type-dependent, always build an | |||
14393 | // overloaded op. | |||
14394 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | |||
14395 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14396 | ||||
14397 | // Otherwise, build an overloaded op if either expression has an | |||
14398 | // overloadable type. | |||
14399 | if (LHSExpr->getType()->isOverloadableType() || | |||
14400 | RHSExpr->getType()->isOverloadableType()) | |||
14401 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | |||
14402 | } | |||
14403 | ||||
14404 | if (getLangOpts().RecoveryAST && | |||
14405 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | |||
14406 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14406, __PRETTY_FUNCTION__)); | |||
14407 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14408, __PRETTY_FUNCTION__)) | |||
14408 | "Should only occur in error-recovery path.")(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14408, __PRETTY_FUNCTION__)); | |||
14409 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | |||
14410 | // C [6.15.16] p3: | |||
14411 | // An assignment expression has the value of the left operand after the | |||
14412 | // assignment, but is not an lvalue. | |||
14413 | return CompoundAssignOperator::Create( | |||
14414 | Context, LHSExpr, RHSExpr, Opc, | |||
14415 | LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, | |||
14416 | OpLoc, CurFPFeatureOverrides()); | |||
14417 | QualType ResultType; | |||
14418 | switch (Opc) { | |||
14419 | case BO_Assign: | |||
14420 | ResultType = LHSExpr->getType().getUnqualifiedType(); | |||
14421 | break; | |||
14422 | case BO_LT: | |||
14423 | case BO_GT: | |||
14424 | case BO_LE: | |||
14425 | case BO_GE: | |||
14426 | case BO_EQ: | |||
14427 | case BO_NE: | |||
14428 | case BO_LAnd: | |||
14429 | case BO_LOr: | |||
14430 | // These operators have a fixed result type regardless of operands. | |||
14431 | ResultType = Context.IntTy; | |||
14432 | break; | |||
14433 | case BO_Comma: | |||
14434 | ResultType = RHSExpr->getType(); | |||
14435 | break; | |||
14436 | default: | |||
14437 | ResultType = Context.DependentTy; | |||
14438 | break; | |||
14439 | } | |||
14440 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | |||
14441 | VK_RValue, OK_Ordinary, OpLoc, | |||
14442 | CurFPFeatureOverrides()); | |||
14443 | } | |||
14444 | ||||
14445 | // Build a built-in binary operation. | |||
14446 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | |||
14447 | } | |||
14448 | ||||
14449 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | |||
14450 | if (T.isNull() || T->isDependentType()) | |||
14451 | return false; | |||
14452 | ||||
14453 | if (!T->isPromotableIntegerType()) | |||
14454 | return true; | |||
14455 | ||||
14456 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | |||
14457 | } | |||
14458 | ||||
14459 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | |||
14460 | UnaryOperatorKind Opc, | |||
14461 | Expr *InputExpr) { | |||
14462 | ExprResult Input = InputExpr; | |||
14463 | ExprValueKind VK = VK_RValue; | |||
14464 | ExprObjectKind OK = OK_Ordinary; | |||
14465 | QualType resultType; | |||
14466 | bool CanOverflow = false; | |||
14467 | ||||
14468 | bool ConvertHalfVec = false; | |||
14469 | if (getLangOpts().OpenCL) { | |||
14470 | QualType Ty = InputExpr->getType(); | |||
14471 | // The only legal unary operation for atomics is '&'. | |||
14472 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | |||
14473 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | |||
14474 | // only with a builtin functions and therefore should be disallowed here. | |||
14475 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | |||
14476 | || Ty->isBlockPointerType())) { | |||
14477 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14478 | << InputExpr->getType() | |||
14479 | << Input.get()->getSourceRange()); | |||
14480 | } | |||
14481 | } | |||
14482 | ||||
14483 | switch (Opc) { | |||
14484 | case UO_PreInc: | |||
14485 | case UO_PreDec: | |||
14486 | case UO_PostInc: | |||
14487 | case UO_PostDec: | |||
14488 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | |||
14489 | OpLoc, | |||
14490 | Opc == UO_PreInc || | |||
14491 | Opc == UO_PostInc, | |||
14492 | Opc == UO_PreInc || | |||
14493 | Opc == UO_PreDec); | |||
14494 | CanOverflow = isOverflowingIntegerType(Context, resultType); | |||
14495 | break; | |||
14496 | case UO_AddrOf: | |||
14497 | resultType = CheckAddressOfOperand(Input, OpLoc); | |||
14498 | CheckAddressOfNoDeref(InputExpr); | |||
14499 | RecordModifiableNonNullParam(*this, InputExpr); | |||
14500 | break; | |||
14501 | case UO_Deref: { | |||
14502 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | |||
14503 | if (Input.isInvalid()) return ExprError(); | |||
14504 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | |||
14505 | break; | |||
14506 | } | |||
14507 | case UO_Plus: | |||
14508 | case UO_Minus: | |||
14509 | CanOverflow = Opc == UO_Minus && | |||
14510 | isOverflowingIntegerType(Context, Input.get()->getType()); | |||
14511 | Input = UsualUnaryConversions(Input.get()); | |||
14512 | if (Input.isInvalid()) return ExprError(); | |||
14513 | // Unary plus and minus require promoting an operand of half vector to a | |||
14514 | // float vector and truncating the result back to a half vector. For now, we | |||
14515 | // do this only when HalfArgsAndReturns is set (that is, when the target is | |||
14516 | // arm or arm64). | |||
14517 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | |||
14518 | ||||
14519 | // If the operand is a half vector, promote it to a float vector. | |||
14520 | if (ConvertHalfVec) | |||
14521 | Input = convertVector(Input.get(), Context.FloatTy, *this); | |||
14522 | resultType = Input.get()->getType(); | |||
14523 | if (resultType->isDependentType()) | |||
14524 | break; | |||
14525 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | |||
14526 | break; | |||
14527 | else if (resultType->isVectorType() && | |||
14528 | // The z vector extensions don't allow + or - with bool vectors. | |||
14529 | (!Context.getLangOpts().ZVector || | |||
14530 | resultType->castAs<VectorType>()->getVectorKind() != | |||
14531 | VectorType::AltiVecBool)) | |||
14532 | break; | |||
14533 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | |||
14534 | Opc == UO_Plus && | |||
14535 | resultType->isPointerType()) | |||
14536 | break; | |||
14537 | ||||
14538 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14539 | << resultType << Input.get()->getSourceRange()); | |||
14540 | ||||
14541 | case UO_Not: // bitwise complement | |||
14542 | Input = UsualUnaryConversions(Input.get()); | |||
14543 | if (Input.isInvalid()) | |||
14544 | return ExprError(); | |||
14545 | resultType = Input.get()->getType(); | |||
14546 | if (resultType->isDependentType()) | |||
14547 | break; | |||
14548 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | |||
14549 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | |||
14550 | // C99 does not support '~' for complex conjugation. | |||
14551 | Diag(OpLoc, diag::ext_integer_complement_complex) | |||
14552 | << resultType << Input.get()->getSourceRange(); | |||
14553 | else if (resultType->hasIntegerRepresentation()) | |||
14554 | break; | |||
14555 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | |||
14556 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | |||
14557 | // on vector float types. | |||
14558 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | |||
14559 | if (!T->isIntegerType()) | |||
14560 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14561 | << resultType << Input.get()->getSourceRange()); | |||
14562 | } else { | |||
14563 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14564 | << resultType << Input.get()->getSourceRange()); | |||
14565 | } | |||
14566 | break; | |||
14567 | ||||
14568 | case UO_LNot: // logical negation | |||
14569 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | |||
14570 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | |||
14571 | if (Input.isInvalid()) return ExprError(); | |||
14572 | resultType = Input.get()->getType(); | |||
14573 | ||||
14574 | // Though we still have to promote half FP to float... | |||
14575 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | |||
14576 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | |||
14577 | resultType = Context.FloatTy; | |||
14578 | } | |||
14579 | ||||
14580 | if (resultType->isDependentType()) | |||
14581 | break; | |||
14582 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | |||
14583 | // C99 6.5.3.3p1: ok, fallthrough; | |||
14584 | if (Context.getLangOpts().CPlusPlus) { | |||
14585 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | |||
14586 | // operand contextually converted to bool. | |||
14587 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | |||
14588 | ScalarTypeToBooleanCastKind(resultType)); | |||
14589 | } else if (Context.getLangOpts().OpenCL && | |||
14590 | Context.getLangOpts().OpenCLVersion < 120) { | |||
14591 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | |||
14592 | // operate on scalar float types. | |||
14593 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | |||
14594 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14595 | << resultType << Input.get()->getSourceRange()); | |||
14596 | } | |||
14597 | } else if (resultType->isExtVectorType()) { | |||
14598 | if (Context.getLangOpts().OpenCL && | |||
14599 | Context.getLangOpts().OpenCLVersion < 120 && | |||
14600 | !Context.getLangOpts().OpenCLCPlusPlus) { | |||
14601 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | |||
14602 | // operate on vector float types. | |||
14603 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | |||
14604 | if (!T->isIntegerType()) | |||
14605 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14606 | << resultType << Input.get()->getSourceRange()); | |||
14607 | } | |||
14608 | // Vector logical not returns the signed variant of the operand type. | |||
14609 | resultType = GetSignedVectorType(resultType); | |||
14610 | break; | |||
14611 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | |||
14612 | const VectorType *VTy = resultType->castAs<VectorType>(); | |||
14613 | if (VTy->getVectorKind() != VectorType::GenericVector) | |||
14614 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14615 | << resultType << Input.get()->getSourceRange()); | |||
14616 | ||||
14617 | // Vector logical not returns the signed variant of the operand type. | |||
14618 | resultType = GetSignedVectorType(resultType); | |||
14619 | break; | |||
14620 | } else { | |||
14621 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | |||
14622 | << resultType << Input.get()->getSourceRange()); | |||
14623 | } | |||
14624 | ||||
14625 | // LNot always has type int. C99 6.5.3.3p5. | |||
14626 | // In C++, it's bool. C++ 5.3.1p8 | |||
14627 | resultType = Context.getLogicalOperationType(); | |||
14628 | break; | |||
14629 | case UO_Real: | |||
14630 | case UO_Imag: | |||
14631 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | |||
14632 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | |||
14633 | // complex l-values to ordinary l-values and all other values to r-values. | |||
14634 | if (Input.isInvalid()) return ExprError(); | |||
14635 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | |||
14636 | if (Input.get()->getValueKind() != VK_RValue && | |||
14637 | Input.get()->getObjectKind() == OK_Ordinary) | |||
14638 | VK = Input.get()->getValueKind(); | |||
14639 | } else if (!getLangOpts().CPlusPlus) { | |||
14640 | // In C, a volatile scalar is read by __imag. In C++, it is not. | |||
14641 | Input = DefaultLvalueConversion(Input.get()); | |||
14642 | } | |||
14643 | break; | |||
14644 | case UO_Extension: | |||
14645 | resultType = Input.get()->getType(); | |||
14646 | VK = Input.get()->getValueKind(); | |||
14647 | OK = Input.get()->getObjectKind(); | |||
14648 | break; | |||
14649 | case UO_Coawait: | |||
14650 | // It's unnecessary to represent the pass-through operator co_await in the | |||
14651 | // AST; just return the input expression instead. | |||
14652 | assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14654, __PRETTY_FUNCTION__)) | |||
14653 | "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14654, __PRETTY_FUNCTION__)) | |||
14654 | "building operator co_await")((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14654, __PRETTY_FUNCTION__)); | |||
14655 | return Input; | |||
14656 | } | |||
14657 | if (resultType.isNull() || Input.isInvalid()) | |||
14658 | return ExprError(); | |||
14659 | ||||
14660 | // Check for array bounds violations in the operand of the UnaryOperator, | |||
14661 | // except for the '*' and '&' operators that have to be handled specially | |||
14662 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | |||
14663 | // that are explicitly defined as valid by the standard). | |||
14664 | if (Opc != UO_AddrOf && Opc != UO_Deref) | |||
14665 | CheckArrayAccess(Input.get()); | |||
14666 | ||||
14667 | auto *UO = | |||
14668 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | |||
14669 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | |||
14670 | ||||
14671 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | |||
14672 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | |||
14673 | !isUnevaluatedContext()) | |||
14674 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | |||
14675 | ||||
14676 | // Convert the result back to a half vector. | |||
14677 | if (ConvertHalfVec) | |||
14678 | return convertVector(UO, Context.HalfTy, *this); | |||
14679 | return UO; | |||
14680 | } | |||
14681 | ||||
14682 | /// Determine whether the given expression is a qualified member | |||
14683 | /// access expression, of a form that could be turned into a pointer to member | |||
14684 | /// with the address-of operator. | |||
14685 | bool Sema::isQualifiedMemberAccess(Expr *E) { | |||
14686 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
14687 | if (!DRE->getQualifier()) | |||
14688 | return false; | |||
14689 | ||||
14690 | ValueDecl *VD = DRE->getDecl(); | |||
14691 | if (!VD->isCXXClassMember()) | |||
14692 | return false; | |||
14693 | ||||
14694 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | |||
14695 | return true; | |||
14696 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | |||
14697 | return Method->isInstance(); | |||
14698 | ||||
14699 | return false; | |||
14700 | } | |||
14701 | ||||
14702 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | |||
14703 | if (!ULE->getQualifier()) | |||
14704 | return false; | |||
14705 | ||||
14706 | for (NamedDecl *D : ULE->decls()) { | |||
14707 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | |||
14708 | if (Method->isInstance()) | |||
14709 | return true; | |||
14710 | } else { | |||
14711 | // Overload set does not contain methods. | |||
14712 | break; | |||
14713 | } | |||
14714 | } | |||
14715 | ||||
14716 | return false; | |||
14717 | } | |||
14718 | ||||
14719 | return false; | |||
14720 | } | |||
14721 | ||||
14722 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | |||
14723 | UnaryOperatorKind Opc, Expr *Input) { | |||
14724 | // First things first: handle placeholders so that the | |||
14725 | // overloaded-operator check considers the right type. | |||
14726 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | |||
14727 | // Increment and decrement of pseudo-object references. | |||
14728 | if (pty->getKind() == BuiltinType::PseudoObject && | |||
14729 | UnaryOperator::isIncrementDecrementOp(Opc)) | |||
14730 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | |||
14731 | ||||
14732 | // extension is always a builtin operator. | |||
14733 | if (Opc == UO_Extension) | |||
14734 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
14735 | ||||
14736 | // & gets special logic for several kinds of placeholder. | |||
14737 | // The builtin code knows what to do. | |||
14738 | if (Opc == UO_AddrOf && | |||
14739 | (pty->getKind() == BuiltinType::Overload || | |||
14740 | pty->getKind() == BuiltinType::UnknownAny || | |||
14741 | pty->getKind() == BuiltinType::BoundMember)) | |||
14742 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
14743 | ||||
14744 | // Anything else needs to be handled now. | |||
14745 | ExprResult Result = CheckPlaceholderExpr(Input); | |||
14746 | if (Result.isInvalid()) return ExprError(); | |||
14747 | Input = Result.get(); | |||
14748 | } | |||
14749 | ||||
14750 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | |||
14751 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | |||
14752 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | |||
14753 | // Find all of the overloaded operators visible from this point. | |||
14754 | UnresolvedSet<16> Functions; | |||
14755 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | |||
14756 | if (S && OverOp != OO_None) | |||
14757 | LookupOverloadedOperatorName(OverOp, S, Functions); | |||
14758 | ||||
14759 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | |||
14760 | } | |||
14761 | ||||
14762 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
14763 | } | |||
14764 | ||||
14765 | // Unary Operators. 'Tok' is the token for the operator. | |||
14766 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | |||
14767 | tok::TokenKind Op, Expr *Input) { | |||
14768 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | |||
14769 | } | |||
14770 | ||||
14771 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | |||
14772 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | |||
14773 | LabelDecl *TheDecl) { | |||
14774 | TheDecl->markUsed(Context); | |||
14775 | // Create the AST node. The address of a label always has type 'void*'. | |||
14776 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | |||
14777 | Context.getPointerType(Context.VoidTy)); | |||
14778 | } | |||
14779 | ||||
14780 | void Sema::ActOnStartStmtExpr() { | |||
14781 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | |||
14782 | } | |||
14783 | ||||
14784 | void Sema::ActOnStmtExprError() { | |||
14785 | // Note that function is also called by TreeTransform when leaving a | |||
14786 | // StmtExpr scope without rebuilding anything. | |||
14787 | ||||
14788 | DiscardCleanupsInEvaluationContext(); | |||
14789 | PopExpressionEvaluationContext(); | |||
14790 | } | |||
14791 | ||||
14792 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | |||
14793 | SourceLocation RPLoc) { | |||
14794 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | |||
14795 | } | |||
14796 | ||||
14797 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | |||
14798 | SourceLocation RPLoc, unsigned TemplateDepth) { | |||
14799 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!") ? static_cast<void> (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14799, __PRETTY_FUNCTION__)); | |||
14800 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | |||
14801 | ||||
14802 | if (hasAnyUnrecoverableErrorsInThisFunction()) | |||
14803 | DiscardCleanupsInEvaluationContext(); | |||
14804 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14805, __PRETTY_FUNCTION__)) | |||
14805 | "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 14805, __PRETTY_FUNCTION__)); | |||
14806 | PopExpressionEvaluationContext(); | |||
14807 | ||||
14808 | // FIXME: there are a variety of strange constraints to enforce here, for | |||
14809 | // example, it is not possible to goto into a stmt expression apparently. | |||
14810 | // More semantic analysis is needed. | |||
14811 | ||||
14812 | // If there are sub-stmts in the compound stmt, take the type of the last one | |||
14813 | // as the type of the stmtexpr. | |||
14814 | QualType Ty = Context.VoidTy; | |||
14815 | bool StmtExprMayBindToTemp = false; | |||
14816 | if (!Compound->body_empty()) { | |||
14817 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | |||
14818 | if (const auto *LastStmt = | |||
14819 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | |||
14820 | if (const Expr *Value = LastStmt->getExprStmt()) { | |||
14821 | StmtExprMayBindToTemp = true; | |||
14822 | Ty = Value->getType(); | |||
14823 | } | |||
14824 | } | |||
14825 | } | |||
14826 | ||||
14827 | // FIXME: Check that expression type is complete/non-abstract; statement | |||
14828 | // expressions are not lvalues. | |||
14829 | Expr *ResStmtExpr = | |||
14830 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | |||
14831 | if (StmtExprMayBindToTemp) | |||
14832 | return MaybeBindToTemporary(ResStmtExpr); | |||
14833 | return ResStmtExpr; | |||
14834 | } | |||
14835 | ||||
14836 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | |||
14837 | if (ER.isInvalid()) | |||
14838 | return ExprError(); | |||
14839 | ||||
14840 | // Do function/array conversion on the last expression, but not | |||
14841 | // lvalue-to-rvalue. However, initialize an unqualified type. | |||
14842 | ER = DefaultFunctionArrayConversion(ER.get()); | |||
14843 | if (ER.isInvalid()) | |||
14844 | return ExprError(); | |||
14845 | Expr *E = ER.get(); | |||
14846 | ||||
14847 | if (E->isTypeDependent()) | |||
14848 | return E; | |||
14849 | ||||
14850 | // In ARC, if the final expression ends in a consume, splice | |||
14851 | // the consume out and bind it later. In the alternate case | |||
14852 | // (when dealing with a retainable type), the result | |||
14853 | // initialization will create a produce. In both cases the | |||
14854 | // result will be +1, and we'll need to balance that out with | |||
14855 | // a bind. | |||
14856 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | |||
14857 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | |||
14858 | return Cast->getSubExpr(); | |||
14859 | ||||
14860 | // FIXME: Provide a better location for the initialization. | |||
14861 | return PerformCopyInitialization( | |||
14862 | InitializedEntity::InitializeStmtExprResult( | |||
14863 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | |||
14864 | SourceLocation(), E); | |||
14865 | } | |||
14866 | ||||
14867 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | |||
14868 | TypeSourceInfo *TInfo, | |||
14869 | ArrayRef<OffsetOfComponent> Components, | |||
14870 | SourceLocation RParenLoc) { | |||
14871 | QualType ArgTy = TInfo->getType(); | |||
14872 | bool Dependent = ArgTy->isDependentType(); | |||
14873 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | |||
14874 | ||||
14875 | // We must have at least one component that refers to the type, and the first | |||
14876 | // one is known to be a field designator. Verify that the ArgTy represents | |||
14877 | // a struct/union/class. | |||
14878 | if (!Dependent && !ArgTy->isRecordType()) | |||
14879 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | |||
14880 | << ArgTy << TypeRange); | |||
14881 | ||||
14882 | // Type must be complete per C99 7.17p3 because a declaring a variable | |||
14883 | // with an incomplete type would be ill-formed. | |||
14884 | if (!Dependent | |||
14885 | && RequireCompleteType(BuiltinLoc, ArgTy, | |||
14886 | diag::err_offsetof_incomplete_type, TypeRange)) | |||
14887 | return ExprError(); | |||
14888 | ||||
14889 | bool DidWarnAboutNonPOD = false; | |||
14890 | QualType CurrentType = ArgTy; | |||
14891 | SmallVector<OffsetOfNode, 4> Comps; | |||
14892 | SmallVector<Expr*, 4> Exprs; | |||
14893 | for (const OffsetOfComponent &OC : Components) { | |||
14894 | if (OC.isBrackets) { | |||
14895 | // Offset of an array sub-field. TODO: Should we allow vector elements? | |||
14896 | if (!CurrentType->isDependentType()) { | |||
14897 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | |||
14898 | if(!AT) | |||
14899 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | |||
14900 | << CurrentType); | |||
14901 | CurrentType = AT->getElementType(); | |||
14902 | } else | |||
14903 | CurrentType = Context.DependentTy; | |||
14904 | ||||
14905 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | |||
14906 | if (IdxRval.isInvalid()) | |||
14907 | return ExprError(); | |||
14908 | Expr *Idx = IdxRval.get(); | |||
14909 | ||||
14910 | // The expression must be an integral expression. | |||
14911 | // FIXME: An integral constant expression? | |||
14912 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | |||
14913 | !Idx->getType()->isIntegerType()) | |||
14914 | return ExprError( | |||
14915 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | |||
14916 | << Idx->getSourceRange()); | |||
14917 | ||||
14918 | // Record this array index. | |||
14919 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | |||
14920 | Exprs.push_back(Idx); | |||
14921 | continue; | |||
14922 | } | |||
14923 | ||||
14924 | // Offset of a field. | |||
14925 | if (CurrentType->isDependentType()) { | |||
14926 | // We have the offset of a field, but we can't look into the dependent | |||
14927 | // type. Just record the identifier of the field. | |||
14928 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | |||
14929 | CurrentType = Context.DependentTy; | |||
14930 | continue; | |||
14931 | } | |||
14932 | ||||
14933 | // We need to have a complete type to look into. | |||
14934 | if (RequireCompleteType(OC.LocStart, CurrentType, | |||
14935 | diag::err_offsetof_incomplete_type)) | |||
14936 | return ExprError(); | |||
14937 | ||||
14938 | // Look for the designated field. | |||
14939 | const RecordType *RC = CurrentType->getAs<RecordType>(); | |||
14940 | if (!RC) | |||
14941 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | |||
14942 | << CurrentType); | |||
14943 | RecordDecl *RD = RC->getDecl(); | |||
14944 | ||||
14945 | // C++ [lib.support.types]p5: | |||
14946 | // The macro offsetof accepts a restricted set of type arguments in this | |||
14947 | // International Standard. type shall be a POD structure or a POD union | |||
14948 | // (clause 9). | |||
14949 | // C++11 [support.types]p4: | |||
14950 | // If type is not a standard-layout class (Clause 9), the results are | |||
14951 | // undefined. | |||
14952 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | |||
14953 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | |||
14954 | unsigned DiagID = | |||
14955 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | |||
14956 | : diag::ext_offsetof_non_pod_type; | |||
14957 | ||||
14958 | if (!IsSafe && !DidWarnAboutNonPOD && | |||
14959 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | |||
14960 | PDiag(DiagID) | |||
14961 | << SourceRange(Components[0].LocStart, OC.LocEnd) | |||
14962 | << CurrentType)) | |||
14963 | DidWarnAboutNonPOD = true; | |||
14964 | } | |||
14965 | ||||
14966 | // Look for the field. | |||
14967 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | |||
14968 | LookupQualifiedName(R, RD); | |||
14969 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | |||
14970 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | |||
14971 | if (!MemberDecl) { | |||
14972 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | |||
14973 | MemberDecl = IndirectMemberDecl->getAnonField(); | |||
14974 | } | |||
14975 | ||||
14976 | if (!MemberDecl) | |||
14977 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | |||
14978 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | |||
14979 | OC.LocEnd)); | |||
14980 | ||||
14981 | // C99 7.17p3: | |||
14982 | // (If the specified member is a bit-field, the behavior is undefined.) | |||
14983 | // | |||
14984 | // We diagnose this as an error. | |||
14985 | if (MemberDecl->isBitField()) { | |||
14986 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | |||
14987 | << MemberDecl->getDeclName() | |||
14988 | << SourceRange(BuiltinLoc, RParenLoc); | |||
14989 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | |||
14990 | return ExprError(); | |||
14991 | } | |||
14992 | ||||
14993 | RecordDecl *Parent = MemberDecl->getParent(); | |||
14994 | if (IndirectMemberDecl) | |||
14995 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | |||
14996 | ||||
14997 | // If the member was found in a base class, introduce OffsetOfNodes for | |||
14998 | // the base class indirections. | |||
14999 | CXXBasePaths Paths; | |||
15000 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | |||
15001 | Paths)) { | |||
15002 | if (Paths.getDetectedVirtual()) { | |||
15003 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | |||
15004 | << MemberDecl->getDeclName() | |||
15005 | << SourceRange(BuiltinLoc, RParenLoc); | |||
15006 | return ExprError(); | |||
15007 | } | |||
15008 | ||||
15009 | CXXBasePath &Path = Paths.front(); | |||
15010 | for (const CXXBasePathElement &B : Path) | |||
15011 | Comps.push_back(OffsetOfNode(B.Base)); | |||
15012 | } | |||
15013 | ||||
15014 | if (IndirectMemberDecl) { | |||
15015 | for (auto *FI : IndirectMemberDecl->chain()) { | |||
15016 | assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15016, __PRETTY_FUNCTION__)); | |||
15017 | Comps.push_back(OffsetOfNode(OC.LocStart, | |||
15018 | cast<FieldDecl>(FI), OC.LocEnd)); | |||
15019 | } | |||
15020 | } else | |||
15021 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | |||
15022 | ||||
15023 | CurrentType = MemberDecl->getType().getNonReferenceType(); | |||
15024 | } | |||
15025 | ||||
15026 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | |||
15027 | Comps, Exprs, RParenLoc); | |||
15028 | } | |||
15029 | ||||
15030 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | |||
15031 | SourceLocation BuiltinLoc, | |||
15032 | SourceLocation TypeLoc, | |||
15033 | ParsedType ParsedArgTy, | |||
15034 | ArrayRef<OffsetOfComponent> Components, | |||
15035 | SourceLocation RParenLoc) { | |||
15036 | ||||
15037 | TypeSourceInfo *ArgTInfo; | |||
15038 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | |||
15039 | if (ArgTy.isNull()) | |||
15040 | return ExprError(); | |||
15041 | ||||
15042 | if (!ArgTInfo) | |||
15043 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | |||
15044 | ||||
15045 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | |||
15046 | } | |||
15047 | ||||
15048 | ||||
15049 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | |||
15050 | Expr *CondExpr, | |||
15051 | Expr *LHSExpr, Expr *RHSExpr, | |||
15052 | SourceLocation RPLoc) { | |||
15053 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? static_cast<void> (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15053, __PRETTY_FUNCTION__)); | |||
15054 | ||||
15055 | ExprValueKind VK = VK_RValue; | |||
15056 | ExprObjectKind OK = OK_Ordinary; | |||
15057 | QualType resType; | |||
15058 | bool CondIsTrue = false; | |||
15059 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | |||
15060 | resType = Context.DependentTy; | |||
15061 | } else { | |||
15062 | // The conditional expression is required to be a constant expression. | |||
15063 | llvm::APSInt condEval(32); | |||
15064 | ExprResult CondICE = VerifyIntegerConstantExpression( | |||
15065 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | |||
15066 | if (CondICE.isInvalid()) | |||
15067 | return ExprError(); | |||
15068 | CondExpr = CondICE.get(); | |||
15069 | CondIsTrue = condEval.getZExtValue(); | |||
15070 | ||||
15071 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | |||
15072 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | |||
15073 | ||||
15074 | resType = ActiveExpr->getType(); | |||
15075 | VK = ActiveExpr->getValueKind(); | |||
15076 | OK = ActiveExpr->getObjectKind(); | |||
15077 | } | |||
15078 | ||||
15079 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | |||
15080 | resType, VK, OK, RPLoc, CondIsTrue); | |||
15081 | } | |||
15082 | ||||
15083 | //===----------------------------------------------------------------------===// | |||
15084 | // Clang Extensions. | |||
15085 | //===----------------------------------------------------------------------===// | |||
15086 | ||||
15087 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | |||
15088 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | |||
15089 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | |||
15090 | ||||
15091 | if (LangOpts.CPlusPlus) { | |||
15092 | MangleNumberingContext *MCtx; | |||
15093 | Decl *ManglingContextDecl; | |||
15094 | std::tie(MCtx, ManglingContextDecl) = | |||
15095 | getCurrentMangleNumberContext(Block->getDeclContext()); | |||
15096 | if (MCtx) { | |||
15097 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | |||
15098 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | |||
15099 | } | |||
15100 | } | |||
15101 | ||||
15102 | PushBlockScope(CurScope, Block); | |||
15103 | CurContext->addDecl(Block); | |||
15104 | if (CurScope) | |||
15105 | PushDeclContext(CurScope, Block); | |||
15106 | else | |||
15107 | CurContext = Block; | |||
15108 | ||||
15109 | getCurBlock()->HasImplicitReturnType = true; | |||
15110 | ||||
15111 | // Enter a new evaluation context to insulate the block from any | |||
15112 | // cleanups from the enclosing full-expression. | |||
15113 | PushExpressionEvaluationContext( | |||
15114 | ExpressionEvaluationContext::PotentiallyEvaluated); | |||
15115 | } | |||
15116 | ||||
15117 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | |||
15118 | Scope *CurScope) { | |||
15119 | assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15120, __PRETTY_FUNCTION__)) | |||
| ||||
15120 | "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15120, __PRETTY_FUNCTION__)); | |||
15121 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)((ParamInfo.getContext() == DeclaratorContext::BlockLiteral) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15121, __PRETTY_FUNCTION__)); | |||
15122 | BlockScopeInfo *CurBlock = getCurBlock(); | |||
15123 | ||||
15124 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | |||
15125 | QualType T = Sig->getType(); | |||
15126 | ||||
15127 | // FIXME: We should allow unexpanded parameter packs here, but that would, | |||
15128 | // in turn, make the block expression contain unexpanded parameter packs. | |||
15129 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | |||
15130 | // Drop the parameters. | |||
15131 | FunctionProtoType::ExtProtoInfo EPI; | |||
15132 | EPI.HasTrailingReturn = false; | |||
15133 | EPI.TypeQuals.addConst(); | |||
15134 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | |||
15135 | Sig = Context.getTrivialTypeSourceInfo(T); | |||
15136 | } | |||
15137 | ||||
15138 | // GetTypeForDeclarator always produces a function type for a block | |||
15139 | // literal signature. Furthermore, it is always a FunctionProtoType | |||
15140 | // unless the function was written with a typedef. | |||
15141 | assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15142, __PRETTY_FUNCTION__)) | |||
15142 | "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15142, __PRETTY_FUNCTION__)); | |||
15143 | ||||
15144 | // Look for an explicit signature in that function type. | |||
15145 | FunctionProtoTypeLoc ExplicitSignature; | |||
15146 | ||||
15147 | if ((ExplicitSignature = Sig->getTypeLoc() | |||
15148 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | |||
15149 | ||||
15150 | // Check whether that explicit signature was synthesized by | |||
15151 | // GetTypeForDeclarator. If so, don't save that as part of the | |||
15152 | // written signature. | |||
15153 | if (ExplicitSignature.getLocalRangeBegin() == | |||
15154 | ExplicitSignature.getLocalRangeEnd()) { | |||
15155 | // This would be much cheaper if we stored TypeLocs instead of | |||
15156 | // TypeSourceInfos. | |||
15157 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | |||
15158 | unsigned Size = Result.getFullDataSize(); | |||
15159 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | |||
15160 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | |||
15161 | ||||
15162 | ExplicitSignature = FunctionProtoTypeLoc(); | |||
15163 | } | |||
15164 | } | |||
15165 | ||||
15166 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | |||
15167 | CurBlock->FunctionType = T; | |||
15168 | ||||
15169 | const FunctionType *Fn = T->getAs<FunctionType>(); | |||
15170 | QualType RetTy = Fn->getReturnType(); | |||
| ||||
15171 | bool isVariadic = | |||
15172 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | |||
15173 | ||||
15174 | CurBlock->TheDecl->setIsVariadic(isVariadic); | |||
15175 | ||||
15176 | // Context.DependentTy is used as a placeholder for a missing block | |||
15177 | // return type. TODO: what should we do with declarators like: | |||
15178 | // ^ * { ... } | |||
15179 | // If the answer is "apply template argument deduction".... | |||
15180 | if (RetTy != Context.DependentTy) { | |||
15181 | CurBlock->ReturnType = RetTy; | |||
15182 | CurBlock->TheDecl->setBlockMissingReturnType(false); | |||
15183 | CurBlock->HasImplicitReturnType = false; | |||
15184 | } | |||
15185 | ||||
15186 | // Push block parameters from the declarator if we had them. | |||
15187 | SmallVector<ParmVarDecl*, 8> Params; | |||
15188 | if (ExplicitSignature) { | |||
15189 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | |||
15190 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | |||
15191 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | |||
15192 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | |||
15193 | // Diagnose this as an extension in C17 and earlier. | |||
15194 | if (!getLangOpts().C2x) | |||
15195 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | |||
15196 | } | |||
15197 | Params.push_back(Param); | |||
15198 | } | |||
15199 | ||||
15200 | // Fake up parameter variables if we have a typedef, like | |||
15201 | // ^ fntype { ... } | |||
15202 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | |||
15203 | for (const auto &I : Fn->param_types()) { | |||
15204 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | |||
15205 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | |||
15206 | Params.push_back(Param); | |||
15207 | } | |||
15208 | } | |||
15209 | ||||
15210 | // Set the parameters on the block decl. | |||
15211 | if (!Params.empty()) { | |||
15212 | CurBlock->TheDecl->setParams(Params); | |||
15213 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | |||
15214 | /*CheckParameterNames=*/false); | |||
15215 | } | |||
15216 | ||||
15217 | // Finally we can process decl attributes. | |||
15218 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | |||
15219 | ||||
15220 | // Put the parameter variables in scope. | |||
15221 | for (auto AI : CurBlock->TheDecl->parameters()) { | |||
15222 | AI->setOwningFunction(CurBlock->TheDecl); | |||
15223 | ||||
15224 | // If this has an identifier, add it to the scope stack. | |||
15225 | if (AI->getIdentifier()) { | |||
15226 | CheckShadow(CurBlock->TheScope, AI); | |||
15227 | ||||
15228 | PushOnScopeChains(AI, CurBlock->TheScope); | |||
15229 | } | |||
15230 | } | |||
15231 | } | |||
15232 | ||||
15233 | /// ActOnBlockError - If there is an error parsing a block, this callback | |||
15234 | /// is invoked to pop the information about the block from the action impl. | |||
15235 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | |||
15236 | // Leave the expression-evaluation context. | |||
15237 | DiscardCleanupsInEvaluationContext(); | |||
15238 | PopExpressionEvaluationContext(); | |||
15239 | ||||
15240 | // Pop off CurBlock, handle nested blocks. | |||
15241 | PopDeclContext(); | |||
15242 | PopFunctionScopeInfo(); | |||
15243 | } | |||
15244 | ||||
15245 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | |||
15246 | /// literal was successfully completed. ^(int x){...} | |||
15247 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | |||
15248 | Stmt *Body, Scope *CurScope) { | |||
15249 | // If blocks are disabled, emit an error. | |||
15250 | if (!LangOpts.Blocks) | |||
15251 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
15252 | ||||
15253 | // Leave the expression-evaluation context. | |||
15254 | if (hasAnyUnrecoverableErrorsInThisFunction()) | |||
15255 | DiscardCleanupsInEvaluationContext(); | |||
15256 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15257, __PRETTY_FUNCTION__)) | |||
15257 | "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15257, __PRETTY_FUNCTION__)); | |||
15258 | PopExpressionEvaluationContext(); | |||
15259 | ||||
15260 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | |||
15261 | BlockDecl *BD = BSI->TheDecl; | |||
15262 | ||||
15263 | if (BSI->HasImplicitReturnType) | |||
15264 | deduceClosureReturnType(*BSI); | |||
15265 | ||||
15266 | QualType RetTy = Context.VoidTy; | |||
15267 | if (!BSI->ReturnType.isNull()) | |||
15268 | RetTy = BSI->ReturnType; | |||
15269 | ||||
15270 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | |||
15271 | QualType BlockTy; | |||
15272 | ||||
15273 | // If the user wrote a function type in some form, try to use that. | |||
15274 | if (!BSI->FunctionType.isNull()) { | |||
15275 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | |||
15276 | ||||
15277 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | |||
15278 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | |||
15279 | ||||
15280 | // Turn protoless block types into nullary block types. | |||
15281 | if (isa<FunctionNoProtoType>(FTy)) { | |||
15282 | FunctionProtoType::ExtProtoInfo EPI; | |||
15283 | EPI.ExtInfo = Ext; | |||
15284 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | |||
15285 | ||||
15286 | // Otherwise, if we don't need to change anything about the function type, | |||
15287 | // preserve its sugar structure. | |||
15288 | } else if (FTy->getReturnType() == RetTy && | |||
15289 | (!NoReturn || FTy->getNoReturnAttr())) { | |||
15290 | BlockTy = BSI->FunctionType; | |||
15291 | ||||
15292 | // Otherwise, make the minimal modifications to the function type. | |||
15293 | } else { | |||
15294 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | |||
15295 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
15296 | EPI.TypeQuals = Qualifiers(); | |||
15297 | EPI.ExtInfo = Ext; | |||
15298 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | |||
15299 | } | |||
15300 | ||||
15301 | // If we don't have a function type, just build one from nothing. | |||
15302 | } else { | |||
15303 | FunctionProtoType::ExtProtoInfo EPI; | |||
15304 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | |||
15305 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | |||
15306 | } | |||
15307 | ||||
15308 | DiagnoseUnusedParameters(BD->parameters()); | |||
15309 | BlockTy = Context.getBlockPointerType(BlockTy); | |||
15310 | ||||
15311 | // If needed, diagnose invalid gotos and switches in the block. | |||
15312 | if (getCurFunction()->NeedsScopeChecking() && | |||
15313 | !PP.isCodeCompletionEnabled()) | |||
15314 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | |||
15315 | ||||
15316 | BD->setBody(cast<CompoundStmt>(Body)); | |||
15317 | ||||
15318 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | |||
15319 | DiagnoseUnguardedAvailabilityViolations(BD); | |||
15320 | ||||
15321 | // Try to apply the named return value optimization. We have to check again | |||
15322 | // if we can do this, though, because blocks keep return statements around | |||
15323 | // to deduce an implicit return type. | |||
15324 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | |||
15325 | !BD->isDependentContext()) | |||
15326 | computeNRVO(Body, BSI); | |||
15327 | ||||
15328 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | |||
15329 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | |||
15330 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | |||
15331 | NTCUK_Destruct|NTCUK_Copy); | |||
15332 | ||||
15333 | PopDeclContext(); | |||
15334 | ||||
15335 | // Pop the block scope now but keep it alive to the end of this function. | |||
15336 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | |||
15337 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | |||
15338 | ||||
15339 | // Set the captured variables on the block. | |||
15340 | SmallVector<BlockDecl::Capture, 4> Captures; | |||
15341 | for (Capture &Cap : BSI->Captures) { | |||
15342 | if (Cap.isInvalid() || Cap.isThisCapture()) | |||
15343 | continue; | |||
15344 | ||||
15345 | VarDecl *Var = Cap.getVariable(); | |||
15346 | Expr *CopyExpr = nullptr; | |||
15347 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | |||
15348 | if (const RecordType *Record = | |||
15349 | Cap.getCaptureType()->getAs<RecordType>()) { | |||
15350 | // The capture logic needs the destructor, so make sure we mark it. | |||
15351 | // Usually this is unnecessary because most local variables have | |||
15352 | // their destructors marked at declaration time, but parameters are | |||
15353 | // an exception because it's technically only the call site that | |||
15354 | // actually requires the destructor. | |||
15355 | if (isa<ParmVarDecl>(Var)) | |||
15356 | FinalizeVarWithDestructor(Var, Record); | |||
15357 | ||||
15358 | // Enter a separate potentially-evaluated context while building block | |||
15359 | // initializers to isolate their cleanups from those of the block | |||
15360 | // itself. | |||
15361 | // FIXME: Is this appropriate even when the block itself occurs in an | |||
15362 | // unevaluated operand? | |||
15363 | EnterExpressionEvaluationContext EvalContext( | |||
15364 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | |||
15365 | ||||
15366 | SourceLocation Loc = Cap.getLocation(); | |||
15367 | ||||
15368 | ExprResult Result = BuildDeclarationNameExpr( | |||
15369 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | |||
15370 | ||||
15371 | // According to the blocks spec, the capture of a variable from | |||
15372 | // the stack requires a const copy constructor. This is not true | |||
15373 | // of the copy/move done to move a __block variable to the heap. | |||
15374 | if (!Result.isInvalid() && | |||
15375 | !Result.get()->getType().isConstQualified()) { | |||
15376 | Result = ImpCastExprToType(Result.get(), | |||
15377 | Result.get()->getType().withConst(), | |||
15378 | CK_NoOp, VK_LValue); | |||
15379 | } | |||
15380 | ||||
15381 | if (!Result.isInvalid()) { | |||
15382 | Result = PerformCopyInitialization( | |||
15383 | InitializedEntity::InitializeBlock(Var->getLocation(), | |||
15384 | Cap.getCaptureType(), false), | |||
15385 | Loc, Result.get()); | |||
15386 | } | |||
15387 | ||||
15388 | // Build a full-expression copy expression if initialization | |||
15389 | // succeeded and used a non-trivial constructor. Recover from | |||
15390 | // errors by pretending that the copy isn't necessary. | |||
15391 | if (!Result.isInvalid() && | |||
15392 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | |||
15393 | ->isTrivial()) { | |||
15394 | Result = MaybeCreateExprWithCleanups(Result); | |||
15395 | CopyExpr = Result.get(); | |||
15396 | } | |||
15397 | } | |||
15398 | } | |||
15399 | ||||
15400 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | |||
15401 | CopyExpr); | |||
15402 | Captures.push_back(NewCap); | |||
15403 | } | |||
15404 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | |||
15405 | ||||
15406 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | |||
15407 | ||||
15408 | // If the block isn't obviously global, i.e. it captures anything at | |||
15409 | // all, then we need to do a few things in the surrounding context: | |||
15410 | if (Result->getBlockDecl()->hasCaptures()) { | |||
15411 | // First, this expression has a new cleanup object. | |||
15412 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | |||
15413 | Cleanup.setExprNeedsCleanups(true); | |||
15414 | ||||
15415 | // It also gets a branch-protected scope if any of the captured | |||
15416 | // variables needs destruction. | |||
15417 | for (const auto &CI : Result->getBlockDecl()->captures()) { | |||
15418 | const VarDecl *var = CI.getVariable(); | |||
15419 | if (var->getType().isDestructedType() != QualType::DK_none) { | |||
15420 | setFunctionHasBranchProtectedScope(); | |||
15421 | break; | |||
15422 | } | |||
15423 | } | |||
15424 | } | |||
15425 | ||||
15426 | if (getCurFunction()) | |||
15427 | getCurFunction()->addBlock(BD); | |||
15428 | ||||
15429 | return Result; | |||
15430 | } | |||
15431 | ||||
15432 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | |||
15433 | SourceLocation RPLoc) { | |||
15434 | TypeSourceInfo *TInfo; | |||
15435 | GetTypeFromParser(Ty, &TInfo); | |||
15436 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | |||
15437 | } | |||
15438 | ||||
15439 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | |||
15440 | Expr *E, TypeSourceInfo *TInfo, | |||
15441 | SourceLocation RPLoc) { | |||
15442 | Expr *OrigExpr = E; | |||
15443 | bool IsMS = false; | |||
15444 | ||||
15445 | // CUDA device code does not support varargs. | |||
15446 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | |||
15447 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | |||
15448 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | |||
15449 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | |||
15450 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | |||
15451 | } | |||
15452 | } | |||
15453 | ||||
15454 | // NVPTX does not support va_arg expression. | |||
15455 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | |||
15456 | Context.getTargetInfo().getTriple().isNVPTX()) | |||
15457 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | |||
15458 | ||||
15459 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | |||
15460 | // as Microsoft ABI on an actual Microsoft platform, where | |||
15461 | // __builtin_ms_va_list and __builtin_va_list are the same.) | |||
15462 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | |||
15463 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | |||
15464 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | |||
15465 | if (Context.hasSameType(MSVaListType, E->getType())) { | |||
15466 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | |||
15467 | return ExprError(); | |||
15468 | IsMS = true; | |||
15469 | } | |||
15470 | } | |||
15471 | ||||
15472 | // Get the va_list type | |||
15473 | QualType VaListType = Context.getBuiltinVaListType(); | |||
15474 | if (!IsMS) { | |||
15475 | if (VaListType->isArrayType()) { | |||
15476 | // Deal with implicit array decay; for example, on x86-64, | |||
15477 | // va_list is an array, but it's supposed to decay to | |||
15478 | // a pointer for va_arg. | |||
15479 | VaListType = Context.getArrayDecayedType(VaListType); | |||
15480 | // Make sure the input expression also decays appropriately. | |||
15481 | ExprResult Result = UsualUnaryConversions(E); | |||
15482 | if (Result.isInvalid()) | |||
15483 | return ExprError(); | |||
15484 | E = Result.get(); | |||
15485 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | |||
15486 | // If va_list is a record type and we are compiling in C++ mode, | |||
15487 | // check the argument using reference binding. | |||
15488 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | |||
15489 | Context, Context.getLValueReferenceType(VaListType), false); | |||
15490 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | |||
15491 | if (Init.isInvalid()) | |||
15492 | return ExprError(); | |||
15493 | E = Init.getAs<Expr>(); | |||
15494 | } else { | |||
15495 | // Otherwise, the va_list argument must be an l-value because | |||
15496 | // it is modified by va_arg. | |||
15497 | if (!E->isTypeDependent() && | |||
15498 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | |||
15499 | return ExprError(); | |||
15500 | } | |||
15501 | } | |||
15502 | ||||
15503 | if (!IsMS && !E->isTypeDependent() && | |||
15504 | !Context.hasSameType(VaListType, E->getType())) | |||
15505 | return ExprError( | |||
15506 | Diag(E->getBeginLoc(), | |||
15507 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | |||
15508 | << OrigExpr->getType() << E->getSourceRange()); | |||
15509 | ||||
15510 | if (!TInfo->getType()->isDependentType()) { | |||
15511 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | |||
15512 | diag::err_second_parameter_to_va_arg_incomplete, | |||
15513 | TInfo->getTypeLoc())) | |||
15514 | return ExprError(); | |||
15515 | ||||
15516 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | |||
15517 | TInfo->getType(), | |||
15518 | diag::err_second_parameter_to_va_arg_abstract, | |||
15519 | TInfo->getTypeLoc())) | |||
15520 | return ExprError(); | |||
15521 | ||||
15522 | if (!TInfo->getType().isPODType(Context)) { | |||
15523 | Diag(TInfo->getTypeLoc().getBeginLoc(), | |||
15524 | TInfo->getType()->isObjCLifetimeType() | |||
15525 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | |||
15526 | : diag::warn_second_parameter_to_va_arg_not_pod) | |||
15527 | << TInfo->getType() | |||
15528 | << TInfo->getTypeLoc().getSourceRange(); | |||
15529 | } | |||
15530 | ||||
15531 | // Check for va_arg where arguments of the given type will be promoted | |||
15532 | // (i.e. this va_arg is guaranteed to have undefined behavior). | |||
15533 | QualType PromoteType; | |||
15534 | if (TInfo->getType()->isPromotableIntegerType()) { | |||
15535 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | |||
15536 | if (Context.typesAreCompatible(PromoteType, TInfo->getType())) | |||
15537 | PromoteType = QualType(); | |||
15538 | } | |||
15539 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | |||
15540 | PromoteType = Context.DoubleTy; | |||
15541 | if (!PromoteType.isNull()) | |||
15542 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | |||
15543 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | |||
15544 | << TInfo->getType() | |||
15545 | << PromoteType | |||
15546 | << TInfo->getTypeLoc().getSourceRange()); | |||
15547 | } | |||
15548 | ||||
15549 | QualType T = TInfo->getType().getNonLValueExprType(Context); | |||
15550 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | |||
15551 | } | |||
15552 | ||||
15553 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | |||
15554 | // The type of __null will be int or long, depending on the size of | |||
15555 | // pointers on the target. | |||
15556 | QualType Ty; | |||
15557 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | |||
15558 | if (pw == Context.getTargetInfo().getIntWidth()) | |||
15559 | Ty = Context.IntTy; | |||
15560 | else if (pw == Context.getTargetInfo().getLongWidth()) | |||
15561 | Ty = Context.LongTy; | |||
15562 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | |||
15563 | Ty = Context.LongLongTy; | |||
15564 | else { | |||
15565 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15565); | |||
15566 | } | |||
15567 | ||||
15568 | return new (Context) GNUNullExpr(Ty, TokenLoc); | |||
15569 | } | |||
15570 | ||||
15571 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | |||
15572 | SourceLocation BuiltinLoc, | |||
15573 | SourceLocation RPLoc) { | |||
15574 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); | |||
15575 | } | |||
15576 | ||||
15577 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | |||
15578 | SourceLocation BuiltinLoc, | |||
15579 | SourceLocation RPLoc, | |||
15580 | DeclContext *ParentContext) { | |||
15581 | return new (Context) | |||
15582 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); | |||
15583 | } | |||
15584 | ||||
15585 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | |||
15586 | bool Diagnose) { | |||
15587 | if (!getLangOpts().ObjC) | |||
15588 | return false; | |||
15589 | ||||
15590 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | |||
15591 | if (!PT) | |||
15592 | return false; | |||
15593 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | |||
15594 | ||||
15595 | // Ignore any parens, implicit casts (should only be | |||
15596 | // array-to-pointer decays), and not-so-opaque values. The last is | |||
15597 | // important for making this trigger for property assignments. | |||
15598 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | |||
15599 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | |||
15600 | if (OV->getSourceExpr()) | |||
15601 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | |||
15602 | ||||
15603 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | |||
15604 | if (!PT->isObjCIdType() && | |||
15605 | !(ID && ID->getIdentifier()->isStr("NSString"))) | |||
15606 | return false; | |||
15607 | if (!SL->isAscii()) | |||
15608 | return false; | |||
15609 | ||||
15610 | if (Diagnose) { | |||
15611 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | |||
15612 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | |||
15613 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | |||
15614 | } | |||
15615 | return true; | |||
15616 | } | |||
15617 | ||||
15618 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | |||
15619 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | |||
15620 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | |||
15621 | !SrcExpr->isNullPointerConstant( | |||
15622 | getASTContext(), Expr::NPC_NeverValueDependent)) { | |||
15623 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | |||
15624 | return false; | |||
15625 | if (Diagnose) { | |||
15626 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | |||
15627 | << /*number*/1 | |||
15628 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | |||
15629 | Expr *NumLit = | |||
15630 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | |||
15631 | if (NumLit) | |||
15632 | Exp = NumLit; | |||
15633 | } | |||
15634 | return true; | |||
15635 | } | |||
15636 | ||||
15637 | return false; | |||
15638 | } | |||
15639 | ||||
15640 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | |||
15641 | const Expr *SrcExpr) { | |||
15642 | if (!DstType->isFunctionPointerType() || | |||
15643 | !SrcExpr->getType()->isFunctionType()) | |||
15644 | return false; | |||
15645 | ||||
15646 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | |||
15647 | if (!DRE) | |||
15648 | return false; | |||
15649 | ||||
15650 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | |||
15651 | if (!FD) | |||
15652 | return false; | |||
15653 | ||||
15654 | return !S.checkAddressOfFunctionIsAvailable(FD, | |||
15655 | /*Complain=*/true, | |||
15656 | SrcExpr->getBeginLoc()); | |||
15657 | } | |||
15658 | ||||
15659 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | |||
15660 | SourceLocation Loc, | |||
15661 | QualType DstType, QualType SrcType, | |||
15662 | Expr *SrcExpr, AssignmentAction Action, | |||
15663 | bool *Complained) { | |||
15664 | if (Complained) | |||
15665 | *Complained = false; | |||
15666 | ||||
15667 | // Decode the result (notice that AST's are still created for extensions). | |||
15668 | bool CheckInferredResultType = false; | |||
15669 | bool isInvalid = false; | |||
15670 | unsigned DiagKind = 0; | |||
15671 | ConversionFixItGenerator ConvHints; | |||
15672 | bool MayHaveConvFixit = false; | |||
15673 | bool MayHaveFunctionDiff = false; | |||
15674 | const ObjCInterfaceDecl *IFace = nullptr; | |||
15675 | const ObjCProtocolDecl *PDecl = nullptr; | |||
15676 | ||||
15677 | switch (ConvTy) { | |||
15678 | case Compatible: | |||
15679 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | |||
15680 | return false; | |||
15681 | ||||
15682 | case PointerToInt: | |||
15683 | if (getLangOpts().CPlusPlus) { | |||
15684 | DiagKind = diag::err_typecheck_convert_pointer_int; | |||
15685 | isInvalid = true; | |||
15686 | } else { | |||
15687 | DiagKind = diag::ext_typecheck_convert_pointer_int; | |||
15688 | } | |||
15689 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
15690 | MayHaveConvFixit = true; | |||
15691 | break; | |||
15692 | case IntToPointer: | |||
15693 | if (getLangOpts().CPlusPlus) { | |||
15694 | DiagKind = diag::err_typecheck_convert_int_pointer; | |||
15695 | isInvalid = true; | |||
15696 | } else { | |||
15697 | DiagKind = diag::ext_typecheck_convert_int_pointer; | |||
15698 | } | |||
15699 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
15700 | MayHaveConvFixit = true; | |||
15701 | break; | |||
15702 | case IncompatibleFunctionPointer: | |||
15703 | if (getLangOpts().CPlusPlus) { | |||
15704 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | |||
15705 | isInvalid = true; | |||
15706 | } else { | |||
15707 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | |||
15708 | } | |||
15709 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
15710 | MayHaveConvFixit = true; | |||
15711 | break; | |||
15712 | case IncompatiblePointer: | |||
15713 | if (Action == AA_Passing_CFAudited) { | |||
15714 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | |||
15715 | } else if (getLangOpts().CPlusPlus) { | |||
15716 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | |||
15717 | isInvalid = true; | |||
15718 | } else { | |||
15719 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | |||
15720 | } | |||
15721 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | |||
15722 | SrcType->isObjCObjectPointerType(); | |||
15723 | if (!CheckInferredResultType) { | |||
15724 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
15725 | } else if (CheckInferredResultType) { | |||
15726 | SrcType = SrcType.getUnqualifiedType(); | |||
15727 | DstType = DstType.getUnqualifiedType(); | |||
15728 | } | |||
15729 | MayHaveConvFixit = true; | |||
15730 | break; | |||
15731 | case IncompatiblePointerSign: | |||
15732 | if (getLangOpts().CPlusPlus) { | |||
15733 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | |||
15734 | isInvalid = true; | |||
15735 | } else { | |||
15736 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | |||
15737 | } | |||
15738 | break; | |||
15739 | case FunctionVoidPointer: | |||
15740 | if (getLangOpts().CPlusPlus) { | |||
15741 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | |||
15742 | isInvalid = true; | |||
15743 | } else { | |||
15744 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | |||
15745 | } | |||
15746 | break; | |||
15747 | case IncompatiblePointerDiscardsQualifiers: { | |||
15748 | // Perform array-to-pointer decay if necessary. | |||
15749 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | |||
15750 | ||||
15751 | isInvalid = true; | |||
15752 | ||||
15753 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | |||
15754 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | |||
15755 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | |||
15756 | DiagKind = diag::err_typecheck_incompatible_address_space; | |||
15757 | break; | |||
15758 | ||||
15759 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | |||
15760 | DiagKind = diag::err_typecheck_incompatible_ownership; | |||
15761 | break; | |||
15762 | } | |||
15763 | ||||
15764 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 15764); | |||
15765 | // fallthrough | |||
15766 | } | |||
15767 | case CompatiblePointerDiscardsQualifiers: | |||
15768 | // If the qualifiers lost were because we were applying the | |||
15769 | // (deprecated) C++ conversion from a string literal to a char* | |||
15770 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | |||
15771 | // Ideally, this check would be performed in | |||
15772 | // checkPointerTypesForAssignment. However, that would require a | |||
15773 | // bit of refactoring (so that the second argument is an | |||
15774 | // expression, rather than a type), which should be done as part | |||
15775 | // of a larger effort to fix checkPointerTypesForAssignment for | |||
15776 | // C++ semantics. | |||
15777 | if (getLangOpts().CPlusPlus && | |||
15778 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | |||
15779 | return false; | |||
15780 | if (getLangOpts().CPlusPlus) { | |||
15781 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | |||
15782 | isInvalid = true; | |||
15783 | } else { | |||
15784 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | |||
15785 | } | |||
15786 | ||||
15787 | break; | |||
15788 | case IncompatibleNestedPointerQualifiers: | |||
15789 | if (getLangOpts().CPlusPlus) { | |||
15790 | isInvalid = true; | |||
15791 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | |||
15792 | } else { | |||
15793 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | |||
15794 | } | |||
15795 | break; | |||
15796 | case IncompatibleNestedPointerAddressSpaceMismatch: | |||
15797 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | |||
15798 | isInvalid = true; | |||
15799 | break; | |||
15800 | case IntToBlockPointer: | |||
15801 | DiagKind = diag::err_int_to_block_pointer; | |||
15802 | isInvalid = true; | |||
15803 | break; | |||
15804 | case IncompatibleBlockPointer: | |||
15805 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | |||
15806 | isInvalid = true; | |||
15807 | break; | |||
15808 | case IncompatibleObjCQualifiedId: { | |||
15809 | if (SrcType->isObjCQualifiedIdType()) { | |||
15810 | const ObjCObjectPointerType *srcOPT = | |||
15811 | SrcType->castAs<ObjCObjectPointerType>(); | |||
15812 | for (auto *srcProto : srcOPT->quals()) { | |||
15813 | PDecl = srcProto; | |||
15814 | break; | |||
15815 | } | |||
15816 | if (const ObjCInterfaceType *IFaceT = | |||
15817 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | |||
15818 | IFace = IFaceT->getDecl(); | |||
15819 | } | |||
15820 | else if (DstType->isObjCQualifiedIdType()) { | |||
15821 | const ObjCObjectPointerType *dstOPT = | |||
15822 | DstType->castAs<ObjCObjectPointerType>(); | |||
15823 | for (auto *dstProto : dstOPT->quals()) { | |||
15824 | PDecl = dstProto; | |||
15825 | break; | |||
15826 | } | |||
15827 | if (const ObjCInterfaceType *IFaceT = | |||
15828 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | |||
15829 | IFace = IFaceT->getDecl(); | |||
15830 | } | |||
15831 | if (getLangOpts().CPlusPlus) { | |||
15832 | DiagKind = diag::err_incompatible_qualified_id; | |||
15833 | isInvalid = true; | |||
15834 | } else { | |||
15835 | DiagKind = diag::warn_incompatible_qualified_id; | |||
15836 | } | |||
15837 | break; | |||
15838 | } | |||
15839 | case IncompatibleVectors: | |||
15840 | if (getLangOpts().CPlusPlus) { | |||
15841 | DiagKind = diag::err_incompatible_vectors; | |||
15842 | isInvalid = true; | |||
15843 | } else { | |||
15844 | DiagKind = diag::warn_incompatible_vectors; | |||
15845 | } | |||
15846 | break; | |||
15847 | case IncompatibleObjCWeakRef: | |||
15848 | DiagKind = diag::err_arc_weak_unavailable_assign; | |||
15849 | isInvalid = true; | |||
15850 | break; | |||
15851 | case Incompatible: | |||
15852 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | |||
15853 | if (Complained) | |||
15854 | *Complained = true; | |||
15855 | return true; | |||
15856 | } | |||
15857 | ||||
15858 | DiagKind = diag::err_typecheck_convert_incompatible; | |||
15859 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | |||
15860 | MayHaveConvFixit = true; | |||
15861 | isInvalid = true; | |||
15862 | MayHaveFunctionDiff = true; | |||
15863 | break; | |||
15864 | } | |||
15865 | ||||
15866 | QualType FirstType, SecondType; | |||
15867 | switch (Action) { | |||
15868 | case AA_Assigning: | |||
15869 | case AA_Initializing: | |||
15870 | // The destination type comes first. | |||
15871 | FirstType = DstType; | |||
15872 | SecondType = SrcType; | |||
15873 | break; | |||
15874 | ||||
15875 | case AA_Returning: | |||
15876 | case AA_Passing: | |||
15877 | case AA_Passing_CFAudited: | |||
15878 | case AA_Converting: | |||
15879 | case AA_Sending: | |||
15880 | case AA_Casting: | |||
15881 | // The source type comes first. | |||
15882 | FirstType = SrcType; | |||
15883 | SecondType = DstType; | |||
15884 | break; | |||
15885 | } | |||
15886 | ||||
15887 | PartialDiagnostic FDiag = PDiag(DiagKind); | |||
15888 | if (Action == AA_Passing_CFAudited) | |||
15889 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | |||
15890 | else | |||
15891 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | |||
15892 | ||||
15893 | // If we can fix the conversion, suggest the FixIts. | |||
15894 | if (!ConvHints.isNull()) { | |||
15895 | for (FixItHint &H : ConvHints.Hints) | |||
15896 | FDiag << H; | |||
15897 | } | |||
15898 | ||||
15899 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | |||
15900 | ||||
15901 | if (MayHaveFunctionDiff) | |||
15902 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | |||
15903 | ||||
15904 | Diag(Loc, FDiag); | |||
15905 | if ((DiagKind == diag::warn_incompatible_qualified_id || | |||
15906 | DiagKind == diag::err_incompatible_qualified_id) && | |||
15907 | PDecl && IFace && !IFace->hasDefinition()) | |||
15908 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | |||
15909 | << IFace << PDecl; | |||
15910 | ||||
15911 | if (SecondType == Context.OverloadTy) | |||
15912 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | |||
15913 | FirstType, /*TakingAddress=*/true); | |||
15914 | ||||
15915 | if (CheckInferredResultType) | |||
15916 | EmitRelatedResultTypeNote(SrcExpr); | |||
15917 | ||||
15918 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | |||
15919 | EmitRelatedResultTypeNoteForReturn(DstType); | |||
15920 | ||||
15921 | if (Complained) | |||
15922 | *Complained = true; | |||
15923 | return isInvalid; | |||
15924 | } | |||
15925 | ||||
15926 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | |||
15927 | llvm::APSInt *Result, | |||
15928 | AllowFoldKind CanFold) { | |||
15929 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | |||
15930 | public: | |||
15931 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | |||
15932 | QualType T) override { | |||
15933 | return S.Diag(Loc, diag::err_ice_not_integral) | |||
15934 | << T << S.LangOpts.CPlusPlus; | |||
15935 | } | |||
15936 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | |||
15937 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | |||
15938 | } | |||
15939 | } Diagnoser; | |||
15940 | ||||
15941 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | |||
15942 | } | |||
15943 | ||||
15944 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | |||
15945 | llvm::APSInt *Result, | |||
15946 | unsigned DiagID, | |||
15947 | AllowFoldKind CanFold) { | |||
15948 | class IDDiagnoser : public VerifyICEDiagnoser { | |||
15949 | unsigned DiagID; | |||
15950 | ||||
15951 | public: | |||
15952 | IDDiagnoser(unsigned DiagID) | |||
15953 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | |||
15954 | ||||
15955 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | |||
15956 | return S.Diag(Loc, DiagID); | |||
15957 | } | |||
15958 | } Diagnoser(DiagID); | |||
15959 | ||||
15960 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | |||
15961 | } | |||
15962 | ||||
15963 | Sema::SemaDiagnosticBuilder | |||
15964 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | |||
15965 | QualType T) { | |||
15966 | return diagnoseNotICE(S, Loc); | |||
15967 | } | |||
15968 | ||||
15969 | Sema::SemaDiagnosticBuilder | |||
15970 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | |||
15971 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | |||
15972 | } | |||
15973 | ||||
15974 | ExprResult | |||
15975 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | |||
15976 | VerifyICEDiagnoser &Diagnoser, | |||
15977 | AllowFoldKind CanFold) { | |||
15978 | SourceLocation DiagLoc = E->getBeginLoc(); | |||
15979 | ||||
15980 | if (getLangOpts().CPlusPlus11) { | |||
15981 | // C++11 [expr.const]p5: | |||
15982 | // If an expression of literal class type is used in a context where an | |||
15983 | // integral constant expression is required, then that class type shall | |||
15984 | // have a single non-explicit conversion function to an integral or | |||
15985 | // unscoped enumeration type | |||
15986 | ExprResult Converted; | |||
15987 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | |||
15988 | VerifyICEDiagnoser &BaseDiagnoser; | |||
15989 | public: | |||
15990 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | |||
15991 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | |||
15992 | BaseDiagnoser.Suppress, true), | |||
15993 | BaseDiagnoser(BaseDiagnoser) {} | |||
15994 | ||||
15995 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | |||
15996 | QualType T) override { | |||
15997 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | |||
15998 | } | |||
15999 | ||||
16000 | SemaDiagnosticBuilder diagnoseIncomplete( | |||
16001 | Sema &S, SourceLocation Loc, QualType T) override { | |||
16002 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | |||
16003 | } | |||
16004 | ||||
16005 | SemaDiagnosticBuilder diagnoseExplicitConv( | |||
16006 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
16007 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | |||
16008 | } | |||
16009 | ||||
16010 | SemaDiagnosticBuilder noteExplicitConv( | |||
16011 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
16012 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | |||
16013 | << ConvTy->isEnumeralType() << ConvTy; | |||
16014 | } | |||
16015 | ||||
16016 | SemaDiagnosticBuilder diagnoseAmbiguous( | |||
16017 | Sema &S, SourceLocation Loc, QualType T) override { | |||
16018 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | |||
16019 | } | |||
16020 | ||||
16021 | SemaDiagnosticBuilder noteAmbiguous( | |||
16022 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
16023 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | |||
16024 | << ConvTy->isEnumeralType() << ConvTy; | |||
16025 | } | |||
16026 | ||||
16027 | SemaDiagnosticBuilder diagnoseConversion( | |||
16028 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
16029 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16029); | |||
16030 | } | |||
16031 | } ConvertDiagnoser(Diagnoser); | |||
16032 | ||||
16033 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | |||
16034 | ConvertDiagnoser); | |||
16035 | if (Converted.isInvalid()) | |||
16036 | return Converted; | |||
16037 | E = Converted.get(); | |||
16038 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | |||
16039 | return ExprError(); | |||
16040 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
16041 | // An ICE must be of integral or unscoped enumeration type. | |||
16042 | if (!Diagnoser.Suppress) | |||
16043 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | |||
16044 | << E->getSourceRange(); | |||
16045 | return ExprError(); | |||
16046 | } | |||
16047 | ||||
16048 | ExprResult RValueExpr = DefaultLvalueConversion(E); | |||
16049 | if (RValueExpr.isInvalid()) | |||
16050 | return ExprError(); | |||
16051 | ||||
16052 | E = RValueExpr.get(); | |||
16053 | ||||
16054 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | |||
16055 | // in the non-ICE case. | |||
16056 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | |||
16057 | if (Result) | |||
16058 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | |||
16059 | if (!isa<ConstantExpr>(E)) | |||
16060 | E = ConstantExpr::Create(Context, E); | |||
16061 | return E; | |||
16062 | } | |||
16063 | ||||
16064 | Expr::EvalResult EvalResult; | |||
16065 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
16066 | EvalResult.Diag = &Notes; | |||
16067 | ||||
16068 | // Try to evaluate the expression, and produce diagnostics explaining why it's | |||
16069 | // not a constant expression as a side-effect. | |||
16070 | bool Folded = | |||
16071 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | |||
16072 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | |||
16073 | ||||
16074 | if (!isa<ConstantExpr>(E)) | |||
16075 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | |||
16076 | ||||
16077 | // In C++11, we can rely on diagnostics being produced for any expression | |||
16078 | // which is not a constant expression. If no diagnostics were produced, then | |||
16079 | // this is a constant expression. | |||
16080 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | |||
16081 | if (Result) | |||
16082 | *Result = EvalResult.Val.getInt(); | |||
16083 | return E; | |||
16084 | } | |||
16085 | ||||
16086 | // If our only note is the usual "invalid subexpression" note, just point | |||
16087 | // the caret at its location rather than producing an essentially | |||
16088 | // redundant note. | |||
16089 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | |||
16090 | diag::note_invalid_subexpr_in_const_expr) { | |||
16091 | DiagLoc = Notes[0].first; | |||
16092 | Notes.clear(); | |||
16093 | } | |||
16094 | ||||
16095 | if (!Folded || !CanFold) { | |||
16096 | if (!Diagnoser.Suppress) { | |||
16097 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | |||
16098 | for (const PartialDiagnosticAt &Note : Notes) | |||
16099 | Diag(Note.first, Note.second); | |||
16100 | } | |||
16101 | ||||
16102 | return ExprError(); | |||
16103 | } | |||
16104 | ||||
16105 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | |||
16106 | for (const PartialDiagnosticAt &Note : Notes) | |||
16107 | Diag(Note.first, Note.second); | |||
16108 | ||||
16109 | if (Result) | |||
16110 | *Result = EvalResult.Val.getInt(); | |||
16111 | return E; | |||
16112 | } | |||
16113 | ||||
16114 | namespace { | |||
16115 | // Handle the case where we conclude a expression which we speculatively | |||
16116 | // considered to be unevaluated is actually evaluated. | |||
16117 | class TransformToPE : public TreeTransform<TransformToPE> { | |||
16118 | typedef TreeTransform<TransformToPE> BaseTransform; | |||
16119 | ||||
16120 | public: | |||
16121 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | |||
16122 | ||||
16123 | // Make sure we redo semantic analysis | |||
16124 | bool AlwaysRebuild() { return true; } | |||
16125 | bool ReplacingOriginal() { return true; } | |||
16126 | ||||
16127 | // We need to special-case DeclRefExprs referring to FieldDecls which | |||
16128 | // are not part of a member pointer formation; normal TreeTransforming | |||
16129 | // doesn't catch this case because of the way we represent them in the AST. | |||
16130 | // FIXME: This is a bit ugly; is it really the best way to handle this | |||
16131 | // case? | |||
16132 | // | |||
16133 | // Error on DeclRefExprs referring to FieldDecls. | |||
16134 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | |||
16135 | if (isa<FieldDecl>(E->getDecl()) && | |||
16136 | !SemaRef.isUnevaluatedContext()) | |||
16137 | return SemaRef.Diag(E->getLocation(), | |||
16138 | diag::err_invalid_non_static_member_use) | |||
16139 | << E->getDecl() << E->getSourceRange(); | |||
16140 | ||||
16141 | return BaseTransform::TransformDeclRefExpr(E); | |||
16142 | } | |||
16143 | ||||
16144 | // Exception: filter out member pointer formation | |||
16145 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | |||
16146 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | |||
16147 | return E; | |||
16148 | ||||
16149 | return BaseTransform::TransformUnaryOperator(E); | |||
16150 | } | |||
16151 | ||||
16152 | // The body of a lambda-expression is in a separate expression evaluation | |||
16153 | // context so never needs to be transformed. | |||
16154 | // FIXME: Ideally we wouldn't transform the closure type either, and would | |||
16155 | // just recreate the capture expressions and lambda expression. | |||
16156 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | |||
16157 | return SkipLambdaBody(E, Body); | |||
16158 | } | |||
16159 | }; | |||
16160 | } | |||
16161 | ||||
16162 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | |||
16163 | assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16164, __PRETTY_FUNCTION__)) | |||
16164 | "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16164, __PRETTY_FUNCTION__)); | |||
16165 | ExprEvalContexts.back().Context = | |||
16166 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | |||
16167 | if (isUnevaluatedContext()) | |||
16168 | return E; | |||
16169 | return TransformToPE(*this).TransformExpr(E); | |||
16170 | } | |||
16171 | ||||
16172 | void | |||
16173 | Sema::PushExpressionEvaluationContext( | |||
16174 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | |||
16175 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | |||
16176 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | |||
16177 | LambdaContextDecl, ExprContext); | |||
16178 | Cleanup.reset(); | |||
16179 | if (!MaybeODRUseExprs.empty()) | |||
16180 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | |||
16181 | } | |||
16182 | ||||
16183 | void | |||
16184 | Sema::PushExpressionEvaluationContext( | |||
16185 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | |||
16186 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | |||
16187 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | |||
16188 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | |||
16189 | } | |||
16190 | ||||
16191 | namespace { | |||
16192 | ||||
16193 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | |||
16194 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | |||
16195 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | |||
16196 | if (E->getOpcode() == UO_Deref) | |||
16197 | return CheckPossibleDeref(S, E->getSubExpr()); | |||
16198 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | |||
16199 | return CheckPossibleDeref(S, E->getBase()); | |||
16200 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | |||
16201 | return CheckPossibleDeref(S, E->getBase()); | |||
16202 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | |||
16203 | QualType Inner; | |||
16204 | QualType Ty = E->getType(); | |||
16205 | if (const auto *Ptr = Ty->getAs<PointerType>()) | |||
16206 | Inner = Ptr->getPointeeType(); | |||
16207 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | |||
16208 | Inner = Arr->getElementType(); | |||
16209 | else | |||
16210 | return nullptr; | |||
16211 | ||||
16212 | if (Inner->hasAttr(attr::NoDeref)) | |||
16213 | return E; | |||
16214 | } | |||
16215 | return nullptr; | |||
16216 | } | |||
16217 | ||||
16218 | } // namespace | |||
16219 | ||||
16220 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | |||
16221 | for (const Expr *E : Rec.PossibleDerefs) { | |||
16222 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | |||
16223 | if (DeclRef) { | |||
16224 | const ValueDecl *Decl = DeclRef->getDecl(); | |||
16225 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | |||
16226 | << Decl->getName() << E->getSourceRange(); | |||
16227 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | |||
16228 | } else { | |||
16229 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | |||
16230 | << E->getSourceRange(); | |||
16231 | } | |||
16232 | } | |||
16233 | Rec.PossibleDerefs.clear(); | |||
16234 | } | |||
16235 | ||||
16236 | /// Check whether E, which is either a discarded-value expression or an | |||
16237 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | |||
16238 | /// and if so, remove it from the list of volatile-qualified assignments that | |||
16239 | /// we are going to warn are deprecated. | |||
16240 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | |||
16241 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | |||
16242 | return; | |||
16243 | ||||
16244 | // Note: ignoring parens here is not justified by the standard rules, but | |||
16245 | // ignoring parentheses seems like a more reasonable approach, and this only | |||
16246 | // drives a deprecation warning so doesn't affect conformance. | |||
16247 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | |||
16248 | if (BO->getOpcode() == BO_Assign) { | |||
16249 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | |||
16250 | LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), | |||
16251 | LHSs.end()); | |||
16252 | } | |||
16253 | } | |||
16254 | } | |||
16255 | ||||
16256 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | |||
16257 | if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || | |||
16258 | RebuildingImmediateInvocation) | |||
16259 | return E; | |||
16260 | ||||
16261 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | |||
16262 | /// It's OK if this fails; we'll also remove this in | |||
16263 | /// HandleImmediateInvocations, but catching it here allows us to avoid | |||
16264 | /// walking the AST looking for it in simple cases. | |||
16265 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | |||
16266 | if (auto *DeclRef = | |||
16267 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | |||
16268 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | |||
16269 | ||||
16270 | E = MaybeCreateExprWithCleanups(E); | |||
16271 | ||||
16272 | ConstantExpr *Res = ConstantExpr::Create( | |||
16273 | getASTContext(), E.get(), | |||
16274 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | |||
16275 | getASTContext()), | |||
16276 | /*IsImmediateInvocation*/ true); | |||
16277 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | |||
16278 | return Res; | |||
16279 | } | |||
16280 | ||||
16281 | static void EvaluateAndDiagnoseImmediateInvocation( | |||
16282 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | |||
16283 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | |||
16284 | Expr::EvalResult Eval; | |||
16285 | Eval.Diag = &Notes; | |||
16286 | ConstantExpr *CE = Candidate.getPointer(); | |||
16287 | bool Result = CE->EvaluateAsConstantExpr( | |||
16288 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | |||
16289 | if (!Result || !Notes.empty()) { | |||
16290 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | |||
16291 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | |||
16292 | InnerExpr = FunctionalCast->getSubExpr(); | |||
16293 | FunctionDecl *FD = nullptr; | |||
16294 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | |||
16295 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | |||
16296 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | |||
16297 | FD = Call->getConstructor(); | |||
16298 | else | |||
16299 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16299); | |||
16300 | assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail ("FD->isConsteval()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16300, __PRETTY_FUNCTION__)); | |||
16301 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | |||
16302 | for (auto &Note : Notes) | |||
16303 | SemaRef.Diag(Note.first, Note.second); | |||
16304 | return; | |||
16305 | } | |||
16306 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | |||
16307 | } | |||
16308 | ||||
16309 | static void RemoveNestedImmediateInvocation( | |||
16310 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | |||
16311 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | |||
16312 | struct ComplexRemove : TreeTransform<ComplexRemove> { | |||
16313 | using Base = TreeTransform<ComplexRemove>; | |||
16314 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | |||
16315 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | |||
16316 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | |||
16317 | CurrentII; | |||
16318 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | |||
16319 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | |||
16320 | SmallVector<Sema::ImmediateInvocationCandidate, | |||
16321 | 4>::reverse_iterator Current) | |||
16322 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | |||
16323 | void RemoveImmediateInvocation(ConstantExpr* E) { | |||
16324 | auto It = std::find_if(CurrentII, IISet.rend(), | |||
16325 | [E](Sema::ImmediateInvocationCandidate Elem) { | |||
16326 | return Elem.getPointer() == E; | |||
16327 | }); | |||
16328 | assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16330, __PRETTY_FUNCTION__)) | |||
16329 | "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16330, __PRETTY_FUNCTION__)) | |||
16330 | "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16330, __PRETTY_FUNCTION__)); | |||
16331 | It->setInt(1); // Mark as deleted | |||
16332 | } | |||
16333 | ExprResult TransformConstantExpr(ConstantExpr *E) { | |||
16334 | if (!E->isImmediateInvocation()) | |||
16335 | return Base::TransformConstantExpr(E); | |||
16336 | RemoveImmediateInvocation(E); | |||
16337 | return Base::TransformExpr(E->getSubExpr()); | |||
16338 | } | |||
16339 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | |||
16340 | /// we need to remove its DeclRefExpr from the DRSet. | |||
16341 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
16342 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | |||
16343 | return Base::TransformCXXOperatorCallExpr(E); | |||
16344 | } | |||
16345 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | |||
16346 | /// here. | |||
16347 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | |||
16348 | if (!Init) | |||
16349 | return Init; | |||
16350 | /// ConstantExpr are the first layer of implicit node to be removed so if | |||
16351 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | |||
16352 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | |||
16353 | if (CE->isImmediateInvocation()) | |||
16354 | RemoveImmediateInvocation(CE); | |||
16355 | return Base::TransformInitializer(Init, NotCopyInit); | |||
16356 | } | |||
16357 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | |||
16358 | DRSet.erase(E); | |||
16359 | return E; | |||
16360 | } | |||
16361 | bool AlwaysRebuild() { return false; } | |||
16362 | bool ReplacingOriginal() { return true; } | |||
16363 | bool AllowSkippingCXXConstructExpr() { | |||
16364 | bool Res = AllowSkippingFirstCXXConstructExpr; | |||
16365 | AllowSkippingFirstCXXConstructExpr = true; | |||
16366 | return Res; | |||
16367 | } | |||
16368 | bool AllowSkippingFirstCXXConstructExpr = true; | |||
16369 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | |||
16370 | Rec.ImmediateInvocationCandidates, It); | |||
16371 | ||||
16372 | /// CXXConstructExpr with a single argument are getting skipped by | |||
16373 | /// TreeTransform in some situtation because they could be implicit. This | |||
16374 | /// can only occur for the top-level CXXConstructExpr because it is used | |||
16375 | /// nowhere in the expression being transformed therefore will not be rebuilt. | |||
16376 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | |||
16377 | /// skipping the first CXXConstructExpr. | |||
16378 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | |||
16379 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | |||
16380 | ||||
16381 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | |||
16382 | assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail ("Res.isUsable()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16382, __PRETTY_FUNCTION__)); | |||
16383 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | |||
16384 | It->getPointer()->setSubExpr(Res.get()); | |||
16385 | } | |||
16386 | ||||
16387 | static void | |||
16388 | HandleImmediateInvocations(Sema &SemaRef, | |||
16389 | Sema::ExpressionEvaluationContextRecord &Rec) { | |||
16390 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | |||
16391 | Rec.ReferenceToConsteval.size() == 0) || | |||
16392 | SemaRef.RebuildingImmediateInvocation) | |||
16393 | return; | |||
16394 | ||||
16395 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | |||
16396 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | |||
16397 | /// need to remove ReferenceToConsteval in the immediate invocation. | |||
16398 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | |||
16399 | ||||
16400 | /// Prevent sema calls during the tree transform from adding pointers that | |||
16401 | /// are already in the sets. | |||
16402 | llvm::SaveAndRestore<bool> DisableIITracking( | |||
16403 | SemaRef.RebuildingImmediateInvocation, true); | |||
16404 | ||||
16405 | /// Prevent diagnostic during tree transfrom as they are duplicates | |||
16406 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | |||
16407 | ||||
16408 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | |||
16409 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | |||
16410 | if (!It->getInt()) | |||
16411 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | |||
16412 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | |||
16413 | Rec.ReferenceToConsteval.size()) { | |||
16414 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | |||
16415 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | |||
16416 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | |||
16417 | bool VisitDeclRefExpr(DeclRefExpr *E) { | |||
16418 | DRSet.erase(E); | |||
16419 | return DRSet.size(); | |||
16420 | } | |||
16421 | } Visitor(Rec.ReferenceToConsteval); | |||
16422 | Visitor.TraverseStmt( | |||
16423 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | |||
16424 | } | |||
16425 | for (auto CE : Rec.ImmediateInvocationCandidates) | |||
16426 | if (!CE.getInt()) | |||
16427 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | |||
16428 | for (auto DR : Rec.ReferenceToConsteval) { | |||
16429 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | |||
16430 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | |||
16431 | << FD; | |||
16432 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | |||
16433 | } | |||
16434 | } | |||
16435 | ||||
16436 | void Sema::PopExpressionEvaluationContext() { | |||
16437 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | |||
16438 | unsigned NumTypos = Rec.NumTypos; | |||
16439 | ||||
16440 | if (!Rec.Lambdas.empty()) { | |||
16441 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | |||
16442 | if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || | |||
16443 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { | |||
16444 | unsigned D; | |||
16445 | if (Rec.isUnevaluated()) { | |||
16446 | // C++11 [expr.prim.lambda]p2: | |||
16447 | // A lambda-expression shall not appear in an unevaluated operand | |||
16448 | // (Clause 5). | |||
16449 | D = diag::err_lambda_unevaluated_operand; | |||
16450 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | |||
16451 | // C++1y [expr.const]p2: | |||
16452 | // A conditional-expression e is a core constant expression unless the | |||
16453 | // evaluation of e, following the rules of the abstract machine, would | |||
16454 | // evaluate [...] a lambda-expression. | |||
16455 | D = diag::err_lambda_in_constant_expression; | |||
16456 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | |||
16457 | // C++17 [expr.prim.lamda]p2: | |||
16458 | // A lambda-expression shall not appear [...] in a template-argument. | |||
16459 | D = diag::err_lambda_in_invalid_context; | |||
16460 | } else | |||
16461 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16461); | |||
16462 | ||||
16463 | for (const auto *L : Rec.Lambdas) | |||
16464 | Diag(L->getBeginLoc(), D); | |||
16465 | } | |||
16466 | } | |||
16467 | ||||
16468 | WarnOnPendingNoDerefs(Rec); | |||
16469 | HandleImmediateInvocations(*this, Rec); | |||
16470 | ||||
16471 | // Warn on any volatile-qualified simple-assignments that are not discarded- | |||
16472 | // value expressions nor unevaluated operands (those cases get removed from | |||
16473 | // this list by CheckUnusedVolatileAssignment). | |||
16474 | for (auto *BO : Rec.VolatileAssignmentLHSs) | |||
16475 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | |||
16476 | << BO->getType(); | |||
16477 | ||||
16478 | // When are coming out of an unevaluated context, clear out any | |||
16479 | // temporaries that we may have created as part of the evaluation of | |||
16480 | // the expression in that context: they aren't relevant because they | |||
16481 | // will never be constructed. | |||
16482 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | |||
16483 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | |||
16484 | ExprCleanupObjects.end()); | |||
16485 | Cleanup = Rec.ParentCleanup; | |||
16486 | CleanupVarDeclMarking(); | |||
16487 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | |||
16488 | // Otherwise, merge the contexts together. | |||
16489 | } else { | |||
16490 | Cleanup.mergeFrom(Rec.ParentCleanup); | |||
16491 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | |||
16492 | Rec.SavedMaybeODRUseExprs.end()); | |||
16493 | } | |||
16494 | ||||
16495 | // Pop the current expression evaluation context off the stack. | |||
16496 | ExprEvalContexts.pop_back(); | |||
16497 | ||||
16498 | // The global expression evaluation context record is never popped. | |||
16499 | ExprEvalContexts.back().NumTypos += NumTypos; | |||
16500 | } | |||
16501 | ||||
16502 | void Sema::DiscardCleanupsInEvaluationContext() { | |||
16503 | ExprCleanupObjects.erase( | |||
16504 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | |||
16505 | ExprCleanupObjects.end()); | |||
16506 | Cleanup.reset(); | |||
16507 | MaybeODRUseExprs.clear(); | |||
16508 | } | |||
16509 | ||||
16510 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | |||
16511 | ExprResult Result = CheckPlaceholderExpr(E); | |||
16512 | if (Result.isInvalid()) | |||
16513 | return ExprError(); | |||
16514 | E = Result.get(); | |||
16515 | if (!E->getType()->isVariablyModifiedType()) | |||
16516 | return E; | |||
16517 | return TransformToPotentiallyEvaluated(E); | |||
16518 | } | |||
16519 | ||||
16520 | /// Are we in a context that is potentially constant evaluated per C++20 | |||
16521 | /// [expr.const]p12? | |||
16522 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | |||
16523 | /// C++2a [expr.const]p12: | |||
16524 | // An expression or conversion is potentially constant evaluated if it is | |||
16525 | switch (SemaRef.ExprEvalContexts.back().Context) { | |||
16526 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | |||
16527 | // -- a manifestly constant-evaluated expression, | |||
16528 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | |||
16529 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
16530 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | |||
16531 | // -- a potentially-evaluated expression, | |||
16532 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | |||
16533 | // -- an immediate subexpression of a braced-init-list, | |||
16534 | ||||
16535 | // -- [FIXME] an expression of the form & cast-expression that occurs | |||
16536 | // within a templated entity | |||
16537 | // -- a subexpression of one of the above that is not a subexpression of | |||
16538 | // a nested unevaluated operand. | |||
16539 | return true; | |||
16540 | ||||
16541 | case Sema::ExpressionEvaluationContext::Unevaluated: | |||
16542 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | |||
16543 | // Expressions in this context are never evaluated. | |||
16544 | return false; | |||
16545 | } | |||
16546 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16546); | |||
16547 | } | |||
16548 | ||||
16549 | /// Return true if this function has a calling convention that requires mangling | |||
16550 | /// in the size of the parameter pack. | |||
16551 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | |||
16552 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | |||
16553 | // we don't need parameter type sizes. | |||
16554 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | |||
16555 | if (!TT.isOSWindows() || !TT.isX86()) | |||
16556 | return false; | |||
16557 | ||||
16558 | // If this is C++ and this isn't an extern "C" function, parameters do not | |||
16559 | // need to be complete. In this case, C++ mangling will apply, which doesn't | |||
16560 | // use the size of the parameters. | |||
16561 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | |||
16562 | return false; | |||
16563 | ||||
16564 | // Stdcall, fastcall, and vectorcall need this special treatment. | |||
16565 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | |||
16566 | switch (CC) { | |||
16567 | case CC_X86StdCall: | |||
16568 | case CC_X86FastCall: | |||
16569 | case CC_X86VectorCall: | |||
16570 | return true; | |||
16571 | default: | |||
16572 | break; | |||
16573 | } | |||
16574 | return false; | |||
16575 | } | |||
16576 | ||||
16577 | /// Require that all of the parameter types of function be complete. Normally, | |||
16578 | /// parameter types are only required to be complete when a function is called | |||
16579 | /// or defined, but to mangle functions with certain calling conventions, the | |||
16580 | /// mangler needs to know the size of the parameter list. In this situation, | |||
16581 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | |||
16582 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | |||
16583 | /// result in a linker error. Clang doesn't implement this behavior, and instead | |||
16584 | /// attempts to error at compile time. | |||
16585 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | |||
16586 | SourceLocation Loc) { | |||
16587 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | |||
16588 | FunctionDecl *FD; | |||
16589 | ParmVarDecl *Param; | |||
16590 | ||||
16591 | public: | |||
16592 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | |||
16593 | : FD(FD), Param(Param) {} | |||
16594 | ||||
16595 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
16596 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | |||
16597 | StringRef CCName; | |||
16598 | switch (CC) { | |||
16599 | case CC_X86StdCall: | |||
16600 | CCName = "stdcall"; | |||
16601 | break; | |||
16602 | case CC_X86FastCall: | |||
16603 | CCName = "fastcall"; | |||
16604 | break; | |||
16605 | case CC_X86VectorCall: | |||
16606 | CCName = "vectorcall"; | |||
16607 | break; | |||
16608 | default: | |||
16609 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16609); | |||
16610 | } | |||
16611 | ||||
16612 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | |||
16613 | << Param->getDeclName() << FD->getDeclName() << CCName; | |||
16614 | } | |||
16615 | }; | |||
16616 | ||||
16617 | for (ParmVarDecl *Param : FD->parameters()) { | |||
16618 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | |||
16619 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | |||
16620 | } | |||
16621 | } | |||
16622 | ||||
16623 | namespace { | |||
16624 | enum class OdrUseContext { | |||
16625 | /// Declarations in this context are not odr-used. | |||
16626 | None, | |||
16627 | /// Declarations in this context are formally odr-used, but this is a | |||
16628 | /// dependent context. | |||
16629 | Dependent, | |||
16630 | /// Declarations in this context are odr-used but not actually used (yet). | |||
16631 | FormallyOdrUsed, | |||
16632 | /// Declarations in this context are used. | |||
16633 | Used | |||
16634 | }; | |||
16635 | } | |||
16636 | ||||
16637 | /// Are we within a context in which references to resolved functions or to | |||
16638 | /// variables result in odr-use? | |||
16639 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | |||
16640 | OdrUseContext Result; | |||
16641 | ||||
16642 | switch (SemaRef.ExprEvalContexts.back().Context) { | |||
16643 | case Sema::ExpressionEvaluationContext::Unevaluated: | |||
16644 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | |||
16645 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | |||
16646 | return OdrUseContext::None; | |||
16647 | ||||
16648 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | |||
16649 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | |||
16650 | Result = OdrUseContext::Used; | |||
16651 | break; | |||
16652 | ||||
16653 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | |||
16654 | Result = OdrUseContext::FormallyOdrUsed; | |||
16655 | break; | |||
16656 | ||||
16657 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
16658 | // A default argument formally results in odr-use, but doesn't actually | |||
16659 | // result in a use in any real sense until it itself is used. | |||
16660 | Result = OdrUseContext::FormallyOdrUsed; | |||
16661 | break; | |||
16662 | } | |||
16663 | ||||
16664 | if (SemaRef.CurContext->isDependentContext()) | |||
16665 | return OdrUseContext::Dependent; | |||
16666 | ||||
16667 | return Result; | |||
16668 | } | |||
16669 | ||||
16670 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | |||
16671 | if (!Func->isConstexpr()) | |||
16672 | return false; | |||
16673 | ||||
16674 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | |||
16675 | return true; | |||
16676 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | |||
16677 | return CCD && CCD->getInheritedConstructor(); | |||
16678 | } | |||
16679 | ||||
16680 | /// Mark a function referenced, and check whether it is odr-used | |||
16681 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | |||
16682 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | |||
16683 | bool MightBeOdrUse) { | |||
16684 | assert(Func && "No function?")((Func && "No function?") ? static_cast<void> ( 0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 16684, __PRETTY_FUNCTION__)); | |||
16685 | ||||
16686 | Func->setReferenced(); | |||
16687 | ||||
16688 | // Recursive functions aren't really used until they're used from some other | |||
16689 | // context. | |||
16690 | bool IsRecursiveCall = CurContext == Func; | |||
16691 | ||||
16692 | // C++11 [basic.def.odr]p3: | |||
16693 | // A function whose name appears as a potentially-evaluated expression is | |||
16694 | // odr-used if it is the unique lookup result or the selected member of a | |||
16695 | // set of overloaded functions [...]. | |||
16696 | // | |||
16697 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | |||
16698 | // can just check that here. | |||
16699 | OdrUseContext OdrUse = | |||
16700 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | |||
16701 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | |||
16702 | OdrUse = OdrUseContext::FormallyOdrUsed; | |||
16703 | ||||
16704 | // Trivial default constructors and destructors are never actually used. | |||
16705 | // FIXME: What about other special members? | |||
16706 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | |||
16707 | OdrUse == OdrUseContext::Used) { | |||
16708 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | |||
16709 | if (Constructor->isDefaultConstructor()) | |||
16710 | OdrUse = OdrUseContext::FormallyOdrUsed; | |||
16711 | if (isa<CXXDestructorDecl>(Func)) | |||
16712 | OdrUse = OdrUseContext::FormallyOdrUsed; | |||
16713 | } | |||
16714 | ||||
16715 | // C++20 [expr.const]p12: | |||
16716 | // A function [...] is needed for constant evaluation if it is [...] a | |||
16717 | // constexpr function that is named by an expression that is potentially | |||
16718 | // constant evaluated | |||
16719 | bool NeededForConstantEvaluation = | |||
16720 | isPotentiallyConstantEvaluatedContext(*this) && | |||
16721 | isImplicitlyDefinableConstexprFunction(Func); | |||
16722 | ||||
16723 | // Determine whether we require a function definition to exist, per | |||
16724 | // C++11 [temp.inst]p3: | |||
16725 | // Unless a function template specialization has been explicitly | |||
16726 | // instantiated or explicitly specialized, the function template | |||
16727 | // specialization is implicitly instantiated when the specialization is | |||
16728 | // referenced in a context that requires a function definition to exist. | |||
16729 | // C++20 [temp.inst]p7: | |||
16730 | // The existence of a definition of a [...] function is considered to | |||
16731 | // affect the semantics of the program if the [...] function is needed for | |||
16732 | // constant evaluation by an expression | |||
16733 | // C++20 [basic.def.odr]p10: | |||
16734 | // Every program shall contain exactly one definition of every non-inline | |||
16735 | // function or variable that is odr-used in that program outside of a | |||
16736 | // discarded statement | |||
16737 | // C++20 [special]p1: | |||
16738 | // The implementation will implicitly define [defaulted special members] | |||
16739 | // if they are odr-used or needed for constant evaluation. | |||
16740 | // | |||
16741 | // Note that we skip the implicit instantiation of templates that are only | |||
16742 | // used in unused default arguments or by recursive calls to themselves. | |||
16743 | // This is formally non-conforming, but seems reasonable in practice. | |||
16744 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | |||
16745 | NeededForConstantEvaluation); | |||
16746 | ||||
16747 | // C++14 [temp.expl.spec]p6: | |||
16748 | // If a template [...] is explicitly specialized then that specialization | |||
16749 | // shall be declared before the first use of that specialization that would | |||
16750 | // cause an implicit instantiation to take place, in every translation unit | |||
16751 | // in which such a use occurs | |||
16752 | if (NeedDefinition && | |||
16753 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | |||
16754 | Func->getMemberSpecializationInfo())) | |||
16755 | checkSpecializationVisibility(Loc, Func); | |||
16756 | ||||
16757 | if (getLangOpts().CUDA) | |||
16758 | CheckCUDACall(Loc, Func); | |||
16759 | ||||
16760 | if (getLangOpts().SYCLIsDevice) | |||
16761 | checkSYCLDeviceFunction(Loc, Func); | |||
16762 | ||||
16763 | // If we need a definition, try to create one. | |||
16764 | if (NeedDefinition && !Func->getBody()) { | |||
16765 | runWithSufficientStackSpace(Loc, [&] { | |||
16766 | if (CXXConstructorDecl *Constructor = | |||
16767 | dyn_cast<CXXConstructorDecl>(Func)) { | |||
16768 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | |||
16769 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | |||
16770 | if (Constructor->isDefaultConstructor()) { | |||
16771 | if (Constructor->isTrivial() && | |||
16772 | !Constructor->hasAttr<DLLExportAttr>()) | |||
16773 | return; | |||
16774 | DefineImplicitDefaultConstructor(Loc, Constructor); | |||
16775 | } else if (Constructor->isCopyConstructor()) { | |||
16776 | DefineImplicitCopyConstructor(Loc, Constructor); | |||
16777 | } else if (Constructor->isMoveConstructor()) { | |||
16778 | DefineImplicitMoveConstructor(Loc, Constructor); | |||
16779 | } | |||
16780 | } else if (Constructor->getInheritedConstructor()) { | |||
16781 | DefineInheritingConstructor(Loc, Constructor); | |||
16782 | } | |||
16783 | } else if (CXXDestructorDecl *Destructor = | |||
16784 | dyn_cast<CXXDestructorDecl>(Func)) { | |||
16785 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | |||
16786 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | |||
16787 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | |||
16788 | return; | |||
16789 | DefineImplicitDestructor(Loc, Destructor); | |||
16790 | } | |||
16791 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | |||
16792 | MarkVTableUsed(Loc, Destructor->getParent()); | |||
16793 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | |||
16794 | if (MethodDecl->isOverloadedOperator() && | |||
16795 | MethodDecl->getOverloadedOperator() == OO_Equal) { | |||
16796 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | |||
16797 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | |||
16798 | if (MethodDecl->isCopyAssignmentOperator()) | |||
16799 | DefineImplicitCopyAssignment(Loc, MethodDecl); | |||
16800 | else if (MethodDecl->isMoveAssignmentOperator()) | |||
16801 | DefineImplicitMoveAssignment(Loc, MethodDecl); | |||
16802 | } | |||
16803 | } else if (isa<CXXConversionDecl>(MethodDecl) && | |||
16804 | MethodDecl->getParent()->isLambda()) { | |||
16805 | CXXConversionDecl *Conversion = | |||
16806 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | |||
16807 | if (Conversion->isLambdaToBlockPointerConversion()) | |||
16808 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | |||
16809 | else | |||
16810 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | |||
16811 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | |||
16812 | MarkVTableUsed(Loc, MethodDecl->getParent()); | |||
16813 | } | |||
16814 | ||||
16815 | if (Func->isDefaulted() && !Func->isDeleted()) { | |||
16816 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | |||
16817 | if (DCK != DefaultedComparisonKind::None) | |||
16818 | DefineDefaultedComparison(Loc, Func, DCK); | |||
16819 | } | |||
16820 | ||||
16821 | // Implicit instantiation of function templates and member functions of | |||
16822 | // class templates. | |||
16823 | if (Func->isImplicitlyInstantiable()) { | |||
16824 | TemplateSpecializationKind TSK = | |||
16825 | Func->getTemplateSpecializationKindForInstantiation(); | |||
16826 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | |||
16827 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | |||
16828 | if (FirstInstantiation) { | |||
16829 | PointOfInstantiation = Loc; | |||
16830 | if (auto *MSI = Func->getMemberSpecializationInfo()) | |||
16831 | MSI->setPointOfInstantiation(Loc); | |||
16832 | // FIXME: Notify listener. | |||
16833 | else | |||
16834 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | |||
16835 | } else if (TSK != TSK_ImplicitInstantiation) { | |||
16836 | // Use the point of use as the point of instantiation, instead of the | |||
16837 | // point of explicit instantiation (which we track as the actual point | |||
16838 | // of instantiation). This gives better backtraces in diagnostics. | |||
16839 | PointOfInstantiation = Loc; | |||
16840 | } | |||
16841 | ||||
16842 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | |||
16843 | Func->isConstexpr()) { | |||
16844 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | |||
16845 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | |||
16846 | CodeSynthesisContexts.size()) | |||
16847 | PendingLocalImplicitInstantiations.push_back( | |||
16848 | std::make_pair(Func, PointOfInstantiation)); | |||
16849 | else if (Func->isConstexpr()) | |||
16850 | // Do not defer instantiations of constexpr functions, to avoid the | |||
16851 | // expression evaluator needing to call back into Sema if it sees a | |||
16852 | // call to such a function. | |||
16853 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | |||
16854 | else { | |||
16855 | Func->setInstantiationIsPending(true); | |||
16856 | PendingInstantiations.push_back( | |||
16857 | std::make_pair(Func, PointOfInstantiation)); | |||
16858 | // Notify the consumer that a function was implicitly instantiated. | |||
16859 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | |||
16860 | } | |||
16861 | } | |||
16862 | } else { | |||
16863 | // Walk redefinitions, as some of them may be instantiable. | |||
16864 | for (auto i : Func->redecls()) { | |||
16865 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | |||
16866 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | |||
16867 | } | |||
16868 | } | |||
16869 | }); | |||
16870 | } | |||
16871 | ||||
16872 | // C++14 [except.spec]p17: | |||
16873 | // An exception-specification is considered to be needed when: | |||
16874 | // - the function is odr-used or, if it appears in an unevaluated operand, | |||
16875 | // would be odr-used if the expression were potentially-evaluated; | |||
16876 | // | |||
16877 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | |||
16878 | // function is a pure virtual function we're calling, and in that case the | |||
16879 | // function was selected by overload resolution and we need to resolve its | |||
16880 | // exception specification for a different reason. | |||
16881 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | |||
16882 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | |||
16883 | ResolveExceptionSpec(Loc, FPT); | |||
16884 | ||||
16885 | // If this is the first "real" use, act on that. | |||
16886 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | |||
16887 | // Keep track of used but undefined functions. | |||
16888 | if (!Func->isDefined()) { | |||
16889 | if (mightHaveNonExternalLinkage(Func)) | |||
16890 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
16891 | else if (Func->getMostRecentDecl()->isInlined() && | |||
16892 | !LangOpts.GNUInline && | |||
16893 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | |||
16894 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
16895 | else if (isExternalWithNoLinkageType(Func)) | |||
16896 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | |||
16897 | } | |||
16898 | ||||
16899 | // Some x86 Windows calling conventions mangle the size of the parameter | |||
16900 | // pack into the name. Computing the size of the parameters requires the | |||
16901 | // parameter types to be complete. Check that now. | |||
16902 | if (funcHasParameterSizeMangling(*this, Func)) | |||
16903 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | |||
16904 | ||||
16905 | // In the MS C++ ABI, the compiler emits destructor variants where they are | |||
16906 | // used. If the destructor is used here but defined elsewhere, mark the | |||
16907 | // virtual base destructors referenced. If those virtual base destructors | |||
16908 | // are inline, this will ensure they are defined when emitting the complete | |||
16909 | // destructor variant. This checking may be redundant if the destructor is | |||
16910 | // provided later in this TU. | |||
16911 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
16912 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | |||
16913 | CXXRecordDecl *Parent = Dtor->getParent(); | |||
16914 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | |||
16915 | CheckCompleteDestructorVariant(Loc, Dtor); | |||
16916 | } | |||
16917 | } | |||
16918 | ||||
16919 | Func->markUsed(Context); | |||
16920 | } | |||
16921 | } | |||
16922 | ||||
16923 | /// Directly mark a variable odr-used. Given a choice, prefer to use | |||
16924 | /// MarkVariableReferenced since it does additional checks and then | |||
16925 | /// calls MarkVarDeclODRUsed. | |||
16926 | /// If the variable must be captured: | |||
16927 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | |||
16928 | /// - else capture it in the DeclContext that maps to the | |||
16929 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | |||
16930 | static void | |||
16931 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | |||
16932 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | |||
16933 | // Keep track of used but undefined variables. | |||
16934 | // FIXME: We shouldn't suppress this warning for static data members. | |||
16935 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | |||
16936 | (!Var->isExternallyVisible() || Var->isInline() || | |||
16937 | SemaRef.isExternalWithNoLinkageType(Var)) && | |||
16938 | !(Var->isStaticDataMember() && Var->hasInit())) { | |||
16939 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | |||
16940 | if (old.isInvalid()) | |||
16941 | old = Loc; | |||
16942 | } | |||
16943 | QualType CaptureType, DeclRefType; | |||
16944 | if (SemaRef.LangOpts.OpenMP) | |||
16945 | SemaRef.tryCaptureOpenMPLambdas(Var); | |||
16946 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | |||
16947 | /*EllipsisLoc*/ SourceLocation(), | |||
16948 | /*BuildAndDiagnose*/ true, | |||
16949 | CaptureType, DeclRefType, | |||
16950 | FunctionScopeIndexToStopAt); | |||
16951 | ||||
16952 | Var->markUsed(SemaRef.Context); | |||
16953 | } | |||
16954 | ||||
16955 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | |||
16956 | SourceLocation Loc, | |||
16957 | unsigned CapturingScopeIndex) { | |||
16958 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | |||
16959 | } | |||
16960 | ||||
16961 | static void | |||
16962 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
16963 | ValueDecl *var, DeclContext *DC) { | |||
16964 | DeclContext *VarDC = var->getDeclContext(); | |||
16965 | ||||
16966 | // If the parameter still belongs to the translation unit, then | |||
16967 | // we're actually just using one parameter in the declaration of | |||
16968 | // the next. | |||
16969 | if (isa<ParmVarDecl>(var) && | |||
16970 | isa<TranslationUnitDecl>(VarDC)) | |||
16971 | return; | |||
16972 | ||||
16973 | // For C code, don't diagnose about capture if we're not actually in code | |||
16974 | // right now; it's impossible to write a non-constant expression outside of | |||
16975 | // function context, so we'll get other (more useful) diagnostics later. | |||
16976 | // | |||
16977 | // For C++, things get a bit more nasty... it would be nice to suppress this | |||
16978 | // diagnostic for certain cases like using a local variable in an array bound | |||
16979 | // for a member of a local class, but the correct predicate is not obvious. | |||
16980 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | |||
16981 | return; | |||
16982 | ||||
16983 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | |||
16984 | unsigned ContextKind = 3; // unknown | |||
16985 | if (isa<CXXMethodDecl>(VarDC) && | |||
16986 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | |||
16987 | ContextKind = 2; | |||
16988 | } else if (isa<FunctionDecl>(VarDC)) { | |||
16989 | ContextKind = 0; | |||
16990 | } else if (isa<BlockDecl>(VarDC)) { | |||
16991 | ContextKind = 1; | |||
16992 | } | |||
16993 | ||||
16994 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | |||
16995 | << var << ValueKind << ContextKind << VarDC; | |||
16996 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | |||
16997 | << var; | |||
16998 | ||||
16999 | // FIXME: Add additional diagnostic info about class etc. which prevents | |||
17000 | // capture. | |||
17001 | } | |||
17002 | ||||
17003 | ||||
17004 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | |||
17005 | bool &SubCapturesAreNested, | |||
17006 | QualType &CaptureType, | |||
17007 | QualType &DeclRefType) { | |||
17008 | // Check whether we've already captured it. | |||
17009 | if (CSI->CaptureMap.count(Var)) { | |||
17010 | // If we found a capture, any subcaptures are nested. | |||
17011 | SubCapturesAreNested = true; | |||
17012 | ||||
17013 | // Retrieve the capture type for this variable. | |||
17014 | CaptureType = CSI->getCapture(Var).getCaptureType(); | |||
17015 | ||||
17016 | // Compute the type of an expression that refers to this variable. | |||
17017 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17018 | ||||
17019 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | |||
17020 | // are mutable in the sense that user can change their value - they are | |||
17021 | // private instances of the captured declarations. | |||
17022 | const Capture &Cap = CSI->getCapture(Var); | |||
17023 | if (Cap.isCopyCapture() && | |||
17024 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | |||
17025 | !(isa<CapturedRegionScopeInfo>(CSI) && | |||
17026 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | |||
17027 | DeclRefType.addConst(); | |||
17028 | return true; | |||
17029 | } | |||
17030 | return false; | |||
17031 | } | |||
17032 | ||||
17033 | // Only block literals, captured statements, and lambda expressions can | |||
17034 | // capture; other scopes don't work. | |||
17035 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | |||
17036 | SourceLocation Loc, | |||
17037 | const bool Diagnose, Sema &S) { | |||
17038 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | |||
17039 | return getLambdaAwareParentOfDeclContext(DC); | |||
17040 | else if (Var->hasLocalStorage()) { | |||
17041 | if (Diagnose) | |||
17042 | diagnoseUncapturableValueReference(S, Loc, Var, DC); | |||
17043 | } | |||
17044 | return nullptr; | |||
17045 | } | |||
17046 | ||||
17047 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | |||
17048 | // certain types of variables (unnamed, variably modified types etc.) | |||
17049 | // so check for eligibility. | |||
17050 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | |||
17051 | SourceLocation Loc, | |||
17052 | const bool Diagnose, Sema &S) { | |||
17053 | ||||
17054 | bool IsBlock = isa<BlockScopeInfo>(CSI); | |||
17055 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | |||
17056 | ||||
17057 | // Lambdas are not allowed to capture unnamed variables | |||
17058 | // (e.g. anonymous unions). | |||
17059 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | |||
17060 | // assuming that's the intent. | |||
17061 | if (IsLambda && !Var->getDeclName()) { | |||
17062 | if (Diagnose) { | |||
17063 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | |||
17064 | S.Diag(Var->getLocation(), diag::note_declared_at); | |||
17065 | } | |||
17066 | return false; | |||
17067 | } | |||
17068 | ||||
17069 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | |||
17070 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | |||
17071 | if (Diagnose) { | |||
17072 | S.Diag(Loc, diag::err_ref_vm_type); | |||
17073 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17074 | } | |||
17075 | return false; | |||
17076 | } | |||
17077 | // Prohibit structs with flexible array members too. | |||
17078 | // We cannot capture what is in the tail end of the struct. | |||
17079 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | |||
17080 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | |||
17081 | if (Diagnose) { | |||
17082 | if (IsBlock) | |||
17083 | S.Diag(Loc, diag::err_ref_flexarray_type); | |||
17084 | else | |||
17085 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | |||
17086 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17087 | } | |||
17088 | return false; | |||
17089 | } | |||
17090 | } | |||
17091 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | |||
17092 | // Lambdas and captured statements are not allowed to capture __block | |||
17093 | // variables; they don't support the expected semantics. | |||
17094 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | |||
17095 | if (Diagnose) { | |||
17096 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | |||
17097 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17098 | } | |||
17099 | return false; | |||
17100 | } | |||
17101 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | |||
17102 | if (S.getLangOpts().OpenCL && IsBlock && | |||
17103 | Var->getType()->isBlockPointerType()) { | |||
17104 | if (Diagnose) | |||
17105 | S.Diag(Loc, diag::err_opencl_block_ref_block); | |||
17106 | return false; | |||
17107 | } | |||
17108 | ||||
17109 | return true; | |||
17110 | } | |||
17111 | ||||
17112 | // Returns true if the capture by block was successful. | |||
17113 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | |||
17114 | SourceLocation Loc, | |||
17115 | const bool BuildAndDiagnose, | |||
17116 | QualType &CaptureType, | |||
17117 | QualType &DeclRefType, | |||
17118 | const bool Nested, | |||
17119 | Sema &S, bool Invalid) { | |||
17120 | bool ByRef = false; | |||
17121 | ||||
17122 | // Blocks are not allowed to capture arrays, excepting OpenCL. | |||
17123 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | |||
17124 | // (decayed to pointers). | |||
17125 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | |||
17126 | if (BuildAndDiagnose) { | |||
17127 | S.Diag(Loc, diag::err_ref_array_type); | |||
17128 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17129 | Invalid = true; | |||
17130 | } else { | |||
17131 | return false; | |||
17132 | } | |||
17133 | } | |||
17134 | ||||
17135 | // Forbid the block-capture of autoreleasing variables. | |||
17136 | if (!Invalid && | |||
17137 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | |||
17138 | if (BuildAndDiagnose) { | |||
17139 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | |||
17140 | << /*block*/ 0; | |||
17141 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17142 | Invalid = true; | |||
17143 | } else { | |||
17144 | return false; | |||
17145 | } | |||
17146 | } | |||
17147 | ||||
17148 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | |||
17149 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | |||
17150 | QualType PointeeTy = PT->getPointeeType(); | |||
17151 | ||||
17152 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | |||
17153 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | |||
17154 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | |||
17155 | if (BuildAndDiagnose) { | |||
17156 | SourceLocation VarLoc = Var->getLocation(); | |||
17157 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | |||
17158 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | |||
17159 | } | |||
17160 | } | |||
17161 | } | |||
17162 | ||||
17163 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | |||
17164 | if (HasBlocksAttr || CaptureType->isReferenceType() || | |||
17165 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | |||
17166 | // Block capture by reference does not change the capture or | |||
17167 | // declaration reference types. | |||
17168 | ByRef = true; | |||
17169 | } else { | |||
17170 | // Block capture by copy introduces 'const'. | |||
17171 | CaptureType = CaptureType.getNonReferenceType().withConst(); | |||
17172 | DeclRefType = CaptureType; | |||
17173 | } | |||
17174 | ||||
17175 | // Actually capture the variable. | |||
17176 | if (BuildAndDiagnose) | |||
17177 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | |||
17178 | CaptureType, Invalid); | |||
17179 | ||||
17180 | return !Invalid; | |||
17181 | } | |||
17182 | ||||
17183 | ||||
17184 | /// Capture the given variable in the captured region. | |||
17185 | static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, | |||
17186 | VarDecl *Var, | |||
17187 | SourceLocation Loc, | |||
17188 | const bool BuildAndDiagnose, | |||
17189 | QualType &CaptureType, | |||
17190 | QualType &DeclRefType, | |||
17191 | const bool RefersToCapturedVariable, | |||
17192 | Sema &S, bool Invalid) { | |||
17193 | // By default, capture variables by reference. | |||
17194 | bool ByRef = true; | |||
17195 | // Using an LValue reference type is consistent with Lambdas (see below). | |||
17196 | if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | |||
17197 | if (S.isOpenMPCapturedDecl(Var)) { | |||
17198 | bool HasConst = DeclRefType.isConstQualified(); | |||
17199 | DeclRefType = DeclRefType.getUnqualifiedType(); | |||
17200 | // Don't lose diagnostics about assignments to const. | |||
17201 | if (HasConst) | |||
17202 | DeclRefType.addConst(); | |||
17203 | } | |||
17204 | // Do not capture firstprivates in tasks. | |||
17205 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | |||
17206 | OMPC_unknown) | |||
17207 | return true; | |||
17208 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | |||
17209 | RSI->OpenMPCaptureLevel); | |||
17210 | } | |||
17211 | ||||
17212 | if (ByRef) | |||
17213 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | |||
17214 | else | |||
17215 | CaptureType = DeclRefType; | |||
17216 | ||||
17217 | // Actually capture the variable. | |||
17218 | if (BuildAndDiagnose) | |||
17219 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | |||
17220 | Loc, SourceLocation(), CaptureType, Invalid); | |||
17221 | ||||
17222 | return !Invalid; | |||
17223 | } | |||
17224 | ||||
17225 | /// Capture the given variable in the lambda. | |||
17226 | static bool captureInLambda(LambdaScopeInfo *LSI, | |||
17227 | VarDecl *Var, | |||
17228 | SourceLocation Loc, | |||
17229 | const bool BuildAndDiagnose, | |||
17230 | QualType &CaptureType, | |||
17231 | QualType &DeclRefType, | |||
17232 | const bool RefersToCapturedVariable, | |||
17233 | const Sema::TryCaptureKind Kind, | |||
17234 | SourceLocation EllipsisLoc, | |||
17235 | const bool IsTopScope, | |||
17236 | Sema &S, bool Invalid) { | |||
17237 | // Determine whether we are capturing by reference or by value. | |||
17238 | bool ByRef = false; | |||
17239 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | |||
17240 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | |||
17241 | } else { | |||
17242 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | |||
17243 | } | |||
17244 | ||||
17245 | // Compute the type of the field that will capture this variable. | |||
17246 | if (ByRef) { | |||
17247 | // C++11 [expr.prim.lambda]p15: | |||
17248 | // An entity is captured by reference if it is implicitly or | |||
17249 | // explicitly captured but not captured by copy. It is | |||
17250 | // unspecified whether additional unnamed non-static data | |||
17251 | // members are declared in the closure type for entities | |||
17252 | // captured by reference. | |||
17253 | // | |||
17254 | // FIXME: It is not clear whether we want to build an lvalue reference | |||
17255 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | |||
17256 | // to do the former, while EDG does the latter. Core issue 1249 will | |||
17257 | // clarify, but for now we follow GCC because it's a more permissive and | |||
17258 | // easily defensible position. | |||
17259 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | |||
17260 | } else { | |||
17261 | // C++11 [expr.prim.lambda]p14: | |||
17262 | // For each entity captured by copy, an unnamed non-static | |||
17263 | // data member is declared in the closure type. The | |||
17264 | // declaration order of these members is unspecified. The type | |||
17265 | // of such a data member is the type of the corresponding | |||
17266 | // captured entity if the entity is not a reference to an | |||
17267 | // object, or the referenced type otherwise. [Note: If the | |||
17268 | // captured entity is a reference to a function, the | |||
17269 | // corresponding data member is also a reference to a | |||
17270 | // function. - end note ] | |||
17271 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | |||
17272 | if (!RefType->getPointeeType()->isFunctionType()) | |||
17273 | CaptureType = RefType->getPointeeType(); | |||
17274 | } | |||
17275 | ||||
17276 | // Forbid the lambda copy-capture of autoreleasing variables. | |||
17277 | if (!Invalid && | |||
17278 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | |||
17279 | if (BuildAndDiagnose) { | |||
17280 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | |||
17281 | S.Diag(Var->getLocation(), diag::note_previous_decl) | |||
17282 | << Var->getDeclName(); | |||
17283 | Invalid = true; | |||
17284 | } else { | |||
17285 | return false; | |||
17286 | } | |||
17287 | } | |||
17288 | ||||
17289 | // Make sure that by-copy captures are of a complete and non-abstract type. | |||
17290 | if (!Invalid && BuildAndDiagnose) { | |||
17291 | if (!CaptureType->isDependentType() && | |||
17292 | S.RequireCompleteSizedType( | |||
17293 | Loc, CaptureType, | |||
17294 | diag::err_capture_of_incomplete_or_sizeless_type, | |||
17295 | Var->getDeclName())) | |||
17296 | Invalid = true; | |||
17297 | else if (S.RequireNonAbstractType(Loc, CaptureType, | |||
17298 | diag::err_capture_of_abstract_type)) | |||
17299 | Invalid = true; | |||
17300 | } | |||
17301 | } | |||
17302 | ||||
17303 | // Compute the type of a reference to this captured variable. | |||
17304 | if (ByRef) | |||
17305 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17306 | else { | |||
17307 | // C++ [expr.prim.lambda]p5: | |||
17308 | // The closure type for a lambda-expression has a public inline | |||
17309 | // function call operator [...]. This function call operator is | |||
17310 | // declared const (9.3.1) if and only if the lambda-expression's | |||
17311 | // parameter-declaration-clause is not followed by mutable. | |||
17312 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17313 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | |||
17314 | DeclRefType.addConst(); | |||
17315 | } | |||
17316 | ||||
17317 | // Add the capture. | |||
17318 | if (BuildAndDiagnose) | |||
17319 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | |||
17320 | Loc, EllipsisLoc, CaptureType, Invalid); | |||
17321 | ||||
17322 | return !Invalid; | |||
17323 | } | |||
17324 | ||||
17325 | bool Sema::tryCaptureVariable( | |||
17326 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | |||
17327 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | |||
17328 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | |||
17329 | // An init-capture is notionally from the context surrounding its | |||
17330 | // declaration, but its parent DC is the lambda class. | |||
17331 | DeclContext *VarDC = Var->getDeclContext(); | |||
17332 | if (Var->isInitCapture()) | |||
17333 | VarDC = VarDC->getParent(); | |||
17334 | ||||
17335 | DeclContext *DC = CurContext; | |||
17336 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | |||
17337 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | |||
17338 | // We need to sync up the Declaration Context with the | |||
17339 | // FunctionScopeIndexToStopAt | |||
17340 | if (FunctionScopeIndexToStopAt) { | |||
17341 | unsigned FSIndex = FunctionScopes.size() - 1; | |||
17342 | while (FSIndex != MaxFunctionScopesIndex) { | |||
17343 | DC = getLambdaAwareParentOfDeclContext(DC); | |||
17344 | --FSIndex; | |||
17345 | } | |||
17346 | } | |||
17347 | ||||
17348 | ||||
17349 | // If the variable is declared in the current context, there is no need to | |||
17350 | // capture it. | |||
17351 | if (VarDC == DC) return true; | |||
17352 | ||||
17353 | // Capture global variables if it is required to use private copy of this | |||
17354 | // variable. | |||
17355 | bool IsGlobal = !Var->hasLocalStorage(); | |||
17356 | if (IsGlobal && | |||
17357 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | |||
17358 | MaxFunctionScopesIndex))) | |||
17359 | return true; | |||
17360 | Var = Var->getCanonicalDecl(); | |||
17361 | ||||
17362 | // Walk up the stack to determine whether we can capture the variable, | |||
17363 | // performing the "simple" checks that don't depend on type. We stop when | |||
17364 | // we've either hit the declared scope of the variable or find an existing | |||
17365 | // capture of that variable. We start from the innermost capturing-entity | |||
17366 | // (the DC) and ensure that all intervening capturing-entities | |||
17367 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | |||
17368 | // declcontext can either capture the variable or have already captured | |||
17369 | // the variable. | |||
17370 | CaptureType = Var->getType(); | |||
17371 | DeclRefType = CaptureType.getNonReferenceType(); | |||
17372 | bool Nested = false; | |||
17373 | bool Explicit = (Kind != TryCapture_Implicit); | |||
17374 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | |||
17375 | do { | |||
17376 | // Only block literals, captured statements, and lambda expressions can | |||
17377 | // capture; other scopes don't work. | |||
17378 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | |||
17379 | ExprLoc, | |||
17380 | BuildAndDiagnose, | |||
17381 | *this); | |||
17382 | // We need to check for the parent *first* because, if we *have* | |||
17383 | // private-captured a global variable, we need to recursively capture it in | |||
17384 | // intermediate blocks, lambdas, etc. | |||
17385 | if (!ParentDC) { | |||
17386 | if (IsGlobal) { | |||
17387 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | |||
17388 | break; | |||
17389 | } | |||
17390 | return true; | |||
17391 | } | |||
17392 | ||||
17393 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | |||
17394 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | |||
17395 | ||||
17396 | ||||
17397 | // Check whether we've already captured it. | |||
17398 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | |||
17399 | DeclRefType)) { | |||
17400 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | |||
17401 | break; | |||
17402 | } | |||
17403 | // If we are instantiating a generic lambda call operator body, | |||
17404 | // we do not want to capture new variables. What was captured | |||
17405 | // during either a lambdas transformation or initial parsing | |||
17406 | // should be used. | |||
17407 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | |||
17408 | if (BuildAndDiagnose) { | |||
17409 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | |||
17410 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | |||
17411 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | |||
17412 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17413 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | |||
17414 | } else | |||
17415 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); | |||
17416 | } | |||
17417 | return true; | |||
17418 | } | |||
17419 | ||||
17420 | // Try to capture variable-length arrays types. | |||
17421 | if (Var->getType()->isVariablyModifiedType()) { | |||
17422 | // We're going to walk down into the type and look for VLA | |||
17423 | // expressions. | |||
17424 | QualType QTy = Var->getType(); | |||
17425 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | |||
17426 | QTy = PVD->getOriginalType(); | |||
17427 | captureVariablyModifiedType(Context, QTy, CSI); | |||
17428 | } | |||
17429 | ||||
17430 | if (getLangOpts().OpenMP) { | |||
17431 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
17432 | // OpenMP private variables should not be captured in outer scope, so | |||
17433 | // just break here. Similarly, global variables that are captured in a | |||
17434 | // target region should not be captured outside the scope of the region. | |||
17435 | if (RSI->CapRegionKind == CR_OpenMP) { | |||
17436 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | |||
17437 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | |||
17438 | // If the variable is private (i.e. not captured) and has variably | |||
17439 | // modified type, we still need to capture the type for correct | |||
17440 | // codegen in all regions, associated with the construct. Currently, | |||
17441 | // it is captured in the innermost captured region only. | |||
17442 | if (IsOpenMPPrivateDecl != OMPC_unknown && | |||
17443 | Var->getType()->isVariablyModifiedType()) { | |||
17444 | QualType QTy = Var->getType(); | |||
17445 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | |||
17446 | QTy = PVD->getOriginalType(); | |||
17447 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | |||
17448 | I < E; ++I) { | |||
17449 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | |||
17450 | FunctionScopes[FunctionScopesIndex - I]); | |||
17451 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17453, __PRETTY_FUNCTION__)) | |||
17452 | "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17453, __PRETTY_FUNCTION__)) | |||
17453 | "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17453, __PRETTY_FUNCTION__)); | |||
17454 | captureVariablyModifiedType(Context, QTy, OuterRSI); | |||
17455 | } | |||
17456 | } | |||
17457 | bool IsTargetCap = | |||
17458 | IsOpenMPPrivateDecl != OMPC_private && | |||
17459 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | |||
17460 | RSI->OpenMPCaptureLevel); | |||
17461 | // Do not capture global if it is not privatized in outer regions. | |||
17462 | bool IsGlobalCap = | |||
17463 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | |||
17464 | RSI->OpenMPCaptureLevel); | |||
17465 | ||||
17466 | // When we detect target captures we are looking from inside the | |||
17467 | // target region, therefore we need to propagate the capture from the | |||
17468 | // enclosing region. Therefore, the capture is not initially nested. | |||
17469 | if (IsTargetCap) | |||
17470 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | |||
17471 | ||||
17472 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | |||
17473 | (IsGlobal && !IsGlobalCap)) { | |||
17474 | Nested = !IsTargetCap; | |||
17475 | bool HasConst = DeclRefType.isConstQualified(); | |||
17476 | DeclRefType = DeclRefType.getUnqualifiedType(); | |||
17477 | // Don't lose diagnostics about assignments to const. | |||
17478 | if (HasConst) | |||
17479 | DeclRefType.addConst(); | |||
17480 | CaptureType = Context.getLValueReferenceType(DeclRefType); | |||
17481 | break; | |||
17482 | } | |||
17483 | } | |||
17484 | } | |||
17485 | } | |||
17486 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | |||
17487 | // No capture-default, and this is not an explicit capture | |||
17488 | // so cannot capture this variable. | |||
17489 | if (BuildAndDiagnose) { | |||
17490 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | |||
17491 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | |||
17492 | if (cast<LambdaScopeInfo>(CSI)->Lambda) | |||
17493 | Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), | |||
17494 | diag::note_lambda_decl); | |||
17495 | // FIXME: If we error out because an outer lambda can not implicitly | |||
17496 | // capture a variable that an inner lambda explicitly captures, we | |||
17497 | // should have the inner lambda do the explicit capture - because | |||
17498 | // it makes for cleaner diagnostics later. This would purely be done | |||
17499 | // so that the diagnostic does not misleadingly claim that a variable | |||
17500 | // can not be captured by a lambda implicitly even though it is captured | |||
17501 | // explicitly. Suggestion: | |||
17502 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | |||
17503 | // at the function head | |||
17504 | // - cache the StartingDeclContext - this must be a lambda | |||
17505 | // - captureInLambda in the innermost lambda the variable. | |||
17506 | } | |||
17507 | return true; | |||
17508 | } | |||
17509 | ||||
17510 | FunctionScopesIndex--; | |||
17511 | DC = ParentDC; | |||
17512 | Explicit = false; | |||
17513 | } while (!VarDC->Equals(DC)); | |||
17514 | ||||
17515 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | |||
17516 | // computing the type of the capture at each step, checking type-specific | |||
17517 | // requirements, and adding captures if requested. | |||
17518 | // If the variable had already been captured previously, we start capturing | |||
17519 | // at the lambda nested within that one. | |||
17520 | bool Invalid = false; | |||
17521 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | |||
17522 | ++I) { | |||
17523 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | |||
17524 | ||||
17525 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | |||
17526 | // certain types of variables (unnamed, variably modified types etc.) | |||
17527 | // so check for eligibility. | |||
17528 | if (!Invalid) | |||
17529 | Invalid = | |||
17530 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | |||
17531 | ||||
17532 | // After encountering an error, if we're actually supposed to capture, keep | |||
17533 | // capturing in nested contexts to suppress any follow-on diagnostics. | |||
17534 | if (Invalid && !BuildAndDiagnose) | |||
17535 | return true; | |||
17536 | ||||
17537 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | |||
17538 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | |||
17539 | DeclRefType, Nested, *this, Invalid); | |||
17540 | Nested = true; | |||
17541 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | |||
17542 | Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, | |||
17543 | CaptureType, DeclRefType, Nested, | |||
17544 | *this, Invalid); | |||
17545 | Nested = true; | |||
17546 | } else { | |||
17547 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | |||
17548 | Invalid = | |||
17549 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | |||
17550 | DeclRefType, Nested, Kind, EllipsisLoc, | |||
17551 | /*IsTopScope*/ I == N - 1, *this, Invalid); | |||
17552 | Nested = true; | |||
17553 | } | |||
17554 | ||||
17555 | if (Invalid && !BuildAndDiagnose) | |||
17556 | return true; | |||
17557 | } | |||
17558 | return Invalid; | |||
17559 | } | |||
17560 | ||||
17561 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | |||
17562 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | |||
17563 | QualType CaptureType; | |||
17564 | QualType DeclRefType; | |||
17565 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | |||
17566 | /*BuildAndDiagnose=*/true, CaptureType, | |||
17567 | DeclRefType, nullptr); | |||
17568 | } | |||
17569 | ||||
17570 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | |||
17571 | QualType CaptureType; | |||
17572 | QualType DeclRefType; | |||
17573 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | |||
17574 | /*BuildAndDiagnose=*/false, CaptureType, | |||
17575 | DeclRefType, nullptr); | |||
17576 | } | |||
17577 | ||||
17578 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | |||
17579 | QualType CaptureType; | |||
17580 | QualType DeclRefType; | |||
17581 | ||||
17582 | // Determine whether we can capture this variable. | |||
17583 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | |||
17584 | /*BuildAndDiagnose=*/false, CaptureType, | |||
17585 | DeclRefType, nullptr)) | |||
17586 | return QualType(); | |||
17587 | ||||
17588 | return DeclRefType; | |||
17589 | } | |||
17590 | ||||
17591 | namespace { | |||
17592 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | |||
17593 | // The produced TemplateArgumentListInfo* points to data stored within this | |||
17594 | // object, so should only be used in contexts where the pointer will not be | |||
17595 | // used after the CopiedTemplateArgs object is destroyed. | |||
17596 | class CopiedTemplateArgs { | |||
17597 | bool HasArgs; | |||
17598 | TemplateArgumentListInfo TemplateArgStorage; | |||
17599 | public: | |||
17600 | template<typename RefExpr> | |||
17601 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | |||
17602 | if (HasArgs) | |||
17603 | E->copyTemplateArgumentsInto(TemplateArgStorage); | |||
17604 | } | |||
17605 | operator TemplateArgumentListInfo*() | |||
17606 | #ifdef __has_cpp_attribute | |||
17607 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | |||
17608 | [[clang::lifetimebound]] | |||
17609 | #endif | |||
17610 | #endif | |||
17611 | { | |||
17612 | return HasArgs ? &TemplateArgStorage : nullptr; | |||
17613 | } | |||
17614 | }; | |||
17615 | } | |||
17616 | ||||
17617 | /// Walk the set of potential results of an expression and mark them all as | |||
17618 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | |||
17619 | /// | |||
17620 | /// \return A new expression if we found any potential results, ExprEmpty() if | |||
17621 | /// not, and ExprError() if we diagnosed an error. | |||
17622 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | |||
17623 | NonOdrUseReason NOUR) { | |||
17624 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | |||
17625 | // an object that satisfies the requirements for appearing in a | |||
17626 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | |||
17627 | // is immediately applied." This function handles the lvalue-to-rvalue | |||
17628 | // conversion part. | |||
17629 | // | |||
17630 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | |||
17631 | // transform it into the relevant kind of non-odr-use node and rebuild the | |||
17632 | // tree of nodes leading to it. | |||
17633 | // | |||
17634 | // This is a mini-TreeTransform that only transforms a restricted subset of | |||
17635 | // nodes (and only certain operands of them). | |||
17636 | ||||
17637 | // Rebuild a subexpression. | |||
17638 | auto Rebuild = [&](Expr *Sub) { | |||
17639 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | |||
17640 | }; | |||
17641 | ||||
17642 | // Check whether a potential result satisfies the requirements of NOUR. | |||
17643 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | |||
17644 | // Any entity other than a VarDecl is always odr-used whenever it's named | |||
17645 | // in a potentially-evaluated expression. | |||
17646 | auto *VD = dyn_cast<VarDecl>(D); | |||
17647 | if (!VD) | |||
17648 | return true; | |||
17649 | ||||
17650 | // C++2a [basic.def.odr]p4: | |||
17651 | // A variable x whose name appears as a potentially-evalauted expression | |||
17652 | // e is odr-used by e unless | |||
17653 | // -- x is a reference that is usable in constant expressions, or | |||
17654 | // -- x is a variable of non-reference type that is usable in constant | |||
17655 | // expressions and has no mutable subobjects, and e is an element of | |||
17656 | // the set of potential results of an expression of | |||
17657 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | |||
17658 | // conversion is applied, or | |||
17659 | // -- x is a variable of non-reference type, and e is an element of the | |||
17660 | // set of potential results of a discarded-value expression to which | |||
17661 | // the lvalue-to-rvalue conversion is not applied | |||
17662 | // | |||
17663 | // We check the first bullet and the "potentially-evaluated" condition in | |||
17664 | // BuildDeclRefExpr. We check the type requirements in the second bullet | |||
17665 | // in CheckLValueToRValueConversionOperand below. | |||
17666 | switch (NOUR) { | |||
17667 | case NOUR_None: | |||
17668 | case NOUR_Unevaluated: | |||
17669 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17669); | |||
17670 | ||||
17671 | case NOUR_Constant: | |||
17672 | // Constant references were handled when they were built. | |||
17673 | if (VD->getType()->isReferenceType()) | |||
17674 | return true; | |||
17675 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | |||
17676 | if (RD->hasMutableFields()) | |||
17677 | return true; | |||
17678 | if (!VD->isUsableInConstantExpressions(S.Context)) | |||
17679 | return true; | |||
17680 | break; | |||
17681 | ||||
17682 | case NOUR_Discarded: | |||
17683 | if (VD->getType()->isReferenceType()) | |||
17684 | return true; | |||
17685 | break; | |||
17686 | } | |||
17687 | return false; | |||
17688 | }; | |||
17689 | ||||
17690 | // Mark that this expression does not constitute an odr-use. | |||
17691 | auto MarkNotOdrUsed = [&] { | |||
17692 | S.MaybeODRUseExprs.remove(E); | |||
17693 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | |||
17694 | LSI->markVariableExprAsNonODRUsed(E); | |||
17695 | }; | |||
17696 | ||||
17697 | // C++2a [basic.def.odr]p2: | |||
17698 | // The set of potential results of an expression e is defined as follows: | |||
17699 | switch (E->getStmtClass()) { | |||
17700 | // -- If e is an id-expression, ... | |||
17701 | case Expr::DeclRefExprClass: { | |||
17702 | auto *DRE = cast<DeclRefExpr>(E); | |||
17703 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | |||
17704 | break; | |||
17705 | ||||
17706 | // Rebuild as a non-odr-use DeclRefExpr. | |||
17707 | MarkNotOdrUsed(); | |||
17708 | return DeclRefExpr::Create( | |||
17709 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | |||
17710 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | |||
17711 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | |||
17712 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | |||
17713 | } | |||
17714 | ||||
17715 | case Expr::FunctionParmPackExprClass: { | |||
17716 | auto *FPPE = cast<FunctionParmPackExpr>(E); | |||
17717 | // If any of the declarations in the pack is odr-used, then the expression | |||
17718 | // as a whole constitutes an odr-use. | |||
17719 | for (VarDecl *D : *FPPE) | |||
17720 | if (IsPotentialResultOdrUsed(D)) | |||
17721 | return ExprEmpty(); | |||
17722 | ||||
17723 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | |||
17724 | // nothing cares about whether we marked this as an odr-use, but it might | |||
17725 | // be useful for non-compiler tools. | |||
17726 | MarkNotOdrUsed(); | |||
17727 | break; | |||
17728 | } | |||
17729 | ||||
17730 | // -- If e is a subscripting operation with an array operand... | |||
17731 | case Expr::ArraySubscriptExprClass: { | |||
17732 | auto *ASE = cast<ArraySubscriptExpr>(E); | |||
17733 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | |||
17734 | if (!OldBase->getType()->isArrayType()) | |||
17735 | break; | |||
17736 | ExprResult Base = Rebuild(OldBase); | |||
17737 | if (!Base.isUsable()) | |||
17738 | return Base; | |||
17739 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | |||
17740 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | |||
17741 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | |||
17742 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | |||
17743 | ASE->getRBracketLoc()); | |||
17744 | } | |||
17745 | ||||
17746 | case Expr::MemberExprClass: { | |||
17747 | auto *ME = cast<MemberExpr>(E); | |||
17748 | // -- If e is a class member access expression [...] naming a non-static | |||
17749 | // data member... | |||
17750 | if (isa<FieldDecl>(ME->getMemberDecl())) { | |||
17751 | ExprResult Base = Rebuild(ME->getBase()); | |||
17752 | if (!Base.isUsable()) | |||
17753 | return Base; | |||
17754 | return MemberExpr::Create( | |||
17755 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | |||
17756 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | |||
17757 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | |||
17758 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | |||
17759 | ME->getObjectKind(), ME->isNonOdrUse()); | |||
17760 | } | |||
17761 | ||||
17762 | if (ME->getMemberDecl()->isCXXInstanceMember()) | |||
17763 | break; | |||
17764 | ||||
17765 | // -- If e is a class member access expression naming a static data member, | |||
17766 | // ... | |||
17767 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | |||
17768 | break; | |||
17769 | ||||
17770 | // Rebuild as a non-odr-use MemberExpr. | |||
17771 | MarkNotOdrUsed(); | |||
17772 | return MemberExpr::Create( | |||
17773 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | |||
17774 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | |||
17775 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | |||
17776 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | |||
17777 | return ExprEmpty(); | |||
17778 | } | |||
17779 | ||||
17780 | case Expr::BinaryOperatorClass: { | |||
17781 | auto *BO = cast<BinaryOperator>(E); | |||
17782 | Expr *LHS = BO->getLHS(); | |||
17783 | Expr *RHS = BO->getRHS(); | |||
17784 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | |||
17785 | if (BO->getOpcode() == BO_PtrMemD) { | |||
17786 | ExprResult Sub = Rebuild(LHS); | |||
17787 | if (!Sub.isUsable()) | |||
17788 | return Sub; | |||
17789 | LHS = Sub.get(); | |||
17790 | // -- If e is a comma expression, ... | |||
17791 | } else if (BO->getOpcode() == BO_Comma) { | |||
17792 | ExprResult Sub = Rebuild(RHS); | |||
17793 | if (!Sub.isUsable()) | |||
17794 | return Sub; | |||
17795 | RHS = Sub.get(); | |||
17796 | } else { | |||
17797 | break; | |||
17798 | } | |||
17799 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | |||
17800 | LHS, RHS); | |||
17801 | } | |||
17802 | ||||
17803 | // -- If e has the form (e1)... | |||
17804 | case Expr::ParenExprClass: { | |||
17805 | auto *PE = cast<ParenExpr>(E); | |||
17806 | ExprResult Sub = Rebuild(PE->getSubExpr()); | |||
17807 | if (!Sub.isUsable()) | |||
17808 | return Sub; | |||
17809 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | |||
17810 | } | |||
17811 | ||||
17812 | // -- If e is a glvalue conditional expression, ... | |||
17813 | // We don't apply this to a binary conditional operator. FIXME: Should we? | |||
17814 | case Expr::ConditionalOperatorClass: { | |||
17815 | auto *CO = cast<ConditionalOperator>(E); | |||
17816 | ExprResult LHS = Rebuild(CO->getLHS()); | |||
17817 | if (LHS.isInvalid()) | |||
17818 | return ExprError(); | |||
17819 | ExprResult RHS = Rebuild(CO->getRHS()); | |||
17820 | if (RHS.isInvalid()) | |||
17821 | return ExprError(); | |||
17822 | if (!LHS.isUsable() && !RHS.isUsable()) | |||
17823 | return ExprEmpty(); | |||
17824 | if (!LHS.isUsable()) | |||
17825 | LHS = CO->getLHS(); | |||
17826 | if (!RHS.isUsable()) | |||
17827 | RHS = CO->getRHS(); | |||
17828 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | |||
17829 | CO->getCond(), LHS.get(), RHS.get()); | |||
17830 | } | |||
17831 | ||||
17832 | // [Clang extension] | |||
17833 | // -- If e has the form __extension__ e1... | |||
17834 | case Expr::UnaryOperatorClass: { | |||
17835 | auto *UO = cast<UnaryOperator>(E); | |||
17836 | if (UO->getOpcode() != UO_Extension) | |||
17837 | break; | |||
17838 | ExprResult Sub = Rebuild(UO->getSubExpr()); | |||
17839 | if (!Sub.isUsable()) | |||
17840 | return Sub; | |||
17841 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | |||
17842 | Sub.get()); | |||
17843 | } | |||
17844 | ||||
17845 | // [Clang extension] | |||
17846 | // -- If e has the form _Generic(...), the set of potential results is the | |||
17847 | // union of the sets of potential results of the associated expressions. | |||
17848 | case Expr::GenericSelectionExprClass: { | |||
17849 | auto *GSE = cast<GenericSelectionExpr>(E); | |||
17850 | ||||
17851 | SmallVector<Expr *, 4> AssocExprs; | |||
17852 | bool AnyChanged = false; | |||
17853 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | |||
17854 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | |||
17855 | if (AssocExpr.isInvalid()) | |||
17856 | return ExprError(); | |||
17857 | if (AssocExpr.isUsable()) { | |||
17858 | AssocExprs.push_back(AssocExpr.get()); | |||
17859 | AnyChanged = true; | |||
17860 | } else { | |||
17861 | AssocExprs.push_back(OrigAssocExpr); | |||
17862 | } | |||
17863 | } | |||
17864 | ||||
17865 | return AnyChanged ? S.CreateGenericSelectionExpr( | |||
17866 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | |||
17867 | GSE->getRParenLoc(), GSE->getControllingExpr(), | |||
17868 | GSE->getAssocTypeSourceInfos(), AssocExprs) | |||
17869 | : ExprEmpty(); | |||
17870 | } | |||
17871 | ||||
17872 | // [Clang extension] | |||
17873 | // -- If e has the form __builtin_choose_expr(...), the set of potential | |||
17874 | // results is the union of the sets of potential results of the | |||
17875 | // second and third subexpressions. | |||
17876 | case Expr::ChooseExprClass: { | |||
17877 | auto *CE = cast<ChooseExpr>(E); | |||
17878 | ||||
17879 | ExprResult LHS = Rebuild(CE->getLHS()); | |||
17880 | if (LHS.isInvalid()) | |||
17881 | return ExprError(); | |||
17882 | ||||
17883 | ExprResult RHS = Rebuild(CE->getLHS()); | |||
17884 | if (RHS.isInvalid()) | |||
17885 | return ExprError(); | |||
17886 | ||||
17887 | if (!LHS.get() && !RHS.get()) | |||
17888 | return ExprEmpty(); | |||
17889 | if (!LHS.isUsable()) | |||
17890 | LHS = CE->getLHS(); | |||
17891 | if (!RHS.isUsable()) | |||
17892 | RHS = CE->getRHS(); | |||
17893 | ||||
17894 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | |||
17895 | RHS.get(), CE->getRParenLoc()); | |||
17896 | } | |||
17897 | ||||
17898 | // Step through non-syntactic nodes. | |||
17899 | case Expr::ConstantExprClass: { | |||
17900 | auto *CE = cast<ConstantExpr>(E); | |||
17901 | ExprResult Sub = Rebuild(CE->getSubExpr()); | |||
17902 | if (!Sub.isUsable()) | |||
17903 | return Sub; | |||
17904 | return ConstantExpr::Create(S.Context, Sub.get()); | |||
17905 | } | |||
17906 | ||||
17907 | // We could mostly rely on the recursive rebuilding to rebuild implicit | |||
17908 | // casts, but not at the top level, so rebuild them here. | |||
17909 | case Expr::ImplicitCastExprClass: { | |||
17910 | auto *ICE = cast<ImplicitCastExpr>(E); | |||
17911 | // Only step through the narrow set of cast kinds we expect to encounter. | |||
17912 | // Anything else suggests we've left the region in which potential results | |||
17913 | // can be found. | |||
17914 | switch (ICE->getCastKind()) { | |||
17915 | case CK_NoOp: | |||
17916 | case CK_DerivedToBase: | |||
17917 | case CK_UncheckedDerivedToBase: { | |||
17918 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | |||
17919 | if (!Sub.isUsable()) | |||
17920 | return Sub; | |||
17921 | CXXCastPath Path(ICE->path()); | |||
17922 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | |||
17923 | ICE->getValueKind(), &Path); | |||
17924 | } | |||
17925 | ||||
17926 | default: | |||
17927 | break; | |||
17928 | } | |||
17929 | break; | |||
17930 | } | |||
17931 | ||||
17932 | default: | |||
17933 | break; | |||
17934 | } | |||
17935 | ||||
17936 | // Can't traverse through this node. Nothing to do. | |||
17937 | return ExprEmpty(); | |||
17938 | } | |||
17939 | ||||
17940 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | |||
17941 | // Check whether the operand is or contains an object of non-trivial C union | |||
17942 | // type. | |||
17943 | if (E->getType().isVolatileQualified() && | |||
17944 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | |||
17945 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | |||
17946 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | |||
17947 | Sema::NTCUC_LValueToRValueVolatile, | |||
17948 | NTCUK_Destruct|NTCUK_Copy); | |||
17949 | ||||
17950 | // C++2a [basic.def.odr]p4: | |||
17951 | // [...] an expression of non-volatile-qualified non-class type to which | |||
17952 | // the lvalue-to-rvalue conversion is applied [...] | |||
17953 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | |||
17954 | return E; | |||
17955 | ||||
17956 | ExprResult Result = | |||
17957 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | |||
17958 | if (Result.isInvalid()) | |||
17959 | return ExprError(); | |||
17960 | return Result.get() ? Result : E; | |||
17961 | } | |||
17962 | ||||
17963 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | |||
17964 | Res = CorrectDelayedTyposInExpr(Res); | |||
17965 | ||||
17966 | if (!Res.isUsable()) | |||
17967 | return Res; | |||
17968 | ||||
17969 | // If a constant-expression is a reference to a variable where we delay | |||
17970 | // deciding whether it is an odr-use, just assume we will apply the | |||
17971 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | |||
17972 | // (a non-type template argument), we have special handling anyway. | |||
17973 | return CheckLValueToRValueConversionOperand(Res.get()); | |||
17974 | } | |||
17975 | ||||
17976 | void Sema::CleanupVarDeclMarking() { | |||
17977 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | |||
17978 | // call. | |||
17979 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | |||
17980 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | |||
17981 | ||||
17982 | for (Expr *E : LocalMaybeODRUseExprs) { | |||
17983 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
17984 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | |||
17985 | DRE->getLocation(), *this); | |||
17986 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | |||
17987 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | |||
17988 | *this); | |||
17989 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | |||
17990 | for (VarDecl *VD : *FP) | |||
17991 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | |||
17992 | } else { | |||
17993 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17993); | |||
17994 | } | |||
17995 | } | |||
17996 | ||||
17997 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17998, __PRETTY_FUNCTION__)) | |||
17998 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 17998, __PRETTY_FUNCTION__)); | |||
17999 | } | |||
18000 | ||||
18001 | static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, | |||
18002 | VarDecl *Var, Expr *E) { | |||
18003 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18005, __PRETTY_FUNCTION__)) | |||
18004 | isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18005, __PRETTY_FUNCTION__)) | |||
18005 | "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18005, __PRETTY_FUNCTION__)); | |||
18006 | Var->setReferenced(); | |||
18007 | ||||
18008 | if (Var->isInvalidDecl()) | |||
18009 | return; | |||
18010 | ||||
18011 | // Record a CUDA/HIP static device/constant variable if it is referenced | |||
18012 | // by host code. This is done conservatively, when the variable is referenced | |||
18013 | // in any of the following contexts: | |||
18014 | // - a non-function context | |||
18015 | // - a host function | |||
18016 | // - a host device function | |||
18017 | // This also requires the reference of the static device/constant variable by | |||
18018 | // host code to be visible in the device compilation for the compiler to be | |||
18019 | // able to externalize the static device/constant variable. | |||
18020 | if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { | |||
18021 | auto *CurContext = SemaRef.CurContext; | |||
18022 | if (!CurContext || !isa<FunctionDecl>(CurContext) || | |||
18023 | cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || | |||
18024 | (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && | |||
18025 | !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) | |||
18026 | SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); | |||
18027 | } | |||
18028 | ||||
18029 | auto *MSI = Var->getMemberSpecializationInfo(); | |||
18030 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | |||
18031 | : Var->getTemplateSpecializationKind(); | |||
18032 | ||||
18033 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | |||
18034 | bool UsableInConstantExpr = | |||
18035 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | |||
18036 | ||||
18037 | // C++20 [expr.const]p12: | |||
18038 | // A variable [...] is needed for constant evaluation if it is [...] a | |||
18039 | // variable whose name appears as a potentially constant evaluated | |||
18040 | // expression that is either a contexpr variable or is of non-volatile | |||
18041 | // const-qualified integral type or of reference type | |||
18042 | bool NeededForConstantEvaluation = | |||
18043 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | |||
18044 | ||||
18045 | bool NeedDefinition = | |||
18046 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | |||
18047 | ||||
18048 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18049, __PRETTY_FUNCTION__)) | |||
18049 | "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18049, __PRETTY_FUNCTION__)); | |||
18050 | ||||
18051 | // If this might be a member specialization of a static data member, check | |||
18052 | // the specialization is visible. We already did the checks for variable | |||
18053 | // template specializations when we created them. | |||
18054 | if (NeedDefinition && TSK != TSK_Undeclared && | |||
18055 | !isa<VarTemplateSpecializationDecl>(Var)) | |||
18056 | SemaRef.checkSpecializationVisibility(Loc, Var); | |||
18057 | ||||
18058 | // Perform implicit instantiation of static data members, static data member | |||
18059 | // templates of class templates, and variable template specializations. Delay | |||
18060 | // instantiations of variable templates, except for those that could be used | |||
18061 | // in a constant expression. | |||
18062 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | |||
18063 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | |||
18064 | // instantiation declaration if a variable is usable in a constant | |||
18065 | // expression (among other cases). | |||
18066 | bool TryInstantiating = | |||
18067 | TSK == TSK_ImplicitInstantiation || | |||
18068 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | |||
18069 | ||||
18070 | if (TryInstantiating) { | |||
18071 | SourceLocation PointOfInstantiation = | |||
18072 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | |||
18073 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | |||
18074 | if (FirstInstantiation) { | |||
18075 | PointOfInstantiation = Loc; | |||
18076 | if (MSI) | |||
18077 | MSI->setPointOfInstantiation(PointOfInstantiation); | |||
18078 | // FIXME: Notify listener. | |||
18079 | else | |||
18080 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | |||
18081 | } | |||
18082 | ||||
18083 | if (UsableInConstantExpr) { | |||
18084 | // Do not defer instantiations of variables that could be used in a | |||
18085 | // constant expression. | |||
18086 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | |||
18087 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
18088 | }); | |||
18089 | } else if (FirstInstantiation || | |||
18090 | isa<VarTemplateSpecializationDecl>(Var)) { | |||
18091 | // FIXME: For a specialization of a variable template, we don't | |||
18092 | // distinguish between "declaration and type implicitly instantiated" | |||
18093 | // and "implicit instantiation of definition requested", so we have | |||
18094 | // no direct way to avoid enqueueing the pending instantiation | |||
18095 | // multiple times. | |||
18096 | SemaRef.PendingInstantiations | |||
18097 | .push_back(std::make_pair(Var, PointOfInstantiation)); | |||
18098 | } | |||
18099 | } | |||
18100 | } | |||
18101 | ||||
18102 | // C++2a [basic.def.odr]p4: | |||
18103 | // A variable x whose name appears as a potentially-evaluated expression e | |||
18104 | // is odr-used by e unless | |||
18105 | // -- x is a reference that is usable in constant expressions | |||
18106 | // -- x is a variable of non-reference type that is usable in constant | |||
18107 | // expressions and has no mutable subobjects [FIXME], and e is an | |||
18108 | // element of the set of potential results of an expression of | |||
18109 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | |||
18110 | // conversion is applied | |||
18111 | // -- x is a variable of non-reference type, and e is an element of the set | |||
18112 | // of potential results of a discarded-value expression to which the | |||
18113 | // lvalue-to-rvalue conversion is not applied [FIXME] | |||
18114 | // | |||
18115 | // We check the first part of the second bullet here, and | |||
18116 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | |||
18117 | // FIXME: To get the third bullet right, we need to delay this even for | |||
18118 | // variables that are not usable in constant expressions. | |||
18119 | ||||
18120 | // If we already know this isn't an odr-use, there's nothing more to do. | |||
18121 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | |||
18122 | if (DRE->isNonOdrUse()) | |||
18123 | return; | |||
18124 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | |||
18125 | if (ME->isNonOdrUse()) | |||
18126 | return; | |||
18127 | ||||
18128 | switch (OdrUse) { | |||
18129 | case OdrUseContext::None: | |||
18130 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18131, __PRETTY_FUNCTION__)) | |||
18131 | "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18131, __PRETTY_FUNCTION__)); | |||
18132 | break; | |||
18133 | ||||
18134 | case OdrUseContext::FormallyOdrUsed: | |||
18135 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | |||
18136 | // behavior. | |||
18137 | break; | |||
18138 | ||||
18139 | case OdrUseContext::Used: | |||
18140 | // If we might later find that this expression isn't actually an odr-use, | |||
18141 | // delay the marking. | |||
18142 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | |||
18143 | SemaRef.MaybeODRUseExprs.insert(E); | |||
18144 | else | |||
18145 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | |||
18146 | break; | |||
18147 | ||||
18148 | case OdrUseContext::Dependent: | |||
18149 | // If this is a dependent context, we don't need to mark variables as | |||
18150 | // odr-used, but we may still need to track them for lambda capture. | |||
18151 | // FIXME: Do we also need to do this inside dependent typeid expressions | |||
18152 | // (which are modeled as unevaluated at this point)? | |||
18153 | const bool RefersToEnclosingScope = | |||
18154 | (SemaRef.CurContext != Var->getDeclContext() && | |||
18155 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | |||
18156 | if (RefersToEnclosingScope) { | |||
18157 | LambdaScopeInfo *const LSI = | |||
18158 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | |||
18159 | if (LSI && (!LSI->CallOperator || | |||
18160 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | |||
18161 | // If a variable could potentially be odr-used, defer marking it so | |||
18162 | // until we finish analyzing the full expression for any | |||
18163 | // lvalue-to-rvalue | |||
18164 | // or discarded value conversions that would obviate odr-use. | |||
18165 | // Add it to the list of potential captures that will be analyzed | |||
18166 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | |||
18167 | // unless the variable is a reference that was initialized by a constant | |||
18168 | // expression (this will never need to be captured or odr-used). | |||
18169 | // | |||
18170 | // FIXME: We can simplify this a lot after implementing P0588R1. | |||
18171 | assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression." ) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18171, __PRETTY_FUNCTION__)); | |||
18172 | if (!Var->getType()->isReferenceType() || | |||
18173 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | |||
18174 | LSI->addPotentialCapture(E->IgnoreParens()); | |||
18175 | } | |||
18176 | } | |||
18177 | break; | |||
18178 | } | |||
18179 | } | |||
18180 | ||||
18181 | /// Mark a variable referenced, and check whether it is odr-used | |||
18182 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | |||
18183 | /// used directly for normal expressions referring to VarDecl. | |||
18184 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | |||
18185 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); | |||
18186 | } | |||
18187 | ||||
18188 | static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, | |||
18189 | Decl *D, Expr *E, bool MightBeOdrUse) { | |||
18190 | if (SemaRef.isInOpenMPDeclareTargetContext()) | |||
18191 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | |||
18192 | ||||
18193 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | |||
18194 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); | |||
18195 | return; | |||
18196 | } | |||
18197 | ||||
18198 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | |||
18199 | ||||
18200 | // If this is a call to a method via a cast, also mark the method in the | |||
18201 | // derived class used in case codegen can devirtualize the call. | |||
18202 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | |||
18203 | if (!ME) | |||
18204 | return; | |||
18205 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | |||
18206 | if (!MD) | |||
18207 | return; | |||
18208 | // Only attempt to devirtualize if this is truly a virtual call. | |||
18209 | bool IsVirtualCall = MD->isVirtual() && | |||
18210 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | |||
18211 | if (!IsVirtualCall) | |||
18212 | return; | |||
18213 | ||||
18214 | // If it's possible to devirtualize the call, mark the called function | |||
18215 | // referenced. | |||
18216 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | |||
18217 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | |||
18218 | if (DM) | |||
18219 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | |||
18220 | } | |||
18221 | ||||
18222 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | |||
18223 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | |||
18224 | // TODO: update this with DR# once a defect report is filed. | |||
18225 | // C++11 defect. The address of a pure member should not be an ODR use, even | |||
18226 | // if it's a qualified reference. | |||
18227 | bool OdrUse = true; | |||
18228 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | |||
18229 | if (Method->isVirtual() && | |||
18230 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | |||
18231 | OdrUse = false; | |||
18232 | ||||
18233 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | |||
18234 | if (!isConstantEvaluated() && FD->isConsteval() && | |||
18235 | !RebuildingImmediateInvocation) | |||
18236 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | |||
18237 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); | |||
18238 | } | |||
18239 | ||||
18240 | /// Perform reference-marking and odr-use handling for a MemberExpr. | |||
18241 | void Sema::MarkMemberReferenced(MemberExpr *E) { | |||
18242 | // C++11 [basic.def.odr]p2: | |||
18243 | // A non-overloaded function whose name appears as a potentially-evaluated | |||
18244 | // expression or a member of a set of candidate functions, if selected by | |||
18245 | // overload resolution when referred to from a potentially-evaluated | |||
18246 | // expression, is odr-used, unless it is a pure virtual function and its | |||
18247 | // name is not explicitly qualified. | |||
18248 | bool MightBeOdrUse = true; | |||
18249 | if (E->performsVirtualDispatch(getLangOpts())) { | |||
18250 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | |||
18251 | if (Method->isPure()) | |||
18252 | MightBeOdrUse = false; | |||
18253 | } | |||
18254 | SourceLocation Loc = | |||
18255 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | |||
18256 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); | |||
18257 | } | |||
18258 | ||||
18259 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | |||
18260 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | |||
18261 | for (VarDecl *VD : *E) | |||
18262 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); | |||
18263 | } | |||
18264 | ||||
18265 | /// Perform marking for a reference to an arbitrary declaration. It | |||
18266 | /// marks the declaration referenced, and performs odr-use checking for | |||
18267 | /// functions and variables. This method should not be used when building a | |||
18268 | /// normal expression which refers to a variable. | |||
18269 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | |||
18270 | bool MightBeOdrUse) { | |||
18271 | if (MightBeOdrUse) { | |||
18272 | if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
18273 | MarkVariableReferenced(Loc, VD); | |||
18274 | return; | |||
18275 | } | |||
18276 | } | |||
18277 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
18278 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | |||
18279 | return; | |||
18280 | } | |||
18281 | D->setReferenced(); | |||
18282 | } | |||
18283 | ||||
18284 | namespace { | |||
18285 | // Mark all of the declarations used by a type as referenced. | |||
18286 | // FIXME: Not fully implemented yet! We need to have a better understanding | |||
18287 | // of when we're entering a context we should not recurse into. | |||
18288 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | |||
18289 | // TreeTransforms rebuilding the type in a new context. Rather than | |||
18290 | // duplicating the TreeTransform logic, we should consider reusing it here. | |||
18291 | // Currently that causes problems when rebuilding LambdaExprs. | |||
18292 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | |||
18293 | Sema &S; | |||
18294 | SourceLocation Loc; | |||
18295 | ||||
18296 | public: | |||
18297 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | |||
18298 | ||||
18299 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | |||
18300 | ||||
18301 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | |||
18302 | }; | |||
18303 | } | |||
18304 | ||||
18305 | bool MarkReferencedDecls::TraverseTemplateArgument( | |||
18306 | const TemplateArgument &Arg) { | |||
18307 | { | |||
18308 | // A non-type template argument is a constant-evaluated context. | |||
18309 | EnterExpressionEvaluationContext Evaluated( | |||
18310 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | |||
18311 | if (Arg.getKind() == TemplateArgument::Declaration) { | |||
18312 | if (Decl *D = Arg.getAsDecl()) | |||
18313 | S.MarkAnyDeclReferenced(Loc, D, true); | |||
18314 | } else if (Arg.getKind() == TemplateArgument::Expression) { | |||
18315 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | |||
18316 | } | |||
18317 | } | |||
18318 | ||||
18319 | return Inherited::TraverseTemplateArgument(Arg); | |||
18320 | } | |||
18321 | ||||
18322 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | |||
18323 | MarkReferencedDecls Marker(*this, Loc); | |||
18324 | Marker.TraverseType(T); | |||
18325 | } | |||
18326 | ||||
18327 | namespace { | |||
18328 | /// Helper class that marks all of the declarations referenced by | |||
18329 | /// potentially-evaluated subexpressions as "referenced". | |||
18330 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | |||
18331 | public: | |||
18332 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | |||
18333 | bool SkipLocalVariables; | |||
18334 | ||||
18335 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) | |||
18336 | : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} | |||
18337 | ||||
18338 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | |||
18339 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | |||
18340 | } | |||
18341 | ||||
18342 | void VisitDeclRefExpr(DeclRefExpr *E) { | |||
18343 | // If we were asked not to visit local variables, don't. | |||
18344 | if (SkipLocalVariables) { | |||
18345 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | |||
18346 | if (VD->hasLocalStorage()) | |||
18347 | return; | |||
18348 | } | |||
18349 | S.MarkDeclRefReferenced(E); | |||
18350 | } | |||
18351 | ||||
18352 | void VisitMemberExpr(MemberExpr *E) { | |||
18353 | S.MarkMemberReferenced(E); | |||
18354 | Visit(E->getBase()); | |||
18355 | } | |||
18356 | }; | |||
18357 | } // namespace | |||
18358 | ||||
18359 | /// Mark any declarations that appear within this expression or any | |||
18360 | /// potentially-evaluated subexpressions as "referenced". | |||
18361 | /// | |||
18362 | /// \param SkipLocalVariables If true, don't mark local variables as | |||
18363 | /// 'referenced'. | |||
18364 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | |||
18365 | bool SkipLocalVariables) { | |||
18366 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); | |||
18367 | } | |||
18368 | ||||
18369 | /// Emit a diagnostic that describes an effect on the run-time behavior | |||
18370 | /// of the program being compiled. | |||
18371 | /// | |||
18372 | /// This routine emits the given diagnostic when the code currently being | |||
18373 | /// type-checked is "potentially evaluated", meaning that there is a | |||
18374 | /// possibility that the code will actually be executable. Code in sizeof() | |||
18375 | /// expressions, code used only during overload resolution, etc., are not | |||
18376 | /// potentially evaluated. This routine will suppress such diagnostics or, | |||
18377 | /// in the absolutely nutty case of potentially potentially evaluated | |||
18378 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | |||
18379 | /// later. | |||
18380 | /// | |||
18381 | /// This routine should be used for all diagnostics that describe the run-time | |||
18382 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | |||
18383 | /// Failure to do so will likely result in spurious diagnostics or failures | |||
18384 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | |||
18385 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | |||
18386 | const PartialDiagnostic &PD) { | |||
18387 | switch (ExprEvalContexts.back().Context) { | |||
18388 | case ExpressionEvaluationContext::Unevaluated: | |||
18389 | case ExpressionEvaluationContext::UnevaluatedList: | |||
18390 | case ExpressionEvaluationContext::UnevaluatedAbstract: | |||
18391 | case ExpressionEvaluationContext::DiscardedStatement: | |||
18392 | // The argument will never be evaluated, so don't complain. | |||
18393 | break; | |||
18394 | ||||
18395 | case ExpressionEvaluationContext::ConstantEvaluated: | |||
18396 | // Relevant diagnostics should be produced by constant evaluation. | |||
18397 | break; | |||
18398 | ||||
18399 | case ExpressionEvaluationContext::PotentiallyEvaluated: | |||
18400 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | |||
18401 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | |||
18402 | FunctionScopes.back()->PossiblyUnreachableDiags. | |||
18403 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | |||
18404 | return true; | |||
18405 | } | |||
18406 | ||||
18407 | // The initializer of a constexpr variable or of the first declaration of a | |||
18408 | // static data member is not syntactically a constant evaluated constant, | |||
18409 | // but nonetheless is always required to be a constant expression, so we | |||
18410 | // can skip diagnosing. | |||
18411 | // FIXME: Using the mangling context here is a hack. | |||
18412 | if (auto *VD = dyn_cast_or_null<VarDecl>( | |||
18413 | ExprEvalContexts.back().ManglingContextDecl)) { | |||
18414 | if (VD->isConstexpr() || | |||
18415 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | |||
18416 | break; | |||
18417 | // FIXME: For any other kind of variable, we should build a CFG for its | |||
18418 | // initializer and check whether the context in question is reachable. | |||
18419 | } | |||
18420 | ||||
18421 | Diag(Loc, PD); | |||
18422 | return true; | |||
18423 | } | |||
18424 | ||||
18425 | return false; | |||
18426 | } | |||
18427 | ||||
18428 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | |||
18429 | const PartialDiagnostic &PD) { | |||
18430 | return DiagRuntimeBehavior( | |||
18431 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | |||
18432 | } | |||
18433 | ||||
18434 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | |||
18435 | CallExpr *CE, FunctionDecl *FD) { | |||
18436 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | |||
18437 | return false; | |||
18438 | ||||
18439 | // If we're inside a decltype's expression, don't check for a valid return | |||
18440 | // type or construct temporaries until we know whether this is the last call. | |||
18441 | if (ExprEvalContexts.back().ExprContext == | |||
18442 | ExpressionEvaluationContextRecord::EK_Decltype) { | |||
18443 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | |||
18444 | return false; | |||
18445 | } | |||
18446 | ||||
18447 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | |||
18448 | FunctionDecl *FD; | |||
18449 | CallExpr *CE; | |||
18450 | ||||
18451 | public: | |||
18452 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | |||
18453 | : FD(FD), CE(CE) { } | |||
18454 | ||||
18455 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
18456 | if (!FD) { | |||
18457 | S.Diag(Loc, diag::err_call_incomplete_return) | |||
18458 | << T << CE->getSourceRange(); | |||
18459 | return; | |||
18460 | } | |||
18461 | ||||
18462 | S.Diag(Loc, diag::err_call_function_incomplete_return) | |||
18463 | << CE->getSourceRange() << FD << T; | |||
18464 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | |||
18465 | << FD->getDeclName(); | |||
18466 | } | |||
18467 | } Diagnoser(FD, CE); | |||
18468 | ||||
18469 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | |||
18470 | return true; | |||
18471 | ||||
18472 | return false; | |||
18473 | } | |||
18474 | ||||
18475 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | |||
18476 | // will prevent this condition from triggering, which is what we want. | |||
18477 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | |||
18478 | SourceLocation Loc; | |||
18479 | ||||
18480 | unsigned diagnostic = diag::warn_condition_is_assignment; | |||
18481 | bool IsOrAssign = false; | |||
18482 | ||||
18483 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | |||
18484 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | |||
18485 | return; | |||
18486 | ||||
18487 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | |||
18488 | ||||
18489 | // Greylist some idioms by putting them into a warning subcategory. | |||
18490 | if (ObjCMessageExpr *ME | |||
18491 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | |||
18492 | Selector Sel = ME->getSelector(); | |||
18493 | ||||
18494 | // self = [<foo> init...] | |||
18495 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | |||
18496 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | |||
18497 | ||||
18498 | // <foo> = [<bar> nextObject] | |||
18499 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | |||
18500 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | |||
18501 | } | |||
18502 | ||||
18503 | Loc = Op->getOperatorLoc(); | |||
18504 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
18505 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | |||
18506 | return; | |||
18507 | ||||
18508 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | |||
18509 | Loc = Op->getOperatorLoc(); | |||
18510 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | |||
18511 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | |||
18512 | else { | |||
18513 | // Not an assignment. | |||
18514 | return; | |||
18515 | } | |||
18516 | ||||
18517 | Diag(Loc, diagnostic) << E->getSourceRange(); | |||
18518 | ||||
18519 | SourceLocation Open = E->getBeginLoc(); | |||
18520 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | |||
18521 | Diag(Loc, diag::note_condition_assign_silence) | |||
18522 | << FixItHint::CreateInsertion(Open, "(") | |||
18523 | << FixItHint::CreateInsertion(Close, ")"); | |||
18524 | ||||
18525 | if (IsOrAssign) | |||
18526 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | |||
18527 | << FixItHint::CreateReplacement(Loc, "!="); | |||
18528 | else | |||
18529 | Diag(Loc, diag::note_condition_assign_to_comparison) | |||
18530 | << FixItHint::CreateReplacement(Loc, "=="); | |||
18531 | } | |||
18532 | ||||
18533 | /// Redundant parentheses over an equality comparison can indicate | |||
18534 | /// that the user intended an assignment used as condition. | |||
18535 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | |||
18536 | // Don't warn if the parens came from a macro. | |||
18537 | SourceLocation parenLoc = ParenE->getBeginLoc(); | |||
18538 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | |||
18539 | return; | |||
18540 | // Don't warn for dependent expressions. | |||
18541 | if (ParenE->isTypeDependent()) | |||
18542 | return; | |||
18543 | ||||
18544 | Expr *E = ParenE->IgnoreParens(); | |||
18545 | ||||
18546 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | |||
18547 | if (opE->getOpcode() == BO_EQ && | |||
18548 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | |||
18549 | == Expr::MLV_Valid) { | |||
18550 | SourceLocation Loc = opE->getOperatorLoc(); | |||
18551 | ||||
18552 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | |||
18553 | SourceRange ParenERange = ParenE->getSourceRange(); | |||
18554 | Diag(Loc, diag::note_equality_comparison_silence) | |||
18555 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | |||
18556 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | |||
18557 | Diag(Loc, diag::note_equality_comparison_to_assign) | |||
18558 | << FixItHint::CreateReplacement(Loc, "="); | |||
18559 | } | |||
18560 | } | |||
18561 | ||||
18562 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | |||
18563 | bool IsConstexpr) { | |||
18564 | DiagnoseAssignmentAsCondition(E); | |||
18565 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | |||
18566 | DiagnoseEqualityWithExtraParens(parenE); | |||
18567 | ||||
18568 | ExprResult result = CheckPlaceholderExpr(E); | |||
18569 | if (result.isInvalid()) return ExprError(); | |||
18570 | E = result.get(); | |||
18571 | ||||
18572 | if (!E->isTypeDependent()) { | |||
18573 | if (getLangOpts().CPlusPlus) | |||
18574 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | |||
18575 | ||||
18576 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | |||
18577 | if (ERes.isInvalid()) | |||
18578 | return ExprError(); | |||
18579 | E = ERes.get(); | |||
18580 | ||||
18581 | QualType T = E->getType(); | |||
18582 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | |||
18583 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | |||
18584 | << T << E->getSourceRange(); | |||
18585 | return ExprError(); | |||
18586 | } | |||
18587 | CheckBoolLikeConversion(E, Loc); | |||
18588 | } | |||
18589 | ||||
18590 | return E; | |||
18591 | } | |||
18592 | ||||
18593 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | |||
18594 | Expr *SubExpr, ConditionKind CK) { | |||
18595 | // Empty conditions are valid in for-statements. | |||
18596 | if (!SubExpr) | |||
18597 | return ConditionResult(); | |||
18598 | ||||
18599 | ExprResult Cond; | |||
18600 | switch (CK) { | |||
18601 | case ConditionKind::Boolean: | |||
18602 | Cond = CheckBooleanCondition(Loc, SubExpr); | |||
18603 | break; | |||
18604 | ||||
18605 | case ConditionKind::ConstexprIf: | |||
18606 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | |||
18607 | break; | |||
18608 | ||||
18609 | case ConditionKind::Switch: | |||
18610 | Cond = CheckSwitchCondition(Loc, SubExpr); | |||
18611 | break; | |||
18612 | } | |||
18613 | if (Cond.isInvalid()) { | |||
18614 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | |||
18615 | {SubExpr}); | |||
18616 | if (!Cond.get()) | |||
18617 | return ConditionError(); | |||
18618 | } | |||
18619 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | |||
18620 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | |||
18621 | if (!FullExpr.get()) | |||
18622 | return ConditionError(); | |||
18623 | ||||
18624 | return ConditionResult(*this, nullptr, FullExpr, | |||
18625 | CK == ConditionKind::ConstexprIf); | |||
18626 | } | |||
18627 | ||||
18628 | namespace { | |||
18629 | /// A visitor for rebuilding a call to an __unknown_any expression | |||
18630 | /// to have an appropriate type. | |||
18631 | struct RebuildUnknownAnyFunction | |||
18632 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | |||
18633 | ||||
18634 | Sema &S; | |||
18635 | ||||
18636 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | |||
18637 | ||||
18638 | ExprResult VisitStmt(Stmt *S) { | |||
18639 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18639); | |||
18640 | } | |||
18641 | ||||
18642 | ExprResult VisitExpr(Expr *E) { | |||
18643 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | |||
18644 | << E->getSourceRange(); | |||
18645 | return ExprError(); | |||
18646 | } | |||
18647 | ||||
18648 | /// Rebuild an expression which simply semantically wraps another | |||
18649 | /// expression which it shares the type and value kind of. | |||
18650 | template <class T> ExprResult rebuildSugarExpr(T *E) { | |||
18651 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
18652 | if (SubResult.isInvalid()) return ExprError(); | |||
18653 | ||||
18654 | Expr *SubExpr = SubResult.get(); | |||
18655 | E->setSubExpr(SubExpr); | |||
18656 | E->setType(SubExpr->getType()); | |||
18657 | E->setValueKind(SubExpr->getValueKind()); | |||
18658 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18658, __PRETTY_FUNCTION__)); | |||
18659 | return E; | |||
18660 | } | |||
18661 | ||||
18662 | ExprResult VisitParenExpr(ParenExpr *E) { | |||
18663 | return rebuildSugarExpr(E); | |||
18664 | } | |||
18665 | ||||
18666 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | |||
18667 | return rebuildSugarExpr(E); | |||
18668 | } | |||
18669 | ||||
18670 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | |||
18671 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
18672 | if (SubResult.isInvalid()) return ExprError(); | |||
18673 | ||||
18674 | Expr *SubExpr = SubResult.get(); | |||
18675 | E->setSubExpr(SubExpr); | |||
18676 | E->setType(S.Context.getPointerType(SubExpr->getType())); | |||
18677 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18677, __PRETTY_FUNCTION__)); | |||
18678 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18678, __PRETTY_FUNCTION__)); | |||
18679 | return E; | |||
18680 | } | |||
18681 | ||||
18682 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | |||
18683 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | |||
18684 | ||||
18685 | E->setType(VD->getType()); | |||
18686 | ||||
18687 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18687, __PRETTY_FUNCTION__)); | |||
18688 | if (S.getLangOpts().CPlusPlus && | |||
18689 | !(isa<CXXMethodDecl>(VD) && | |||
18690 | cast<CXXMethodDecl>(VD)->isInstance())) | |||
18691 | E->setValueKind(VK_LValue); | |||
18692 | ||||
18693 | return E; | |||
18694 | } | |||
18695 | ||||
18696 | ExprResult VisitMemberExpr(MemberExpr *E) { | |||
18697 | return resolveDecl(E, E->getMemberDecl()); | |||
18698 | } | |||
18699 | ||||
18700 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | |||
18701 | return resolveDecl(E, E->getDecl()); | |||
18702 | } | |||
18703 | }; | |||
18704 | } | |||
18705 | ||||
18706 | /// Given a function expression of unknown-any type, try to rebuild it | |||
18707 | /// to have a function type. | |||
18708 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | |||
18709 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | |||
18710 | if (Result.isInvalid()) return ExprError(); | |||
18711 | return S.DefaultFunctionArrayConversion(Result.get()); | |||
18712 | } | |||
18713 | ||||
18714 | namespace { | |||
18715 | /// A visitor for rebuilding an expression of type __unknown_anytype | |||
18716 | /// into one which resolves the type directly on the referring | |||
18717 | /// expression. Strict preservation of the original source | |||
18718 | /// structure is not a goal. | |||
18719 | struct RebuildUnknownAnyExpr | |||
18720 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | |||
18721 | ||||
18722 | Sema &S; | |||
18723 | ||||
18724 | /// The current destination type. | |||
18725 | QualType DestType; | |||
18726 | ||||
18727 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | |||
18728 | : S(S), DestType(CastType) {} | |||
18729 | ||||
18730 | ExprResult VisitStmt(Stmt *S) { | |||
18731 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18731); | |||
18732 | } | |||
18733 | ||||
18734 | ExprResult VisitExpr(Expr *E) { | |||
18735 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | |||
18736 | << E->getSourceRange(); | |||
18737 | return ExprError(); | |||
18738 | } | |||
18739 | ||||
18740 | ExprResult VisitCallExpr(CallExpr *E); | |||
18741 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | |||
18742 | ||||
18743 | /// Rebuild an expression which simply semantically wraps another | |||
18744 | /// expression which it shares the type and value kind of. | |||
18745 | template <class T> ExprResult rebuildSugarExpr(T *E) { | |||
18746 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
18747 | if (SubResult.isInvalid()) return ExprError(); | |||
18748 | Expr *SubExpr = SubResult.get(); | |||
18749 | E->setSubExpr(SubExpr); | |||
18750 | E->setType(SubExpr->getType()); | |||
18751 | E->setValueKind(SubExpr->getValueKind()); | |||
18752 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18752, __PRETTY_FUNCTION__)); | |||
18753 | return E; | |||
18754 | } | |||
18755 | ||||
18756 | ExprResult VisitParenExpr(ParenExpr *E) { | |||
18757 | return rebuildSugarExpr(E); | |||
18758 | } | |||
18759 | ||||
18760 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | |||
18761 | return rebuildSugarExpr(E); | |||
18762 | } | |||
18763 | ||||
18764 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | |||
18765 | const PointerType *Ptr = DestType->getAs<PointerType>(); | |||
18766 | if (!Ptr) { | |||
18767 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | |||
18768 | << E->getSourceRange(); | |||
18769 | return ExprError(); | |||
18770 | } | |||
18771 | ||||
18772 | if (isa<CallExpr>(E->getSubExpr())) { | |||
18773 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | |||
18774 | << E->getSourceRange(); | |||
18775 | return ExprError(); | |||
18776 | } | |||
18777 | ||||
18778 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18778, __PRETTY_FUNCTION__)); | |||
18779 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18779, __PRETTY_FUNCTION__)); | |||
18780 | E->setType(DestType); | |||
18781 | ||||
18782 | // Build the sub-expression as if it were an object of the pointee type. | |||
18783 | DestType = Ptr->getPointeeType(); | |||
18784 | ExprResult SubResult = Visit(E->getSubExpr()); | |||
18785 | if (SubResult.isInvalid()) return ExprError(); | |||
18786 | E->setSubExpr(SubResult.get()); | |||
18787 | return E; | |||
18788 | } | |||
18789 | ||||
18790 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | |||
18791 | ||||
18792 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | |||
18793 | ||||
18794 | ExprResult VisitMemberExpr(MemberExpr *E) { | |||
18795 | return resolveDecl(E, E->getMemberDecl()); | |||
18796 | } | |||
18797 | ||||
18798 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | |||
18799 | return resolveDecl(E, E->getDecl()); | |||
18800 | } | |||
18801 | }; | |||
18802 | } | |||
18803 | ||||
18804 | /// Rebuilds a call expression which yielded __unknown_anytype. | |||
18805 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | |||
18806 | Expr *CalleeExpr = E->getCallee(); | |||
18807 | ||||
18808 | enum FnKind { | |||
18809 | FK_MemberFunction, | |||
18810 | FK_FunctionPointer, | |||
18811 | FK_BlockPointer | |||
18812 | }; | |||
18813 | ||||
18814 | FnKind Kind; | |||
18815 | QualType CalleeType = CalleeExpr->getType(); | |||
18816 | if (CalleeType == S.Context.BoundMemberTy) { | |||
18817 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr >(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18817, __PRETTY_FUNCTION__)); | |||
18818 | Kind = FK_MemberFunction; | |||
18819 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | |||
18820 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | |||
18821 | CalleeType = Ptr->getPointeeType(); | |||
18822 | Kind = FK_FunctionPointer; | |||
18823 | } else { | |||
18824 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | |||
18825 | Kind = FK_BlockPointer; | |||
18826 | } | |||
18827 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | |||
18828 | ||||
18829 | // Verify that this is a legal result type of a function. | |||
18830 | if (DestType->isArrayType() || DestType->isFunctionType()) { | |||
18831 | unsigned diagID = diag::err_func_returning_array_function; | |||
18832 | if (Kind == FK_BlockPointer) | |||
18833 | diagID = diag::err_block_returning_array_function; | |||
18834 | ||||
18835 | S.Diag(E->getExprLoc(), diagID) | |||
18836 | << DestType->isFunctionType() << DestType; | |||
18837 | return ExprError(); | |||
18838 | } | |||
18839 | ||||
18840 | // Otherwise, go ahead and set DestType as the call's result. | |||
18841 | E->setType(DestType.getNonLValueExprType(S.Context)); | |||
18842 | E->setValueKind(Expr::getValueKindForType(DestType)); | |||
18843 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18843, __PRETTY_FUNCTION__)); | |||
18844 | ||||
18845 | // Rebuild the function type, replacing the result type with DestType. | |||
18846 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | |||
18847 | if (Proto) { | |||
18848 | // __unknown_anytype(...) is a special case used by the debugger when | |||
18849 | // it has no idea what a function's signature is. | |||
18850 | // | |||
18851 | // We want to build this call essentially under the K&R | |||
18852 | // unprototyped rules, but making a FunctionNoProtoType in C++ | |||
18853 | // would foul up all sorts of assumptions. However, we cannot | |||
18854 | // simply pass all arguments as variadic arguments, nor can we | |||
18855 | // portably just call the function under a non-variadic type; see | |||
18856 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | |||
18857 | // However, it turns out that in practice it is generally safe to | |||
18858 | // call a function declared as "A foo(B,C,D);" under the prototype | |||
18859 | // "A foo(B,C,D,...);". The only known exception is with the | |||
18860 | // Windows ABI, where any variadic function is implicitly cdecl | |||
18861 | // regardless of its normal CC. Therefore we change the parameter | |||
18862 | // types to match the types of the arguments. | |||
18863 | // | |||
18864 | // This is a hack, but it is far superior to moving the | |||
18865 | // corresponding target-specific code from IR-gen to Sema/AST. | |||
18866 | ||||
18867 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | |||
18868 | SmallVector<QualType, 8> ArgTypes; | |||
18869 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | |||
18870 | ArgTypes.reserve(E->getNumArgs()); | |||
18871 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | |||
18872 | Expr *Arg = E->getArg(i); | |||
18873 | QualType ArgType = Arg->getType(); | |||
18874 | if (E->isLValue()) { | |||
18875 | ArgType = S.Context.getLValueReferenceType(ArgType); | |||
18876 | } else if (E->isXValue()) { | |||
18877 | ArgType = S.Context.getRValueReferenceType(ArgType); | |||
18878 | } | |||
18879 | ArgTypes.push_back(ArgType); | |||
18880 | } | |||
18881 | ParamTypes = ArgTypes; | |||
18882 | } | |||
18883 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | |||
18884 | Proto->getExtProtoInfo()); | |||
18885 | } else { | |||
18886 | DestType = S.Context.getFunctionNoProtoType(DestType, | |||
18887 | FnType->getExtInfo()); | |||
18888 | } | |||
18889 | ||||
18890 | // Rebuild the appropriate pointer-to-function type. | |||
18891 | switch (Kind) { | |||
18892 | case FK_MemberFunction: | |||
18893 | // Nothing to do. | |||
18894 | break; | |||
18895 | ||||
18896 | case FK_FunctionPointer: | |||
18897 | DestType = S.Context.getPointerType(DestType); | |||
18898 | break; | |||
18899 | ||||
18900 | case FK_BlockPointer: | |||
18901 | DestType = S.Context.getBlockPointerType(DestType); | |||
18902 | break; | |||
18903 | } | |||
18904 | ||||
18905 | // Finally, we can recurse. | |||
18906 | ExprResult CalleeResult = Visit(CalleeExpr); | |||
18907 | if (!CalleeResult.isUsable()) return ExprError(); | |||
18908 | E->setCallee(CalleeResult.get()); | |||
18909 | ||||
18910 | // Bind a temporary if necessary. | |||
18911 | return S.MaybeBindToTemporary(E); | |||
18912 | } | |||
18913 | ||||
18914 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | |||
18915 | // Verify that this is a legal result type of a call. | |||
18916 | if (DestType->isArrayType() || DestType->isFunctionType()) { | |||
18917 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | |||
18918 | << DestType->isFunctionType() << DestType; | |||
18919 | return ExprError(); | |||
18920 | } | |||
18921 | ||||
18922 | // Rewrite the method result type if available. | |||
18923 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | |||
18924 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast <void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18924, __PRETTY_FUNCTION__)); | |||
18925 | Method->setReturnType(DestType); | |||
18926 | } | |||
18927 | ||||
18928 | // Change the type of the message. | |||
18929 | E->setType(DestType.getNonReferenceType()); | |||
18930 | E->setValueKind(Expr::getValueKindForType(DestType)); | |||
18931 | ||||
18932 | return S.MaybeBindToTemporary(E); | |||
18933 | } | |||
18934 | ||||
18935 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
18936 | // The only case we should ever see here is a function-to-pointer decay. | |||
18937 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | |||
18938 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18938, __PRETTY_FUNCTION__)); | |||
18939 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18939, __PRETTY_FUNCTION__)); | |||
18940 | ||||
18941 | E->setType(DestType); | |||
18942 | ||||
18943 | // Rebuild the sub-expression as the pointee (function) type. | |||
18944 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | |||
18945 | ||||
18946 | ExprResult Result = Visit(E->getSubExpr()); | |||
18947 | if (!Result.isUsable()) return ExprError(); | |||
18948 | ||||
18949 | E->setSubExpr(Result.get()); | |||
18950 | return E; | |||
18951 | } else if (E->getCastKind() == CK_LValueToRValue) { | |||
18952 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18952, __PRETTY_FUNCTION__)); | |||
18953 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18953, __PRETTY_FUNCTION__)); | |||
18954 | ||||
18955 | assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast <void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18955, __PRETTY_FUNCTION__)); | |||
18956 | ||||
18957 | E->setType(DestType); | |||
18958 | ||||
18959 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | |||
18960 | DestType = S.Context.getLValueReferenceType(DestType); | |||
18961 | ||||
18962 | ExprResult Result = Visit(E->getSubExpr()); | |||
18963 | if (!Result.isUsable()) return ExprError(); | |||
18964 | ||||
18965 | E->setSubExpr(Result.get()); | |||
18966 | return E; | |||
18967 | } else { | |||
18968 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 18968); | |||
18969 | } | |||
18970 | } | |||
18971 | ||||
18972 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | |||
18973 | ExprValueKind ValueKind = VK_LValue; | |||
18974 | QualType Type = DestType; | |||
18975 | ||||
18976 | // We know how to make this work for certain kinds of decls: | |||
18977 | ||||
18978 | // - functions | |||
18979 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | |||
18980 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | |||
18981 | DestType = Ptr->getPointeeType(); | |||
18982 | ExprResult Result = resolveDecl(E, VD); | |||
18983 | if (Result.isInvalid()) return ExprError(); | |||
18984 | return S.ImpCastExprToType(Result.get(), Type, | |||
18985 | CK_FunctionToPointerDecay, VK_RValue); | |||
18986 | } | |||
18987 | ||||
18988 | if (!Type->isFunctionType()) { | |||
18989 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | |||
18990 | << VD << E->getSourceRange(); | |||
18991 | return ExprError(); | |||
18992 | } | |||
18993 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | |||
18994 | // We must match the FunctionDecl's type to the hack introduced in | |||
18995 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | |||
18996 | // type. See the lengthy commentary in that routine. | |||
18997 | QualType FDT = FD->getType(); | |||
18998 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | |||
18999 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | |||
19000 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | |||
19001 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | |||
19002 | SourceLocation Loc = FD->getLocation(); | |||
19003 | FunctionDecl *NewFD = FunctionDecl::Create( | |||
19004 | S.Context, FD->getDeclContext(), Loc, Loc, | |||
19005 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | |||
19006 | SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), | |||
19007 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | |||
19008 | ||||
19009 | if (FD->getQualifier()) | |||
19010 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | |||
19011 | ||||
19012 | SmallVector<ParmVarDecl*, 16> Params; | |||
19013 | for (const auto &AI : FT->param_types()) { | |||
19014 | ParmVarDecl *Param = | |||
19015 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | |||
19016 | Param->setScopeInfo(0, Params.size()); | |||
19017 | Params.push_back(Param); | |||
19018 | } | |||
19019 | NewFD->setParams(Params); | |||
19020 | DRE->setDecl(NewFD); | |||
19021 | VD = DRE->getDecl(); | |||
19022 | } | |||
19023 | } | |||
19024 | ||||
19025 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | |||
19026 | if (MD->isInstance()) { | |||
19027 | ValueKind = VK_RValue; | |||
19028 | Type = S.Context.BoundMemberTy; | |||
19029 | } | |||
19030 | ||||
19031 | // Function references aren't l-values in C. | |||
19032 | if (!S.getLangOpts().CPlusPlus) | |||
19033 | ValueKind = VK_RValue; | |||
19034 | ||||
19035 | // - variables | |||
19036 | } else if (isa<VarDecl>(VD)) { | |||
19037 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | |||
19038 | Type = RefTy->getPointeeType(); | |||
19039 | } else if (Type->isFunctionType()) { | |||
19040 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | |||
19041 | << VD << E->getSourceRange(); | |||
19042 | return ExprError(); | |||
19043 | } | |||
19044 | ||||
19045 | // - nothing else | |||
19046 | } else { | |||
19047 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | |||
19048 | << VD << E->getSourceRange(); | |||
19049 | return ExprError(); | |||
19050 | } | |||
19051 | ||||
19052 | // Modifying the declaration like this is friendly to IR-gen but | |||
19053 | // also really dangerous. | |||
19054 | VD->setType(DestType); | |||
19055 | E->setType(Type); | |||
19056 | E->setValueKind(ValueKind); | |||
19057 | return E; | |||
19058 | } | |||
19059 | ||||
19060 | /// Check a cast of an unknown-any type. We intentionally only | |||
19061 | /// trigger this for C-style casts. | |||
19062 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | |||
19063 | Expr *CastExpr, CastKind &CastKind, | |||
19064 | ExprValueKind &VK, CXXCastPath &Path) { | |||
19065 | // The type we're casting to must be either void or complete. | |||
19066 | if (!CastType->isVoidType() && | |||
19067 | RequireCompleteType(TypeRange.getBegin(), CastType, | |||
19068 | diag::err_typecheck_cast_to_incomplete)) | |||
19069 | return ExprError(); | |||
19070 | ||||
19071 | // Rewrite the casted expression from scratch. | |||
19072 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | |||
19073 | if (!result.isUsable()) return ExprError(); | |||
19074 | ||||
19075 | CastExpr = result.get(); | |||
19076 | VK = CastExpr->getValueKind(); | |||
19077 | CastKind = CK_NoOp; | |||
19078 | ||||
19079 | return CastExpr; | |||
19080 | } | |||
19081 | ||||
19082 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | |||
19083 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | |||
19084 | } | |||
19085 | ||||
19086 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | |||
19087 | Expr *arg, QualType ¶mType) { | |||
19088 | // If the syntactic form of the argument is not an explicit cast of | |||
19089 | // any sort, just do default argument promotion. | |||
19090 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | |||
19091 | if (!castArg) { | |||
19092 | ExprResult result = DefaultArgumentPromotion(arg); | |||
19093 | if (result.isInvalid()) return ExprError(); | |||
19094 | paramType = result.get()->getType(); | |||
19095 | return result; | |||
19096 | } | |||
19097 | ||||
19098 | // Otherwise, use the type that was written in the explicit cast. | |||
19099 | assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0 ) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 19099, __PRETTY_FUNCTION__)); | |||
19100 | paramType = castArg->getTypeAsWritten(); | |||
19101 | ||||
19102 | // Copy-initialize a parameter of that type. | |||
19103 | InitializedEntity entity = | |||
19104 | InitializedEntity::InitializeParameter(Context, paramType, | |||
19105 | /*consumed*/ false); | |||
19106 | return PerformCopyInitialization(entity, callLoc, arg); | |||
19107 | } | |||
19108 | ||||
19109 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | |||
19110 | Expr *orig = E; | |||
19111 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | |||
19112 | while (true) { | |||
19113 | E = E->IgnoreParenImpCasts(); | |||
19114 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | |||
19115 | E = call->getCallee(); | |||
19116 | diagID = diag::err_uncasted_call_of_unknown_any; | |||
19117 | } else { | |||
19118 | break; | |||
19119 | } | |||
19120 | } | |||
19121 | ||||
19122 | SourceLocation loc; | |||
19123 | NamedDecl *d; | |||
19124 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | |||
19125 | loc = ref->getLocation(); | |||
19126 | d = ref->getDecl(); | |||
19127 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | |||
19128 | loc = mem->getMemberLoc(); | |||
19129 | d = mem->getMemberDecl(); | |||
19130 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | |||
19131 | diagID = diag::err_uncasted_call_of_unknown_any; | |||
19132 | loc = msg->getSelectorStartLoc(); | |||
19133 | d = msg->getMethodDecl(); | |||
19134 | if (!d) { | |||
19135 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | |||
19136 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | |||
19137 | << orig->getSourceRange(); | |||
19138 | return ExprError(); | |||
19139 | } | |||
19140 | } else { | |||
19141 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | |||
19142 | << E->getSourceRange(); | |||
19143 | return ExprError(); | |||
19144 | } | |||
19145 | ||||
19146 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | |||
19147 | ||||
19148 | // Never recoverable. | |||
19149 | return ExprError(); | |||
19150 | } | |||
19151 | ||||
19152 | /// Check for operands with placeholder types and complain if found. | |||
19153 | /// Returns ExprError() if there was an error and no recovery was possible. | |||
19154 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | |||
19155 | if (!Context.isDependenceAllowed()) { | |||
19156 | // C cannot handle TypoExpr nodes on either side of a binop because it | |||
19157 | // doesn't handle dependent types properly, so make sure any TypoExprs have | |||
19158 | // been dealt with before checking the operands. | |||
19159 | ExprResult Result = CorrectDelayedTyposInExpr(E); | |||
19160 | if (!Result.isUsable()) return ExprError(); | |||
19161 | E = Result.get(); | |||
19162 | } | |||
19163 | ||||
19164 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | |||
19165 | if (!placeholderType) return E; | |||
19166 | ||||
19167 | switch (placeholderType->getKind()) { | |||
19168 | ||||
19169 | // Overloaded expressions. | |||
19170 | case BuiltinType::Overload: { | |||
19171 | // Try to resolve a single function template specialization. | |||
19172 | // This is obligatory. | |||
19173 | ExprResult Result = E; | |||
19174 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | |||
19175 | return Result; | |||
19176 | ||||
19177 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | |||
19178 | // leaves Result unchanged on failure. | |||
19179 | Result = E; | |||
19180 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | |||
19181 | return Result; | |||
19182 | ||||
19183 | // If that failed, try to recover with a call. | |||
19184 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | |||
19185 | /*complain*/ true); | |||
19186 | return Result; | |||
19187 | } | |||
19188 | ||||
19189 | // Bound member functions. | |||
19190 | case BuiltinType::BoundMember: { | |||
19191 | ExprResult result = E; | |||
19192 | const Expr *BME = E->IgnoreParens(); | |||
19193 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | |||
19194 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | |||
19195 | if (isa<CXXPseudoDestructorExpr>(BME)) { | |||
19196 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | |||
19197 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | |||
19198 | if (ME->getMemberNameInfo().getName().getNameKind() == | |||
19199 | DeclarationName::CXXDestructorName) | |||
19200 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | |||
19201 | } | |||
19202 | tryToRecoverWithCall(result, PD, | |||
19203 | /*complain*/ true); | |||
19204 | return result; | |||
19205 | } | |||
19206 | ||||
19207 | // ARC unbridged casts. | |||
19208 | case BuiltinType::ARCUnbridgedCast: { | |||
19209 | Expr *realCast = stripARCUnbridgedCast(E); | |||
19210 | diagnoseARCUnbridgedCast(realCast); | |||
19211 | return realCast; | |||
19212 | } | |||
19213 | ||||
19214 | // Expressions of unknown type. | |||
19215 | case BuiltinType::UnknownAny: | |||
19216 | return diagnoseUnknownAnyExpr(*this, E); | |||
19217 | ||||
19218 | // Pseudo-objects. | |||
19219 | case BuiltinType::PseudoObject: | |||
19220 | return checkPseudoObjectRValue(E); | |||
19221 | ||||
19222 | case BuiltinType::BuiltinFn: { | |||
19223 | // Accept __noop without parens by implicitly converting it to a call expr. | |||
19224 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | |||
19225 | if (DRE) { | |||
19226 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | |||
19227 | if (FD->getBuiltinID() == Builtin::BI__noop) { | |||
19228 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | |||
19229 | CK_BuiltinFnToFnPtr) | |||
19230 | .get(); | |||
19231 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | |||
19232 | VK_RValue, SourceLocation(), | |||
19233 | FPOptionsOverride()); | |||
19234 | } | |||
19235 | } | |||
19236 | ||||
19237 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | |||
19238 | return ExprError(); | |||
19239 | } | |||
19240 | ||||
19241 | case BuiltinType::IncompleteMatrixIdx: | |||
19242 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | |||
19243 | ->getRowIdx() | |||
19244 | ->getBeginLoc(), | |||
19245 | diag::err_matrix_incomplete_index); | |||
19246 | return ExprError(); | |||
19247 | ||||
19248 | // Expressions of unknown type. | |||
19249 | case BuiltinType::OMPArraySection: | |||
19250 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | |||
19251 | return ExprError(); | |||
19252 | ||||
19253 | // Expressions of unknown type. | |||
19254 | case BuiltinType::OMPArrayShaping: | |||
19255 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | |||
19256 | ||||
19257 | case BuiltinType::OMPIterator: | |||
19258 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | |||
19259 | ||||
19260 | // Everything else should be impossible. | |||
19261 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
19262 | case BuiltinType::Id: | |||
19263 | #include "clang/Basic/OpenCLImageTypes.def" | |||
19264 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
19265 | case BuiltinType::Id: | |||
19266 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
19267 | #define SVE_TYPE(Name, Id, SingletonId) \ | |||
19268 | case BuiltinType::Id: | |||
19269 | #include "clang/Basic/AArch64SVEACLETypes.def" | |||
19270 | #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ | |||
19271 | case BuiltinType::Id: | |||
19272 | #include "clang/Basic/PPCTypes.def" | |||
19273 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | |||
19274 | #define PLACEHOLDER_TYPE(Id, SingletonId) | |||
19275 | #include "clang/AST/BuiltinTypes.def" | |||
19276 | break; | |||
19277 | } | |||
19278 | ||||
19279 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 19279); | |||
19280 | } | |||
19281 | ||||
19282 | bool Sema::CheckCaseExpression(Expr *E) { | |||
19283 | if (E->isTypeDependent()) | |||
19284 | return true; | |||
19285 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | |||
19286 | return E->getType()->isIntegralOrEnumerationType(); | |||
19287 | return false; | |||
19288 | } | |||
19289 | ||||
19290 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | |||
19291 | ExprResult | |||
19292 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | |||
19293 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 19294, __PRETTY_FUNCTION__)) | |||
19294 | "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaExpr.cpp" , 19294, __PRETTY_FUNCTION__)); | |||
19295 | QualType BoolT = Context.ObjCBuiltinBoolTy; | |||
19296 | if (!Context.getBOOLDecl()) { | |||
19297 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | |||
19298 | Sema::LookupOrdinaryName); | |||
19299 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | |||
19300 | NamedDecl *ND = Result.getFoundDecl(); | |||
19301 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | |||
19302 | Context.setBOOLDecl(TD); | |||
19303 | } | |||
19304 | } | |||
19305 | if (Context.getBOOLDecl()) | |||
19306 | BoolT = Context.getBOOLType(); | |||
19307 | return new (Context) | |||
19308 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | |||
19309 | } | |||
19310 | ||||
19311 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | |||
19312 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | |||
19313 | SourceLocation RParen) { | |||
19314 | ||||
19315 | StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); | |||
19316 | ||||
19317 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | |||
19318 | return Spec.getPlatform() == Platform; | |||
19319 | }); | |||
19320 | ||||
19321 | VersionTuple Version; | |||
19322 | if (Spec != AvailSpecs.end()) | |||
19323 | Version = Spec->getVersion(); | |||
19324 | ||||
19325 | // The use of `@available` in the enclosing function should be analyzed to | |||
19326 | // warn when it's used inappropriately (i.e. not if(@available)). | |||
19327 | if (getCurFunctionOrMethodDecl()) | |||
19328 | getEnclosingFunction()->HasPotentialAvailabilityViolations = true; | |||
19329 | else if (getCurBlock() || getCurLambda()) | |||
19330 | getCurFunction()->HasPotentialAvailabilityViolations = true; | |||
19331 | ||||
19332 | return new (Context) | |||
19333 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | |||
19334 | } | |||
19335 | ||||
19336 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | |||
19337 | ArrayRef<Expr *> SubExprs, QualType T) { | |||
19338 | if (!Context.getLangOpts().RecoveryAST) | |||
19339 | return ExprError(); | |||
19340 | ||||
19341 | if (isSFINAEContext()) | |||
19342 | return ExprError(); | |||
19343 | ||||
19344 | if (T.isNull() || !Context.getLangOpts().RecoveryASTType) | |||
19345 | // We don't know the concrete type, fallback to dependent type. | |||
19346 | T = Context.DependentTy; | |||
19347 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | |||
19348 | } |