File: | build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaExpr.cpp |
Warning: | line 9709, column 27 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/ParentMapContext.h" | ||||
29 | #include "clang/AST/RecursiveASTVisitor.h" | ||||
30 | #include "clang/AST/Type.h" | ||||
31 | #include "clang/AST/TypeLoc.h" | ||||
32 | #include "clang/Basic/Builtins.h" | ||||
33 | #include "clang/Basic/DiagnosticSema.h" | ||||
34 | #include "clang/Basic/PartialDiagnostic.h" | ||||
35 | #include "clang/Basic/SourceManager.h" | ||||
36 | #include "clang/Basic/Specifiers.h" | ||||
37 | #include "clang/Basic/TargetInfo.h" | ||||
38 | #include "clang/Lex/LiteralSupport.h" | ||||
39 | #include "clang/Lex/Preprocessor.h" | ||||
40 | #include "clang/Sema/AnalysisBasedWarnings.h" | ||||
41 | #include "clang/Sema/DeclSpec.h" | ||||
42 | #include "clang/Sema/DelayedDiagnostic.h" | ||||
43 | #include "clang/Sema/Designator.h" | ||||
44 | #include "clang/Sema/Initialization.h" | ||||
45 | #include "clang/Sema/Lookup.h" | ||||
46 | #include "clang/Sema/Overload.h" | ||||
47 | #include "clang/Sema/ParsedTemplate.h" | ||||
48 | #include "clang/Sema/Scope.h" | ||||
49 | #include "clang/Sema/ScopeInfo.h" | ||||
50 | #include "clang/Sema/SemaFixItUtils.h" | ||||
51 | #include "clang/Sema/SemaInternal.h" | ||||
52 | #include "clang/Sema/Template.h" | ||||
53 | #include "llvm/ADT/STLExtras.h" | ||||
54 | #include "llvm/ADT/StringExtras.h" | ||||
55 | #include "llvm/Support/Casting.h" | ||||
56 | #include "llvm/Support/ConvertUTF.h" | ||||
57 | #include "llvm/Support/SaveAndRestore.h" | ||||
58 | #include "llvm/Support/TypeSize.h" | ||||
59 | |||||
60 | using namespace clang; | ||||
61 | using namespace sema; | ||||
62 | |||||
63 | /// Determine whether the use of this declaration is valid, without | ||||
64 | /// emitting diagnostics. | ||||
65 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||
66 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
67 | if (ParsingInitForAutoVars.count(D)) | ||||
68 | return false; | ||||
69 | |||||
70 | // See if this is a deleted function. | ||||
71 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
72 | if (FD->isDeleted()) | ||||
73 | return false; | ||||
74 | |||||
75 | // If the function has a deduced return type, and we can't deduce it, | ||||
76 | // then we can't use it either. | ||||
77 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
78 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||
79 | return false; | ||||
80 | |||||
81 | // See if this is an aligned allocation/deallocation function that is | ||||
82 | // unavailable. | ||||
83 | if (TreatUnavailableAsInvalid && | ||||
84 | isUnavailableAlignedAllocationFunction(*FD)) | ||||
85 | return false; | ||||
86 | } | ||||
87 | |||||
88 | // See if this function is unavailable. | ||||
89 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||
90 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||
91 | return false; | ||||
92 | |||||
93 | if (isa<UnresolvedUsingIfExistsDecl>(D)) | ||||
94 | return false; | ||||
95 | |||||
96 | return true; | ||||
97 | } | ||||
98 | |||||
99 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||
100 | // Warn if this is used but marked unused. | ||||
101 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||
102 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||
103 | // should diagnose them. | ||||
104 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||
105 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||
106 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||
107 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||
108 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||
109 | } | ||||
110 | } | ||||
111 | } | ||||
112 | |||||
113 | /// Emit a note explaining that this function is deleted. | ||||
114 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||
115 | assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted ()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()" , "clang/lib/Sema/SemaExpr.cpp", 115, __extension__ __PRETTY_FUNCTION__ )); | ||||
116 | |||||
117 | if (Decl->isDefaulted()) { | ||||
118 | // If the method was explicitly defaulted, point at that declaration. | ||||
119 | if (!Decl->isImplicit()) | ||||
120 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||
121 | |||||
122 | // Try to diagnose why this special member function was implicitly | ||||
123 | // deleted. This might fail, if that reason no longer applies. | ||||
124 | DiagnoseDeletedDefaultedFunction(Decl); | ||||
125 | return; | ||||
126 | } | ||||
127 | |||||
128 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||
129 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
130 | return NoteDeletedInheritingConstructor(Ctor); | ||||
131 | |||||
132 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||
133 | << Decl << 1; | ||||
134 | } | ||||
135 | |||||
136 | /// Determine whether a FunctionDecl was ever declared with an | ||||
137 | /// explicit storage class. | ||||
138 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||
139 | for (auto *I : D->redecls()) { | ||||
140 | if (I->getStorageClass() != SC_None) | ||||
141 | return true; | ||||
142 | } | ||||
143 | return false; | ||||
144 | } | ||||
145 | |||||
146 | /// Check whether we're in an extern inline function and referring to a | ||||
147 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||
148 | /// | ||||
149 | /// This is only a warning because we used to silently accept this code, but | ||||
150 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||
151 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||
152 | /// and so while there may still be user mistakes, most of the time we can't | ||||
153 | /// prove that there are errors. | ||||
154 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||
155 | const NamedDecl *D, | ||||
156 | SourceLocation Loc) { | ||||
157 | // This is disabled under C++; there are too many ways for this to fire in | ||||
158 | // contexts where the warning is a false positive, or where it is technically | ||||
159 | // correct but benign. | ||||
160 | if (S.getLangOpts().CPlusPlus) | ||||
161 | return; | ||||
162 | |||||
163 | // Check if this is an inlined function or method. | ||||
164 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||
165 | if (!Current) | ||||
166 | return; | ||||
167 | if (!Current->isInlined()) | ||||
168 | return; | ||||
169 | if (!Current->isExternallyVisible()) | ||||
170 | return; | ||||
171 | |||||
172 | // Check if the decl has internal linkage. | ||||
173 | if (D->getFormalLinkage() != InternalLinkage) | ||||
174 | return; | ||||
175 | |||||
176 | // Downgrade from ExtWarn to Extension if | ||||
177 | // (1) the supposedly external inline function is in the main file, | ||||
178 | // and probably won't be included anywhere else. | ||||
179 | // (2) the thing we're referencing is a pure function. | ||||
180 | // (3) the thing we're referencing is another inline function. | ||||
181 | // This last can give us false negatives, but it's better than warning on | ||||
182 | // wrappers for simple C library functions. | ||||
183 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||
184 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||
185 | if (!DowngradeWarning && UsedFn) | ||||
186 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||
187 | |||||
188 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||
189 | : diag::ext_internal_in_extern_inline) | ||||
190 | << /*IsVar=*/!UsedFn << D; | ||||
191 | |||||
192 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||
193 | |||||
194 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||
195 | << D; | ||||
196 | } | ||||
197 | |||||
198 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||
199 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||
200 | |||||
201 | // Suggest "static" on the function, if possible. | ||||
202 | if (!hasAnyExplicitStorageClass(First)) { | ||||
203 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||
204 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||
205 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||
206 | } | ||||
207 | } | ||||
208 | |||||
209 | /// Determine whether the use of this declaration is valid, and | ||||
210 | /// emit any corresponding diagnostics. | ||||
211 | /// | ||||
212 | /// This routine diagnoses various problems with referencing | ||||
213 | /// declarations that can occur when using a declaration. For example, | ||||
214 | /// it might warn if a deprecated or unavailable declaration is being | ||||
215 | /// used, or produce an error (and return true) if a C++0x deleted | ||||
216 | /// function is being used. | ||||
217 | /// | ||||
218 | /// \returns true if there was an error (this declaration cannot be | ||||
219 | /// referenced), false otherwise. | ||||
220 | /// | ||||
221 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||
222 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||
223 | bool ObjCPropertyAccess, | ||||
224 | bool AvoidPartialAvailabilityChecks, | ||||
225 | ObjCInterfaceDecl *ClassReceiver) { | ||||
226 | SourceLocation Loc = Locs.front(); | ||||
227 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||
228 | // If there were any diagnostics suppressed by template argument deduction, | ||||
229 | // emit them now. | ||||
230 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||
231 | if (Pos != SuppressedDiagnostics.end()) { | ||||
232 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||
233 | Diag(Suppressed.first, Suppressed.second); | ||||
234 | |||||
235 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||
236 | // them again for this specialization. However, we don't obsolete this | ||||
237 | // entry from the table, because we want to avoid ever emitting these | ||||
238 | // diagnostics again. | ||||
239 | Pos->second.clear(); | ||||
240 | } | ||||
241 | |||||
242 | // C++ [basic.start.main]p3: | ||||
243 | // The function 'main' shall not be used within a program. | ||||
244 | if (cast<FunctionDecl>(D)->isMain()) | ||||
245 | Diag(Loc, diag::ext_main_used); | ||||
246 | |||||
247 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||
248 | } | ||||
249 | |||||
250 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
251 | if (ParsingInitForAutoVars.count(D)) { | ||||
252 | if (isa<BindingDecl>(D)) { | ||||
253 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||
254 | << D->getDeclName(); | ||||
255 | } else { | ||||
256 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||
257 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||
258 | } | ||||
259 | return true; | ||||
260 | } | ||||
261 | |||||
262 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
263 | // See if this is a deleted function. | ||||
264 | if (FD->isDeleted()) { | ||||
265 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||
266 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
267 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||
268 | << Ctor->getParent() | ||||
269 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||
270 | else | ||||
271 | Diag(Loc, diag::err_deleted_function_use); | ||||
272 | NoteDeletedFunction(FD); | ||||
273 | return true; | ||||
274 | } | ||||
275 | |||||
276 | // [expr.prim.id]p4 | ||||
277 | // A program that refers explicitly or implicitly to a function with a | ||||
278 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||
279 | // other than to declare it, is ill-formed. [...] | ||||
280 | // | ||||
281 | // See if this is a function with constraints that need to be satisfied. | ||||
282 | // Check this before deducing the return type, as it might instantiate the | ||||
283 | // definition. | ||||
284 | if (FD->getTrailingRequiresClause()) { | ||||
285 | ConstraintSatisfaction Satisfaction; | ||||
286 | if (CheckFunctionConstraints(FD, Satisfaction, Loc, | ||||
287 | /*ForOverloadResolution*/ true)) | ||||
288 | // A diagnostic will have already been generated (non-constant | ||||
289 | // constraint expression, for example) | ||||
290 | return true; | ||||
291 | if (!Satisfaction.IsSatisfied) { | ||||
292 | Diag(Loc, | ||||
293 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||
294 | << D; | ||||
295 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||
296 | return true; | ||||
297 | } | ||||
298 | } | ||||
299 | |||||
300 | // If the function has a deduced return type, and we can't deduce it, | ||||
301 | // then we can't use it either. | ||||
302 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
303 | DeduceReturnType(FD, Loc)) | ||||
304 | return true; | ||||
305 | |||||
306 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||
307 | return true; | ||||
308 | |||||
309 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||
310 | return true; | ||||
311 | } | ||||
312 | |||||
313 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
314 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||
315 | if (MD->getParent()->isLambda() && | ||||
316 | ((isa<CXXConstructorDecl>(MD) && | ||||
317 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||
318 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||
319 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||
320 | << !isa<CXXConstructorDecl>(MD); | ||||
321 | } | ||||
322 | } | ||||
323 | |||||
324 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||
325 | const ObjCPropertyDecl * { | ||||
326 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||
327 | return MD->findPropertyDecl(); | ||||
328 | return nullptr; | ||||
329 | }; | ||||
330 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||
331 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||
332 | return true; | ||||
333 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||
334 | return true; | ||||
335 | } | ||||
336 | |||||
337 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||
338 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||
339 | // Only the variables omp_priv and omp_orig are allowed in the | ||||
340 | // initializer-clause. | ||||
341 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||
342 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||
343 | isa<VarDecl>(D)) { | ||||
344 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||
345 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||
346 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
347 | return true; | ||||
348 | } | ||||
349 | |||||
350 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||
351 | // List-items in map clauses on this construct may only refer to the declared | ||||
352 | // variable var and entities that could be referenced by a procedure defined | ||||
353 | // at the same location | ||||
354 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||
355 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||
356 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||
357 | << getOpenMPDeclareMapperVarName(); | ||||
358 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
359 | return true; | ||||
360 | } | ||||
361 | |||||
362 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { | ||||
363 | Diag(Loc, diag::err_use_of_empty_using_if_exists); | ||||
364 | Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); | ||||
365 | return true; | ||||
366 | } | ||||
367 | |||||
368 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||
369 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||
370 | |||||
371 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||
372 | |||||
373 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||
374 | |||||
375 | if (auto *VD = dyn_cast<ValueDecl>(D)) | ||||
376 | checkTypeSupport(VD->getType(), Loc, VD); | ||||
377 | |||||
378 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||
379 | if (!Context.getTargetInfo().isTLSSupported()) | ||||
380 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
381 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||
382 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||
383 | } | ||||
384 | |||||
385 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||
386 | !isUnevaluatedContext()) { | ||||
387 | // C++ [expr.prim.req.nested] p3 | ||||
388 | // A local parameter shall only appear as an unevaluated operand | ||||
389 | // (Clause 8) within the constraint-expression. | ||||
390 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||
391 | << D; | ||||
392 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
393 | return true; | ||||
394 | } | ||||
395 | |||||
396 | return false; | ||||
397 | } | ||||
398 | |||||
399 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||
400 | /// message-send is to a declaration with the sentinel attribute, and | ||||
401 | /// if so, it checks that the requirements of the sentinel are | ||||
402 | /// satisfied. | ||||
403 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||
404 | ArrayRef<Expr *> Args) { | ||||
405 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||
406 | if (!attr) | ||||
407 | return; | ||||
408 | |||||
409 | // The number of formal parameters of the declaration. | ||||
410 | unsigned numFormalParams; | ||||
411 | |||||
412 | // The kind of declaration. This is also an index into a %select in | ||||
413 | // the diagnostic. | ||||
414 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||
415 | |||||
416 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||
417 | numFormalParams = MD->param_size(); | ||||
418 | calleeType = CT_Method; | ||||
419 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
420 | numFormalParams = FD->param_size(); | ||||
421 | calleeType = CT_Function; | ||||
422 | } else if (isa<VarDecl>(D)) { | ||||
423 | QualType type = cast<ValueDecl>(D)->getType(); | ||||
424 | const FunctionType *fn = nullptr; | ||||
425 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||
426 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||
427 | if (!fn) return; | ||||
428 | calleeType = CT_Function; | ||||
429 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||
430 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||
431 | calleeType = CT_Block; | ||||
432 | } else { | ||||
433 | return; | ||||
434 | } | ||||
435 | |||||
436 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||
437 | numFormalParams = proto->getNumParams(); | ||||
438 | } else { | ||||
439 | numFormalParams = 0; | ||||
440 | } | ||||
441 | } else { | ||||
442 | return; | ||||
443 | } | ||||
444 | |||||
445 | // "nullPos" is the number of formal parameters at the end which | ||||
446 | // effectively count as part of the variadic arguments. This is | ||||
447 | // useful if you would prefer to not have *any* formal parameters, | ||||
448 | // but the language forces you to have at least one. | ||||
449 | unsigned nullPos = attr->getNullPos(); | ||||
450 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(static_cast <bool> ((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel") ? void (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "clang/lib/Sema/SemaExpr.cpp", 450, __extension__ __PRETTY_FUNCTION__ )); | ||||
451 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||
452 | |||||
453 | // The number of arguments which should follow the sentinel. | ||||
454 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||
455 | |||||
456 | // If there aren't enough arguments for all the formal parameters, | ||||
457 | // the sentinel, and the args after the sentinel, complain. | ||||
458 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||
459 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||
460 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
461 | return; | ||||
462 | } | ||||
463 | |||||
464 | // Otherwise, find the sentinel expression. | ||||
465 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||
466 | if (!sentinelExpr) return; | ||||
467 | if (sentinelExpr->isValueDependent()) return; | ||||
468 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||
469 | |||||
470 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||
471 | // or 'NULL' if those are actually defined in the context. Only use | ||||
472 | // 'nil' for ObjC methods, where it's much more likely that the | ||||
473 | // variadic arguments form a list of object pointers. | ||||
474 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||
475 | std::string NullValue; | ||||
476 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||
477 | NullValue = "nil"; | ||||
478 | else if (getLangOpts().CPlusPlus11) | ||||
479 | NullValue = "nullptr"; | ||||
480 | else if (PP.isMacroDefined("NULL")) | ||||
481 | NullValue = "NULL"; | ||||
482 | else | ||||
483 | NullValue = "(void*) 0"; | ||||
484 | |||||
485 | if (MissingNilLoc.isInvalid()) | ||||
486 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||
487 | else | ||||
488 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||
489 | << int(calleeType) | ||||
490 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||
491 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
492 | } | ||||
493 | |||||
494 | SourceRange Sema::getExprRange(Expr *E) const { | ||||
495 | return E ? E->getSourceRange() : SourceRange(); | ||||
496 | } | ||||
497 | |||||
498 | //===----------------------------------------------------------------------===// | ||||
499 | // Standard Promotions and Conversions | ||||
500 | //===----------------------------------------------------------------------===// | ||||
501 | |||||
502 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||
503 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||
504 | // Handle any placeholder expressions which made it here. | ||||
505 | if (E->hasPlaceholderType()) { | ||||
506 | ExprResult result = CheckPlaceholderExpr(E); | ||||
507 | if (result.isInvalid()) return ExprError(); | ||||
508 | E = result.get(); | ||||
509 | } | ||||
510 | |||||
511 | QualType Ty = E->getType(); | ||||
512 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 512, __extension__ __PRETTY_FUNCTION__ )); | ||||
513 | |||||
514 | if (Ty->isFunctionType()) { | ||||
515 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||
516 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||
517 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||
518 | return ExprError(); | ||||
519 | |||||
520 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
521 | CK_FunctionToPointerDecay).get(); | ||||
522 | } else if (Ty->isArrayType()) { | ||||
523 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||
524 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||
525 | // type 'array of type' is converted to an expression that has type 'pointer | ||||
526 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||
527 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||
528 | // (C90) to "an expression" (C99). | ||||
529 | // | ||||
530 | // C++ 4.2p1: | ||||
531 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||
532 | // T" can be converted to an rvalue of type "pointer to T". | ||||
533 | // | ||||
534 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { | ||||
535 | ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||
536 | CK_ArrayToPointerDecay); | ||||
537 | if (Res.isInvalid()) | ||||
538 | return ExprError(); | ||||
539 | E = Res.get(); | ||||
540 | } | ||||
541 | } | ||||
542 | return E; | ||||
543 | } | ||||
544 | |||||
545 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||
546 | // Check to see if we are dereferencing a null pointer. If so, | ||||
547 | // and if not volatile-qualified, this is undefined behavior that the | ||||
548 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||
549 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||
550 | // only handles the pattern "*null", which is a very syntactic check. | ||||
551 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||
552 | if (UO && UO->getOpcode() == UO_Deref && | ||||
553 | UO->getSubExpr()->getType()->isPointerType()) { | ||||
554 | const LangAS AS = | ||||
555 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||
556 | if ((!isTargetAddressSpace(AS) || | ||||
557 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||
558 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||
559 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||
560 | !UO->getType().isVolatileQualified()) { | ||||
561 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
562 | S.PDiag(diag::warn_indirection_through_null) | ||||
563 | << UO->getSubExpr()->getSourceRange()); | ||||
564 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
565 | S.PDiag(diag::note_indirection_through_null)); | ||||
566 | } | ||||
567 | } | ||||
568 | } | ||||
569 | |||||
570 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||
571 | SourceLocation AssignLoc, | ||||
572 | const Expr* RHS) { | ||||
573 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||
574 | if (!IV) | ||||
575 | return; | ||||
576 | |||||
577 | DeclarationName MemberName = IV->getDeclName(); | ||||
578 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||
579 | if (!Member || !Member->isStr("isa")) | ||||
580 | return; | ||||
581 | |||||
582 | const Expr *Base = OIRE->getBase(); | ||||
583 | QualType BaseType = Base->getType(); | ||||
584 | if (OIRE->isArrow()) | ||||
585 | BaseType = BaseType->getPointeeType(); | ||||
586 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||
587 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||
588 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||
589 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||
590 | if (!ClassDeclared->getSuperClass() | ||||
591 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||
592 | if (RHS) { | ||||
593 | NamedDecl *ObjectSetClass = | ||||
594 | S.LookupSingleName(S.TUScope, | ||||
595 | &S.Context.Idents.get("object_setClass"), | ||||
596 | SourceLocation(), S.LookupOrdinaryName); | ||||
597 | if (ObjectSetClass) { | ||||
598 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||
599 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||
600 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
601 | "object_setClass(") | ||||
602 | << FixItHint::CreateReplacement( | ||||
603 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||
604 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
605 | } | ||||
606 | else | ||||
607 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||
608 | } else { | ||||
609 | NamedDecl *ObjectGetClass = | ||||
610 | S.LookupSingleName(S.TUScope, | ||||
611 | &S.Context.Idents.get("object_getClass"), | ||||
612 | SourceLocation(), S.LookupOrdinaryName); | ||||
613 | if (ObjectGetClass) | ||||
614 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||
615 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
616 | "object_getClass(") | ||||
617 | << FixItHint::CreateReplacement( | ||||
618 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||
619 | else | ||||
620 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||
621 | } | ||||
622 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||
623 | } | ||||
624 | } | ||||
625 | } | ||||
626 | |||||
627 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||
628 | // Handle any placeholder expressions which made it here. | ||||
629 | if (E->hasPlaceholderType()) { | ||||
630 | ExprResult result = CheckPlaceholderExpr(E); | ||||
631 | if (result.isInvalid()) return ExprError(); | ||||
632 | E = result.get(); | ||||
633 | } | ||||
634 | |||||
635 | // C++ [conv.lval]p1: | ||||
636 | // A glvalue of a non-function, non-array type T can be | ||||
637 | // converted to a prvalue. | ||||
638 | if (!E->isGLValue()) return E; | ||||
639 | |||||
640 | QualType T = E->getType(); | ||||
641 | assert(!T.isNull() && "r-value conversion on typeless expression?")(static_cast <bool> (!T.isNull() && "r-value conversion on typeless expression?" ) ? void (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "clang/lib/Sema/SemaExpr.cpp", 641, __extension__ __PRETTY_FUNCTION__ )); | ||||
642 | |||||
643 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||
644 | if (T->isFunctionType() || T->isArrayType()) | ||||
645 | return E; | ||||
646 | |||||
647 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||
648 | // expressions of certain types in C++. | ||||
649 | if (getLangOpts().CPlusPlus && | ||||
650 | (E->getType() == Context.OverloadTy || | ||||
651 | T->isDependentType() || | ||||
652 | T->isRecordType())) | ||||
653 | return E; | ||||
654 | |||||
655 | // The C standard is actually really unclear on this point, and | ||||
656 | // DR106 tells us what the result should be but not why. It's | ||||
657 | // generally best to say that void types just doesn't undergo | ||||
658 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||
659 | // 'void' type are never l-values, but qualified void can be. | ||||
660 | if (T->isVoidType()) | ||||
661 | return E; | ||||
662 | |||||
663 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||
664 | if (getLangOpts().OpenCL && | ||||
665 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
666 | T->isHalfType()) { | ||||
667 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||
668 | << 0 << T; | ||||
669 | return ExprError(); | ||||
670 | } | ||||
671 | |||||
672 | CheckForNullPointerDereference(*this, E); | ||||
673 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||
674 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||
675 | &Context.Idents.get("object_getClass"), | ||||
676 | SourceLocation(), LookupOrdinaryName); | ||||
677 | if (ObjectGetClass) | ||||
678 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||
679 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||
680 | << FixItHint::CreateReplacement( | ||||
681 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||
682 | else | ||||
683 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||
684 | } | ||||
685 | else if (const ObjCIvarRefExpr *OIRE = | ||||
686 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||
687 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||
688 | |||||
689 | // C++ [conv.lval]p1: | ||||
690 | // [...] If T is a non-class type, the type of the prvalue is the | ||||
691 | // cv-unqualified version of T. Otherwise, the type of the | ||||
692 | // rvalue is T. | ||||
693 | // | ||||
694 | // C99 6.3.2.1p2: | ||||
695 | // If the lvalue has qualified type, the value has the unqualified | ||||
696 | // version of the type of the lvalue; otherwise, the value has the | ||||
697 | // type of the lvalue. | ||||
698 | if (T.hasQualifiers()) | ||||
699 | T = T.getUnqualifiedType(); | ||||
700 | |||||
701 | // Under the MS ABI, lock down the inheritance model now. | ||||
702 | if (T->isMemberPointerType() && | ||||
703 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
704 | (void)isCompleteType(E->getExprLoc(), T); | ||||
705 | |||||
706 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||
707 | if (Res.isInvalid()) | ||||
708 | return Res; | ||||
709 | E = Res.get(); | ||||
710 | |||||
711 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||
712 | // balance that. | ||||
713 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
714 | Cleanup.setExprNeedsCleanups(true); | ||||
715 | |||||
716 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
717 | Cleanup.setExprNeedsCleanups(true); | ||||
718 | |||||
719 | // C++ [conv.lval]p3: | ||||
720 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||
721 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||
722 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, | ||||
723 | CurFPFeatureOverrides()); | ||||
724 | |||||
725 | // C11 6.3.2.1p2: | ||||
726 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||
727 | // of the type of the lvalue ... | ||||
728 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||
729 | T = Atomic->getValueType().getUnqualifiedType(); | ||||
730 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||
731 | nullptr, VK_PRValue, FPOptionsOverride()); | ||||
732 | } | ||||
733 | |||||
734 | return Res; | ||||
735 | } | ||||
736 | |||||
737 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||
738 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||
739 | if (Res.isInvalid()) | ||||
740 | return ExprError(); | ||||
741 | Res = DefaultLvalueConversion(Res.get()); | ||||
742 | if (Res.isInvalid()) | ||||
743 | return ExprError(); | ||||
744 | return Res; | ||||
745 | } | ||||
746 | |||||
747 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||
748 | /// performed on a function designator of a call expression. | ||||
749 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||
750 | QualType Ty = E->getType(); | ||||
751 | ExprResult Res = E; | ||||
752 | // Only do implicit cast for a function type, but not for a pointer | ||||
753 | // to function type. | ||||
754 | if (Ty->isFunctionType()) { | ||||
755 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
756 | CK_FunctionToPointerDecay); | ||||
757 | if (Res.isInvalid()) | ||||
758 | return ExprError(); | ||||
759 | } | ||||
760 | Res = DefaultLvalueConversion(Res.get()); | ||||
761 | if (Res.isInvalid()) | ||||
762 | return ExprError(); | ||||
763 | return Res.get(); | ||||
764 | } | ||||
765 | |||||
766 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||
767 | /// operators (C99 6.3). The conversions of array and function types are | ||||
768 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||
769 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||
770 | /// In these instances, this routine should *not* be called. | ||||
771 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||
772 | // First, convert to an r-value. | ||||
773 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||
774 | if (Res.isInvalid()) | ||||
775 | return ExprError(); | ||||
776 | E = Res.get(); | ||||
777 | |||||
778 | QualType Ty = E->getType(); | ||||
779 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 779, __extension__ __PRETTY_FUNCTION__ )); | ||||
780 | |||||
781 | LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); | ||||
782 | if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && | ||||
783 | (getLangOpts().getFPEvalMethod() != | ||||
784 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || | ||||
785 | PP.getLastFPEvalPragmaLocation().isValid())) { | ||||
786 | switch (EvalMethod) { | ||||
787 | default: | ||||
788 | llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method" , "clang/lib/Sema/SemaExpr.cpp", 788); | ||||
789 | break; | ||||
790 | case LangOptions::FEM_UnsetOnCommandLine: | ||||
791 | llvm_unreachable("Float evaluation method should be set by now")::llvm::llvm_unreachable_internal("Float evaluation method should be set by now" , "clang/lib/Sema/SemaExpr.cpp", 791); | ||||
792 | break; | ||||
793 | case LangOptions::FEM_Double: | ||||
794 | if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) | ||||
795 | // Widen the expression to double. | ||||
796 | return Ty->isComplexType() | ||||
797 | ? ImpCastExprToType(E, | ||||
798 | Context.getComplexType(Context.DoubleTy), | ||||
799 | CK_FloatingComplexCast) | ||||
800 | : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); | ||||
801 | break; | ||||
802 | case LangOptions::FEM_Extended: | ||||
803 | if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) | ||||
804 | // Widen the expression to long double. | ||||
805 | return Ty->isComplexType() | ||||
806 | ? ImpCastExprToType( | ||||
807 | E, Context.getComplexType(Context.LongDoubleTy), | ||||
808 | CK_FloatingComplexCast) | ||||
809 | : ImpCastExprToType(E, Context.LongDoubleTy, | ||||
810 | CK_FloatingCast); | ||||
811 | break; | ||||
812 | } | ||||
813 | } | ||||
814 | |||||
815 | // Half FP have to be promoted to float unless it is natively supported | ||||
816 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||
817 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||
818 | |||||
819 | // Try to perform integral promotions if the object has a theoretically | ||||
820 | // promotable type. | ||||
821 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||
822 | // C99 6.3.1.1p2: | ||||
823 | // | ||||
824 | // The following may be used in an expression wherever an int or | ||||
825 | // unsigned int may be used: | ||||
826 | // - an object or expression with an integer type whose integer | ||||
827 | // conversion rank is less than or equal to the rank of int | ||||
828 | // and unsigned int. | ||||
829 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||
830 | // | ||||
831 | // If an int can represent all values of the original type, the | ||||
832 | // value is converted to an int; otherwise, it is converted to an | ||||
833 | // unsigned int. These are called the integer promotions. All | ||||
834 | // other types are unchanged by the integer promotions. | ||||
835 | |||||
836 | QualType PTy = Context.isPromotableBitField(E); | ||||
837 | if (!PTy.isNull()) { | ||||
838 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||
839 | return E; | ||||
840 | } | ||||
841 | if (Ty->isPromotableIntegerType()) { | ||||
842 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||
843 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||
844 | return E; | ||||
845 | } | ||||
846 | } | ||||
847 | return E; | ||||
848 | } | ||||
849 | |||||
850 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||
851 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||
852 | /// are promoted to double. All other argument types are converted by | ||||
853 | /// UsualUnaryConversions(). | ||||
854 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||
855 | QualType Ty = E->getType(); | ||||
856 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 856, __extension__ __PRETTY_FUNCTION__ )); | ||||
857 | |||||
858 | ExprResult Res = UsualUnaryConversions(E); | ||||
859 | if (Res.isInvalid()) | ||||
860 | return ExprError(); | ||||
861 | E = Res.get(); | ||||
862 | |||||
863 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||
864 | // promote to double. | ||||
865 | // Note that default argument promotion applies only to float (and | ||||
866 | // half/fp16); it does not apply to _Float16. | ||||
867 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||
868 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||
869 | BTy->getKind() == BuiltinType::Float)) { | ||||
870 | if (getLangOpts().OpenCL && | ||||
871 | !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { | ||||
872 | if (BTy->getKind() == BuiltinType::Half) { | ||||
873 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||
874 | } | ||||
875 | } else { | ||||
876 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||
877 | } | ||||
878 | } | ||||
879 | if (BTy && | ||||
880 | getLangOpts().getExtendIntArgs() == | ||||
881 | LangOptions::ExtendArgsKind::ExtendTo64 && | ||||
882 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && | ||||
883 | Context.getTypeSizeInChars(BTy) < | ||||
884 | Context.getTypeSizeInChars(Context.LongLongTy)) { | ||||
885 | E = (Ty->isUnsignedIntegerType()) | ||||
886 | ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) | ||||
887 | .get() | ||||
888 | : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); | ||||
889 | assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&(static_cast <bool> (8 == Context.getTypeSizeInChars(Context .LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy" ) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\"" , "clang/lib/Sema/SemaExpr.cpp", 890, __extension__ __PRETTY_FUNCTION__ )) | ||||
890 | "Unexpected typesize for LongLongTy")(static_cast <bool> (8 == Context.getTypeSizeInChars(Context .LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy" ) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\"" , "clang/lib/Sema/SemaExpr.cpp", 890, __extension__ __PRETTY_FUNCTION__ )); | ||||
891 | } | ||||
892 | |||||
893 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||
894 | // promotion, even on class types, but note: | ||||
895 | // C++11 [conv.lval]p2: | ||||
896 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||
897 | // operand or a subexpression thereof the value contained in the | ||||
898 | // referenced object is not accessed. Otherwise, if the glvalue | ||||
899 | // has a class type, the conversion copy-initializes a temporary | ||||
900 | // of type T from the glvalue and the result of the conversion | ||||
901 | // is a prvalue for the temporary. | ||||
902 | // FIXME: add some way to gate this entire thing for correctness in | ||||
903 | // potentially potentially evaluated contexts. | ||||
904 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||
905 | ExprResult Temp = PerformCopyInitialization( | ||||
906 | InitializedEntity::InitializeTemporary(E->getType()), | ||||
907 | E->getExprLoc(), E); | ||||
908 | if (Temp.isInvalid()) | ||||
909 | return ExprError(); | ||||
910 | E = Temp.get(); | ||||
911 | } | ||||
912 | |||||
913 | return E; | ||||
914 | } | ||||
915 | |||||
916 | /// Determine the degree of POD-ness for an expression. | ||||
917 | /// Incomplete types are considered POD, since this check can be performed | ||||
918 | /// when we're in an unevaluated context. | ||||
919 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||
920 | if (Ty->isIncompleteType()) { | ||||
921 | // C++11 [expr.call]p7: | ||||
922 | // After these conversions, if the argument does not have arithmetic, | ||||
923 | // enumeration, pointer, pointer to member, or class type, the program | ||||
924 | // is ill-formed. | ||||
925 | // | ||||
926 | // Since we've already performed array-to-pointer and function-to-pointer | ||||
927 | // decay, the only such type in C++ is cv void. This also handles | ||||
928 | // initializer lists as variadic arguments. | ||||
929 | if (Ty->isVoidType()) | ||||
930 | return VAK_Invalid; | ||||
931 | |||||
932 | if (Ty->isObjCObjectType()) | ||||
933 | return VAK_Invalid; | ||||
934 | return VAK_Valid; | ||||
935 | } | ||||
936 | |||||
937 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
938 | return VAK_Invalid; | ||||
939 | |||||
940 | if (Ty.isCXX98PODType(Context)) | ||||
941 | return VAK_Valid; | ||||
942 | |||||
943 | // C++11 [expr.call]p7: | ||||
944 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||
945 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||
946 | // or a non-trivial destructor, with no corresponding parameter, | ||||
947 | // is conditionally-supported with implementation-defined semantics. | ||||
948 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||
949 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||
950 | if (!Record->hasNonTrivialCopyConstructor() && | ||||
951 | !Record->hasNonTrivialMoveConstructor() && | ||||
952 | !Record->hasNonTrivialDestructor()) | ||||
953 | return VAK_ValidInCXX11; | ||||
954 | |||||
955 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||
956 | return VAK_Valid; | ||||
957 | |||||
958 | if (Ty->isObjCObjectType()) | ||||
959 | return VAK_Invalid; | ||||
960 | |||||
961 | if (getLangOpts().MSVCCompat) | ||||
962 | return VAK_MSVCUndefined; | ||||
963 | |||||
964 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||
965 | // permitted to reject them. We should consider doing so. | ||||
966 | return VAK_Undefined; | ||||
967 | } | ||||
968 | |||||
969 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||
970 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||
971 | const QualType &Ty = E->getType(); | ||||
972 | VarArgKind VAK = isValidVarArgType(Ty); | ||||
973 | |||||
974 | // Complain about passing non-POD types through varargs. | ||||
975 | switch (VAK) { | ||||
976 | case VAK_ValidInCXX11: | ||||
977 | DiagRuntimeBehavior( | ||||
978 | E->getBeginLoc(), nullptr, | ||||
979 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||
980 | [[fallthrough]]; | ||||
981 | case VAK_Valid: | ||||
982 | if (Ty->isRecordType()) { | ||||
983 | // This is unlikely to be what the user intended. If the class has a | ||||
984 | // 'c_str' member function, the user probably meant to call that. | ||||
985 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
986 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||
987 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||
988 | } | ||||
989 | break; | ||||
990 | |||||
991 | case VAK_Undefined: | ||||
992 | case VAK_MSVCUndefined: | ||||
993 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
994 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||
995 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||
996 | break; | ||||
997 | |||||
998 | case VAK_Invalid: | ||||
999 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
1000 | Diag(E->getBeginLoc(), | ||||
1001 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||
1002 | << Ty << CT; | ||||
1003 | else if (Ty->isObjCObjectType()) | ||||
1004 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
1005 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||
1006 | << Ty << CT); | ||||
1007 | else | ||||
1008 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||
1009 | << isa<InitListExpr>(E) << Ty << CT; | ||||
1010 | break; | ||||
1011 | } | ||||
1012 | } | ||||
1013 | |||||
1014 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||
1015 | /// will create a trap if the resulting type is not a POD type. | ||||
1016 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||
1017 | FunctionDecl *FDecl) { | ||||
1018 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||
1019 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
1020 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||
1021 | (CT == VariadicMethod || | ||||
1022 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||
1023 | E = stripARCUnbridgedCast(E); | ||||
1024 | |||||
1025 | // Otherwise, do normal placeholder checking. | ||||
1026 | } else { | ||||
1027 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||
1028 | if (ExprRes.isInvalid()) | ||||
1029 | return ExprError(); | ||||
1030 | E = ExprRes.get(); | ||||
1031 | } | ||||
1032 | } | ||||
1033 | |||||
1034 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||
1035 | if (ExprRes.isInvalid()) | ||||
1036 | return ExprError(); | ||||
1037 | |||||
1038 | // Copy blocks to the heap. | ||||
1039 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||
1040 | maybeExtendBlockObject(ExprRes); | ||||
1041 | |||||
1042 | E = ExprRes.get(); | ||||
1043 | |||||
1044 | // Diagnostics regarding non-POD argument types are | ||||
1045 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||
1046 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||
1047 | // Turn this into a trap. | ||||
1048 | CXXScopeSpec SS; | ||||
1049 | SourceLocation TemplateKWLoc; | ||||
1050 | UnqualifiedId Name; | ||||
1051 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||
1052 | E->getBeginLoc()); | ||||
1053 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||
1054 | /*HasTrailingLParen=*/true, | ||||
1055 | /*IsAddressOfOperand=*/false); | ||||
1056 | if (TrapFn.isInvalid()) | ||||
1057 | return ExprError(); | ||||
1058 | |||||
1059 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||
1060 | None, E->getEndLoc()); | ||||
1061 | if (Call.isInvalid()) | ||||
1062 | return ExprError(); | ||||
1063 | |||||
1064 | ExprResult Comma = | ||||
1065 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||
1066 | if (Comma.isInvalid()) | ||||
1067 | return ExprError(); | ||||
1068 | return Comma.get(); | ||||
1069 | } | ||||
1070 | |||||
1071 | if (!getLangOpts().CPlusPlus && | ||||
1072 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||
1073 | diag::err_call_incomplete_argument)) | ||||
1074 | return ExprError(); | ||||
1075 | |||||
1076 | return E; | ||||
1077 | } | ||||
1078 | |||||
1079 | /// Converts an integer to complex float type. Helper function of | ||||
1080 | /// UsualArithmeticConversions() | ||||
1081 | /// | ||||
1082 | /// \return false if the integer expression is an integer type and is | ||||
1083 | /// successfully converted to the complex type. | ||||
1084 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||
1085 | ExprResult &ComplexExpr, | ||||
1086 | QualType IntTy, | ||||
1087 | QualType ComplexTy, | ||||
1088 | bool SkipCast) { | ||||
1089 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||
1090 | if (SkipCast) return false; | ||||
1091 | if (IntTy->isIntegerType()) { | ||||
1092 | QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); | ||||
1093 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||
1094 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1095 | CK_FloatingRealToComplex); | ||||
1096 | } else { | ||||
1097 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "clang/lib/Sema/SemaExpr.cpp", 1097, __extension__ __PRETTY_FUNCTION__ )); | ||||
1098 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1099 | CK_IntegralComplexToFloatingComplex); | ||||
1100 | } | ||||
1101 | return false; | ||||
1102 | } | ||||
1103 | |||||
1104 | // This handles complex/complex, complex/float, or float/complex. | ||||
1105 | // When both operands are complex, the shorter operand is converted to the | ||||
1106 | // type of the longer, and that is the type of the result. This corresponds | ||||
1107 | // to what is done when combining two real floating-point operands. | ||||
1108 | // The fun begins when size promotion occur across type domains. | ||||
1109 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||
1110 | // floating-point type, the less precise type is converted, within it's | ||||
1111 | // real or complex domain, to the precision of the other type. For example, | ||||
1112 | // when combining a "long double" with a "double _Complex", the | ||||
1113 | // "double _Complex" is promoted to "long double _Complex". | ||||
1114 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, | ||||
1115 | QualType ShorterType, | ||||
1116 | QualType LongerType, | ||||
1117 | bool PromotePrecision) { | ||||
1118 | bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType()); | ||||
1119 | QualType Result = | ||||
1120 | LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType); | ||||
1121 | |||||
1122 | if (PromotePrecision) { | ||||
1123 | if (isa<ComplexType>(ShorterType.getCanonicalType())) { | ||||
1124 | Shorter = | ||||
1125 | S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast); | ||||
1126 | } else { | ||||
1127 | if (LongerIsComplex) | ||||
1128 | LongerType = LongerType->castAs<ComplexType>()->getElementType(); | ||||
1129 | Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast); | ||||
1130 | } | ||||
1131 | } | ||||
1132 | return Result; | ||||
1133 | } | ||||
1134 | |||||
1135 | /// Handle arithmetic conversion with complex types. Helper function of | ||||
1136 | /// UsualArithmeticConversions() | ||||
1137 | static QualType handleComplexConversion(Sema &S, ExprResult &LHS, | ||||
1138 | ExprResult &RHS, QualType LHSType, | ||||
1139 | QualType RHSType, bool IsCompAssign) { | ||||
1140 | // if we have an integer operand, the result is the complex type. | ||||
1141 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1142 | /*SkipCast=*/false)) | ||||
1143 | return LHSType; | ||||
1144 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1145 | /*SkipCast=*/IsCompAssign)) | ||||
1146 | return RHSType; | ||||
1147 | |||||
1148 | // Compute the rank of the two types, regardless of whether they are complex. | ||||
1149 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1150 | if (Order < 0) | ||||
1151 | // Promote the precision of the LHS if not an assignment. | ||||
1152 | return handleComplexFloatConversion(S, LHS, LHSType, RHSType, | ||||
1153 | /*PromotePrecision=*/!IsCompAssign); | ||||
1154 | // Promote the precision of the RHS unless it is already the same as the LHS. | ||||
1155 | return handleComplexFloatConversion(S, RHS, RHSType, LHSType, | ||||
1156 | /*PromotePrecision=*/Order > 0); | ||||
1157 | } | ||||
1158 | |||||
1159 | /// Handle arithmetic conversion from integer to float. Helper function | ||||
1160 | /// of UsualArithmeticConversions() | ||||
1161 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||
1162 | ExprResult &IntExpr, | ||||
1163 | QualType FloatTy, QualType IntTy, | ||||
1164 | bool ConvertFloat, bool ConvertInt) { | ||||
1165 | if (IntTy->isIntegerType()) { | ||||
1166 | if (ConvertInt) | ||||
1167 | // Convert intExpr to the lhs floating point type. | ||||
1168 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||
1169 | CK_IntegralToFloating); | ||||
1170 | return FloatTy; | ||||
1171 | } | ||||
1172 | |||||
1173 | // Convert both sides to the appropriate complex float. | ||||
1174 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "clang/lib/Sema/SemaExpr.cpp", 1174, __extension__ __PRETTY_FUNCTION__ )); | ||||
1175 | QualType result = S.Context.getComplexType(FloatTy); | ||||
1176 | |||||
1177 | // _Complex int -> _Complex float | ||||
1178 | if (ConvertInt) | ||||
1179 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||
1180 | CK_IntegralComplexToFloatingComplex); | ||||
1181 | |||||
1182 | // float -> _Complex float | ||||
1183 | if (ConvertFloat) | ||||
1184 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||
1185 | CK_FloatingRealToComplex); | ||||
1186 | |||||
1187 | return result; | ||||
1188 | } | ||||
1189 | |||||
1190 | /// Handle arithmethic conversion with floating point types. Helper | ||||
1191 | /// function of UsualArithmeticConversions() | ||||
1192 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||
1193 | ExprResult &RHS, QualType LHSType, | ||||
1194 | QualType RHSType, bool IsCompAssign) { | ||||
1195 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||
1196 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||
1197 | |||||
1198 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||
1199 | // operand has a fixed-point type, the fixed-point operand | ||||
1200 | // is converted to the floating type [...] | ||||
1201 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||
1202 | if (LHSFloat) | ||||
1203 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||
1204 | else if (!IsCompAssign) | ||||
1205 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||
1206 | return LHSFloat ? LHSType : RHSType; | ||||
1207 | } | ||||
1208 | |||||
1209 | // If we have two real floating types, convert the smaller operand | ||||
1210 | // to the bigger result. | ||||
1211 | if (LHSFloat && RHSFloat) { | ||||
1212 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1213 | if (order > 0) { | ||||
1214 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||
1215 | return LHSType; | ||||
1216 | } | ||||
1217 | |||||
1218 | assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison" ) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "clang/lib/Sema/SemaExpr.cpp", 1218, __extension__ __PRETTY_FUNCTION__ )); | ||||
1219 | if (!IsCompAssign) | ||||
1220 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||
1221 | return RHSType; | ||||
1222 | } | ||||
1223 | |||||
1224 | if (LHSFloat) { | ||||
1225 | // Half FP has to be promoted to float unless it is natively supported | ||||
1226 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||
1227 | LHSType = S.Context.FloatTy; | ||||
1228 | |||||
1229 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1230 | /*ConvertFloat=*/!IsCompAssign, | ||||
1231 | /*ConvertInt=*/ true); | ||||
1232 | } | ||||
1233 | assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail ("RHSFloat", "clang/lib/Sema/SemaExpr.cpp", 1233, __extension__ __PRETTY_FUNCTION__)); | ||||
1234 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1235 | /*ConvertFloat=*/ true, | ||||
1236 | /*ConvertInt=*/!IsCompAssign); | ||||
1237 | } | ||||
1238 | |||||
1239 | /// Diagnose attempts to convert between __float128, __ibm128 and | ||||
1240 | /// long double if there is no support for such conversion. | ||||
1241 | /// Helper function of UsualArithmeticConversions(). | ||||
1242 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||
1243 | QualType RHSType) { | ||||
1244 | // No issue if either is not a floating point type. | ||||
1245 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) | ||||
1246 | return false; | ||||
1247 | |||||
1248 | // No issue if both have the same 128-bit float semantics. | ||||
1249 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||
1250 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||
1251 | |||||
1252 | QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; | ||||
1253 | QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; | ||||
1254 | |||||
1255 | const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); | ||||
1256 | const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); | ||||
1257 | |||||
1258 | if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || | ||||
1259 | &RHSSem != &llvm::APFloat::IEEEquad()) && | ||||
1260 | (&LHSSem != &llvm::APFloat::IEEEquad() || | ||||
1261 | &RHSSem != &llvm::APFloat::PPCDoubleDouble())) | ||||
1262 | return false; | ||||
1263 | |||||
1264 | return true; | ||||
1265 | } | ||||
1266 | |||||
1267 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||
1268 | |||||
1269 | namespace { | ||||
1270 | /// These helper callbacks are placed in an anonymous namespace to | ||||
1271 | /// permit their use as function template parameters. | ||||
1272 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1273 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||
1274 | } | ||||
1275 | |||||
1276 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1277 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||
1278 | CK_IntegralComplexCast); | ||||
1279 | } | ||||
1280 | } | ||||
1281 | |||||
1282 | /// Handle integer arithmetic conversions. Helper function of | ||||
1283 | /// UsualArithmeticConversions() | ||||
1284 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||
1285 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||
1286 | ExprResult &RHS, QualType LHSType, | ||||
1287 | QualType RHSType, bool IsCompAssign) { | ||||
1288 | // The rules for this case are in C99 6.3.1.8 | ||||
1289 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||
1290 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||
1291 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||
1292 | if (LHSSigned == RHSSigned) { | ||||
1293 | // Same signedness; use the higher-ranked type | ||||
1294 | if (order >= 0) { | ||||
1295 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1296 | return LHSType; | ||||
1297 | } else if (!IsCompAssign) | ||||
1298 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1299 | return RHSType; | ||||
1300 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||
1301 | // The unsigned type has greater than or equal rank to the | ||||
1302 | // signed type, so use the unsigned type | ||||
1303 | if (RHSSigned) { | ||||
1304 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1305 | return LHSType; | ||||
1306 | } else if (!IsCompAssign) | ||||
1307 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1308 | return RHSType; | ||||
1309 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||
1310 | // The two types are different widths; if we are here, that | ||||
1311 | // means the signed type is larger than the unsigned type, so | ||||
1312 | // use the signed type. | ||||
1313 | if (LHSSigned) { | ||||
1314 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1315 | return LHSType; | ||||
1316 | } else if (!IsCompAssign) | ||||
1317 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1318 | return RHSType; | ||||
1319 | } else { | ||||
1320 | // The signed type is higher-ranked than the unsigned type, | ||||
1321 | // but isn't actually any bigger (like unsigned int and long | ||||
1322 | // on most 32-bit systems). Use the unsigned type corresponding | ||||
1323 | // to the signed type. | ||||
1324 | QualType result = | ||||
1325 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||
1326 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||
1327 | if (!IsCompAssign) | ||||
1328 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||
1329 | return result; | ||||
1330 | } | ||||
1331 | } | ||||
1332 | |||||
1333 | /// Handle conversions with GCC complex int extension. Helper function | ||||
1334 | /// of UsualArithmeticConversions() | ||||
1335 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||
1336 | ExprResult &RHS, QualType LHSType, | ||||
1337 | QualType RHSType, | ||||
1338 | bool IsCompAssign) { | ||||
1339 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||
1340 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||
1341 | |||||
1342 | if (LHSComplexInt && RHSComplexInt) { | ||||
1343 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1344 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1345 | QualType ScalarType = | ||||
1346 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||
1347 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||
1348 | |||||
1349 | return S.Context.getComplexType(ScalarType); | ||||
1350 | } | ||||
1351 | |||||
1352 | if (LHSComplexInt) { | ||||
1353 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1354 | QualType ScalarType = | ||||
1355 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||
1356 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||
1357 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1358 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||
1359 | CK_IntegralRealToComplex); | ||||
1360 | |||||
1361 | return ComplexType; | ||||
1362 | } | ||||
1363 | |||||
1364 | assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail ("RHSComplexInt", "clang/lib/Sema/SemaExpr.cpp", 1364, __extension__ __PRETTY_FUNCTION__)); | ||||
1365 | |||||
1366 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1367 | QualType ScalarType = | ||||
1368 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||
1369 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||
1370 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1371 | |||||
1372 | if (!IsCompAssign) | ||||
1373 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||
1374 | CK_IntegralRealToComplex); | ||||
1375 | return ComplexType; | ||||
1376 | } | ||||
1377 | |||||
1378 | /// Return the rank of a given fixed point or integer type. The value itself | ||||
1379 | /// doesn't matter, but the values must be increasing with proper increasing | ||||
1380 | /// rank as described in N1169 4.1.1. | ||||
1381 | static unsigned GetFixedPointRank(QualType Ty) { | ||||
1382 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||
1383 | assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type." ) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "clang/lib/Sema/SemaExpr.cpp", 1383, __extension__ __PRETTY_FUNCTION__ )); | ||||
1384 | |||||
1385 | switch (BTy->getKind()) { | ||||
1386 | case BuiltinType::ShortFract: | ||||
1387 | case BuiltinType::UShortFract: | ||||
1388 | case BuiltinType::SatShortFract: | ||||
1389 | case BuiltinType::SatUShortFract: | ||||
1390 | return 1; | ||||
1391 | case BuiltinType::Fract: | ||||
1392 | case BuiltinType::UFract: | ||||
1393 | case BuiltinType::SatFract: | ||||
1394 | case BuiltinType::SatUFract: | ||||
1395 | return 2; | ||||
1396 | case BuiltinType::LongFract: | ||||
1397 | case BuiltinType::ULongFract: | ||||
1398 | case BuiltinType::SatLongFract: | ||||
1399 | case BuiltinType::SatULongFract: | ||||
1400 | return 3; | ||||
1401 | case BuiltinType::ShortAccum: | ||||
1402 | case BuiltinType::UShortAccum: | ||||
1403 | case BuiltinType::SatShortAccum: | ||||
1404 | case BuiltinType::SatUShortAccum: | ||||
1405 | return 4; | ||||
1406 | case BuiltinType::Accum: | ||||
1407 | case BuiltinType::UAccum: | ||||
1408 | case BuiltinType::SatAccum: | ||||
1409 | case BuiltinType::SatUAccum: | ||||
1410 | return 5; | ||||
1411 | case BuiltinType::LongAccum: | ||||
1412 | case BuiltinType::ULongAccum: | ||||
1413 | case BuiltinType::SatLongAccum: | ||||
1414 | case BuiltinType::SatULongAccum: | ||||
1415 | return 6; | ||||
1416 | default: | ||||
1417 | if (BTy->isInteger()) | ||||
1418 | return 0; | ||||
1419 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "clang/lib/Sema/SemaExpr.cpp", 1419); | ||||
1420 | } | ||||
1421 | } | ||||
1422 | |||||
1423 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||
1424 | /// point types and integers or other fixed point types do not fall under | ||||
1425 | /// usual arithmetic conversion since these conversions could result in loss | ||||
1426 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||
1427 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||
1428 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||
1429 | QualType RHSTy) { | ||||
1430 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy ->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type" ) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "clang/lib/Sema/SemaExpr.cpp", 1431, __extension__ __PRETTY_FUNCTION__ )) | ||||
1431 | "Expected at least one of the operands to be a fixed point type")(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy ->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type" ) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "clang/lib/Sema/SemaExpr.cpp", 1431, __extension__ __PRETTY_FUNCTION__ )); | ||||
1432 | assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1435, __extension__ __PRETTY_FUNCTION__ )) | ||||
1433 | RHSTy->isFixedPointOrIntegerType()) &&(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1435, __extension__ __PRETTY_FUNCTION__ )) | ||||
1434 | "Special fixed point arithmetic operation conversions are only "(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1435, __extension__ __PRETTY_FUNCTION__ )) | ||||
1435 | "applied to ints or other fixed point types")(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "clang/lib/Sema/SemaExpr.cpp", 1435, __extension__ __PRETTY_FUNCTION__ )); | ||||
1436 | |||||
1437 | // If one operand has signed fixed-point type and the other operand has | ||||
1438 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||
1439 | // converted to its corresponding signed fixed-point type and the resulting | ||||
1440 | // type is the type of the converted operand. | ||||
1441 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||
1442 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||
1443 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||
1444 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||
1445 | |||||
1446 | // The result type is the type with the highest rank, whereby a fixed-point | ||||
1447 | // conversion rank is always greater than an integer conversion rank; if the | ||||
1448 | // type of either of the operands is a saturating fixedpoint type, the result | ||||
1449 | // type shall be the saturating fixed-point type corresponding to the type | ||||
1450 | // with the highest rank; the resulting value is converted (taking into | ||||
1451 | // account rounding and overflow) to the precision of the resulting type. | ||||
1452 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||
1453 | // types are either signed or both unsigned at this point. | ||||
1454 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||
1455 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||
1456 | |||||
1457 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||
1458 | |||||
1459 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||
1460 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||
1461 | |||||
1462 | return ResultTy; | ||||
1463 | } | ||||
1464 | |||||
1465 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||
1466 | /// expressions that might be of enumeration type. | ||||
1467 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||
1468 | SourceLocation Loc, | ||||
1469 | Sema::ArithConvKind ACK) { | ||||
1470 | // C++2a [expr.arith.conv]p1: | ||||
1471 | // If one operand is of enumeration type and the other operand is of a | ||||
1472 | // different enumeration type or a floating-point type, this behavior is | ||||
1473 | // deprecated ([depr.arith.conv.enum]). | ||||
1474 | // | ||||
1475 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||
1476 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||
1477 | QualType L = LHS->getType(), R = RHS->getType(); | ||||
1478 | bool LEnum = L->isUnscopedEnumerationType(), | ||||
1479 | REnum = R->isUnscopedEnumerationType(); | ||||
1480 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||
1481 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||
1482 | (REnum && L->isFloatingType())) { | ||||
1483 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||
1484 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||
1485 | : diag::warn_arith_conv_enum_float) | ||||
1486 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1487 | << (int)ACK << LEnum << L << R; | ||||
1488 | } else if (!IsCompAssign && LEnum && REnum && | ||||
1489 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||
1490 | unsigned DiagID; | ||||
1491 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||
1492 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||
1493 | // If either enumeration type is unnamed, it's less likely that the | ||||
1494 | // user cares about this, but this situation is still deprecated in | ||||
1495 | // C++2a. Use a different warning group. | ||||
1496 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1497 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||
1498 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||
1499 | } else if (ACK == Sema::ACK_Conditional) { | ||||
1500 | // Conditional expressions are separated out because they have | ||||
1501 | // historically had a different warning flag. | ||||
1502 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1503 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||
1504 | : diag::warn_conditional_mixed_enum_types; | ||||
1505 | } else if (ACK == Sema::ACK_Comparison) { | ||||
1506 | // Comparison expressions are separated out because they have | ||||
1507 | // historically had a different warning flag. | ||||
1508 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1509 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||
1510 | : diag::warn_comparison_mixed_enum_types; | ||||
1511 | } else { | ||||
1512 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1513 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||
1514 | : diag::warn_arith_conv_mixed_enum_types; | ||||
1515 | } | ||||
1516 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1517 | << (int)ACK << L << R; | ||||
1518 | } | ||||
1519 | } | ||||
1520 | |||||
1521 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||
1522 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||
1523 | /// routine returns the first non-arithmetic type found. The client is | ||||
1524 | /// responsible for emitting appropriate error diagnostics. | ||||
1525 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||
1526 | SourceLocation Loc, | ||||
1527 | ArithConvKind ACK) { | ||||
1528 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||
1529 | |||||
1530 | if (ACK != ACK_CompAssign) { | ||||
1531 | LHS = UsualUnaryConversions(LHS.get()); | ||||
1532 | if (LHS.isInvalid()) | ||||
1533 | return QualType(); | ||||
1534 | } | ||||
1535 | |||||
1536 | RHS = UsualUnaryConversions(RHS.get()); | ||||
1537 | if (RHS.isInvalid()) | ||||
1538 | return QualType(); | ||||
1539 | |||||
1540 | // For conversion purposes, we ignore any qualifiers. | ||||
1541 | // For example, "const float" and "float" are equivalent. | ||||
1542 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
1543 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
1544 | |||||
1545 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||
1546 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||
1547 | LHSType = AtomicLHS->getValueType(); | ||||
1548 | |||||
1549 | // If both types are identical, no conversion is needed. | ||||
1550 | if (Context.hasSameType(LHSType, RHSType)) | ||||
1551 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
1552 | |||||
1553 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||
1554 | // The caller can deal with this (e.g. pointer + int). | ||||
1555 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||
1556 | return QualType(); | ||||
1557 | |||||
1558 | // Apply unary and bitfield promotions to the LHS's type. | ||||
1559 | QualType LHSUnpromotedType = LHSType; | ||||
1560 | if (LHSType->isPromotableIntegerType()) | ||||
1561 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||
1562 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||
1563 | if (!LHSBitfieldPromoteTy.isNull()) | ||||
1564 | LHSType = LHSBitfieldPromoteTy; | ||||
1565 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||
1566 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||
1567 | |||||
1568 | // If both types are identical, no conversion is needed. | ||||
1569 | if (Context.hasSameType(LHSType, RHSType)) | ||||
1570 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
1571 | |||||
1572 | // At this point, we have two different arithmetic types. | ||||
1573 | |||||
1574 | // Diagnose attempts to convert between __ibm128, __float128 and long double | ||||
1575 | // where such conversions currently can't be handled. | ||||
1576 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
1577 | return QualType(); | ||||
1578 | |||||
1579 | // Handle complex types first (C99 6.3.1.8p1). | ||||
1580 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||
1581 | return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1582 | ACK == ACK_CompAssign); | ||||
1583 | |||||
1584 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
1585 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
1586 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1587 | ACK == ACK_CompAssign); | ||||
1588 | |||||
1589 | // Handle GCC complex int extension. | ||||
1590 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||
1591 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1592 | ACK == ACK_CompAssign); | ||||
1593 | |||||
1594 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||
1595 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||
1596 | |||||
1597 | // Finally, we have two differing integer types. | ||||
1598 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
1599 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||
1600 | } | ||||
1601 | |||||
1602 | //===----------------------------------------------------------------------===// | ||||
1603 | // Semantic Analysis for various Expression Types | ||||
1604 | //===----------------------------------------------------------------------===// | ||||
1605 | |||||
1606 | |||||
1607 | ExprResult | ||||
1608 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1609 | SourceLocation DefaultLoc, | ||||
1610 | SourceLocation RParenLoc, | ||||
1611 | Expr *ControllingExpr, | ||||
1612 | ArrayRef<ParsedType> ArgTypes, | ||||
1613 | ArrayRef<Expr *> ArgExprs) { | ||||
1614 | unsigned NumAssocs = ArgTypes.size(); | ||||
1615 | assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "clang/lib/Sema/SemaExpr.cpp" , 1615, __extension__ __PRETTY_FUNCTION__)); | ||||
1616 | |||||
1617 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||
1618 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1619 | if (ArgTypes[i]) | ||||
1620 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||
1621 | else | ||||
1622 | Types[i] = nullptr; | ||||
1623 | } | ||||
1624 | |||||
1625 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||
1626 | ControllingExpr, | ||||
1627 | llvm::makeArrayRef(Types, NumAssocs), | ||||
1628 | ArgExprs); | ||||
1629 | delete [] Types; | ||||
1630 | return ER; | ||||
1631 | } | ||||
1632 | |||||
1633 | ExprResult | ||||
1634 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1635 | SourceLocation DefaultLoc, | ||||
1636 | SourceLocation RParenLoc, | ||||
1637 | Expr *ControllingExpr, | ||||
1638 | ArrayRef<TypeSourceInfo *> Types, | ||||
1639 | ArrayRef<Expr *> Exprs) { | ||||
1640 | unsigned NumAssocs = Types.size(); | ||||
1641 | assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void ( 0) : __assert_fail ("NumAssocs == Exprs.size()", "clang/lib/Sema/SemaExpr.cpp" , 1641, __extension__ __PRETTY_FUNCTION__)); | ||||
1642 | |||||
1643 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||
1644 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||
1645 | { | ||||
1646 | EnterExpressionEvaluationContext Unevaluated( | ||||
1647 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||
1648 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||
1649 | if (R.isInvalid()) | ||||
1650 | return ExprError(); | ||||
1651 | ControllingExpr = R.get(); | ||||
1652 | } | ||||
1653 | |||||
1654 | bool TypeErrorFound = false, | ||||
1655 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||
1656 | ContainsUnexpandedParameterPack | ||||
1657 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||
1658 | |||||
1659 | // The controlling expression is an unevaluated operand, so side effects are | ||||
1660 | // likely unintended. | ||||
1661 | if (!inTemplateInstantiation() && !IsResultDependent && | ||||
1662 | ControllingExpr->HasSideEffects(Context, false)) | ||||
1663 | Diag(ControllingExpr->getExprLoc(), | ||||
1664 | diag::warn_side_effects_unevaluated_context); | ||||
1665 | |||||
1666 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1667 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||
1668 | ContainsUnexpandedParameterPack = true; | ||||
1669 | |||||
1670 | if (Types[i]) { | ||||
1671 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||
1672 | ContainsUnexpandedParameterPack = true; | ||||
1673 | |||||
1674 | if (Types[i]->getType()->isDependentType()) { | ||||
1675 | IsResultDependent = true; | ||||
1676 | } else { | ||||
1677 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||
1678 | // complete object type other than a variably modified type." | ||||
1679 | unsigned D = 0; | ||||
1680 | if (Types[i]->getType()->isIncompleteType()) | ||||
1681 | D = diag::err_assoc_type_incomplete; | ||||
1682 | else if (!Types[i]->getType()->isObjectType()) | ||||
1683 | D = diag::err_assoc_type_nonobject; | ||||
1684 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||
1685 | D = diag::err_assoc_type_variably_modified; | ||||
1686 | else { | ||||
1687 | // Because the controlling expression undergoes lvalue conversion, | ||||
1688 | // array conversion, and function conversion, an association which is | ||||
1689 | // of array type, function type, or is qualified can never be | ||||
1690 | // reached. We will warn about this so users are less surprised by | ||||
1691 | // the unreachable association. However, we don't have to handle | ||||
1692 | // function types; that's not an object type, so it's handled above. | ||||
1693 | // | ||||
1694 | // The logic is somewhat different for C++ because C++ has different | ||||
1695 | // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, | ||||
1696 | // If T is a non-class type, the type of the prvalue is the cv- | ||||
1697 | // unqualified version of T. Otherwise, the type of the prvalue is T. | ||||
1698 | // The result of these rules is that all qualified types in an | ||||
1699 | // association in C are unreachable, and in C++, only qualified non- | ||||
1700 | // class types are unreachable. | ||||
1701 | unsigned Reason = 0; | ||||
1702 | QualType QT = Types[i]->getType(); | ||||
1703 | if (QT->isArrayType()) | ||||
1704 | Reason = 1; | ||||
1705 | else if (QT.hasQualifiers() && | ||||
1706 | (!LangOpts.CPlusPlus || !QT->isRecordType())) | ||||
1707 | Reason = 2; | ||||
1708 | |||||
1709 | if (Reason) | ||||
1710 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1711 | diag::warn_unreachable_association) | ||||
1712 | << QT << (Reason - 1); | ||||
1713 | } | ||||
1714 | |||||
1715 | if (D != 0) { | ||||
1716 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||
1717 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1718 | << Types[i]->getType(); | ||||
1719 | TypeErrorFound = true; | ||||
1720 | } | ||||
1721 | |||||
1722 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||
1723 | // selection shall specify compatible types." | ||||
1724 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||
1725 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||
1726 | Context.typesAreCompatible(Types[i]->getType(), | ||||
1727 | Types[j]->getType())) { | ||||
1728 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||
1729 | diag::err_assoc_compatible_types) | ||||
1730 | << Types[j]->getTypeLoc().getSourceRange() | ||||
1731 | << Types[j]->getType() | ||||
1732 | << Types[i]->getType(); | ||||
1733 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1734 | diag::note_compat_assoc) | ||||
1735 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1736 | << Types[i]->getType(); | ||||
1737 | TypeErrorFound = true; | ||||
1738 | } | ||||
1739 | } | ||||
1740 | } | ||||
1741 | } | ||||
1742 | if (TypeErrorFound) | ||||
1743 | return ExprError(); | ||||
1744 | |||||
1745 | // If we determined that the generic selection is result-dependent, don't | ||||
1746 | // try to compute the result expression. | ||||
1747 | if (IsResultDependent) | ||||
1748 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||
1749 | Exprs, DefaultLoc, RParenLoc, | ||||
1750 | ContainsUnexpandedParameterPack); | ||||
1751 | |||||
1752 | SmallVector<unsigned, 1> CompatIndices; | ||||
1753 | unsigned DefaultIndex = -1U; | ||||
1754 | // Look at the canonical type of the controlling expression in case it was a | ||||
1755 | // deduced type like __auto_type. However, when issuing diagnostics, use the | ||||
1756 | // type the user wrote in source rather than the canonical one. | ||||
1757 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1758 | if (!Types[i]) | ||||
1759 | DefaultIndex = i; | ||||
1760 | else if (Context.typesAreCompatible( | ||||
1761 | ControllingExpr->getType().getCanonicalType(), | ||||
1762 | Types[i]->getType())) | ||||
1763 | CompatIndices.push_back(i); | ||||
1764 | } | ||||
1765 | |||||
1766 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||
1767 | // type compatible with at most one of the types named in its generic | ||||
1768 | // association list." | ||||
1769 | if (CompatIndices.size() > 1) { | ||||
1770 | // We strip parens here because the controlling expression is typically | ||||
1771 | // parenthesized in macro definitions. | ||||
1772 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1773 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||
1774 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||
1775 | << (unsigned)CompatIndices.size(); | ||||
1776 | for (unsigned I : CompatIndices) { | ||||
1777 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||
1778 | diag::note_compat_assoc) | ||||
1779 | << Types[I]->getTypeLoc().getSourceRange() | ||||
1780 | << Types[I]->getType(); | ||||
1781 | } | ||||
1782 | return ExprError(); | ||||
1783 | } | ||||
1784 | |||||
1785 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||
1786 | // its controlling expression shall have type compatible with exactly one of | ||||
1787 | // the types named in its generic association list." | ||||
1788 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||
1789 | // We strip parens here because the controlling expression is typically | ||||
1790 | // parenthesized in macro definitions. | ||||
1791 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1792 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||
1793 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||
1794 | return ExprError(); | ||||
1795 | } | ||||
1796 | |||||
1797 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||
1798 | // type name that is compatible with the type of the controlling expression, | ||||
1799 | // then the result expression of the generic selection is the expression | ||||
1800 | // in that generic association. Otherwise, the result expression of the | ||||
1801 | // generic selection is the expression in the default generic association." | ||||
1802 | unsigned ResultIndex = | ||||
1803 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||
1804 | |||||
1805 | return GenericSelectionExpr::Create( | ||||
1806 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||
1807 | ContainsUnexpandedParameterPack, ResultIndex); | ||||
1808 | } | ||||
1809 | |||||
1810 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||
1811 | /// location of the token and the offset of the ud-suffix within it. | ||||
1812 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||
1813 | unsigned Offset) { | ||||
1814 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||
1815 | S.getLangOpts()); | ||||
1816 | } | ||||
1817 | |||||
1818 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||
1819 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||
1820 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||
1821 | IdentifierInfo *UDSuffix, | ||||
1822 | SourceLocation UDSuffixLoc, | ||||
1823 | ArrayRef<Expr*> Args, | ||||
1824 | SourceLocation LitEndLoc) { | ||||
1825 | assert(Args.size() <= 2 && "too many arguments for literal operator")(static_cast <bool> (Args.size() <= 2 && "too many arguments for literal operator" ) ? void (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "clang/lib/Sema/SemaExpr.cpp", 1825, __extension__ __PRETTY_FUNCTION__ )); | ||||
1826 | |||||
1827 | QualType ArgTy[2]; | ||||
1828 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||
1829 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||
1830 | if (ArgTy[ArgIdx]->isArrayType()) | ||||
1831 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||
1832 | } | ||||
1833 | |||||
1834 | DeclarationName OpName = | ||||
1835 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1836 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1837 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1838 | |||||
1839 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||
1840 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||
1841 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||
1842 | /*AllowStringTemplatePack*/ false, | ||||
1843 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||
1844 | return ExprError(); | ||||
1845 | |||||
1846 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||
1847 | } | ||||
1848 | |||||
1849 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||
1850 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||
1851 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||
1852 | /// multiple tokens. However, the common case is that StringToks points to one | ||||
1853 | /// string. | ||||
1854 | /// | ||||
1855 | ExprResult | ||||
1856 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||
1857 | assert(!StringToks.empty() && "Must have at least one string!")(static_cast <bool> (!StringToks.empty() && "Must have at least one string!" ) ? void (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "clang/lib/Sema/SemaExpr.cpp", 1857, __extension__ __PRETTY_FUNCTION__ )); | ||||
1858 | |||||
1859 | StringLiteralParser Literal(StringToks, PP); | ||||
1860 | if (Literal.hadError) | ||||
1861 | return ExprError(); | ||||
1862 | |||||
1863 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||
1864 | for (const Token &Tok : StringToks) | ||||
1865 | StringTokLocs.push_back(Tok.getLocation()); | ||||
1866 | |||||
1867 | QualType CharTy = Context.CharTy; | ||||
1868 | StringLiteral::StringKind Kind = StringLiteral::Ordinary; | ||||
1869 | if (Literal.isWide()) { | ||||
1870 | CharTy = Context.getWideCharType(); | ||||
1871 | Kind = StringLiteral::Wide; | ||||
1872 | } else if (Literal.isUTF8()) { | ||||
1873 | if (getLangOpts().Char8) | ||||
1874 | CharTy = Context.Char8Ty; | ||||
1875 | Kind = StringLiteral::UTF8; | ||||
1876 | } else if (Literal.isUTF16()) { | ||||
1877 | CharTy = Context.Char16Ty; | ||||
1878 | Kind = StringLiteral::UTF16; | ||||
1879 | } else if (Literal.isUTF32()) { | ||||
1880 | CharTy = Context.Char32Ty; | ||||
1881 | Kind = StringLiteral::UTF32; | ||||
1882 | } else if (Literal.isPascal()) { | ||||
1883 | CharTy = Context.UnsignedCharTy; | ||||
1884 | } | ||||
1885 | |||||
1886 | // Warn on initializing an array of char from a u8 string literal; this | ||||
1887 | // becomes ill-formed in C++2a. | ||||
1888 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||
1889 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||
1890 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||
1891 | |||||
1892 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||
1893 | // ensures C++2a compatibility (but may change the program behavior when | ||||
1894 | // built by non-Clang compilers for which the execution character set is | ||||
1895 | // not always UTF-8). | ||||
1896 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||
1897 | SourceLocation RemovalDiagLoc; | ||||
1898 | for (const Token &Tok : StringToks) { | ||||
1899 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||
1900 | if (RemovalDiagLoc.isInvalid()) | ||||
1901 | RemovalDiagLoc = Tok.getLocation(); | ||||
1902 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||
1903 | Tok.getLocation(), | ||||
1904 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||
1905 | getSourceManager(), getLangOpts()))); | ||||
1906 | } | ||||
1907 | } | ||||
1908 | Diag(RemovalDiagLoc, RemovalDiag); | ||||
1909 | } | ||||
1910 | |||||
1911 | QualType StrTy = | ||||
1912 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||
1913 | |||||
1914 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||
1915 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||
1916 | Kind, Literal.Pascal, StrTy, | ||||
1917 | &StringTokLocs[0], | ||||
1918 | StringTokLocs.size()); | ||||
1919 | if (Literal.getUDSuffix().empty()) | ||||
1920 | return Lit; | ||||
1921 | |||||
1922 | // We're building a user-defined literal. | ||||
1923 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
1924 | SourceLocation UDSuffixLoc = | ||||
1925 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||
1926 | Literal.getUDSuffixOffset()); | ||||
1927 | |||||
1928 | // Make sure we're allowed user-defined literals here. | ||||
1929 | if (!UDLScope) | ||||
1930 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||
1931 | |||||
1932 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||
1933 | // operator "" X (str, len) | ||||
1934 | QualType SizeType = Context.getSizeType(); | ||||
1935 | |||||
1936 | DeclarationName OpName = | ||||
1937 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1938 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1939 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1940 | |||||
1941 | QualType ArgTy[] = { | ||||
1942 | Context.getArrayDecayedType(StrTy), SizeType | ||||
1943 | }; | ||||
1944 | |||||
1945 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
1946 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||
1947 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||
1948 | /*AllowStringTemplatePack*/ true, | ||||
1949 | /*DiagnoseMissing*/ true, Lit)) { | ||||
1950 | |||||
1951 | case LOLR_Cooked: { | ||||
1952 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||
1953 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||
1954 | StringTokLocs[0]); | ||||
1955 | Expr *Args[] = { Lit, LenArg }; | ||||
1956 | |||||
1957 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||
1958 | } | ||||
1959 | |||||
1960 | case LOLR_Template: { | ||||
1961 | TemplateArgumentListInfo ExplicitArgs; | ||||
1962 | TemplateArgument Arg(Lit); | ||||
1963 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||
1964 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1965 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1966 | &ExplicitArgs); | ||||
1967 | } | ||||
1968 | |||||
1969 | case LOLR_StringTemplatePack: { | ||||
1970 | TemplateArgumentListInfo ExplicitArgs; | ||||
1971 | |||||
1972 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||
1973 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||
1974 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
1975 | |||||
1976 | TemplateArgument TypeArg(CharTy); | ||||
1977 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||
1978 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||
1979 | |||||
1980 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||
1981 | Value = Lit->getCodeUnit(I); | ||||
1982 | TemplateArgument Arg(Context, Value, CharTy); | ||||
1983 | TemplateArgumentLocInfo ArgInfo; | ||||
1984 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1985 | } | ||||
1986 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1987 | &ExplicitArgs); | ||||
1988 | } | ||||
1989 | case LOLR_Raw: | ||||
1990 | case LOLR_ErrorNoDiagnostic: | ||||
1991 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 1991); | ||||
1992 | case LOLR_Error: | ||||
1993 | return ExprError(); | ||||
1994 | } | ||||
1995 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 1995); | ||||
1996 | } | ||||
1997 | |||||
1998 | DeclRefExpr * | ||||
1999 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2000 | SourceLocation Loc, | ||||
2001 | const CXXScopeSpec *SS) { | ||||
2002 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||
2003 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||
2004 | } | ||||
2005 | |||||
2006 | DeclRefExpr * | ||||
2007 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2008 | const DeclarationNameInfo &NameInfo, | ||||
2009 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||
2010 | SourceLocation TemplateKWLoc, | ||||
2011 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2012 | NestedNameSpecifierLoc NNS = | ||||
2013 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||
2014 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||
2015 | TemplateArgs); | ||||
2016 | } | ||||
2017 | |||||
2018 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||
2019 | // host variable in a device or host device lambda. | ||||
2020 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||
2021 | VarDecl *VD) { | ||||
2022 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||
2023 | return false; | ||||
2024 | assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType ()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()" , "clang/lib/Sema/SemaExpr.cpp", 2024, __extension__ __PRETTY_FUNCTION__ )); | ||||
2025 | |||||
2026 | // Check whether the reference variable is referencing a host variable. | ||||
2027 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||
2028 | if (!DRE) | ||||
2029 | return false; | ||||
2030 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
2031 | if (!Referee || !Referee->hasGlobalStorage() || | ||||
2032 | Referee->hasAttr<CUDADeviceAttr>()) | ||||
2033 | return false; | ||||
2034 | |||||
2035 | // Check whether the current function is a device or host device lambda. | ||||
2036 | // Check whether the reference variable is a capture by getDeclContext() | ||||
2037 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||
2038 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||
2039 | if (MD && MD->getParent()->isLambda() && | ||||
2040 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||
2041 | VD->getDeclContext() != MD) | ||||
2042 | return true; | ||||
2043 | |||||
2044 | return false; | ||||
2045 | } | ||||
2046 | |||||
2047 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||
2048 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||
2049 | if (isUnevaluatedContext()) | ||||
2050 | return NOUR_Unevaluated; | ||||
2051 | |||||
2052 | // C++2a [basic.def.odr]p4: | ||||
2053 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
2054 | // is odr-used by e unless [...] x is a reference that is usable in | ||||
2055 | // constant expressions. | ||||
2056 | // CUDA/HIP: | ||||
2057 | // If a reference variable referencing a host variable is captured in a | ||||
2058 | // device or host device lambda, the value of the referee must be copied | ||||
2059 | // to the capture and the reference variable must be treated as odr-use | ||||
2060 | // since the value of the referee is not known at compile time and must | ||||
2061 | // be loaded from the captured. | ||||
2062 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2063 | if (VD->getType()->isReferenceType() && | ||||
2064 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||
2065 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||
2066 | VD->isUsableInConstantExpressions(Context)) | ||||
2067 | return NOUR_Constant; | ||||
2068 | } | ||||
2069 | |||||
2070 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||
2071 | // need to wait and see how the expression is used. | ||||
2072 | return NOUR_None; | ||||
2073 | } | ||||
2074 | |||||
2075 | /// BuildDeclRefExpr - Build an expression that references a | ||||
2076 | /// declaration that does not require a closure capture. | ||||
2077 | DeclRefExpr * | ||||
2078 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2079 | const DeclarationNameInfo &NameInfo, | ||||
2080 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||
2081 | SourceLocation TemplateKWLoc, | ||||
2082 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2083 | bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) && | ||||
2084 | NeedToCaptureVariable(D, NameInfo.getLoc()); | ||||
2085 | |||||
2086 | DeclRefExpr *E = DeclRefExpr::Create( | ||||
2087 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||
2088 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||
2089 | MarkDeclRefReferenced(E); | ||||
2090 | |||||
2091 | // C++ [except.spec]p17: | ||||
2092 | // An exception-specification is considered to be needed when: | ||||
2093 | // - in an expression, the function is the unique lookup result or | ||||
2094 | // the selected member of a set of overloaded functions. | ||||
2095 | // | ||||
2096 | // We delay doing this until after we've built the function reference and | ||||
2097 | // marked it as used so that: | ||||
2098 | // a) if the function is defaulted, we get errors from defining it before / | ||||
2099 | // instead of errors from computing its exception specification, and | ||||
2100 | // b) if the function is a defaulted comparison, we can use the body we | ||||
2101 | // build when defining it as input to the exception specification | ||||
2102 | // computation rather than computing a new body. | ||||
2103 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||
2104 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||
2105 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||
2106 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||
2107 | } | ||||
2108 | } | ||||
2109 | |||||
2110 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||
2111 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||
2112 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||
2113 | getCurFunction()->recordUseOfWeak(E); | ||||
2114 | |||||
2115 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||
2116 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||
2117 | FD = IFD->getAnonField(); | ||||
2118 | if (FD) { | ||||
2119 | UnusedPrivateFields.remove(FD); | ||||
2120 | // Just in case we're building an illegal pointer-to-member. | ||||
2121 | if (FD->isBitField()) | ||||
2122 | E->setObjectKind(OK_BitField); | ||||
2123 | } | ||||
2124 | |||||
2125 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||
2126 | // designates a bit-field. | ||||
2127 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||
2128 | if (auto *BE = BD->getBinding()) | ||||
2129 | E->setObjectKind(BE->getObjectKind()); | ||||
2130 | |||||
2131 | return E; | ||||
2132 | } | ||||
2133 | |||||
2134 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||
2135 | /// possibly a list of template arguments. | ||||
2136 | /// | ||||
2137 | /// If this produces template arguments, it is permitted to call | ||||
2138 | /// DecomposeTemplateName. | ||||
2139 | /// | ||||
2140 | /// This actually loses a lot of source location information for | ||||
2141 | /// non-standard name kinds; we should consider preserving that in | ||||
2142 | /// some way. | ||||
2143 | void | ||||
2144 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||
2145 | TemplateArgumentListInfo &Buffer, | ||||
2146 | DeclarationNameInfo &NameInfo, | ||||
2147 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||
2148 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
2149 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||
2150 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||
2151 | |||||
2152 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||
2153 | Id.TemplateId->NumArgs); | ||||
2154 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||
2155 | |||||
2156 | TemplateName TName = Id.TemplateId->Template.get(); | ||||
2157 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||
2158 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||
2159 | TemplateArgs = &Buffer; | ||||
2160 | } else { | ||||
2161 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||
2162 | TemplateArgs = nullptr; | ||||
2163 | } | ||||
2164 | } | ||||
2165 | |||||
2166 | static void emitEmptyLookupTypoDiagnostic( | ||||
2167 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||
2168 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||
2169 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||
2170 | DeclContext *Ctx = | ||||
2171 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||
2172 | if (!TC) { | ||||
2173 | // Emit a special diagnostic for failed member lookups. | ||||
2174 | // FIXME: computing the declaration context might fail here (?) | ||||
2175 | if (Ctx) | ||||
2176 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||
2177 | << SS.getRange(); | ||||
2178 | else | ||||
2179 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||
2180 | return; | ||||
2181 | } | ||||
2182 | |||||
2183 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||
2184 | bool DroppedSpecifier = | ||||
2185 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||
2186 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2187 | ? diag::note_implicit_param_decl | ||||
2188 | : diag::note_previous_decl; | ||||
2189 | if (!Ctx) | ||||
2190 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||
2191 | SemaRef.PDiag(NoteID)); | ||||
2192 | else | ||||
2193 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||
2194 | << Typo << Ctx << DroppedSpecifier | ||||
2195 | << SS.getRange(), | ||||
2196 | SemaRef.PDiag(NoteID)); | ||||
2197 | } | ||||
2198 | |||||
2199 | /// Diagnose a lookup that found results in an enclosing class during error | ||||
2200 | /// recovery. This usually indicates that the results were found in a dependent | ||||
2201 | /// base class that could not be searched as part of a template definition. | ||||
2202 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||
2203 | /// compatibility mode). | ||||
2204 | /// | ||||
2205 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||
2206 | /// should attempt to recover using these lookup results. | ||||
2207 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||
2208 | // During a default argument instantiation the CurContext points | ||||
2209 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||
2210 | // function parameter list, hence add an explicit check. | ||||
2211 | bool isDefaultArgument = | ||||
2212 | !CodeSynthesisContexts.empty() && | ||||
2213 | CodeSynthesisContexts.back().Kind == | ||||
2214 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||
2215 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||
2216 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||
2217 | R.getNamingClass() == CurMethod->getParent() && | ||||
2218 | !isDefaultArgument; | ||||
2219 | |||||
2220 | // There are two ways we can find a class-scope declaration during template | ||||
2221 | // instantiation that we did not find in the template definition: if it is a | ||||
2222 | // member of a dependent base class, or if it is declared after the point of | ||||
2223 | // use in the same class. Distinguish these by comparing the class in which | ||||
2224 | // the member was found to the naming class of the lookup. | ||||
2225 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||
2226 | unsigned NoteID = diag::note_member_declared_at; | ||||
2227 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||
2228 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||
2229 | : diag::err_found_later_in_class; | ||||
2230 | } else if (getLangOpts().MSVCCompat) { | ||||
2231 | DiagID = diag::ext_found_in_dependent_base; | ||||
2232 | NoteID = diag::note_dependent_member_use; | ||||
2233 | } | ||||
2234 | |||||
2235 | if (isInstance) { | ||||
2236 | // Give a code modification hint to insert 'this->'. | ||||
2237 | Diag(R.getNameLoc(), DiagID) | ||||
2238 | << R.getLookupName() | ||||
2239 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||
2240 | CheckCXXThisCapture(R.getNameLoc()); | ||||
2241 | } else { | ||||
2242 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||
2243 | // they're not shadowed). | ||||
2244 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||
2245 | } | ||||
2246 | |||||
2247 | for (NamedDecl *D : R) | ||||
2248 | Diag(D->getLocation(), NoteID); | ||||
2249 | |||||
2250 | // Return true if we are inside a default argument instantiation | ||||
2251 | // and the found name refers to an instance member function, otherwise | ||||
2252 | // the caller will try to create an implicit member call and this is wrong | ||||
2253 | // for default arguments. | ||||
2254 | // | ||||
2255 | // FIXME: Is this special case necessary? We could allow the caller to | ||||
2256 | // diagnose this. | ||||
2257 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||
2258 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||
2259 | return true; | ||||
2260 | } | ||||
2261 | |||||
2262 | // Tell the callee to try to recover. | ||||
2263 | return false; | ||||
2264 | } | ||||
2265 | |||||
2266 | /// Diagnose an empty lookup. | ||||
2267 | /// | ||||
2268 | /// \return false if new lookup candidates were found | ||||
2269 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||
2270 | CorrectionCandidateCallback &CCC, | ||||
2271 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||
2272 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||
2273 | DeclarationName Name = R.getLookupName(); | ||||
2274 | |||||
2275 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||
2276 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||
2277 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||
2278 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||
2279 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
2280 | diagnostic = diag::err_undeclared_use; | ||||
2281 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||
2282 | } | ||||
2283 | |||||
2284 | // If the original lookup was an unqualified lookup, fake an | ||||
2285 | // unqualified lookup. This is useful when (for example) the | ||||
2286 | // original lookup would not have found something because it was a | ||||
2287 | // dependent name. | ||||
2288 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||
2289 | while (DC) { | ||||
2290 | if (isa<CXXRecordDecl>(DC)) { | ||||
2291 | LookupQualifiedName(R, DC); | ||||
2292 | |||||
2293 | if (!R.empty()) { | ||||
2294 | // Don't give errors about ambiguities in this lookup. | ||||
2295 | R.suppressDiagnostics(); | ||||
2296 | |||||
2297 | // If there's a best viable function among the results, only mention | ||||
2298 | // that one in the notes. | ||||
2299 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||
2300 | OverloadCandidateSet::CSK_Normal); | ||||
2301 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||
2302 | OverloadCandidateSet::iterator Best; | ||||
2303 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||
2304 | OR_Success) { | ||||
2305 | R.clear(); | ||||
2306 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||
2307 | R.resolveKind(); | ||||
2308 | } | ||||
2309 | |||||
2310 | return DiagnoseDependentMemberLookup(R); | ||||
2311 | } | ||||
2312 | |||||
2313 | R.clear(); | ||||
2314 | } | ||||
2315 | |||||
2316 | DC = DC->getLookupParent(); | ||||
2317 | } | ||||
2318 | |||||
2319 | // We didn't find anything, so try to correct for a typo. | ||||
2320 | TypoCorrection Corrected; | ||||
2321 | if (S && Out) { | ||||
2322 | SourceLocation TypoLoc = R.getNameLoc(); | ||||
2323 | assert(!ExplicitTemplateArgs &&(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "clang/lib/Sema/SemaExpr.cpp", 2324, __extension__ __PRETTY_FUNCTION__ )) | ||||
2324 | "Diagnosing an empty lookup with explicit template args!")(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "clang/lib/Sema/SemaExpr.cpp", 2324, __extension__ __PRETTY_FUNCTION__ )); | ||||
2325 | *Out = CorrectTypoDelayed( | ||||
2326 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||
2327 | [=](const TypoCorrection &TC) { | ||||
2328 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||
2329 | diagnostic, diagnostic_suggest); | ||||
2330 | }, | ||||
2331 | nullptr, CTK_ErrorRecovery); | ||||
2332 | if (*Out) | ||||
2333 | return true; | ||||
2334 | } else if (S && | ||||
2335 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||
2336 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||
2337 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
2338 | bool DroppedSpecifier = | ||||
2339 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||
2340 | R.setLookupName(Corrected.getCorrection()); | ||||
2341 | |||||
2342 | bool AcceptableWithRecovery = false; | ||||
2343 | bool AcceptableWithoutRecovery = false; | ||||
2344 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||
2345 | if (ND) { | ||||
2346 | if (Corrected.isOverloaded()) { | ||||
2347 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||
2348 | OverloadCandidateSet::CSK_Normal); | ||||
2349 | OverloadCandidateSet::iterator Best; | ||||
2350 | for (NamedDecl *CD : Corrected) { | ||||
2351 | if (FunctionTemplateDecl *FTD = | ||||
2352 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||
2353 | AddTemplateOverloadCandidate( | ||||
2354 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||
2355 | Args, OCS); | ||||
2356 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
2357 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||
2358 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||
2359 | Args, OCS); | ||||
2360 | } | ||||
2361 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||
2362 | case OR_Success: | ||||
2363 | ND = Best->FoundDecl; | ||||
2364 | Corrected.setCorrectionDecl(ND); | ||||
2365 | break; | ||||
2366 | default: | ||||
2367 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||
2368 | Corrected.setCorrectionDecl(ND); | ||||
2369 | break; | ||||
2370 | } | ||||
2371 | } | ||||
2372 | R.addDecl(ND); | ||||
2373 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||
2374 | CXXRecordDecl *Record = nullptr; | ||||
2375 | if (Corrected.getCorrectionSpecifier()) { | ||||
2376 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||
2377 | Record = Ty->getAsCXXRecordDecl(); | ||||
2378 | } | ||||
2379 | if (!Record) | ||||
2380 | Record = cast<CXXRecordDecl>( | ||||
2381 | ND->getDeclContext()->getRedeclContext()); | ||||
2382 | R.setNamingClass(Record); | ||||
2383 | } | ||||
2384 | |||||
2385 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||
2386 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||
2387 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||
2388 | // FIXME: If we ended up with a typo for a type name or | ||||
2389 | // Objective-C class name, we're in trouble because the parser | ||||
2390 | // is in the wrong place to recover. Suggest the typo | ||||
2391 | // correction, but don't make it a fix-it since we're not going | ||||
2392 | // to recover well anyway. | ||||
2393 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||
2394 | getAsTypeTemplateDecl(UnderlyingND) || | ||||
2395 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||
2396 | } else { | ||||
2397 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||
2398 | // because we aren't able to recover. | ||||
2399 | AcceptableWithoutRecovery = true; | ||||
2400 | } | ||||
2401 | |||||
2402 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||
2403 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2404 | ? diag::note_implicit_param_decl | ||||
2405 | : diag::note_previous_decl; | ||||
2406 | if (SS.isEmpty()) | ||||
2407 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||
2408 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2409 | else | ||||
2410 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||
2411 | << Name << computeDeclContext(SS, false) | ||||
2412 | << DroppedSpecifier << SS.getRange(), | ||||
2413 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2414 | |||||
2415 | // Tell the callee whether to try to recover. | ||||
2416 | return !AcceptableWithRecovery; | ||||
2417 | } | ||||
2418 | } | ||||
2419 | R.clear(); | ||||
2420 | |||||
2421 | // Emit a special diagnostic for failed member lookups. | ||||
2422 | // FIXME: computing the declaration context might fail here (?) | ||||
2423 | if (!SS.isEmpty()) { | ||||
2424 | Diag(R.getNameLoc(), diag::err_no_member) | ||||
2425 | << Name << computeDeclContext(SS, false) | ||||
2426 | << SS.getRange(); | ||||
2427 | return true; | ||||
2428 | } | ||||
2429 | |||||
2430 | // Give up, we can't recover. | ||||
2431 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||
2432 | return true; | ||||
2433 | } | ||||
2434 | |||||
2435 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||
2436 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||
2437 | /// assume the identifier is a member of a dependent base class. We can only | ||||
2438 | /// recover successfully in static methods, instance methods, and other contexts | ||||
2439 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||
2440 | /// instantiation model, but it's close enough. | ||||
2441 | static Expr * | ||||
2442 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||
2443 | DeclarationNameInfo &NameInfo, | ||||
2444 | SourceLocation TemplateKWLoc, | ||||
2445 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2446 | // Only try to recover from lookup into dependent bases in static methods or | ||||
2447 | // contexts where 'this' is available. | ||||
2448 | QualType ThisType = S.getCurrentThisType(); | ||||
2449 | const CXXRecordDecl *RD = nullptr; | ||||
2450 | if (!ThisType.isNull()) | ||||
2451 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||
2452 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||
2453 | RD = MD->getParent(); | ||||
2454 | if (!RD || !RD->hasAnyDependentBases()) | ||||
2455 | return nullptr; | ||||
2456 | |||||
2457 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||
2458 | // is available, suggest inserting 'this->' as a fixit. | ||||
2459 | SourceLocation Loc = NameInfo.getLoc(); | ||||
2460 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||
2461 | DB << NameInfo.getName() << RD; | ||||
2462 | |||||
2463 | if (!ThisType.isNull()) { | ||||
2464 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||
2465 | return CXXDependentScopeMemberExpr::Create( | ||||
2466 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||
2467 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||
2468 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||
2469 | } | ||||
2470 | |||||
2471 | // Synthesize a fake NNS that points to the derived class. This will | ||||
2472 | // perform name lookup during template instantiation. | ||||
2473 | CXXScopeSpec SS; | ||||
2474 | auto *NNS = | ||||
2475 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||
2476 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||
2477 | return DependentScopeDeclRefExpr::Create( | ||||
2478 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||
2479 | TemplateArgs); | ||||
2480 | } | ||||
2481 | |||||
2482 | ExprResult | ||||
2483 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||
2484 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||
2485 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||
2486 | CorrectionCandidateCallback *CCC, | ||||
2487 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||
2488 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen ) && "cannot be direct & operand and have a trailing lparen" ) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "clang/lib/Sema/SemaExpr.cpp", 2489, __extension__ __PRETTY_FUNCTION__ )) | ||||
2489 | "cannot be direct & operand and have a trailing lparen")(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen ) && "cannot be direct & operand and have a trailing lparen" ) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "clang/lib/Sema/SemaExpr.cpp", 2489, __extension__ __PRETTY_FUNCTION__ )); | ||||
2490 | if (SS.isInvalid()) | ||||
2491 | return ExprError(); | ||||
2492 | |||||
2493 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||
2494 | |||||
2495 | // Decompose the UnqualifiedId into the following data. | ||||
2496 | DeclarationNameInfo NameInfo; | ||||
2497 | const TemplateArgumentListInfo *TemplateArgs; | ||||
2498 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||
2499 | |||||
2500 | DeclarationName Name = NameInfo.getName(); | ||||
2501 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
2502 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||
2503 | |||||
2504 | if (II && II->isEditorPlaceholder()) { | ||||
2505 | // FIXME: When typed placeholders are supported we can create a typed | ||||
2506 | // placeholder expression node. | ||||
2507 | return ExprError(); | ||||
2508 | } | ||||
2509 | |||||
2510 | // C++ [temp.dep.expr]p3: | ||||
2511 | // An id-expression is type-dependent if it contains: | ||||
2512 | // -- an identifier that was declared with a dependent type, | ||||
2513 | // (note: handled after lookup) | ||||
2514 | // -- a template-id that is dependent, | ||||
2515 | // (note: handled in BuildTemplateIdExpr) | ||||
2516 | // -- a conversion-function-id that specifies a dependent type, | ||||
2517 | // -- a nested-name-specifier that contains a class-name that | ||||
2518 | // names a dependent type. | ||||
2519 | // Determine whether this is a member of an unknown specialization; | ||||
2520 | // we need to handle these differently. | ||||
2521 | bool DependentID = false; | ||||
2522 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||
2523 | Name.getCXXNameType()->isDependentType()) { | ||||
2524 | DependentID = true; | ||||
2525 | } else if (SS.isSet()) { | ||||
2526 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||
2527 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2528 | return ExprError(); | ||||
2529 | } else { | ||||
2530 | DependentID = true; | ||||
2531 | } | ||||
2532 | } | ||||
2533 | |||||
2534 | if (DependentID) | ||||
2535 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2536 | IsAddressOfOperand, TemplateArgs); | ||||
2537 | |||||
2538 | // Perform the required lookup. | ||||
2539 | LookupResult R(*this, NameInfo, | ||||
2540 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||
2541 | ? LookupObjCImplicitSelfParam | ||||
2542 | : LookupOrdinaryName); | ||||
2543 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||
2544 | // Lookup the template name again to correctly establish the context in | ||||
2545 | // which it was found. This is really unfortunate as we already did the | ||||
2546 | // lookup to determine that it was a template name in the first place. If | ||||
2547 | // this becomes a performance hit, we can work harder to preserve those | ||||
2548 | // results until we get here but it's likely not worth it. | ||||
2549 | bool MemberOfUnknownSpecialization; | ||||
2550 | AssumedTemplateKind AssumedTemplate; | ||||
2551 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||
2552 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||
2553 | &AssumedTemplate)) | ||||
2554 | return ExprError(); | ||||
2555 | |||||
2556 | if (MemberOfUnknownSpecialization || | ||||
2557 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||
2558 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2559 | IsAddressOfOperand, TemplateArgs); | ||||
2560 | } else { | ||||
2561 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||
2562 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||
2563 | |||||
2564 | // If the result might be in a dependent base class, this is a dependent | ||||
2565 | // id-expression. | ||||
2566 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2567 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2568 | IsAddressOfOperand, TemplateArgs); | ||||
2569 | |||||
2570 | // If this reference is in an Objective-C method, then we need to do | ||||
2571 | // some special Objective-C lookup, too. | ||||
2572 | if (IvarLookupFollowUp) { | ||||
2573 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||
2574 | if (E.isInvalid()) | ||||
2575 | return ExprError(); | ||||
2576 | |||||
2577 | if (Expr *Ex = E.getAs<Expr>()) | ||||
2578 | return Ex; | ||||
2579 | } | ||||
2580 | } | ||||
2581 | |||||
2582 | if (R.isAmbiguous()) | ||||
2583 | return ExprError(); | ||||
2584 | |||||
2585 | // This could be an implicitly declared function reference if the language | ||||
2586 | // mode allows it as a feature. | ||||
2587 | if (R.empty() && HasTrailingLParen && II && | ||||
2588 | getLangOpts().implicitFunctionsAllowed()) { | ||||
2589 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||
2590 | if (D) R.addDecl(D); | ||||
2591 | } | ||||
2592 | |||||
2593 | // Determine whether this name might be a candidate for | ||||
2594 | // argument-dependent lookup. | ||||
2595 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||
2596 | |||||
2597 | if (R.empty() && !ADL) { | ||||
2598 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
2599 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||
2600 | TemplateKWLoc, TemplateArgs)) | ||||
2601 | return E; | ||||
2602 | } | ||||
2603 | |||||
2604 | // Don't diagnose an empty lookup for inline assembly. | ||||
2605 | if (IsInlineAsmIdentifier) | ||||
2606 | return ExprError(); | ||||
2607 | |||||
2608 | // If this name wasn't predeclared and if this is not a function | ||||
2609 | // call, diagnose the problem. | ||||
2610 | TypoExpr *TE = nullptr; | ||||
2611 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||
2612 | : nullptr); | ||||
2613 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||
2614 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured" ) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "clang/lib/Sema/SemaExpr.cpp", 2615, __extension__ __PRETTY_FUNCTION__ )) | ||||
2615 | "Typo correction callback misconfigured")(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured" ) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "clang/lib/Sema/SemaExpr.cpp", 2615, __extension__ __PRETTY_FUNCTION__ )); | ||||
2616 | if (CCC) { | ||||
2617 | // Make sure the callback knows what the typo being diagnosed is. | ||||
2618 | CCC->setTypoName(II); | ||||
2619 | if (SS.isValid()) | ||||
2620 | CCC->setTypoNNS(SS.getScopeRep()); | ||||
2621 | } | ||||
2622 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||
2623 | // a template name, but we happen to have always already looked up the name | ||||
2624 | // before we get here if it must be a template name. | ||||
2625 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||
2626 | None, &TE)) { | ||||
2627 | if (TE && KeywordReplacement) { | ||||
2628 | auto &State = getTypoExprState(TE); | ||||
2629 | auto BestTC = State.Consumer->getNextCorrection(); | ||||
2630 | if (BestTC.isKeyword()) { | ||||
2631 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||
2632 | if (State.DiagHandler) | ||||
2633 | State.DiagHandler(BestTC); | ||||
2634 | KeywordReplacement->startToken(); | ||||
2635 | KeywordReplacement->setKind(II->getTokenID()); | ||||
2636 | KeywordReplacement->setIdentifierInfo(II); | ||||
2637 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||
2638 | // Clean up the state associated with the TypoExpr, since it has | ||||
2639 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||
2640 | clearDelayedTypo(TE); | ||||
2641 | // Signal that a correction to a keyword was performed by returning a | ||||
2642 | // valid-but-null ExprResult. | ||||
2643 | return (Expr*)nullptr; | ||||
2644 | } | ||||
2645 | State.Consumer->resetCorrectionStream(); | ||||
2646 | } | ||||
2647 | return TE ? TE : ExprError(); | ||||
2648 | } | ||||
2649 | |||||
2650 | assert(!R.empty() &&(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "clang/lib/Sema/SemaExpr.cpp", 2651, __extension__ __PRETTY_FUNCTION__ )) | ||||
2651 | "DiagnoseEmptyLookup returned false but added no results")(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "clang/lib/Sema/SemaExpr.cpp", 2651, __extension__ __PRETTY_FUNCTION__ )); | ||||
2652 | |||||
2653 | // If we found an Objective-C instance variable, let | ||||
2654 | // LookupInObjCMethod build the appropriate expression to | ||||
2655 | // reference the ivar. | ||||
2656 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||
2657 | R.clear(); | ||||
2658 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||
2659 | // In a hopelessly buggy code, Objective-C instance variable | ||||
2660 | // lookup fails and no expression will be built to reference it. | ||||
2661 | if (!E.isInvalid() && !E.get()) | ||||
2662 | return ExprError(); | ||||
2663 | return E; | ||||
2664 | } | ||||
2665 | } | ||||
2666 | |||||
2667 | // This is guaranteed from this point on. | ||||
2668 | assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail ("!R.empty() || ADL", "clang/lib/Sema/SemaExpr.cpp", 2668, __extension__ __PRETTY_FUNCTION__)); | ||||
2669 | |||||
2670 | // Check whether this might be a C++ implicit instance member access. | ||||
2671 | // C++ [class.mfct.non-static]p3: | ||||
2672 | // When an id-expression that is not part of a class member access | ||||
2673 | // syntax and not used to form a pointer to member is used in the | ||||
2674 | // body of a non-static member function of class X, if name lookup | ||||
2675 | // resolves the name in the id-expression to a non-static non-type | ||||
2676 | // member of some class C, the id-expression is transformed into a | ||||
2677 | // class member access expression using (*this) as the | ||||
2678 | // postfix-expression to the left of the . operator. | ||||
2679 | // | ||||
2680 | // But we don't actually need to do this for '&' operands if R | ||||
2681 | // resolved to a function or overloaded function set, because the | ||||
2682 | // expression is ill-formed if it actually works out to be a | ||||
2683 | // non-static member function: | ||||
2684 | // | ||||
2685 | // C++ [expr.ref]p4: | ||||
2686 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||
2687 | // [t]he expression can be used only as the left-hand operand of a | ||||
2688 | // member function call. | ||||
2689 | // | ||||
2690 | // There are other safeguards against such uses, but it's important | ||||
2691 | // to get this right here so that we don't end up making a | ||||
2692 | // spuriously dependent expression if we're inside a dependent | ||||
2693 | // instance method. | ||||
2694 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||
2695 | bool MightBeImplicitMember; | ||||
2696 | if (!IsAddressOfOperand) | ||||
2697 | MightBeImplicitMember = true; | ||||
2698 | else if (!SS.isEmpty()) | ||||
2699 | MightBeImplicitMember = false; | ||||
2700 | else if (R.isOverloadedResult()) | ||||
2701 | MightBeImplicitMember = false; | ||||
2702 | else if (R.isUnresolvableResult()) | ||||
2703 | MightBeImplicitMember = true; | ||||
2704 | else | ||||
2705 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||
2706 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||
2707 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||
2708 | |||||
2709 | if (MightBeImplicitMember) | ||||
2710 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||
2711 | R, TemplateArgs, S); | ||||
2712 | } | ||||
2713 | |||||
2714 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||
2715 | |||||
2716 | // In C++1y, if this is a variable template id, then check it | ||||
2717 | // in BuildTemplateIdExpr(). | ||||
2718 | // The single lookup result must be a variable template declaration. | ||||
2719 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||
2720 | Id.TemplateId->Kind == TNK_Var_template) { | ||||
2721 | assert(R.getAsSingle<VarTemplateDecl>() &&(static_cast <bool> (R.getAsSingle<VarTemplateDecl> () && "There should only be one declaration found.") ? void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "clang/lib/Sema/SemaExpr.cpp", 2722, __extension__ __PRETTY_FUNCTION__ )) | ||||
2722 | "There should only be one declaration found.")(static_cast <bool> (R.getAsSingle<VarTemplateDecl> () && "There should only be one declaration found.") ? void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "clang/lib/Sema/SemaExpr.cpp", 2722, __extension__ __PRETTY_FUNCTION__ )); | ||||
2723 | } | ||||
2724 | |||||
2725 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||
2726 | } | ||||
2727 | |||||
2728 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||
2729 | } | ||||
2730 | |||||
2731 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||
2732 | /// declaration name, generally during template instantiation. | ||||
2733 | /// There's a large number of things which don't need to be done along | ||||
2734 | /// this path. | ||||
2735 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||
2736 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||
2737 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||
2738 | DeclContext *DC = computeDeclContext(SS, false); | ||||
2739 | if (!DC) | ||||
2740 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2741 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2742 | |||||
2743 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2744 | return ExprError(); | ||||
2745 | |||||
2746 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
2747 | LookupQualifiedName(R, DC); | ||||
2748 | |||||
2749 | if (R.isAmbiguous()) | ||||
2750 | return ExprError(); | ||||
2751 | |||||
2752 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2753 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2754 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2755 | |||||
2756 | if (R.empty()) { | ||||
2757 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||
2758 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||
2759 | // is invalid because it's derived from an invalid base class, then missing | ||||
2760 | // members were likely supposed to be inherited. | ||||
2761 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||
2762 | if (CD->isInvalidDecl()) | ||||
2763 | return ExprError(); | ||||
2764 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||
2765 | << NameInfo.getName() << DC << SS.getRange(); | ||||
2766 | return ExprError(); | ||||
2767 | } | ||||
2768 | |||||
2769 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||
2770 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||
2771 | // a dependent context. If we can recover with a type, downgrade this to | ||||
2772 | // a warning in Microsoft compatibility mode. | ||||
2773 | unsigned DiagID = diag::err_typename_missing; | ||||
2774 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||
2775 | DiagID = diag::ext_typename_missing; | ||||
2776 | SourceLocation Loc = SS.getBeginLoc(); | ||||
2777 | auto D = Diag(Loc, DiagID); | ||||
2778 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||
2779 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||
2780 | |||||
2781 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||
2782 | // context. | ||||
2783 | if (!RecoveryTSI) | ||||
2784 | return ExprError(); | ||||
2785 | |||||
2786 | // Only issue the fixit if we're prepared to recover. | ||||
2787 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||
2788 | |||||
2789 | // Recover by pretending this was an elaborated type. | ||||
2790 | QualType Ty = Context.getTypeDeclType(TD); | ||||
2791 | TypeLocBuilder TLB; | ||||
2792 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||
2793 | |||||
2794 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||
2795 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||
2796 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
2797 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
2798 | |||||
2799 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||
2800 | |||||
2801 | return ExprEmpty(); | ||||
2802 | } | ||||
2803 | |||||
2804 | // Defend against this resolving to an implicit member access. We usually | ||||
2805 | // won't get here if this might be a legitimate a class member (we end up in | ||||
2806 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||
2807 | // a pointer-to-member or in an unevaluated context in C++11. | ||||
2808 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||
2809 | return BuildPossibleImplicitMemberExpr(SS, | ||||
2810 | /*TemplateKWLoc=*/SourceLocation(), | ||||
2811 | R, /*TemplateArgs=*/nullptr, S); | ||||
2812 | |||||
2813 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||
2814 | } | ||||
2815 | |||||
2816 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2817 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2818 | /// should form a reference to an ivar. | ||||
2819 | /// | ||||
2820 | /// Ideally, most of this would be done by lookup, but there's | ||||
2821 | /// actually quite a lot of extra work involved. | ||||
2822 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2823 | IdentifierInfo *II) { | ||||
2824 | SourceLocation Loc = Lookup.getNameLoc(); | ||||
2825 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2826 | |||||
2827 | // Check for error condition which is already reported. | ||||
2828 | if (!CurMethod) | ||||
2829 | return DeclResult(true); | ||||
2830 | |||||
2831 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||
2832 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||
2833 | // found a decl, but that decl is outside the current instance method (i.e. | ||||
2834 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||
2835 | // this name, if the lookup sucedes, we replace it our current decl. | ||||
2836 | |||||
2837 | // If we're in a class method, we don't normally want to look for | ||||
2838 | // ivars. But if we don't find anything else, and there's an | ||||
2839 | // ivar, that's an error. | ||||
2840 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||
2841 | |||||
2842 | bool LookForIvars; | ||||
2843 | if (Lookup.empty()) | ||||
2844 | LookForIvars = true; | ||||
2845 | else if (IsClassMethod) | ||||
2846 | LookForIvars = false; | ||||
2847 | else | ||||
2848 | LookForIvars = (Lookup.isSingleResult() && | ||||
2849 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||
2850 | ObjCInterfaceDecl *IFace = nullptr; | ||||
2851 | if (LookForIvars) { | ||||
2852 | IFace = CurMethod->getClassInterface(); | ||||
2853 | ObjCInterfaceDecl *ClassDeclared; | ||||
2854 | ObjCIvarDecl *IV = nullptr; | ||||
2855 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||
2856 | // Diagnose using an ivar in a class method. | ||||
2857 | if (IsClassMethod) { | ||||
2858 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2859 | return DeclResult(true); | ||||
2860 | } | ||||
2861 | |||||
2862 | // Diagnose the use of an ivar outside of the declaring class. | ||||
2863 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||
2864 | !declaresSameEntity(ClassDeclared, IFace) && | ||||
2865 | !getLangOpts().DebuggerSupport) | ||||
2866 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||
2867 | |||||
2868 | // Success. | ||||
2869 | return IV; | ||||
2870 | } | ||||
2871 | } else if (CurMethod->isInstanceMethod()) { | ||||
2872 | // We should warn if a local variable hides an ivar. | ||||
2873 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||
2874 | ObjCInterfaceDecl *ClassDeclared; | ||||
2875 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||
2876 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||
2877 | declaresSameEntity(IFace, ClassDeclared)) | ||||
2878 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||
2879 | } | ||||
2880 | } | ||||
2881 | } else if (Lookup.isSingleResult() && | ||||
2882 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||
2883 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||
2884 | if (const ObjCIvarDecl *IV = | ||||
2885 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||
2886 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2887 | return DeclResult(true); | ||||
2888 | } | ||||
2889 | } | ||||
2890 | |||||
2891 | // Didn't encounter an error, didn't find an ivar. | ||||
2892 | return DeclResult(false); | ||||
2893 | } | ||||
2894 | |||||
2895 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||
2896 | ObjCIvarDecl *IV) { | ||||
2897 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2898 | assert(CurMethod && CurMethod->isInstanceMethod() &&(static_cast <bool> (CurMethod && CurMethod-> isInstanceMethod() && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "clang/lib/Sema/SemaExpr.cpp", 2899, __extension__ __PRETTY_FUNCTION__ )) | ||||
2899 | "should not reference ivar from this context")(static_cast <bool> (CurMethod && CurMethod-> isInstanceMethod() && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "clang/lib/Sema/SemaExpr.cpp", 2899, __extension__ __PRETTY_FUNCTION__ )); | ||||
2900 | |||||
2901 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||
2902 | assert(IFace && "should not reference ivar from this context")(static_cast <bool> (IFace && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "clang/lib/Sema/SemaExpr.cpp", 2902, __extension__ __PRETTY_FUNCTION__ )); | ||||
2903 | |||||
2904 | // If we're referencing an invalid decl, just return this as a silent | ||||
2905 | // error node. The error diagnostic was already emitted on the decl. | ||||
2906 | if (IV->isInvalidDecl()) | ||||
2907 | return ExprError(); | ||||
2908 | |||||
2909 | // Check if referencing a field with __attribute__((deprecated)). | ||||
2910 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||
2911 | return ExprError(); | ||||
2912 | |||||
2913 | // FIXME: This should use a new expr for a direct reference, don't | ||||
2914 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||
2915 | IdentifierInfo &II = Context.Idents.get("self"); | ||||
2916 | UnqualifiedId SelfName; | ||||
2917 | SelfName.setImplicitSelfParam(&II); | ||||
2918 | CXXScopeSpec SelfScopeSpec; | ||||
2919 | SourceLocation TemplateKWLoc; | ||||
2920 | ExprResult SelfExpr = | ||||
2921 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||
2922 | /*HasTrailingLParen=*/false, | ||||
2923 | /*IsAddressOfOperand=*/false); | ||||
2924 | if (SelfExpr.isInvalid()) | ||||
2925 | return ExprError(); | ||||
2926 | |||||
2927 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||
2928 | if (SelfExpr.isInvalid()) | ||||
2929 | return ExprError(); | ||||
2930 | |||||
2931 | MarkAnyDeclReferenced(Loc, IV, true); | ||||
2932 | |||||
2933 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||
2934 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||
2935 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||
2936 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||
2937 | |||||
2938 | ObjCIvarRefExpr *Result = new (Context) | ||||
2939 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||
2940 | IV->getLocation(), SelfExpr.get(), true, true); | ||||
2941 | |||||
2942 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||
2943 | if (!isUnevaluatedContext() && | ||||
2944 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||
2945 | getCurFunction()->recordUseOfWeak(Result); | ||||
2946 | } | ||||
2947 | if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext()) | ||||
2948 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||
2949 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||
2950 | |||||
2951 | return Result; | ||||
2952 | } | ||||
2953 | |||||
2954 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2955 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2956 | /// should form a reference to an ivar. If so, build an expression referencing | ||||
2957 | /// that ivar. | ||||
2958 | ExprResult | ||||
2959 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2960 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||
2961 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||
2962 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||
2963 | if (Ivar.isInvalid()) | ||||
2964 | return ExprError(); | ||||
2965 | if (Ivar.isUsable()) | ||||
2966 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||
2967 | cast<ObjCIvarDecl>(Ivar.get())); | ||||
2968 | |||||
2969 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||
2970 | LookupBuiltin(Lookup); | ||||
2971 | |||||
2972 | // Sentinel value saying that we didn't do anything special. | ||||
2973 | return ExprResult(false); | ||||
2974 | } | ||||
2975 | |||||
2976 | /// Cast a base object to a member's actual type. | ||||
2977 | /// | ||||
2978 | /// There are two relevant checks: | ||||
2979 | /// | ||||
2980 | /// C++ [class.access.base]p7: | ||||
2981 | /// | ||||
2982 | /// If a class member access operator [...] is used to access a non-static | ||||
2983 | /// data member or non-static member function, the reference is ill-formed if | ||||
2984 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||
2985 | /// naming class of the right operand. | ||||
2986 | /// | ||||
2987 | /// C++ [expr.ref]p7: | ||||
2988 | /// | ||||
2989 | /// If E2 is a non-static data member or a non-static member function, the | ||||
2990 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||
2991 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||
2992 | /// | ||||
2993 | /// Note that the latter check does not consider access; the access of the | ||||
2994 | /// "real" base class is checked as appropriate when checking the access of the | ||||
2995 | /// member name. | ||||
2996 | ExprResult | ||||
2997 | Sema::PerformObjectMemberConversion(Expr *From, | ||||
2998 | NestedNameSpecifier *Qualifier, | ||||
2999 | NamedDecl *FoundDecl, | ||||
3000 | NamedDecl *Member) { | ||||
3001 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||
3002 | if (!RD) | ||||
3003 | return From; | ||||
3004 | |||||
3005 | QualType DestRecordType; | ||||
3006 | QualType DestType; | ||||
3007 | QualType FromRecordType; | ||||
3008 | QualType FromType = From->getType(); | ||||
3009 | bool PointerConversions = false; | ||||
3010 | if (isa<FieldDecl>(Member)) { | ||||
3011 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||
3012 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||
3013 | DestRecordType = Context.getAddrSpaceQualType( | ||||
3014 | DestRecordType, FromPtrType | ||||
3015 | ? FromType->getPointeeType().getAddressSpace() | ||||
3016 | : FromType.getAddressSpace()); | ||||
3017 | |||||
3018 | if (FromPtrType) { | ||||
3019 | DestType = Context.getPointerType(DestRecordType); | ||||
3020 | FromRecordType = FromPtrType->getPointeeType(); | ||||
3021 | PointerConversions = true; | ||||
3022 | } else { | ||||
3023 | DestType = DestRecordType; | ||||
3024 | FromRecordType = FromType; | ||||
3025 | } | ||||
3026 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||
3027 | if (Method->isStatic()) | ||||
3028 | return From; | ||||
3029 | |||||
3030 | DestType = Method->getThisType(); | ||||
3031 | DestRecordType = DestType->getPointeeType(); | ||||
3032 | |||||
3033 | if (FromType->getAs<PointerType>()) { | ||||
3034 | FromRecordType = FromType->getPointeeType(); | ||||
3035 | PointerConversions = true; | ||||
3036 | } else { | ||||
3037 | FromRecordType = FromType; | ||||
3038 | DestType = DestRecordType; | ||||
3039 | } | ||||
3040 | |||||
3041 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||
3042 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||
3043 | if (FromAS != DestAS) { | ||||
3044 | QualType FromRecordTypeWithoutAS = | ||||
3045 | Context.removeAddrSpaceQualType(FromRecordType); | ||||
3046 | QualType FromTypeWithDestAS = | ||||
3047 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||
3048 | if (PointerConversions) | ||||
3049 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||
3050 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||
3051 | CK_AddressSpaceConversion, From->getValueKind()) | ||||
3052 | .get(); | ||||
3053 | } | ||||
3054 | } else { | ||||
3055 | // No conversion necessary. | ||||
3056 | return From; | ||||
3057 | } | ||||
3058 | |||||
3059 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||
3060 | return From; | ||||
3061 | |||||
3062 | // If the unqualified types are the same, no conversion is necessary. | ||||
3063 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3064 | return From; | ||||
3065 | |||||
3066 | SourceRange FromRange = From->getSourceRange(); | ||||
3067 | SourceLocation FromLoc = FromRange.getBegin(); | ||||
3068 | |||||
3069 | ExprValueKind VK = From->getValueKind(); | ||||
3070 | |||||
3071 | // C++ [class.member.lookup]p8: | ||||
3072 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||
3073 | // class name. | ||||
3074 | // | ||||
3075 | // If the member was a qualified name and the qualified referred to a | ||||
3076 | // specific base subobject type, we'll cast to that intermediate type | ||||
3077 | // first and then to the object in which the member is declared. That allows | ||||
3078 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||
3079 | // | ||||
3080 | // class Base { public: int x; }; | ||||
3081 | // class Derived1 : public Base { }; | ||||
3082 | // class Derived2 : public Base { }; | ||||
3083 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||
3084 | // | ||||
3085 | // void VeryDerived::f() { | ||||
3086 | // x = 17; // error: ambiguous base subobjects | ||||
3087 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||
3088 | // } | ||||
3089 | if (Qualifier && Qualifier->getAsType()) { | ||||
3090 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||
3091 | assert(QType->isRecordType() && "lookup done with non-record type")(static_cast <bool> (QType->isRecordType() && "lookup done with non-record type") ? void (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "clang/lib/Sema/SemaExpr.cpp", 3091, __extension__ __PRETTY_FUNCTION__ )); | ||||
3092 | |||||
3093 | QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); | ||||
3094 | |||||
3095 | // In C++98, the qualifier type doesn't actually have to be a base | ||||
3096 | // type of the object type, in which case we just ignore it. | ||||
3097 | // Otherwise build the appropriate casts. | ||||
3098 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||
3099 | CXXCastPath BasePath; | ||||
3100 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||
3101 | FromLoc, FromRange, &BasePath)) | ||||
3102 | return ExprError(); | ||||
3103 | |||||
3104 | if (PointerConversions) | ||||
3105 | QType = Context.getPointerType(QType); | ||||
3106 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||
3107 | VK, &BasePath).get(); | ||||
3108 | |||||
3109 | FromType = QType; | ||||
3110 | FromRecordType = QRecordType; | ||||
3111 | |||||
3112 | // If the qualifier type was the same as the destination type, | ||||
3113 | // we're done. | ||||
3114 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3115 | return From; | ||||
3116 | } | ||||
3117 | } | ||||
3118 | |||||
3119 | CXXCastPath BasePath; | ||||
3120 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||
3121 | FromLoc, FromRange, &BasePath, | ||||
3122 | /*IgnoreAccess=*/true)) | ||||
3123 | return ExprError(); | ||||
3124 | |||||
3125 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||
3126 | VK, &BasePath); | ||||
3127 | } | ||||
3128 | |||||
3129 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||
3130 | const LookupResult &R, | ||||
3131 | bool HasTrailingLParen) { | ||||
3132 | // Only when used directly as the postfix-expression of a call. | ||||
3133 | if (!HasTrailingLParen) | ||||
3134 | return false; | ||||
3135 | |||||
3136 | // Never if a scope specifier was provided. | ||||
3137 | if (SS.isSet()) | ||||
3138 | return false; | ||||
3139 | |||||
3140 | // Only in C++ or ObjC++. | ||||
3141 | if (!getLangOpts().CPlusPlus) | ||||
3142 | return false; | ||||
3143 | |||||
3144 | // Turn off ADL when we find certain kinds of declarations during | ||||
3145 | // normal lookup: | ||||
3146 | for (NamedDecl *D : R) { | ||||
3147 | // C++0x [basic.lookup.argdep]p3: | ||||
3148 | // -- a declaration of a class member | ||||
3149 | // Since using decls preserve this property, we check this on the | ||||
3150 | // original decl. | ||||
3151 | if (D->isCXXClassMember()) | ||||
3152 | return false; | ||||
3153 | |||||
3154 | // C++0x [basic.lookup.argdep]p3: | ||||
3155 | // -- a block-scope function declaration that is not a | ||||
3156 | // using-declaration | ||||
3157 | // NOTE: we also trigger this for function templates (in fact, we | ||||
3158 | // don't check the decl type at all, since all other decl types | ||||
3159 | // turn off ADL anyway). | ||||
3160 | if (isa<UsingShadowDecl>(D)) | ||||
3161 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
3162 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
3163 | return false; | ||||
3164 | |||||
3165 | // C++0x [basic.lookup.argdep]p3: | ||||
3166 | // -- a declaration that is neither a function or a function | ||||
3167 | // template | ||||
3168 | // And also for builtin functions. | ||||
3169 | if (isa<FunctionDecl>(D)) { | ||||
3170 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||
3171 | |||||
3172 | // But also builtin functions. | ||||
3173 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||
3174 | return false; | ||||
3175 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||
3176 | return false; | ||||
3177 | } | ||||
3178 | |||||
3179 | return true; | ||||
3180 | } | ||||
3181 | |||||
3182 | |||||
3183 | /// Diagnoses obvious problems with the use of the given declaration | ||||
3184 | /// as an expression. This is only actually called for lookups that | ||||
3185 | /// were not overloaded, and it doesn't promise that the declaration | ||||
3186 | /// will in fact be used. | ||||
3187 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, | ||||
3188 | bool AcceptInvalid) { | ||||
3189 | if (D->isInvalidDecl() && !AcceptInvalid) | ||||
3190 | return true; | ||||
3191 | |||||
3192 | if (isa<TypedefNameDecl>(D)) { | ||||
3193 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||
3194 | return true; | ||||
3195 | } | ||||
3196 | |||||
3197 | if (isa<ObjCInterfaceDecl>(D)) { | ||||
3198 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||
3199 | return true; | ||||
3200 | } | ||||
3201 | |||||
3202 | if (isa<NamespaceDecl>(D)) { | ||||
3203 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||
3204 | return true; | ||||
3205 | } | ||||
3206 | |||||
3207 | return false; | ||||
3208 | } | ||||
3209 | |||||
3210 | // Certain multiversion types should be treated as overloaded even when there is | ||||
3211 | // only one result. | ||||
3212 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||
3213 | assert(R.isSingleResult() && "Expected only a single result")(static_cast <bool> (R.isSingleResult() && "Expected only a single result" ) ? void (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "clang/lib/Sema/SemaExpr.cpp", 3213, __extension__ __PRETTY_FUNCTION__ )); | ||||
3214 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||
3215 | return FD && | ||||
3216 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||
3217 | } | ||||
3218 | |||||
3219 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||
3220 | LookupResult &R, bool NeedsADL, | ||||
3221 | bool AcceptInvalidDecl) { | ||||
3222 | // If this is a single, fully-resolved result and we don't need ADL, | ||||
3223 | // just build an ordinary singleton decl ref. | ||||
3224 | if (!NeedsADL && R.isSingleResult() && | ||||
3225 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||
3226 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||
3227 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||
3228 | R.getRepresentativeDecl(), nullptr, | ||||
3229 | AcceptInvalidDecl); | ||||
3230 | |||||
3231 | // We only need to check the declaration if there's exactly one | ||||
3232 | // result, because in the overloaded case the results can only be | ||||
3233 | // functions and function templates. | ||||
3234 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||
3235 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(), | ||||
3236 | AcceptInvalidDecl)) | ||||
3237 | return ExprError(); | ||||
3238 | |||||
3239 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||
3240 | // any lookup-related diagnostics; we'll hash these out later, when | ||||
3241 | // we've picked a target. | ||||
3242 | R.suppressDiagnostics(); | ||||
3243 | |||||
3244 | UnresolvedLookupExpr *ULE | ||||
3245 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||
3246 | SS.getWithLocInContext(Context), | ||||
3247 | R.getLookupNameInfo(), | ||||
3248 | NeedsADL, R.isOverloadedResult(), | ||||
3249 | R.begin(), R.end()); | ||||
3250 | |||||
3251 | return ULE; | ||||
3252 | } | ||||
3253 | |||||
3254 | static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, | ||||
3255 | SourceLocation loc, | ||||
3256 | ValueDecl *var); | ||||
3257 | |||||
3258 | /// Complete semantic analysis for a reference to the given declaration. | ||||
3259 | ExprResult Sema::BuildDeclarationNameExpr( | ||||
3260 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||
3261 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||
3262 | bool AcceptInvalidDecl) { | ||||
3263 | assert(D && "Cannot refer to a NULL declaration")(static_cast <bool> (D && "Cannot refer to a NULL declaration" ) ? void (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "clang/lib/Sema/SemaExpr.cpp", 3263, __extension__ __PRETTY_FUNCTION__ )); | ||||
3264 | assert(!isa<FunctionTemplateDecl>(D) &&(static_cast <bool> (!isa<FunctionTemplateDecl>(D ) && "Cannot refer unambiguously to a function template" ) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "clang/lib/Sema/SemaExpr.cpp", 3265, __extension__ __PRETTY_FUNCTION__ )) | ||||
3265 | "Cannot refer unambiguously to a function template")(static_cast <bool> (!isa<FunctionTemplateDecl>(D ) && "Cannot refer unambiguously to a function template" ) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "clang/lib/Sema/SemaExpr.cpp", 3265, __extension__ __PRETTY_FUNCTION__ )); | ||||
3266 | |||||
3267 | SourceLocation Loc = NameInfo.getLoc(); | ||||
3268 | if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) { | ||||
3269 | // Recovery from invalid cases (e.g. D is an invalid Decl). | ||||
3270 | // We use the dependent type for the RecoveryExpr to prevent bogus follow-up | ||||
3271 | // diagnostics, as invalid decls use int as a fallback type. | ||||
3272 | return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); | ||||
3273 | } | ||||
3274 | |||||
3275 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||
3276 | // Specifically diagnose references to class templates that are missing | ||||
3277 | // a template argument list. | ||||
3278 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||
3279 | return ExprError(); | ||||
3280 | } | ||||
3281 | |||||
3282 | // Make sure that we're referring to a value. | ||||
3283 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { | ||||
3284 | Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); | ||||
3285 | Diag(D->getLocation(), diag::note_declared_at); | ||||
3286 | return ExprError(); | ||||
3287 | } | ||||
3288 | |||||
3289 | // Check whether this declaration can be used. Note that we suppress | ||||
3290 | // this check when we're going to perform argument-dependent lookup | ||||
3291 | // on this function name, because this might not be the function | ||||
3292 | // that overload resolution actually selects. | ||||
3293 | if (DiagnoseUseOfDecl(D, Loc)) | ||||
3294 | return ExprError(); | ||||
3295 | |||||
3296 | auto *VD = cast<ValueDecl>(D); | ||||
3297 | |||||
3298 | // Only create DeclRefExpr's for valid Decl's. | ||||
3299 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||
3300 | return ExprError(); | ||||
3301 | |||||
3302 | // Handle members of anonymous structs and unions. If we got here, | ||||
3303 | // and the reference is to a class member indirect field, then this | ||||
3304 | // must be the subject of a pointer-to-member expression. | ||||
3305 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||
3306 | if (!indirectField->isCXXClassMember()) | ||||
3307 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||
3308 | indirectField); | ||||
3309 | |||||
3310 | QualType type = VD->getType(); | ||||
3311 | if (type.isNull()) | ||||
3312 | return ExprError(); | ||||
3313 | ExprValueKind valueKind = VK_PRValue; | ||||
3314 | |||||
3315 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||
3316 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||
3317 | // is expanded by some outer '...' in the context of the use. | ||||
3318 | type = type.getNonPackExpansionType(); | ||||
3319 | |||||
3320 | switch (D->getKind()) { | ||||
3321 | // Ignore all the non-ValueDecl kinds. | ||||
3322 | #define ABSTRACT_DECL(kind) | ||||
3323 | #define VALUE(type, base) | ||||
3324 | #define DECL(type, base) case Decl::type: | ||||
3325 | #include "clang/AST/DeclNodes.inc" | ||||
3326 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "clang/lib/Sema/SemaExpr.cpp" , 3326); | ||||
3327 | |||||
3328 | // These shouldn't make it here. | ||||
3329 | case Decl::ObjCAtDefsField: | ||||
3330 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "clang/lib/Sema/SemaExpr.cpp", 3330); | ||||
3331 | |||||
3332 | // Enum constants are always r-values and never references. | ||||
3333 | // Unresolved using declarations are dependent. | ||||
3334 | case Decl::EnumConstant: | ||||
3335 | case Decl::UnresolvedUsingValue: | ||||
3336 | case Decl::OMPDeclareReduction: | ||||
3337 | case Decl::OMPDeclareMapper: | ||||
3338 | valueKind = VK_PRValue; | ||||
3339 | break; | ||||
3340 | |||||
3341 | // Fields and indirect fields that got here must be for | ||||
3342 | // pointer-to-member expressions; we just call them l-values for | ||||
3343 | // internal consistency, because this subexpression doesn't really | ||||
3344 | // exist in the high-level semantics. | ||||
3345 | case Decl::Field: | ||||
3346 | case Decl::IndirectField: | ||||
3347 | case Decl::ObjCIvar: | ||||
3348 | assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast <bool> (getLangOpts().CPlusPlus && "building reference to field in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "clang/lib/Sema/SemaExpr.cpp", 3348, __extension__ __PRETTY_FUNCTION__ )); | ||||
3349 | |||||
3350 | // These can't have reference type in well-formed programs, but | ||||
3351 | // for internal consistency we do this anyway. | ||||
3352 | type = type.getNonReferenceType(); | ||||
3353 | valueKind = VK_LValue; | ||||
3354 | break; | ||||
3355 | |||||
3356 | // Non-type template parameters are either l-values or r-values | ||||
3357 | // depending on the type. | ||||
3358 | case Decl::NonTypeTemplateParm: { | ||||
3359 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||
3360 | type = reftype->getPointeeType(); | ||||
3361 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||
3362 | break; | ||||
3363 | } | ||||
3364 | |||||
3365 | // [expr.prim.id.unqual]p2: | ||||
3366 | // If the entity is a template parameter object for a template | ||||
3367 | // parameter of type T, the type of the expression is const T. | ||||
3368 | // [...] The expression is an lvalue if the entity is a [...] template | ||||
3369 | // parameter object. | ||||
3370 | if (type->isRecordType()) { | ||||
3371 | type = type.getUnqualifiedType().withConst(); | ||||
3372 | valueKind = VK_LValue; | ||||
3373 | break; | ||||
3374 | } | ||||
3375 | |||||
3376 | // For non-references, we need to strip qualifiers just in case | ||||
3377 | // the template parameter was declared as 'const int' or whatever. | ||||
3378 | valueKind = VK_PRValue; | ||||
3379 | type = type.getUnqualifiedType(); | ||||
3380 | break; | ||||
3381 | } | ||||
3382 | |||||
3383 | case Decl::Var: | ||||
3384 | case Decl::VarTemplateSpecialization: | ||||
3385 | case Decl::VarTemplatePartialSpecialization: | ||||
3386 | case Decl::Decomposition: | ||||
3387 | case Decl::OMPCapturedExpr: | ||||
3388 | // In C, "extern void blah;" is valid and is an r-value. | ||||
3389 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && | ||||
3390 | type->isVoidType()) { | ||||
3391 | valueKind = VK_PRValue; | ||||
3392 | break; | ||||
3393 | } | ||||
3394 | [[fallthrough]]; | ||||
3395 | |||||
3396 | case Decl::ImplicitParam: | ||||
3397 | case Decl::ParmVar: { | ||||
3398 | // These are always l-values. | ||||
3399 | valueKind = VK_LValue; | ||||
3400 | type = type.getNonReferenceType(); | ||||
3401 | |||||
3402 | // FIXME: Does the addition of const really only apply in | ||||
3403 | // potentially-evaluated contexts? Since the variable isn't actually | ||||
3404 | // captured in an unevaluated context, it seems that the answer is no. | ||||
3405 | if (!isUnevaluatedContext()) { | ||||
3406 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||
3407 | if (!CapturedType.isNull()) | ||||
3408 | type = CapturedType; | ||||
3409 | } | ||||
3410 | |||||
3411 | break; | ||||
3412 | } | ||||
3413 | |||||
3414 | case Decl::Binding: | ||||
3415 | // These are always lvalues. | ||||
3416 | valueKind = VK_LValue; | ||||
3417 | type = type.getNonReferenceType(); | ||||
3418 | break; | ||||
3419 | |||||
3420 | case Decl::Function: { | ||||
3421 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||
3422 | if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { | ||||
3423 | type = Context.BuiltinFnTy; | ||||
3424 | valueKind = VK_PRValue; | ||||
3425 | break; | ||||
3426 | } | ||||
3427 | } | ||||
3428 | |||||
3429 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||
3430 | |||||
3431 | // If we're referring to a function with an __unknown_anytype | ||||
3432 | // result type, make the entire expression __unknown_anytype. | ||||
3433 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||
3434 | type = Context.UnknownAnyTy; | ||||
3435 | valueKind = VK_PRValue; | ||||
3436 | break; | ||||
3437 | } | ||||
3438 | |||||
3439 | // Functions are l-values in C++. | ||||
3440 | if (getLangOpts().CPlusPlus) { | ||||
3441 | valueKind = VK_LValue; | ||||
3442 | break; | ||||
3443 | } | ||||
3444 | |||||
3445 | // C99 DR 316 says that, if a function type comes from a | ||||
3446 | // function definition (without a prototype), that type is only | ||||
3447 | // used for checking compatibility. Therefore, when referencing | ||||
3448 | // the function, we pretend that we don't have the full function | ||||
3449 | // type. | ||||
3450 | if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) | ||||
3451 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||
3452 | fty->getExtInfo()); | ||||
3453 | |||||
3454 | // Functions are r-values in C. | ||||
3455 | valueKind = VK_PRValue; | ||||
3456 | break; | ||||
3457 | } | ||||
3458 | |||||
3459 | case Decl::CXXDeductionGuide: | ||||
3460 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "clang/lib/Sema/SemaExpr.cpp", 3460); | ||||
3461 | |||||
3462 | case Decl::MSProperty: | ||||
3463 | case Decl::MSGuid: | ||||
3464 | case Decl::TemplateParamObject: | ||||
3465 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||
3466 | // capture in OpenMP, or duplicated between host and device? | ||||
3467 | valueKind = VK_LValue; | ||||
3468 | break; | ||||
3469 | |||||
3470 | case Decl::UnnamedGlobalConstant: | ||||
3471 | valueKind = VK_LValue; | ||||
3472 | break; | ||||
3473 | |||||
3474 | case Decl::CXXMethod: | ||||
3475 | // If we're referring to a method with an __unknown_anytype | ||||
3476 | // result type, make the entire expression __unknown_anytype. | ||||
3477 | // This should only be possible with a type written directly. | ||||
3478 | if (const FunctionProtoType *proto = | ||||
3479 | dyn_cast<FunctionProtoType>(VD->getType())) | ||||
3480 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||
3481 | type = Context.UnknownAnyTy; | ||||
3482 | valueKind = VK_PRValue; | ||||
3483 | break; | ||||
3484 | } | ||||
3485 | |||||
3486 | // C++ methods are l-values if static, r-values if non-static. | ||||
3487 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||
3488 | valueKind = VK_LValue; | ||||
3489 | break; | ||||
3490 | } | ||||
3491 | [[fallthrough]]; | ||||
3492 | |||||
3493 | case Decl::CXXConversion: | ||||
3494 | case Decl::CXXDestructor: | ||||
3495 | case Decl::CXXConstructor: | ||||
3496 | valueKind = VK_PRValue; | ||||
3497 | break; | ||||
3498 | } | ||||
3499 | |||||
3500 | auto *E = | ||||
3501 | BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||
3502 | /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs); | ||||
3503 | // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We | ||||
3504 | // wrap a DeclRefExpr referring to an invalid decl with a dependent-type | ||||
3505 | // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus | ||||
3506 | // diagnostics). | ||||
3507 | if (VD->isInvalidDecl() && E) | ||||
3508 | return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E}); | ||||
3509 | return E; | ||||
3510 | } | ||||
3511 | |||||
3512 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||
3513 | SmallString<32> &Target) { | ||||
3514 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||
3515 | char *ResultPtr = &Target[0]; | ||||
3516 | const llvm::UTF8 *ErrorPtr; | ||||
3517 | bool success = | ||||
3518 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||
3519 | (void)success; | ||||
3520 | assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail ("success", "clang/lib/Sema/SemaExpr.cpp", 3520, __extension__ __PRETTY_FUNCTION__)); | ||||
3521 | Target.resize(ResultPtr - &Target[0]); | ||||
3522 | } | ||||
3523 | |||||
3524 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||
3525 | PredefinedExpr::IdentKind IK) { | ||||
3526 | // Pick the current block, lambda, captured statement or function. | ||||
3527 | Decl *currentDecl = nullptr; | ||||
3528 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||
3529 | currentDecl = BSI->TheDecl; | ||||
3530 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||
3531 | currentDecl = LSI->CallOperator; | ||||
3532 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||
3533 | currentDecl = CSI->TheCapturedDecl; | ||||
3534 | else | ||||
3535 | currentDecl = getCurFunctionOrMethodDecl(); | ||||
3536 | |||||
3537 | if (!currentDecl) { | ||||
3538 | Diag(Loc, diag::ext_predef_outside_function); | ||||
3539 | currentDecl = Context.getTranslationUnitDecl(); | ||||
3540 | } | ||||
3541 | |||||
3542 | QualType ResTy; | ||||
3543 | StringLiteral *SL = nullptr; | ||||
3544 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||
3545 | ResTy = Context.DependentTy; | ||||
3546 | else { | ||||
3547 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||
3548 | // the string. | ||||
3549 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||
3550 | unsigned Length = Str.length(); | ||||
3551 | |||||
3552 | llvm::APInt LengthI(32, Length + 1); | ||||
3553 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||
3554 | ResTy = | ||||
3555 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||
3556 | SmallString<32> RawChars; | ||||
3557 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||
3558 | Str, RawChars); | ||||
3559 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3560 | ArrayType::Normal, | ||||
3561 | /*IndexTypeQuals*/ 0); | ||||
3562 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||
3563 | /*Pascal*/ false, ResTy, Loc); | ||||
3564 | } else { | ||||
3565 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||
3566 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3567 | ArrayType::Normal, | ||||
3568 | /*IndexTypeQuals*/ 0); | ||||
3569 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary, | ||||
3570 | /*Pascal*/ false, ResTy, Loc); | ||||
3571 | } | ||||
3572 | } | ||||
3573 | |||||
3574 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||
3575 | } | ||||
3576 | |||||
3577 | ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, | ||||
3578 | SourceLocation LParen, | ||||
3579 | SourceLocation RParen, | ||||
3580 | TypeSourceInfo *TSI) { | ||||
3581 | return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); | ||||
3582 | } | ||||
3583 | |||||
3584 | ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, | ||||
3585 | SourceLocation LParen, | ||||
3586 | SourceLocation RParen, | ||||
3587 | ParsedType ParsedTy) { | ||||
3588 | TypeSourceInfo *TSI = nullptr; | ||||
3589 | QualType Ty = GetTypeFromParser(ParsedTy, &TSI); | ||||
3590 | |||||
3591 | if (Ty.isNull()) | ||||
3592 | return ExprError(); | ||||
3593 | if (!TSI) | ||||
3594 | TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); | ||||
3595 | |||||
3596 | return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); | ||||
3597 | } | ||||
3598 | |||||
3599 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||
3600 | PredefinedExpr::IdentKind IK; | ||||
3601 | |||||
3602 | switch (Kind) { | ||||
3603 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "clang/lib/Sema/SemaExpr.cpp", 3603); | ||||
3604 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||
3605 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||
3606 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||
3607 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||
3608 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||
3609 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||
3610 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||
3611 | } | ||||
3612 | |||||
3613 | return BuildPredefinedExpr(Loc, IK); | ||||
3614 | } | ||||
3615 | |||||
3616 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||
3617 | SmallString<16> CharBuffer; | ||||
3618 | bool Invalid = false; | ||||
3619 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||
3620 | if (Invalid) | ||||
3621 | return ExprError(); | ||||
3622 | |||||
3623 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||
3624 | PP, Tok.getKind()); | ||||
3625 | if (Literal.hadError()) | ||||
3626 | return ExprError(); | ||||
3627 | |||||
3628 | QualType Ty; | ||||
3629 | if (Literal.isWide()) | ||||
3630 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||
3631 | else if (Literal.isUTF8() && getLangOpts().C2x) | ||||
3632 | Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x | ||||
3633 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||
3634 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||
3635 | else if (Literal.isUTF16()) | ||||
3636 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||
3637 | else if (Literal.isUTF32()) | ||||
3638 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||
3639 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||
3640 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||
3641 | else | ||||
3642 | Ty = Context.CharTy; // 'x' -> char in C++; | ||||
3643 | // u8'x' -> char in C11-C17 and in C++ without char8_t. | ||||
3644 | |||||
3645 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||
3646 | if (Literal.isWide()) | ||||
3647 | Kind = CharacterLiteral::Wide; | ||||
3648 | else if (Literal.isUTF16()) | ||||
3649 | Kind = CharacterLiteral::UTF16; | ||||
3650 | else if (Literal.isUTF32()) | ||||
3651 | Kind = CharacterLiteral::UTF32; | ||||
3652 | else if (Literal.isUTF8()) | ||||
3653 | Kind = CharacterLiteral::UTF8; | ||||
3654 | |||||
3655 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||
3656 | Tok.getLocation()); | ||||
3657 | |||||
3658 | if (Literal.getUDSuffix().empty()) | ||||
3659 | return Lit; | ||||
3660 | |||||
3661 | // We're building a user-defined literal. | ||||
3662 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3663 | SourceLocation UDSuffixLoc = | ||||
3664 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3665 | |||||
3666 | // Make sure we're allowed user-defined literals here. | ||||
3667 | if (!UDLScope) | ||||
3668 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||
3669 | |||||
3670 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||
3671 | // operator "" X (ch) | ||||
3672 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||
3673 | Lit, Tok.getLocation()); | ||||
3674 | } | ||||
3675 | |||||
3676 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||
3677 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3678 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||
3679 | Context.IntTy, Loc); | ||||
3680 | } | ||||
3681 | |||||
3682 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||
3683 | QualType Ty, SourceLocation Loc) { | ||||
3684 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||
3685 | |||||
3686 | using llvm::APFloat; | ||||
3687 | APFloat Val(Format); | ||||
3688 | |||||
3689 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||
3690 | |||||
3691 | // Overflow is always an error, but underflow is only an error if | ||||
3692 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||
3693 | if ((result & APFloat::opOverflow) || | ||||
3694 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||
3695 | unsigned diagnostic; | ||||
3696 | SmallString<20> buffer; | ||||
3697 | if (result & APFloat::opOverflow) { | ||||
3698 | diagnostic = diag::warn_float_overflow; | ||||
3699 | APFloat::getLargest(Format).toString(buffer); | ||||
3700 | } else { | ||||
3701 | diagnostic = diag::warn_float_underflow; | ||||
3702 | APFloat::getSmallest(Format).toString(buffer); | ||||
3703 | } | ||||
3704 | |||||
3705 | S.Diag(Loc, diagnostic) | ||||
3706 | << Ty | ||||
3707 | << StringRef(buffer.data(), buffer.size()); | ||||
3708 | } | ||||
3709 | |||||
3710 | bool isExact = (result == APFloat::opOK); | ||||
3711 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||
3712 | } | ||||
3713 | |||||
3714 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||
3715 | assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression") ? void (0) : __assert_fail ("E && \"Invalid expression\"" , "clang/lib/Sema/SemaExpr.cpp", 3715, __extension__ __PRETTY_FUNCTION__ )); | ||||
3716 | |||||
3717 | if (E->isValueDependent()) | ||||
3718 | return false; | ||||
3719 | |||||
3720 | QualType QT = E->getType(); | ||||
3721 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||
3722 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||
3723 | return true; | ||||
3724 | } | ||||
3725 | |||||
3726 | llvm::APSInt ValueAPS; | ||||
3727 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||
3728 | |||||
3729 | if (R.isInvalid()) | ||||
3730 | return true; | ||||
3731 | |||||
3732 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||
3733 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||
3734 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||
3735 | << toString(ValueAPS, 10) << ValueIsPositive; | ||||
3736 | return true; | ||||
3737 | } | ||||
3738 | |||||
3739 | return false; | ||||
3740 | } | ||||
3741 | |||||
3742 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||
3743 | // Fast path for a single digit (which is quite common). A single digit | ||||
3744 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||
3745 | if (Tok.getLength() == 1) { | ||||
3746 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||
3747 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||
3748 | } | ||||
3749 | |||||
3750 | SmallString<128> SpellingBuffer; | ||||
3751 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||
3752 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||
3753 | // returns a StringRef to the memory buffer, it should have a null char at | ||||
3754 | // the EOF, so it is also safe. | ||||
3755 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||
3756 | |||||
3757 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||
3758 | bool Invalid = false; | ||||
3759 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||
3760 | if (Invalid) | ||||
3761 | return ExprError(); | ||||
3762 | |||||
3763 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||
3764 | PP.getSourceManager(), PP.getLangOpts(), | ||||
3765 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||
3766 | if (Literal.hadError) | ||||
3767 | return ExprError(); | ||||
3768 | |||||
3769 | if (Literal.hasUDSuffix()) { | ||||
3770 | // We're building a user-defined literal. | ||||
3771 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3772 | SourceLocation UDSuffixLoc = | ||||
3773 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3774 | |||||
3775 | // Make sure we're allowed user-defined literals here. | ||||
3776 | if (!UDLScope) | ||||
3777 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||
3778 | |||||
3779 | QualType CookedTy; | ||||
3780 | if (Literal.isFloatingLiteral()) { | ||||
3781 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||
3782 | // long double, the literal is treated as a call of the form | ||||
3783 | // operator "" X (f L) | ||||
3784 | CookedTy = Context.LongDoubleTy; | ||||
3785 | } else { | ||||
3786 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||
3787 | // unsigned long long, the literal is treated as a call of the form | ||||
3788 | // operator "" X (n ULL) | ||||
3789 | CookedTy = Context.UnsignedLongLongTy; | ||||
3790 | } | ||||
3791 | |||||
3792 | DeclarationName OpName = | ||||
3793 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
3794 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
3795 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
3796 | |||||
3797 | SourceLocation TokLoc = Tok.getLocation(); | ||||
3798 | |||||
3799 | // Perform literal operator lookup to determine if we're building a raw | ||||
3800 | // literal or a cooked one. | ||||
3801 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
3802 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||
3803 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||
3804 | /*AllowStringTemplatePack*/ false, | ||||
3805 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||
3806 | case LOLR_ErrorNoDiagnostic: | ||||
3807 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||
3808 | // GNU extension producing _Complex types. | ||||
3809 | break; | ||||
3810 | case LOLR_Error: | ||||
3811 | return ExprError(); | ||||
3812 | case LOLR_Cooked: { | ||||
3813 | Expr *Lit; | ||||
3814 | if (Literal.isFloatingLiteral()) { | ||||
3815 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||
3816 | } else { | ||||
3817 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||
3818 | if (Literal.GetIntegerValue(ResultVal)) | ||||
3819 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3820 | << /* Unsigned */ 1; | ||||
3821 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||
3822 | Tok.getLocation()); | ||||
3823 | } | ||||
3824 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3825 | } | ||||
3826 | |||||
3827 | case LOLR_Raw: { | ||||
3828 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||
3829 | // literal is treated as a call of the form | ||||
3830 | // operator "" X ("n") | ||||
3831 | unsigned Length = Literal.getUDSuffixOffset(); | ||||
3832 | QualType StrTy = Context.getConstantArrayType( | ||||
3833 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||
3834 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||
3835 | Expr *Lit = | ||||
3836 | StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length), | ||||
3837 | StringLiteral::Ordinary, | ||||
3838 | /*Pascal*/ false, StrTy, &TokLoc, 1); | ||||
3839 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3840 | } | ||||
3841 | |||||
3842 | case LOLR_Template: { | ||||
3843 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||
3844 | // template), L is treated as a call fo the form | ||||
3845 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||
3846 | // where n is the source character sequence c1 c2 ... ck. | ||||
3847 | TemplateArgumentListInfo ExplicitArgs; | ||||
3848 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||
3849 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||
3850 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
3851 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||
3852 | Value = TokSpelling[I]; | ||||
3853 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||
3854 | TemplateArgumentLocInfo ArgInfo; | ||||
3855 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
3856 | } | ||||
3857 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||
3858 | &ExplicitArgs); | ||||
3859 | } | ||||
3860 | case LOLR_StringTemplatePack: | ||||
3861 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "clang/lib/Sema/SemaExpr.cpp", 3861); | ||||
3862 | } | ||||
3863 | } | ||||
3864 | |||||
3865 | Expr *Res; | ||||
3866 | |||||
3867 | if (Literal.isFixedPointLiteral()) { | ||||
3868 | QualType Ty; | ||||
3869 | |||||
3870 | if (Literal.isAccum) { | ||||
3871 | if (Literal.isHalf) { | ||||
3872 | Ty = Context.ShortAccumTy; | ||||
3873 | } else if (Literal.isLong) { | ||||
3874 | Ty = Context.LongAccumTy; | ||||
3875 | } else { | ||||
3876 | Ty = Context.AccumTy; | ||||
3877 | } | ||||
3878 | } else if (Literal.isFract) { | ||||
3879 | if (Literal.isHalf) { | ||||
3880 | Ty = Context.ShortFractTy; | ||||
3881 | } else if (Literal.isLong) { | ||||
3882 | Ty = Context.LongFractTy; | ||||
3883 | } else { | ||||
3884 | Ty = Context.FractTy; | ||||
3885 | } | ||||
3886 | } | ||||
3887 | |||||
3888 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||
3889 | |||||
3890 | bool isSigned = !Literal.isUnsigned; | ||||
3891 | unsigned scale = Context.getFixedPointScale(Ty); | ||||
3892 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||
3893 | |||||
3894 | llvm::APInt Val(bit_width, 0, isSigned); | ||||
3895 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||
3896 | bool ValIsZero = Val.isZero() && !Overflowed; | ||||
3897 | |||||
3898 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||
3899 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||
3900 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||
3901 | // representable values for its type, with exception for constants of a | ||||
3902 | // fract type with a value of exactly 1; such a constant shall denote | ||||
3903 | // the maximal value for the type. | ||||
3904 | --Val; | ||||
3905 | else if (Val.ugt(MaxVal) || Overflowed) | ||||
3906 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||
3907 | |||||
3908 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||
3909 | Tok.getLocation(), scale); | ||||
3910 | } else if (Literal.isFloatingLiteral()) { | ||||
3911 | QualType Ty; | ||||
3912 | if (Literal.isHalf){ | ||||
3913 | if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) | ||||
3914 | Ty = Context.HalfTy; | ||||
3915 | else { | ||||
3916 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||
3917 | return ExprError(); | ||||
3918 | } | ||||
3919 | } else if (Literal.isFloat) | ||||
3920 | Ty = Context.FloatTy; | ||||
3921 | else if (Literal.isLong) | ||||
3922 | Ty = Context.LongDoubleTy; | ||||
3923 | else if (Literal.isFloat16) | ||||
3924 | Ty = Context.Float16Ty; | ||||
3925 | else if (Literal.isFloat128) | ||||
3926 | Ty = Context.Float128Ty; | ||||
3927 | else | ||||
3928 | Ty = Context.DoubleTy; | ||||
3929 | |||||
3930 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||
3931 | |||||
3932 | if (Ty == Context.DoubleTy) { | ||||
3933 | if (getLangOpts().SinglePrecisionConstants) { | ||||
3934 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||
3935 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3936 | } | ||||
3937 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( | ||||
3938 | "cl_khr_fp64", getLangOpts())) { | ||||
3939 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||
3940 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) | ||||
3941 | << (getLangOpts().getOpenCLCompatibleVersion() >= 300); | ||||
3942 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3943 | } | ||||
3944 | } | ||||
3945 | } else if (!Literal.isIntegerLiteral()) { | ||||
3946 | return ExprError(); | ||||
3947 | } else { | ||||
3948 | QualType Ty; | ||||
3949 | |||||
3950 | // 'z/uz' literals are a C++2b feature. | ||||
3951 | if (Literal.isSizeT) | ||||
3952 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus | ||||
3953 | ? getLangOpts().CPlusPlus2b | ||||
3954 | ? diag::warn_cxx20_compat_size_t_suffix | ||||
3955 | : diag::ext_cxx2b_size_t_suffix | ||||
3956 | : diag::err_cxx2b_size_t_suffix); | ||||
3957 | |||||
3958 | // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, | ||||
3959 | // but we do not currently support the suffix in C++ mode because it's not | ||||
3960 | // entirely clear whether WG21 will prefer this suffix to return a library | ||||
3961 | // type such as std::bit_int instead of returning a _BitInt. | ||||
3962 | if (Literal.isBitInt && !getLangOpts().CPlusPlus) | ||||
3963 | PP.Diag(Tok.getLocation(), getLangOpts().C2x | ||||
3964 | ? diag::warn_c2x_compat_bitint_suffix | ||||
3965 | : diag::ext_c2x_bitint_suffix); | ||||
3966 | |||||
3967 | // Get the value in the widest-possible width. What is "widest" depends on | ||||
3968 | // whether the literal is a bit-precise integer or not. For a bit-precise | ||||
3969 | // integer type, try to scan the source to determine how many bits are | ||||
3970 | // needed to represent the value. This may seem a bit expensive, but trying | ||||
3971 | // to get the integer value from an overly-wide APInt is *extremely* | ||||
3972 | // expensive, so the naive approach of assuming | ||||
3973 | // llvm::IntegerType::MAX_INT_BITS is a big performance hit. | ||||
3974 | unsigned BitsNeeded = | ||||
3975 | Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( | ||||
3976 | Literal.getLiteralDigits(), Literal.getRadix()) | ||||
3977 | : Context.getTargetInfo().getIntMaxTWidth(); | ||||
3978 | llvm::APInt ResultVal(BitsNeeded, 0); | ||||
3979 | |||||
3980 | if (Literal.GetIntegerValue(ResultVal)) { | ||||
3981 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||
3982 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3983 | << /* Unsigned */ 1; | ||||
3984 | Ty = Context.UnsignedLongLongTy; | ||||
3985 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal .getBitWidth() && "long long is not intmax_t?") ? void (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "clang/lib/Sema/SemaExpr.cpp", 3986, __extension__ __PRETTY_FUNCTION__ )) | ||||
3986 | "long long is not intmax_t?")(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal .getBitWidth() && "long long is not intmax_t?") ? void (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "clang/lib/Sema/SemaExpr.cpp", 3986, __extension__ __PRETTY_FUNCTION__ )); | ||||
3987 | } else { | ||||
3988 | // If this value fits into a ULL, try to figure out what else it fits into | ||||
3989 | // according to the rules of C99 6.4.4.1p5. | ||||
3990 | |||||
3991 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||
3992 | // be an unsigned int. | ||||
3993 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||
3994 | |||||
3995 | // Check from smallest to largest, picking the smallest type we can. | ||||
3996 | unsigned Width = 0; | ||||
3997 | |||||
3998 | // Microsoft specific integer suffixes are explicitly sized. | ||||
3999 | if (Literal.MicrosoftInteger) { | ||||
4000 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||
4001 | Width = 8; | ||||
4002 | Ty = Context.CharTy; | ||||
4003 | } else { | ||||
4004 | Width = Literal.MicrosoftInteger; | ||||
4005 | Ty = Context.getIntTypeForBitwidth(Width, | ||||
4006 | /*Signed=*/!Literal.isUnsigned); | ||||
4007 | } | ||||
4008 | } | ||||
4009 | |||||
4010 | // Bit-precise integer literals are automagically-sized based on the | ||||
4011 | // width required by the literal. | ||||
4012 | if (Literal.isBitInt) { | ||||
4013 | // The signed version has one more bit for the sign value. There are no | ||||
4014 | // zero-width bit-precise integers, even if the literal value is 0. | ||||
4015 | Width = std::max(ResultVal.getActiveBits(), 1u) + | ||||
4016 | (Literal.isUnsigned ? 0u : 1u); | ||||
4017 | |||||
4018 | // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, | ||||
4019 | // and reset the type to the largest supported width. | ||||
4020 | unsigned int MaxBitIntWidth = | ||||
4021 | Context.getTargetInfo().getMaxBitIntWidth(); | ||||
4022 | if (Width > MaxBitIntWidth) { | ||||
4023 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
4024 | << Literal.isUnsigned; | ||||
4025 | Width = MaxBitIntWidth; | ||||
4026 | } | ||||
4027 | |||||
4028 | // Reset the result value to the smaller APInt and select the correct | ||||
4029 | // type to be used. Note, we zext even for signed values because the | ||||
4030 | // literal itself is always an unsigned value (a preceeding - is a | ||||
4031 | // unary operator, not part of the literal). | ||||
4032 | ResultVal = ResultVal.zextOrTrunc(Width); | ||||
4033 | Ty = Context.getBitIntType(Literal.isUnsigned, Width); | ||||
4034 | } | ||||
4035 | |||||
4036 | // Check C++2b size_t literals. | ||||
4037 | if (Literal.isSizeT) { | ||||
4038 | assert(!Literal.MicrosoftInteger &&(static_cast <bool> (!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals") ? void (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "clang/lib/Sema/SemaExpr.cpp", 4039, __extension__ __PRETTY_FUNCTION__ )) | ||||
4039 | "size_t literals can't be Microsoft literals")(static_cast <bool> (!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals") ? void (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "clang/lib/Sema/SemaExpr.cpp", 4039, __extension__ __PRETTY_FUNCTION__ )); | ||||
4040 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( | ||||
4041 | Context.getTargetInfo().getSizeType()); | ||||
4042 | |||||
4043 | // Does it fit in size_t? | ||||
4044 | if (ResultVal.isIntN(SizeTSize)) { | ||||
4045 | // Does it fit in ssize_t? | ||||
4046 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) | ||||
4047 | Ty = Context.getSignedSizeType(); | ||||
4048 | else if (AllowUnsigned) | ||||
4049 | Ty = Context.getSizeType(); | ||||
4050 | Width = SizeTSize; | ||||
4051 | } | ||||
4052 | } | ||||
4053 | |||||
4054 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && | ||||
4055 | !Literal.isSizeT) { | ||||
4056 | // Are int/unsigned possibilities? | ||||
4057 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
4058 | |||||
4059 | // Does it fit in a unsigned int? | ||||
4060 | if (ResultVal.isIntN(IntSize)) { | ||||
4061 | // Does it fit in a signed int? | ||||
4062 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||
4063 | Ty = Context.IntTy; | ||||
4064 | else if (AllowUnsigned) | ||||
4065 | Ty = Context.UnsignedIntTy; | ||||
4066 | Width = IntSize; | ||||
4067 | } | ||||
4068 | } | ||||
4069 | |||||
4070 | // Are long/unsigned long possibilities? | ||||
4071 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { | ||||
4072 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||
4073 | |||||
4074 | // Does it fit in a unsigned long? | ||||
4075 | if (ResultVal.isIntN(LongSize)) { | ||||
4076 | // Does it fit in a signed long? | ||||
4077 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||
4078 | Ty = Context.LongTy; | ||||
4079 | else if (AllowUnsigned) | ||||
4080 | Ty = Context.UnsignedLongTy; | ||||
4081 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||
4082 | // is compatible. | ||||
4083 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||
4084 | const unsigned LongLongSize = | ||||
4085 | Context.getTargetInfo().getLongLongWidth(); | ||||
4086 | Diag(Tok.getLocation(), | ||||
4087 | getLangOpts().CPlusPlus | ||||
4088 | ? Literal.isLong | ||||
4089 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||
4090 | : /*C++98 UB*/ diag:: | ||||
4091 | ext_old_implicitly_unsigned_long_cxx | ||||
4092 | : diag::warn_old_implicitly_unsigned_long) | ||||
4093 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||
4094 | : /*will be ill-formed*/ 1); | ||||
4095 | Ty = Context.UnsignedLongTy; | ||||
4096 | } | ||||
4097 | Width = LongSize; | ||||
4098 | } | ||||
4099 | } | ||||
4100 | |||||
4101 | // Check long long if needed. | ||||
4102 | if (Ty.isNull() && !Literal.isSizeT) { | ||||
4103 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||
4104 | |||||
4105 | // Does it fit in a unsigned long long? | ||||
4106 | if (ResultVal.isIntN(LongLongSize)) { | ||||
4107 | // Does it fit in a signed long long? | ||||
4108 | // To be compatible with MSVC, hex integer literals ending with the | ||||
4109 | // LL or i64 suffix are always signed in Microsoft mode. | ||||
4110 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||
4111 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||
4112 | Ty = Context.LongLongTy; | ||||
4113 | else if (AllowUnsigned) | ||||
4114 | Ty = Context.UnsignedLongLongTy; | ||||
4115 | Width = LongLongSize; | ||||
4116 | |||||
4117 | // 'long long' is a C99 or C++11 feature, whether the literal | ||||
4118 | // explicitly specified 'long long' or we needed the extra width. | ||||
4119 | if (getLangOpts().CPlusPlus) | ||||
4120 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 | ||||
4121 | ? diag::warn_cxx98_compat_longlong | ||||
4122 | : diag::ext_cxx11_longlong); | ||||
4123 | else if (!getLangOpts().C99) | ||||
4124 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||
4125 | } | ||||
4126 | } | ||||
4127 | |||||
4128 | // If we still couldn't decide a type, we either have 'size_t' literal | ||||
4129 | // that is out of range, or a decimal literal that does not fit in a | ||||
4130 | // signed long long and has no U suffix. | ||||
4131 | if (Ty.isNull()) { | ||||
4132 | if (Literal.isSizeT) | ||||
4133 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) | ||||
4134 | << Literal.isUnsigned; | ||||
4135 | else | ||||
4136 | Diag(Tok.getLocation(), | ||||
4137 | diag::ext_integer_literal_too_large_for_signed); | ||||
4138 | Ty = Context.UnsignedLongLongTy; | ||||
4139 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||
4140 | } | ||||
4141 | |||||
4142 | if (ResultVal.getBitWidth() != Width) | ||||
4143 | ResultVal = ResultVal.trunc(Width); | ||||
4144 | } | ||||
4145 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||
4146 | } | ||||
4147 | |||||
4148 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||
4149 | if (Literal.isImaginary) { | ||||
4150 | Res = new (Context) ImaginaryLiteral(Res, | ||||
4151 | Context.getComplexType(Res->getType())); | ||||
4152 | |||||
4153 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||
4154 | } | ||||
4155 | return Res; | ||||
4156 | } | ||||
4157 | |||||
4158 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||
4159 | assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr" ) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "clang/lib/Sema/SemaExpr.cpp", 4159, __extension__ __PRETTY_FUNCTION__ )); | ||||
4160 | QualType ExprTy = E->getType(); | ||||
4161 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && | ||||
4162 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) | ||||
4163 | return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); | ||||
4164 | return new (Context) ParenExpr(L, R, E); | ||||
4165 | } | ||||
4166 | |||||
4167 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||
4168 | SourceLocation Loc, | ||||
4169 | SourceRange ArgRange) { | ||||
4170 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||
4171 | // scalar or vector data type argument..." | ||||
4172 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||
4173 | // type (C99 6.2.5p18) or void. | ||||
4174 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||
4175 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||
4176 | << T << ArgRange; | ||||
4177 | return true; | ||||
4178 | } | ||||
4179 | |||||
4180 | assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType ()) && "Scalar types should always be complete") ? void (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "clang/lib/Sema/SemaExpr.cpp", 4181, __extension__ __PRETTY_FUNCTION__ )) | ||||
4181 | "Scalar types should always be complete")(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType ()) && "Scalar types should always be complete") ? void (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "clang/lib/Sema/SemaExpr.cpp", 4181, __extension__ __PRETTY_FUNCTION__ )); | ||||
4182 | return false; | ||||
4183 | } | ||||
4184 | |||||
4185 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||
4186 | SourceLocation Loc, | ||||
4187 | SourceRange ArgRange, | ||||
4188 | UnaryExprOrTypeTrait TraitKind) { | ||||
4189 | // Invalid types must be hard errors for SFINAE in C++. | ||||
4190 | if (S.LangOpts.CPlusPlus) | ||||
4191 | return true; | ||||
4192 | |||||
4193 | // C99 6.5.3.4p1: | ||||
4194 | if (T->isFunctionType() && | ||||
4195 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||
4196 | TraitKind == UETT_PreferredAlignOf)) { | ||||
4197 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||
4198 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||
4199 | << getTraitSpelling(TraitKind) << ArgRange; | ||||
4200 | return false; | ||||
4201 | } | ||||
4202 | |||||
4203 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||
4204 | // this is an error (OpenCL v1.1 s6.3.k) | ||||
4205 | if (T->isVoidType()) { | ||||
4206 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||
4207 | : diag::ext_sizeof_alignof_void_type; | ||||
4208 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||
4209 | return false; | ||||
4210 | } | ||||
4211 | |||||
4212 | return true; | ||||
4213 | } | ||||
4214 | |||||
4215 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||
4216 | SourceLocation Loc, | ||||
4217 | SourceRange ArgRange, | ||||
4218 | UnaryExprOrTypeTrait TraitKind) { | ||||
4219 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||
4220 | // runtime doesn't allow it. | ||||
4221 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||
4222 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||
4223 | << T << (TraitKind == UETT_SizeOf) | ||||
4224 | << ArgRange; | ||||
4225 | return true; | ||||
4226 | } | ||||
4227 | |||||
4228 | return false; | ||||
4229 | } | ||||
4230 | |||||
4231 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||
4232 | /// pointer type is equal to T) and emit a warning if it is. | ||||
4233 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||
4234 | Expr *E) { | ||||
4235 | // Don't warn if the operation changed the type. | ||||
4236 | if (T != E->getType()) | ||||
4237 | return; | ||||
4238 | |||||
4239 | // Now look for array decays. | ||||
4240 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||
4241 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||
4242 | return; | ||||
4243 | |||||
4244 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||
4245 | << ICE->getType() | ||||
4246 | << ICE->getSubExpr()->getType(); | ||||
4247 | } | ||||
4248 | |||||
4249 | /// Check the constraints on expression operands to unary type expression | ||||
4250 | /// and type traits. | ||||
4251 | /// | ||||
4252 | /// Completes any types necessary and validates the constraints on the operand | ||||
4253 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||
4254 | /// the expression as it completes the type for that expression through template | ||||
4255 | /// instantiation, etc. | ||||
4256 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||
4257 | UnaryExprOrTypeTrait ExprKind) { | ||||
4258 | QualType ExprTy = E->getType(); | ||||
4259 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp" , 4259, __extension__ __PRETTY_FUNCTION__)); | ||||
4260 | |||||
4261 | bool IsUnevaluatedOperand = | ||||
4262 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||
4263 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||
4264 | if (IsUnevaluatedOperand) { | ||||
4265 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||
4266 | if (Result.isInvalid()) | ||||
4267 | return true; | ||||
4268 | E = Result.get(); | ||||
4269 | } | ||||
4270 | |||||
4271 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||
4272 | // so side effects could result in unintended consequences. | ||||
4273 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||
4274 | // used to build SFINAE gadgets. | ||||
4275 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||
4276 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||
4277 | !E->isInstantiationDependent() && | ||||
4278 | !E->getType()->isVariableArrayType() && | ||||
4279 | E->HasSideEffects(Context, false)) | ||||
4280 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||
4281 | |||||
4282 | if (ExprKind == UETT_VecStep) | ||||
4283 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4284 | E->getSourceRange()); | ||||
4285 | |||||
4286 | // Explicitly list some types as extensions. | ||||
4287 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4288 | E->getSourceRange(), ExprKind)) | ||||
4289 | return false; | ||||
4290 | |||||
4291 | // 'alignof' applied to an expression only requires the base element type of | ||||
4292 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||
4293 | // be complete (and will attempt to complete it if it's an array of unknown | ||||
4294 | // bound). | ||||
4295 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4296 | if (RequireCompleteSizedType( | ||||
4297 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||
4298 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4299 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4300 | return true; | ||||
4301 | } else { | ||||
4302 | if (RequireCompleteSizedExprType( | ||||
4303 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4304 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4305 | return true; | ||||
4306 | } | ||||
4307 | |||||
4308 | // Completing the expression's type may have changed it. | ||||
4309 | ExprTy = E->getType(); | ||||
4310 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "clang/lib/Sema/SemaExpr.cpp" , 4310, __extension__ __PRETTY_FUNCTION__)); | ||||
4311 | |||||
4312 | if (ExprTy->isFunctionType()) { | ||||
4313 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||
4314 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||
4315 | return true; | ||||
4316 | } | ||||
4317 | |||||
4318 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||
4319 | E->getSourceRange(), ExprKind)) | ||||
4320 | return true; | ||||
4321 | |||||
4322 | if (ExprKind == UETT_SizeOf) { | ||||
4323 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
4324 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||
4325 | QualType OType = PVD->getOriginalType(); | ||||
4326 | QualType Type = PVD->getType(); | ||||
4327 | if (Type->isPointerType() && OType->isArrayType()) { | ||||
4328 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||
4329 | << Type << OType; | ||||
4330 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||
4331 | } | ||||
4332 | } | ||||
4333 | } | ||||
4334 | |||||
4335 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||
4336 | // decays into a pointer and returns an unintended result. This is most | ||||
4337 | // likely a typo for "sizeof(array) op x". | ||||
4338 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||
4339 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4340 | BO->getLHS()); | ||||
4341 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4342 | BO->getRHS()); | ||||
4343 | } | ||||
4344 | } | ||||
4345 | |||||
4346 | return false; | ||||
4347 | } | ||||
4348 | |||||
4349 | /// Check the constraints on operands to unary expression and type | ||||
4350 | /// traits. | ||||
4351 | /// | ||||
4352 | /// This will complete any types necessary, and validate the various constraints | ||||
4353 | /// on those operands. | ||||
4354 | /// | ||||
4355 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||
4356 | /// C99 6.3.2.1p[2-4] all state: | ||||
4357 | /// Except when it is the operand of the sizeof operator ... | ||||
4358 | /// | ||||
4359 | /// C++ [expr.sizeof]p4 | ||||
4360 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||
4361 | /// standard conversions are not applied to the operand of sizeof. | ||||
4362 | /// | ||||
4363 | /// This policy is followed for all of the unary trait expressions. | ||||
4364 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||
4365 | SourceLocation OpLoc, | ||||
4366 | SourceRange ExprRange, | ||||
4367 | UnaryExprOrTypeTrait ExprKind) { | ||||
4368 | if (ExprType->isDependentType()) | ||||
4369 | return false; | ||||
4370 | |||||
4371 | // C++ [expr.sizeof]p2: | ||||
4372 | // When applied to a reference or a reference type, the result | ||||
4373 | // is the size of the referenced type. | ||||
4374 | // C++11 [expr.alignof]p3: | ||||
4375 | // When alignof is applied to a reference type, the result | ||||
4376 | // shall be the alignment of the referenced type. | ||||
4377 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||
4378 | ExprType = Ref->getPointeeType(); | ||||
4379 | |||||
4380 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||
4381 | // When alignof or _Alignof is applied to an array type, the result | ||||
4382 | // is the alignment of the element type. | ||||
4383 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||
4384 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||
4385 | ExprType = Context.getBaseElementType(ExprType); | ||||
4386 | |||||
4387 | if (ExprKind == UETT_VecStep) | ||||
4388 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||
4389 | |||||
4390 | // Explicitly list some types as extensions. | ||||
4391 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||
4392 | ExprKind)) | ||||
4393 | return false; | ||||
4394 | |||||
4395 | if (RequireCompleteSizedType( | ||||
4396 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4397 | getTraitSpelling(ExprKind), ExprRange)) | ||||
4398 | return true; | ||||
4399 | |||||
4400 | if (ExprType->isFunctionType()) { | ||||
4401 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||
4402 | << getTraitSpelling(ExprKind) << ExprRange; | ||||
4403 | return true; | ||||
4404 | } | ||||
4405 | |||||
4406 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||
4407 | ExprKind)) | ||||
4408 | return true; | ||||
4409 | |||||
4410 | return false; | ||||
4411 | } | ||||
4412 | |||||
4413 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||
4414 | // Cannot know anything else if the expression is dependent. | ||||
4415 | if (E->isTypeDependent()) | ||||
4416 | return false; | ||||
4417 | |||||
4418 | if (E->getObjectKind() == OK_BitField) { | ||||
4419 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||
4420 | << 1 << E->getSourceRange(); | ||||
4421 | return true; | ||||
4422 | } | ||||
4423 | |||||
4424 | ValueDecl *D = nullptr; | ||||
4425 | Expr *Inner = E->IgnoreParens(); | ||||
4426 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||
4427 | D = DRE->getDecl(); | ||||
4428 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||
4429 | D = ME->getMemberDecl(); | ||||
4430 | } | ||||
4431 | |||||
4432 | // If it's a field, require the containing struct to have a | ||||
4433 | // complete definition so that we can compute the layout. | ||||
4434 | // | ||||
4435 | // This can happen in C++11 onwards, either by naming the member | ||||
4436 | // in a way that is not transformed into a member access expression | ||||
4437 | // (in an unevaluated operand, for instance), or by naming the member | ||||
4438 | // in a trailing-return-type. | ||||
4439 | // | ||||
4440 | // For the record, since __alignof__ on expressions is a GCC | ||||
4441 | // extension, GCC seems to permit this but always gives the | ||||
4442 | // nonsensical answer 0. | ||||
4443 | // | ||||
4444 | // We don't really need the layout here --- we could instead just | ||||
4445 | // directly check for all the appropriate alignment-lowing | ||||
4446 | // attributes --- but that would require duplicating a lot of | ||||
4447 | // logic that just isn't worth duplicating for such a marginal | ||||
4448 | // use-case. | ||||
4449 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||
4450 | // Fast path this check, since we at least know the record has a | ||||
4451 | // definition if we can find a member of it. | ||||
4452 | if (!FD->getParent()->isCompleteDefinition()) { | ||||
4453 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||
4454 | << E->getSourceRange(); | ||||
4455 | return true; | ||||
4456 | } | ||||
4457 | |||||
4458 | // Otherwise, if it's a field, and the field doesn't have | ||||
4459 | // reference type, then it must have a complete type (or be a | ||||
4460 | // flexible array member, which we explicitly want to | ||||
4461 | // white-list anyway), which makes the following checks trivial. | ||||
4462 | if (!FD->getType()->isReferenceType()) | ||||
4463 | return false; | ||||
4464 | } | ||||
4465 | |||||
4466 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||
4467 | } | ||||
4468 | |||||
4469 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||
4470 | E = E->IgnoreParens(); | ||||
4471 | |||||
4472 | // Cannot know anything else if the expression is dependent. | ||||
4473 | if (E->isTypeDependent()) | ||||
4474 | return false; | ||||
4475 | |||||
4476 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||
4477 | } | ||||
4478 | |||||
4479 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||
4480 | CapturingScopeInfo *CSI) { | ||||
4481 | assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void (0) : __assert_fail ("T->isVariablyModifiedType()", "clang/lib/Sema/SemaExpr.cpp" , 4481, __extension__ __PRETTY_FUNCTION__)); | ||||
4482 | assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail ("CSI != nullptr", "clang/lib/Sema/SemaExpr.cpp", 4482, __extension__ __PRETTY_FUNCTION__)); | ||||
4483 | |||||
4484 | // We're going to walk down into the type and look for VLA expressions. | ||||
4485 | do { | ||||
4486 | const Type *Ty = T.getTypePtr(); | ||||
4487 | switch (Ty->getTypeClass()) { | ||||
4488 | #define TYPE(Class, Base) | ||||
4489 | #define ABSTRACT_TYPE(Class, Base) | ||||
4490 | #define NON_CANONICAL_TYPE(Class, Base) | ||||
4491 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||
4492 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||
4493 | #include "clang/AST/TypeNodes.inc" | ||||
4494 | T = QualType(); | ||||
4495 | break; | ||||
4496 | // These types are never variably-modified. | ||||
4497 | case Type::Builtin: | ||||
4498 | case Type::Complex: | ||||
4499 | case Type::Vector: | ||||
4500 | case Type::ExtVector: | ||||
4501 | case Type::ConstantMatrix: | ||||
4502 | case Type::Record: | ||||
4503 | case Type::Enum: | ||||
4504 | case Type::TemplateSpecialization: | ||||
4505 | case Type::ObjCObject: | ||||
4506 | case Type::ObjCInterface: | ||||
4507 | case Type::ObjCObjectPointer: | ||||
4508 | case Type::ObjCTypeParam: | ||||
4509 | case Type::Pipe: | ||||
4510 | case Type::BitInt: | ||||
4511 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "clang/lib/Sema/SemaExpr.cpp", 4511); | ||||
4512 | case Type::Elaborated: | ||||
4513 | T = cast<ElaboratedType>(Ty)->getNamedType(); | ||||
4514 | break; | ||||
4515 | case Type::Adjusted: | ||||
4516 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||
4517 | break; | ||||
4518 | case Type::Decayed: | ||||
4519 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||
4520 | break; | ||||
4521 | case Type::Pointer: | ||||
4522 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||
4523 | break; | ||||
4524 | case Type::BlockPointer: | ||||
4525 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||
4526 | break; | ||||
4527 | case Type::LValueReference: | ||||
4528 | case Type::RValueReference: | ||||
4529 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||
4530 | break; | ||||
4531 | case Type::MemberPointer: | ||||
4532 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||
4533 | break; | ||||
4534 | case Type::ConstantArray: | ||||
4535 | case Type::IncompleteArray: | ||||
4536 | // Losing element qualification here is fine. | ||||
4537 | T = cast<ArrayType>(Ty)->getElementType(); | ||||
4538 | break; | ||||
4539 | case Type::VariableArray: { | ||||
4540 | // Losing element qualification here is fine. | ||||
4541 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||
4542 | |||||
4543 | // Unknown size indication requires no size computation. | ||||
4544 | // Otherwise, evaluate and record it. | ||||
4545 | auto Size = VAT->getSizeExpr(); | ||||
4546 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||
4547 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||
4548 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||
4549 | |||||
4550 | T = VAT->getElementType(); | ||||
4551 | break; | ||||
4552 | } | ||||
4553 | case Type::FunctionProto: | ||||
4554 | case Type::FunctionNoProto: | ||||
4555 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||
4556 | break; | ||||
4557 | case Type::Paren: | ||||
4558 | case Type::TypeOf: | ||||
4559 | case Type::UnaryTransform: | ||||
4560 | case Type::Attributed: | ||||
4561 | case Type::BTFTagAttributed: | ||||
4562 | case Type::SubstTemplateTypeParm: | ||||
4563 | case Type::MacroQualified: | ||||
4564 | // Keep walking after single level desugaring. | ||||
4565 | T = T.getSingleStepDesugaredType(Context); | ||||
4566 | break; | ||||
4567 | case Type::Typedef: | ||||
4568 | T = cast<TypedefType>(Ty)->desugar(); | ||||
4569 | break; | ||||
4570 | case Type::Decltype: | ||||
4571 | T = cast<DecltypeType>(Ty)->desugar(); | ||||
4572 | break; | ||||
4573 | case Type::Using: | ||||
4574 | T = cast<UsingType>(Ty)->desugar(); | ||||
4575 | break; | ||||
4576 | case Type::Auto: | ||||
4577 | case Type::DeducedTemplateSpecialization: | ||||
4578 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||
4579 | break; | ||||
4580 | case Type::TypeOfExpr: | ||||
4581 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||
4582 | break; | ||||
4583 | case Type::Atomic: | ||||
4584 | T = cast<AtomicType>(Ty)->getValueType(); | ||||
4585 | break; | ||||
4586 | } | ||||
4587 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||
4588 | } | ||||
4589 | |||||
4590 | /// Build a sizeof or alignof expression given a type operand. | ||||
4591 | ExprResult | ||||
4592 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||
4593 | SourceLocation OpLoc, | ||||
4594 | UnaryExprOrTypeTrait ExprKind, | ||||
4595 | SourceRange R) { | ||||
4596 | if (!TInfo) | ||||
4597 | return ExprError(); | ||||
4598 | |||||
4599 | QualType T = TInfo->getType(); | ||||
4600 | |||||
4601 | if (!T->isDependentType() && | ||||
4602 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||
4603 | return ExprError(); | ||||
4604 | |||||
4605 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||
4606 | if (auto *TT = T->getAs<TypedefType>()) { | ||||
4607 | for (auto I = FunctionScopes.rbegin(), | ||||
4608 | E = std::prev(FunctionScopes.rend()); | ||||
4609 | I != E; ++I) { | ||||
4610 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
4611 | if (CSI == nullptr) | ||||
4612 | break; | ||||
4613 | DeclContext *DC = nullptr; | ||||
4614 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
4615 | DC = LSI->CallOperator; | ||||
4616 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
4617 | DC = CRSI->TheCapturedDecl; | ||||
4618 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
4619 | DC = BSI->TheDecl; | ||||
4620 | if (DC) { | ||||
4621 | if (DC->containsDecl(TT->getDecl())) | ||||
4622 | break; | ||||
4623 | captureVariablyModifiedType(Context, T, CSI); | ||||
4624 | } | ||||
4625 | } | ||||
4626 | } | ||||
4627 | } | ||||
4628 | |||||
4629 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4630 | if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && | ||||
4631 | TInfo->getType()->isVariablyModifiedType()) | ||||
4632 | TInfo = TransformToPotentiallyEvaluated(TInfo); | ||||
4633 | |||||
4634 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4635 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||
4636 | } | ||||
4637 | |||||
4638 | /// Build a sizeof or alignof expression given an expression | ||||
4639 | /// operand. | ||||
4640 | ExprResult | ||||
4641 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||
4642 | UnaryExprOrTypeTrait ExprKind) { | ||||
4643 | ExprResult PE = CheckPlaceholderExpr(E); | ||||
4644 | if (PE.isInvalid()) | ||||
4645 | return ExprError(); | ||||
4646 | |||||
4647 | E = PE.get(); | ||||
4648 | |||||
4649 | // Verify that the operand is valid. | ||||
4650 | bool isInvalid = false; | ||||
4651 | if (E->isTypeDependent()) { | ||||
4652 | // Delay type-checking for type-dependent expressions. | ||||
4653 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4654 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||
4655 | } else if (ExprKind == UETT_VecStep) { | ||||
4656 | isInvalid = CheckVecStepExpr(E); | ||||
4657 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||
4658 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||
4659 | isInvalid = true; | ||||
4660 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||
4661 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||
4662 | isInvalid = true; | ||||
4663 | } else { | ||||
4664 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||
4665 | } | ||||
4666 | |||||
4667 | if (isInvalid) | ||||
4668 | return ExprError(); | ||||
4669 | |||||
4670 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||
4671 | PE = TransformToPotentiallyEvaluated(E); | ||||
4672 | if (PE.isInvalid()) return ExprError(); | ||||
4673 | E = PE.get(); | ||||
4674 | } | ||||
4675 | |||||
4676 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4677 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4678 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||
4679 | } | ||||
4680 | |||||
4681 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||
4682 | /// expr and the same for @c alignof and @c __alignof | ||||
4683 | /// Note that the ArgRange is invalid if isType is false. | ||||
4684 | ExprResult | ||||
4685 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||
4686 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||
4687 | void *TyOrEx, SourceRange ArgRange) { | ||||
4688 | // If error parsing type, ignore. | ||||
4689 | if (!TyOrEx) return ExprError(); | ||||
4690 | |||||
4691 | if (IsType) { | ||||
4692 | TypeSourceInfo *TInfo; | ||||
4693 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||
4694 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||
4695 | } | ||||
4696 | |||||
4697 | Expr *ArgEx = (Expr *)TyOrEx; | ||||
4698 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||
4699 | return Result; | ||||
4700 | } | ||||
4701 | |||||
4702 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||
4703 | bool IsReal) { | ||||
4704 | if (V.get()->isTypeDependent()) | ||||
4705 | return S.Context.DependentTy; | ||||
4706 | |||||
4707 | // _Real and _Imag are only l-values for normal l-values. | ||||
4708 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||
4709 | V = S.DefaultLvalueConversion(V.get()); | ||||
4710 | if (V.isInvalid()) | ||||
4711 | return QualType(); | ||||
4712 | } | ||||
4713 | |||||
4714 | // These operators return the element type of a complex type. | ||||
4715 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||
4716 | return CT->getElementType(); | ||||
4717 | |||||
4718 | // Otherwise they pass through real integer and floating point types here. | ||||
4719 | if (V.get()->getType()->isArithmeticType()) | ||||
4720 | return V.get()->getType(); | ||||
4721 | |||||
4722 | // Test for placeholders. | ||||
4723 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||
4724 | if (PR.isInvalid()) return QualType(); | ||||
4725 | if (PR.get() != V.get()) { | ||||
4726 | V = PR; | ||||
4727 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||
4728 | } | ||||
4729 | |||||
4730 | // Reject anything else. | ||||
4731 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||
4732 | << (IsReal ? "__real" : "__imag"); | ||||
4733 | return QualType(); | ||||
4734 | } | ||||
4735 | |||||
4736 | |||||
4737 | |||||
4738 | ExprResult | ||||
4739 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
4740 | tok::TokenKind Kind, Expr *Input) { | ||||
4741 | UnaryOperatorKind Opc; | ||||
4742 | switch (Kind) { | ||||
4743 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp" , 4743); | ||||
4744 | case tok::plusplus: Opc = UO_PostInc; break; | ||||
4745 | case tok::minusminus: Opc = UO_PostDec; break; | ||||
4746 | } | ||||
4747 | |||||
4748 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||
4749 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||
4750 | if (Result.isInvalid()) return ExprError(); | ||||
4751 | Input = Result.get(); | ||||
4752 | |||||
4753 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||
4754 | } | ||||
4755 | |||||
4756 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||
4757 | /// | ||||
4758 | /// \return true on error | ||||
4759 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||
4760 | SourceLocation opLoc, | ||||
4761 | Expr *op) { | ||||
4762 | assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType ()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 4762, __extension__ __PRETTY_FUNCTION__ )); | ||||
4763 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||
4764 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||
4765 | return false; | ||||
4766 | |||||
4767 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||
4768 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||
4769 | << op->getSourceRange(); | ||||
4770 | return true; | ||||
4771 | } | ||||
4772 | |||||
4773 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||
4774 | auto *BaseNoParens = Base->IgnoreParens(); | ||||
4775 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||
4776 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||
4777 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||
4778 | } | ||||
4779 | |||||
4780 | // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. | ||||
4781 | // Typically this is DependentTy, but can sometimes be more precise. | ||||
4782 | // | ||||
4783 | // There are cases when we could determine a non-dependent type: | ||||
4784 | // - LHS and RHS may have non-dependent types despite being type-dependent | ||||
4785 | // (e.g. unbounded array static members of the current instantiation) | ||||
4786 | // - one may be a dependent-sized array with known element type | ||||
4787 | // - one may be a dependent-typed valid index (enum in current instantiation) | ||||
4788 | // | ||||
4789 | // We *always* return a dependent type, in such cases it is DependentTy. | ||||
4790 | // This avoids creating type-dependent expressions with non-dependent types. | ||||
4791 | // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 | ||||
4792 | static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, | ||||
4793 | const ASTContext &Ctx) { | ||||
4794 | assert(LHS->isTypeDependent() || RHS->isTypeDependent())(static_cast <bool> (LHS->isTypeDependent() || RHS-> isTypeDependent()) ? void (0) : __assert_fail ("LHS->isTypeDependent() || RHS->isTypeDependent()" , "clang/lib/Sema/SemaExpr.cpp", 4794, __extension__ __PRETTY_FUNCTION__ )); | ||||
4795 | QualType LTy = LHS->getType(), RTy = RHS->getType(); | ||||
4796 | QualType Result = Ctx.DependentTy; | ||||
4797 | if (RTy->isIntegralOrUnscopedEnumerationType()) { | ||||
4798 | if (const PointerType *PT = LTy->getAs<PointerType>()) | ||||
4799 | Result = PT->getPointeeType(); | ||||
4800 | else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) | ||||
4801 | Result = AT->getElementType(); | ||||
4802 | } else if (LTy->isIntegralOrUnscopedEnumerationType()) { | ||||
4803 | if (const PointerType *PT = RTy->getAs<PointerType>()) | ||||
4804 | Result = PT->getPointeeType(); | ||||
4805 | else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) | ||||
4806 | Result = AT->getElementType(); | ||||
4807 | } | ||||
4808 | // Ensure we return a dependent type. | ||||
4809 | return Result->isDependentType() ? Result : Ctx.DependentTy; | ||||
4810 | } | ||||
4811 | |||||
4812 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); | ||||
4813 | |||||
4814 | ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, | ||||
4815 | SourceLocation lbLoc, | ||||
4816 | MultiExprArg ArgExprs, | ||||
4817 | SourceLocation rbLoc) { | ||||
4818 | |||||
4819 | if (base && !base->getType().isNull() && | ||||
4820 | base->hasPlaceholderType(BuiltinType::OMPArraySection)) | ||||
4821 | return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), | ||||
4822 | SourceLocation(), /*Length*/ nullptr, | ||||
4823 | /*Stride=*/nullptr, rbLoc); | ||||
4824 | |||||
4825 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
4826 | if (isa<ParenListExpr>(base)) { | ||||
4827 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||
4828 | if (result.isInvalid()) | ||||
4829 | return ExprError(); | ||||
4830 | base = result.get(); | ||||
4831 | } | ||||
4832 | |||||
4833 | // Check if base and idx form a MatrixSubscriptExpr. | ||||
4834 | // | ||||
4835 | // Helper to check for comma expressions, which are not allowed as indices for | ||||
4836 | // matrix subscript expressions. | ||||
4837 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||
4838 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||
4839 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||
4840 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4841 | return true; | ||||
4842 | } | ||||
4843 | return false; | ||||
4844 | }; | ||||
4845 | // The matrix subscript operator ([][])is considered a single operator. | ||||
4846 | // Separating the index expressions by parenthesis is not allowed. | ||||
4847 | if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && | ||||
4848 | !isa<MatrixSubscriptExpr>(base)) { | ||||
4849 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||
4850 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4851 | return ExprError(); | ||||
4852 | } | ||||
4853 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||
4854 | // MatrixSubscriptExpr. | ||||
4855 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||
4856 | if (matSubscriptE) { | ||||
4857 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4857, __extension__ __PRETTY_FUNCTION__)); | ||||
4858 | if (CheckAndReportCommaError(ArgExprs.front())) | ||||
4859 | return ExprError(); | ||||
4860 | |||||
4861 | assert(matSubscriptE->isIncomplete() &&(static_cast <bool> (matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript") ? void (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "clang/lib/Sema/SemaExpr.cpp", 4862, __extension__ __PRETTY_FUNCTION__ )) | ||||
4862 | "base has to be an incomplete matrix subscript")(static_cast <bool> (matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript") ? void (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "clang/lib/Sema/SemaExpr.cpp", 4862, __extension__ __PRETTY_FUNCTION__ )); | ||||
4863 | return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), | ||||
4864 | matSubscriptE->getRowIdx(), | ||||
4865 | ArgExprs.front(), rbLoc); | ||||
4866 | } | ||||
4867 | |||||
4868 | // Handle any non-overload placeholder types in the base and index | ||||
4869 | // expressions. We can't handle overloads here because the other | ||||
4870 | // operand might be an overloadable type, in which case the overload | ||||
4871 | // resolution for the operator overload should get the first crack | ||||
4872 | // at the overload. | ||||
4873 | bool IsMSPropertySubscript = false; | ||||
4874 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||
4875 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||
4876 | if (!IsMSPropertySubscript) { | ||||
4877 | ExprResult result = CheckPlaceholderExpr(base); | ||||
4878 | if (result.isInvalid()) | ||||
4879 | return ExprError(); | ||||
4880 | base = result.get(); | ||||
4881 | } | ||||
4882 | } | ||||
4883 | |||||
4884 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||
4885 | if (base->getType()->isMatrixType()) { | ||||
4886 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4886, __extension__ __PRETTY_FUNCTION__)); | ||||
4887 | if (CheckAndReportCommaError(ArgExprs.front())) | ||||
4888 | return ExprError(); | ||||
4889 | |||||
4890 | return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, | ||||
4891 | rbLoc); | ||||
4892 | } | ||||
4893 | |||||
4894 | if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { | ||||
4895 | Expr *idx = ArgExprs[0]; | ||||
4896 | if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||
4897 | (isa<CXXOperatorCallExpr>(idx) && | ||||
4898 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { | ||||
4899 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||
4900 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4901 | } | ||||
4902 | } | ||||
4903 | |||||
4904 | if (ArgExprs.size() == 1 && | ||||
4905 | ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { | ||||
4906 | ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); | ||||
4907 | if (result.isInvalid()) | ||||
4908 | return ExprError(); | ||||
4909 | ArgExprs[0] = result.get(); | ||||
4910 | } else { | ||||
4911 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
4912 | return ExprError(); | ||||
4913 | } | ||||
4914 | |||||
4915 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4916 | if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && | ||||
4917 | (base->isTypeDependent() || | ||||
4918 | Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
4919 | return new (Context) ArraySubscriptExpr( | ||||
4920 | base, ArgExprs.front(), | ||||
4921 | getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), | ||||
4922 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4923 | } | ||||
4924 | |||||
4925 | // MSDN, property (C++) | ||||
4926 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||
4927 | // This attribute can also be used in the declaration of an empty array in a | ||||
4928 | // class or structure definition. For example: | ||||
4929 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||
4930 | // The above statement indicates that x[] can be used with one or more array | ||||
4931 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||
4932 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||
4933 | if (IsMSPropertySubscript) { | ||||
4934 | assert(ArgExprs.size() == 1)(static_cast <bool> (ArgExprs.size() == 1) ? void (0) : __assert_fail ("ArgExprs.size() == 1", "clang/lib/Sema/SemaExpr.cpp" , 4934, __extension__ __PRETTY_FUNCTION__)); | ||||
4935 | // Build MS property subscript expression if base is MS property reference | ||||
4936 | // or MS property subscript. | ||||
4937 | return new (Context) | ||||
4938 | MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, | ||||
4939 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4940 | } | ||||
4941 | |||||
4942 | // Use C++ overloaded-operator rules if either operand has record | ||||
4943 | // type. The spec says to do this if either type is *overloadable*, | ||||
4944 | // but enum types can't declare subscript operators or conversion | ||||
4945 | // operators, so there's nothing interesting for overload resolution | ||||
4946 | // to do if there aren't any record types involved. | ||||
4947 | // | ||||
4948 | // ObjC pointers have their own subscripting logic that is not tied | ||||
4949 | // to overload resolution and so should not take this path. | ||||
4950 | if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && | ||||
4951 | ((base->getType()->isRecordType() || | ||||
4952 | (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { | ||||
4953 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); | ||||
4954 | } | ||||
4955 | |||||
4956 | ExprResult Res = | ||||
4957 | CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); | ||||
4958 | |||||
4959 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||
4960 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||
4961 | |||||
4962 | return Res; | ||||
4963 | } | ||||
4964 | |||||
4965 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||
4966 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||
4967 | InitializationKind Kind = | ||||
4968 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||
4969 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||
4970 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||
4971 | } | ||||
4972 | |||||
4973 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||
4974 | Expr *ColumnIdx, | ||||
4975 | SourceLocation RBLoc) { | ||||
4976 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||
4977 | if (BaseR.isInvalid()) | ||||
4978 | return BaseR; | ||||
4979 | Base = BaseR.get(); | ||||
4980 | |||||
4981 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||
4982 | if (RowR.isInvalid()) | ||||
4983 | return RowR; | ||||
4984 | RowIdx = RowR.get(); | ||||
4985 | |||||
4986 | if (!ColumnIdx) | ||||
4987 | return new (Context) MatrixSubscriptExpr( | ||||
4988 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||
4989 | |||||
4990 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||
4991 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||
4992 | ColumnIdx->isTypeDependent()) | ||||
4993 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4994 | Context.DependentTy, RBLoc); | ||||
4995 | |||||
4996 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||
4997 | if (ColumnR.isInvalid()) | ||||
4998 | return ColumnR; | ||||
4999 | ColumnIdx = ColumnR.get(); | ||||
5000 | |||||
5001 | // Check that IndexExpr is an integer expression. If it is a constant | ||||
5002 | // expression, check that it is less than Dim (= the number of elements in the | ||||
5003 | // corresponding dimension). | ||||
5004 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||
5005 | bool IsColumnIdx) -> Expr * { | ||||
5006 | if (!IndexExpr->getType()->isIntegerType() && | ||||
5007 | !IndexExpr->isTypeDependent()) { | ||||
5008 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||
5009 | << IsColumnIdx; | ||||
5010 | return nullptr; | ||||
5011 | } | ||||
5012 | |||||
5013 | if (Optional<llvm::APSInt> Idx = | ||||
5014 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||
5015 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||
5016 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||
5017 | << IsColumnIdx << Dim; | ||||
5018 | return nullptr; | ||||
5019 | } | ||||
5020 | } | ||||
5021 | |||||
5022 | ExprResult ConvExpr = | ||||
5023 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||
5024 | assert(!ConvExpr.isInvalid() &&(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "clang/lib/Sema/SemaExpr.cpp", 5025, __extension__ __PRETTY_FUNCTION__ )) | ||||
5025 | "should be able to convert any integer type to size type")(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "clang/lib/Sema/SemaExpr.cpp", 5025, __extension__ __PRETTY_FUNCTION__ )); | ||||
5026 | return ConvExpr.get(); | ||||
5027 | }; | ||||
5028 | |||||
5029 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||
5030 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||
5031 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||
5032 | if (!RowIdx || !ColumnIdx) | ||||
5033 | return ExprError(); | ||||
5034 | |||||
5035 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
5036 | MTy->getElementType(), RBLoc); | ||||
5037 | } | ||||
5038 | |||||
5039 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||
5040 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
5041 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||
5042 | |||||
5043 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||
5044 | // checked. | ||||
5045 | const MemberExpr *Member = nullptr; | ||||
5046 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||
5047 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||
5048 | |||||
5049 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||
5050 | } | ||||
5051 | |||||
5052 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||
5053 | if (isUnevaluatedContext()) | ||||
5054 | return; | ||||
5055 | |||||
5056 | QualType ResultTy = E->getType(); | ||||
5057 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
5058 | |||||
5059 | // Bail if the element is an array since it is not memory access. | ||||
5060 | if (isa<ArrayType>(ResultTy)) | ||||
5061 | return; | ||||
5062 | |||||
5063 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||
5064 | LastRecord.PossibleDerefs.insert(E); | ||||
5065 | return; | ||||
5066 | } | ||||
5067 | |||||
5068 | // Check if the base type is a pointer to a member access of a struct | ||||
5069 | // marked with noderef. | ||||
5070 | const Expr *Base = E->getBase(); | ||||
5071 | QualType BaseTy = Base->getType(); | ||||
5072 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||
5073 | // Not a pointer access | ||||
5074 | return; | ||||
5075 | |||||
5076 | const MemberExpr *Member = nullptr; | ||||
5077 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||
5078 | Member->isArrow()) | ||||
5079 | Base = Member->getBase(); | ||||
5080 | |||||
5081 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||
5082 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||
5083 | LastRecord.PossibleDerefs.insert(E); | ||||
5084 | } | ||||
5085 | } | ||||
5086 | |||||
5087 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||
5088 | Expr *LowerBound, | ||||
5089 | SourceLocation ColonLocFirst, | ||||
5090 | SourceLocation ColonLocSecond, | ||||
5091 | Expr *Length, Expr *Stride, | ||||
5092 | SourceLocation RBLoc) { | ||||
5093 | if (Base->hasPlaceholderType() && | ||||
5094 | !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { | ||||
5095 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5096 | if (Result.isInvalid()) | ||||
5097 | return ExprError(); | ||||
5098 | Base = Result.get(); | ||||
5099 | } | ||||
5100 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||
5101 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||
5102 | if (Result.isInvalid()) | ||||
5103 | return ExprError(); | ||||
5104 | Result = DefaultLvalueConversion(Result.get()); | ||||
5105 | if (Result.isInvalid()) | ||||
5106 | return ExprError(); | ||||
5107 | LowerBound = Result.get(); | ||||
5108 | } | ||||
5109 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||
5110 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||
5111 | if (Result.isInvalid()) | ||||
5112 | return ExprError(); | ||||
5113 | Result = DefaultLvalueConversion(Result.get()); | ||||
5114 | if (Result.isInvalid()) | ||||
5115 | return ExprError(); | ||||
5116 | Length = Result.get(); | ||||
5117 | } | ||||
5118 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||
5119 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||
5120 | if (Result.isInvalid()) | ||||
5121 | return ExprError(); | ||||
5122 | Result = DefaultLvalueConversion(Result.get()); | ||||
5123 | if (Result.isInvalid()) | ||||
5124 | return ExprError(); | ||||
5125 | Stride = Result.get(); | ||||
5126 | } | ||||
5127 | |||||
5128 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
5129 | if (Base->isTypeDependent() || | ||||
5130 | (LowerBound && | ||||
5131 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||
5132 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||
5133 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||
5134 | return new (Context) OMPArraySectionExpr( | ||||
5135 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||
5136 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5137 | } | ||||
5138 | |||||
5139 | // Perform default conversions. | ||||
5140 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||
5141 | QualType ResultTy; | ||||
5142 | if (OriginalTy->isAnyPointerType()) { | ||||
5143 | ResultTy = OriginalTy->getPointeeType(); | ||||
5144 | } else if (OriginalTy->isArrayType()) { | ||||
5145 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||
5146 | } else { | ||||
5147 | return ExprError( | ||||
5148 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||
5149 | << Base->getSourceRange()); | ||||
5150 | } | ||||
5151 | // C99 6.5.2.1p1 | ||||
5152 | if (LowerBound) { | ||||
5153 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||
5154 | LowerBound); | ||||
5155 | if (Res.isInvalid()) | ||||
5156 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||
5157 | diag::err_omp_typecheck_section_not_integer) | ||||
5158 | << 0 << LowerBound->getSourceRange()); | ||||
5159 | LowerBound = Res.get(); | ||||
5160 | |||||
5161 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5162 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5163 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5164 | << 0 << LowerBound->getSourceRange(); | ||||
5165 | } | ||||
5166 | if (Length) { | ||||
5167 | auto Res = | ||||
5168 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||
5169 | if (Res.isInvalid()) | ||||
5170 | return ExprError(Diag(Length->getExprLoc(), | ||||
5171 | diag::err_omp_typecheck_section_not_integer) | ||||
5172 | << 1 << Length->getSourceRange()); | ||||
5173 | Length = Res.get(); | ||||
5174 | |||||
5175 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5176 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5177 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5178 | << 1 << Length->getSourceRange(); | ||||
5179 | } | ||||
5180 | if (Stride) { | ||||
5181 | ExprResult Res = | ||||
5182 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||
5183 | if (Res.isInvalid()) | ||||
5184 | return ExprError(Diag(Stride->getExprLoc(), | ||||
5185 | diag::err_omp_typecheck_section_not_integer) | ||||
5186 | << 1 << Stride->getSourceRange()); | ||||
5187 | Stride = Res.get(); | ||||
5188 | |||||
5189 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5190 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5191 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5192 | << 1 << Stride->getSourceRange(); | ||||
5193 | } | ||||
5194 | |||||
5195 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5196 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5197 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||
5198 | // incomplete types are not object types. | ||||
5199 | if (ResultTy->isFunctionType()) { | ||||
5200 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||
5201 | << ResultTy << Base->getSourceRange(); | ||||
5202 | return ExprError(); | ||||
5203 | } | ||||
5204 | |||||
5205 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||
5206 | diag::err_omp_section_incomplete_type, Base)) | ||||
5207 | return ExprError(); | ||||
5208 | |||||
5209 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||
5210 | Expr::EvalResult Result; | ||||
5211 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||
5212 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5213 | // The array section must be a subset of the original array. | ||||
5214 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||
5215 | if (LowerBoundValue.isNegative()) { | ||||
5216 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||
5217 | << LowerBound->getSourceRange(); | ||||
5218 | return ExprError(); | ||||
5219 | } | ||||
5220 | } | ||||
5221 | } | ||||
5222 | |||||
5223 | if (Length) { | ||||
5224 | Expr::EvalResult Result; | ||||
5225 | if (Length->EvaluateAsInt(Result, Context)) { | ||||
5226 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5227 | // The length must evaluate to non-negative integers. | ||||
5228 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||
5229 | if (LengthValue.isNegative()) { | ||||
5230 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||
5231 | << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) | ||||
5232 | << Length->getSourceRange(); | ||||
5233 | return ExprError(); | ||||
5234 | } | ||||
5235 | } | ||||
5236 | } else if (ColonLocFirst.isValid() && | ||||
5237 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||
5238 | !OriginalTy->isVariableArrayType()))) { | ||||
5239 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5240 | // When the size of the array dimension is not known, the length must be | ||||
5241 | // specified explicitly. | ||||
5242 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||
5243 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||
5244 | return ExprError(); | ||||
5245 | } | ||||
5246 | |||||
5247 | if (Stride) { | ||||
5248 | Expr::EvalResult Result; | ||||
5249 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||
5250 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5251 | // The stride must evaluate to a positive integer. | ||||
5252 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||
5253 | if (!StrideValue.isStrictlyPositive()) { | ||||
5254 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||
5255 | << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) | ||||
5256 | << Stride->getSourceRange(); | ||||
5257 | return ExprError(); | ||||
5258 | } | ||||
5259 | } | ||||
5260 | } | ||||
5261 | |||||
5262 | if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { | ||||
5263 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||
5264 | if (Result.isInvalid()) | ||||
5265 | return ExprError(); | ||||
5266 | Base = Result.get(); | ||||
5267 | } | ||||
5268 | return new (Context) OMPArraySectionExpr( | ||||
5269 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||
5270 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5271 | } | ||||
5272 | |||||
5273 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||
5274 | SourceLocation RParenLoc, | ||||
5275 | ArrayRef<Expr *> Dims, | ||||
5276 | ArrayRef<SourceRange> Brackets) { | ||||
5277 | if (Base->hasPlaceholderType()) { | ||||
5278 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5279 | if (Result.isInvalid()) | ||||
5280 | return ExprError(); | ||||
5281 | Result = DefaultLvalueConversion(Result.get()); | ||||
5282 | if (Result.isInvalid()) | ||||
5283 | return ExprError(); | ||||
5284 | Base = Result.get(); | ||||
5285 | } | ||||
5286 | QualType BaseTy = Base->getType(); | ||||
5287 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||
5288 | // required. | ||||
5289 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||
5290 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||
5291 | LParenLoc, RParenLoc, Dims, Brackets); | ||||
5292 | if (!BaseTy->isPointerType() || | ||||
5293 | (!Base->isTypeDependent() && | ||||
5294 | BaseTy->getPointeeType()->isIncompleteType())) | ||||
5295 | return ExprError(Diag(Base->getExprLoc(), | ||||
5296 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||
5297 | << Base->getSourceRange()); | ||||
5298 | |||||
5299 | SmallVector<Expr *, 4> NewDims; | ||||
5300 | bool ErrorFound = false; | ||||
5301 | for (Expr *Dim : Dims) { | ||||
5302 | if (Dim->hasPlaceholderType()) { | ||||
5303 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||
5304 | if (Result.isInvalid()) { | ||||
5305 | ErrorFound = true; | ||||
5306 | continue; | ||||
5307 | } | ||||
5308 | Result = DefaultLvalueConversion(Result.get()); | ||||
5309 | if (Result.isInvalid()) { | ||||
5310 | ErrorFound = true; | ||||
5311 | continue; | ||||
5312 | } | ||||
5313 | Dim = Result.get(); | ||||
5314 | } | ||||
5315 | if (!Dim->isTypeDependent()) { | ||||
5316 | ExprResult Result = | ||||
5317 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||
5318 | if (Result.isInvalid()) { | ||||
5319 | ErrorFound = true; | ||||
5320 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||
5321 | << Dim->getSourceRange(); | ||||
5322 | continue; | ||||
5323 | } | ||||
5324 | Dim = Result.get(); | ||||
5325 | Expr::EvalResult EvResult; | ||||
5326 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||
5327 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||
5328 | // Each si is an integral type expression that must evaluate to a | ||||
5329 | // positive integer. | ||||
5330 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||
5331 | if (!Value.isStrictlyPositive()) { | ||||
5332 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||
5333 | << toString(Value, /*Radix=*/10, /*Signed=*/true) | ||||
5334 | << Dim->getSourceRange(); | ||||
5335 | ErrorFound = true; | ||||
5336 | continue; | ||||
5337 | } | ||||
5338 | } | ||||
5339 | } | ||||
5340 | NewDims.push_back(Dim); | ||||
5341 | } | ||||
5342 | if (ErrorFound) | ||||
5343 | return ExprError(); | ||||
5344 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||
5345 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||
5346 | } | ||||
5347 | |||||
5348 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||
5349 | SourceLocation LLoc, SourceLocation RLoc, | ||||
5350 | ArrayRef<OMPIteratorData> Data) { | ||||
5351 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||
5352 | bool IsCorrect = true; | ||||
5353 | for (const OMPIteratorData &D : Data) { | ||||
5354 | TypeSourceInfo *TInfo = nullptr; | ||||
5355 | SourceLocation StartLoc; | ||||
5356 | QualType DeclTy; | ||||
5357 | if (!D.Type.getAsOpaquePtr()) { | ||||
5358 | // OpenMP 5.0, 2.1.6 Iterators | ||||
5359 | // In an iterator-specifier, if the iterator-type is not specified then | ||||
5360 | // the type of that iterator is of int type. | ||||
5361 | DeclTy = Context.IntTy; | ||||
5362 | StartLoc = D.DeclIdentLoc; | ||||
5363 | } else { | ||||
5364 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||
5365 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
5366 | } | ||||
5367 | |||||
5368 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||
5369 | DeclTy->containsUnexpandedParameterPack() || | ||||
5370 | DeclTy->isInstantiationDependentType(); | ||||
5371 | if (!IsDeclTyDependent) { | ||||
5372 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||
5373 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5374 | // The iterator-type must be an integral or pointer type. | ||||
5375 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5376 | << DeclTy; | ||||
5377 | IsCorrect = false; | ||||
5378 | continue; | ||||
5379 | } | ||||
5380 | if (DeclTy.isConstant(Context)) { | ||||
5381 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5382 | // The iterator-type must not be const qualified. | ||||
5383 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5384 | << DeclTy; | ||||
5385 | IsCorrect = false; | ||||
5386 | continue; | ||||
5387 | } | ||||
5388 | } | ||||
5389 | |||||
5390 | // Iterator declaration. | ||||
5391 | assert(D.DeclIdent && "Identifier expected.")(static_cast <bool> (D.DeclIdent && "Identifier expected." ) ? void (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "clang/lib/Sema/SemaExpr.cpp", 5391, __extension__ __PRETTY_FUNCTION__ )); | ||||
5392 | // Always try to create iterator declarator to avoid extra error messages | ||||
5393 | // about unknown declarations use. | ||||
5394 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||
5395 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||
5396 | VD->setImplicit(); | ||||
5397 | if (S) { | ||||
5398 | // Check for conflicting previous declaration. | ||||
5399 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||
5400 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5401 | ForVisibleRedeclaration); | ||||
5402 | Previous.suppressDiagnostics(); | ||||
5403 | LookupName(Previous, S); | ||||
5404 | |||||
5405 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||
5406 | /*AllowInlineNamespace=*/false); | ||||
5407 | if (!Previous.empty()) { | ||||
5408 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||
5409 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||
5410 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
5411 | } else { | ||||
5412 | PushOnScopeChains(VD, S); | ||||
5413 | } | ||||
5414 | } else { | ||||
5415 | CurContext->addDecl(VD); | ||||
5416 | } | ||||
5417 | Expr *Begin = D.Range.Begin; | ||||
5418 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||
5419 | ExprResult BeginRes = | ||||
5420 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||
5421 | Begin = BeginRes.get(); | ||||
5422 | } | ||||
5423 | Expr *End = D.Range.End; | ||||
5424 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||
5425 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||
5426 | End = EndRes.get(); | ||||
5427 | } | ||||
5428 | Expr *Step = D.Range.Step; | ||||
5429 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||
5430 | if (!Step->getType()->isIntegralType(Context)) { | ||||
5431 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||
5432 | << Step << Step->getSourceRange(); | ||||
5433 | IsCorrect = false; | ||||
5434 | continue; | ||||
5435 | } | ||||
5436 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||
5437 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||
5438 | // If the step expression of a range-specification equals zero, the | ||||
5439 | // behavior is unspecified. | ||||
5440 | if (Result && Result->isZero()) { | ||||
5441 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||
5442 | << Step << Step->getSourceRange(); | ||||
5443 | IsCorrect = false; | ||||
5444 | continue; | ||||
5445 | } | ||||
5446 | } | ||||
5447 | if (!Begin || !End || !IsCorrect) { | ||||
5448 | IsCorrect = false; | ||||
5449 | continue; | ||||
5450 | } | ||||
5451 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||
5452 | IDElem.IteratorDecl = VD; | ||||
5453 | IDElem.AssignmentLoc = D.AssignLoc; | ||||
5454 | IDElem.Range.Begin = Begin; | ||||
5455 | IDElem.Range.End = End; | ||||
5456 | IDElem.Range.Step = Step; | ||||
5457 | IDElem.ColonLoc = D.ColonLoc; | ||||
5458 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||
5459 | } | ||||
5460 | if (!IsCorrect) { | ||||
5461 | // Invalidate all created iterator declarations if error is found. | ||||
5462 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5463 | if (Decl *ID = D.IteratorDecl) | ||||
5464 | ID->setInvalidDecl(); | ||||
5465 | } | ||||
5466 | return ExprError(); | ||||
5467 | } | ||||
5468 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||
5469 | if (!CurContext->isDependentContext()) { | ||||
5470 | // Build number of ityeration for each iteration range. | ||||
5471 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||
5472 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||
5473 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5474 | // (Endi - Begini) | ||||
5475 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||
5476 | D.Range.Begin); | ||||
5477 | if(!Res.isUsable()) { | ||||
5478 | IsCorrect = false; | ||||
5479 | continue; | ||||
5480 | } | ||||
5481 | ExprResult St, St1; | ||||
5482 | if (D.Range.Step) { | ||||
5483 | St = D.Range.Step; | ||||
5484 | // (Endi - Begini) + Stepi | ||||
5485 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||
5486 | if (!Res.isUsable()) { | ||||
5487 | IsCorrect = false; | ||||
5488 | continue; | ||||
5489 | } | ||||
5490 | // (Endi - Begini) + Stepi - 1 | ||||
5491 | Res = | ||||
5492 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||
5493 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5494 | if (!Res.isUsable()) { | ||||
5495 | IsCorrect = false; | ||||
5496 | continue; | ||||
5497 | } | ||||
5498 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||
5499 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||
5500 | if (!Res.isUsable()) { | ||||
5501 | IsCorrect = false; | ||||
5502 | continue; | ||||
5503 | } | ||||
5504 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||
5505 | // (Begini - Endi) | ||||
5506 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||
5507 | D.Range.Begin, D.Range.End); | ||||
5508 | if (!Res1.isUsable()) { | ||||
5509 | IsCorrect = false; | ||||
5510 | continue; | ||||
5511 | } | ||||
5512 | // (Begini - Endi) - Stepi | ||||
5513 | Res1 = | ||||
5514 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||
5515 | if (!Res1.isUsable()) { | ||||
5516 | IsCorrect = false; | ||||
5517 | continue; | ||||
5518 | } | ||||
5519 | // (Begini - Endi) - Stepi - 1 | ||||
5520 | Res1 = | ||||
5521 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||
5522 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5523 | if (!Res1.isUsable()) { | ||||
5524 | IsCorrect = false; | ||||
5525 | continue; | ||||
5526 | } | ||||
5527 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||
5528 | Res1 = | ||||
5529 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||
5530 | if (!Res1.isUsable()) { | ||||
5531 | IsCorrect = false; | ||||
5532 | continue; | ||||
5533 | } | ||||
5534 | // Stepi > 0. | ||||
5535 | ExprResult CmpRes = | ||||
5536 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||
5537 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||
5538 | if (!CmpRes.isUsable()) { | ||||
5539 | IsCorrect = false; | ||||
5540 | continue; | ||||
5541 | } | ||||
5542 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||
5543 | Res.get(), Res1.get()); | ||||
5544 | if (!Res.isUsable()) { | ||||
5545 | IsCorrect = false; | ||||
5546 | continue; | ||||
5547 | } | ||||
5548 | } | ||||
5549 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||
5550 | if (!Res.isUsable()) { | ||||
5551 | IsCorrect = false; | ||||
5552 | continue; | ||||
5553 | } | ||||
5554 | |||||
5555 | // Build counter update. | ||||
5556 | // Build counter. | ||||
5557 | auto *CounterVD = | ||||
5558 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||
5559 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||
5560 | Res.get()->getType(), nullptr, SC_None); | ||||
5561 | CounterVD->setImplicit(); | ||||
5562 | ExprResult RefRes = | ||||
5563 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||
5564 | D.IteratorDecl->getBeginLoc()); | ||||
5565 | // Build counter update. | ||||
5566 | // I = Begini + counter * Stepi; | ||||
5567 | ExprResult UpdateRes; | ||||
5568 | if (D.Range.Step) { | ||||
5569 | UpdateRes = CreateBuiltinBinOp( | ||||
5570 | D.AssignmentLoc, BO_Mul, | ||||
5571 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||
5572 | } else { | ||||
5573 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||
5574 | } | ||||
5575 | if (!UpdateRes.isUsable()) { | ||||
5576 | IsCorrect = false; | ||||
5577 | continue; | ||||
5578 | } | ||||
5579 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||
5580 | UpdateRes.get()); | ||||
5581 | if (!UpdateRes.isUsable()) { | ||||
5582 | IsCorrect = false; | ||||
5583 | continue; | ||||
5584 | } | ||||
5585 | ExprResult VDRes = | ||||
5586 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||
5587 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||
5588 | D.IteratorDecl->getBeginLoc()); | ||||
5589 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||
5590 | UpdateRes.get()); | ||||
5591 | if (!UpdateRes.isUsable()) { | ||||
5592 | IsCorrect = false; | ||||
5593 | continue; | ||||
5594 | } | ||||
5595 | UpdateRes = | ||||
5596 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||
5597 | if (!UpdateRes.isUsable()) { | ||||
5598 | IsCorrect = false; | ||||
5599 | continue; | ||||
5600 | } | ||||
5601 | ExprResult CounterUpdateRes = | ||||
5602 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||
5603 | if (!CounterUpdateRes.isUsable()) { | ||||
5604 | IsCorrect = false; | ||||
5605 | continue; | ||||
5606 | } | ||||
5607 | CounterUpdateRes = | ||||
5608 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||
5609 | if (!CounterUpdateRes.isUsable()) { | ||||
5610 | IsCorrect = false; | ||||
5611 | continue; | ||||
5612 | } | ||||
5613 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||
5614 | HD.CounterVD = CounterVD; | ||||
5615 | HD.Upper = Res.get(); | ||||
5616 | HD.Update = UpdateRes.get(); | ||||
5617 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||
5618 | } | ||||
5619 | } else { | ||||
5620 | Helpers.assign(ID.size(), {}); | ||||
5621 | } | ||||
5622 | if (!IsCorrect) { | ||||
5623 | // Invalidate all created iterator declarations if error is found. | ||||
5624 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5625 | if (Decl *ID = D.IteratorDecl) | ||||
5626 | ID->setInvalidDecl(); | ||||
5627 | } | ||||
5628 | return ExprError(); | ||||
5629 | } | ||||
5630 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||
5631 | LLoc, RLoc, ID, Helpers); | ||||
5632 | } | ||||
5633 | |||||
5634 | ExprResult | ||||
5635 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||
5636 | Expr *Idx, SourceLocation RLoc) { | ||||
5637 | Expr *LHSExp = Base; | ||||
5638 | Expr *RHSExp = Idx; | ||||
5639 | |||||
5640 | ExprValueKind VK = VK_LValue; | ||||
5641 | ExprObjectKind OK = OK_Ordinary; | ||||
5642 | |||||
5643 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||
5644 | // a non-lvalue array, and an lvalue otherwise. | ||||
5645 | if (getLangOpts().CPlusPlus11) { | ||||
5646 | for (auto *Op : {LHSExp, RHSExp}) { | ||||
5647 | Op = Op->IgnoreImplicit(); | ||||
5648 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||
5649 | VK = VK_XValue; | ||||
5650 | } | ||||
5651 | } | ||||
5652 | |||||
5653 | // Perform default conversions. | ||||
5654 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||
5655 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||
5656 | if (Result.isInvalid()) | ||||
5657 | return ExprError(); | ||||
5658 | LHSExp = Result.get(); | ||||
5659 | } | ||||
5660 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||
5661 | if (Result.isInvalid()) | ||||
5662 | return ExprError(); | ||||
5663 | RHSExp = Result.get(); | ||||
5664 | |||||
5665 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||
5666 | |||||
5667 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||
5668 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||
5669 | // in the subscript position. As a result, we need to derive the array base | ||||
5670 | // and index from the expression types. | ||||
5671 | Expr *BaseExpr, *IndexExpr; | ||||
5672 | QualType ResultType; | ||||
5673 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||
5674 | BaseExpr = LHSExp; | ||||
5675 | IndexExpr = RHSExp; | ||||
5676 | ResultType = | ||||
5677 | getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); | ||||
5678 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||
5679 | BaseExpr = LHSExp; | ||||
5680 | IndexExpr = RHSExp; | ||||
5681 | ResultType = PTy->getPointeeType(); | ||||
5682 | } else if (const ObjCObjectPointerType *PTy = | ||||
5683 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5684 | BaseExpr = LHSExp; | ||||
5685 | IndexExpr = RHSExp; | ||||
5686 | |||||
5687 | // Use custom logic if this should be the pseudo-object subscript | ||||
5688 | // expression. | ||||
5689 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||
5690 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||
5691 | nullptr); | ||||
5692 | |||||
5693 | ResultType = PTy->getPointeeType(); | ||||
5694 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||
5695 | // Handle the uncommon case of "123[Ptr]". | ||||
5696 | BaseExpr = RHSExp; | ||||
5697 | IndexExpr = LHSExp; | ||||
5698 | ResultType = PTy->getPointeeType(); | ||||
5699 | } else if (const ObjCObjectPointerType *PTy = | ||||
5700 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5701 | // Handle the uncommon case of "123[Ptr]". | ||||
5702 | BaseExpr = RHSExp; | ||||
5703 | IndexExpr = LHSExp; | ||||
5704 | ResultType = PTy->getPointeeType(); | ||||
5705 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||
5706 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||
5707 | << ResultType << BaseExpr->getSourceRange(); | ||||
5708 | return ExprError(); | ||||
5709 | } | ||||
5710 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||
5711 | BaseExpr = LHSExp; // vectors: V[123] | ||||
5712 | IndexExpr = RHSExp; | ||||
5713 | // We apply C++ DR1213 to vector subscripting too. | ||||
5714 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { | ||||
5715 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5716 | if (Materialized.isInvalid()) | ||||
5717 | return ExprError(); | ||||
5718 | LHSExp = Materialized.get(); | ||||
5719 | } | ||||
5720 | VK = LHSExp->getValueKind(); | ||||
5721 | if (VK != VK_PRValue) | ||||
5722 | OK = OK_VectorComponent; | ||||
5723 | |||||
5724 | ResultType = VTy->getElementType(); | ||||
5725 | QualType BaseType = BaseExpr->getType(); | ||||
5726 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5727 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5728 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5729 | if (Combined != MemberQuals) | ||||
5730 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5731 | } else if (LHSTy->isBuiltinType() && | ||||
5732 | LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { | ||||
5733 | const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); | ||||
5734 | if (BTy->isSVEBool()) | ||||
5735 | return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) | ||||
5736 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5737 | |||||
5738 | BaseExpr = LHSExp; | ||||
5739 | IndexExpr = RHSExp; | ||||
5740 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { | ||||
5741 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5742 | if (Materialized.isInvalid()) | ||||
5743 | return ExprError(); | ||||
5744 | LHSExp = Materialized.get(); | ||||
5745 | } | ||||
5746 | VK = LHSExp->getValueKind(); | ||||
5747 | if (VK != VK_PRValue) | ||||
5748 | OK = OK_VectorComponent; | ||||
5749 | |||||
5750 | ResultType = BTy->getSveEltType(Context); | ||||
5751 | |||||
5752 | QualType BaseType = BaseExpr->getType(); | ||||
5753 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5754 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5755 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5756 | if (Combined != MemberQuals) | ||||
5757 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5758 | } else if (LHSTy->isArrayType()) { | ||||
5759 | // If we see an array that wasn't promoted by | ||||
5760 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||
5761 | // wasn't promoted because of the C90 rule that doesn't | ||||
5762 | // allow promoting non-lvalue arrays. Warn, then | ||||
5763 | // force the promotion here. | ||||
5764 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5765 | << LHSExp->getSourceRange(); | ||||
5766 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||
5767 | CK_ArrayToPointerDecay).get(); | ||||
5768 | LHSTy = LHSExp->getType(); | ||||
5769 | |||||
5770 | BaseExpr = LHSExp; | ||||
5771 | IndexExpr = RHSExp; | ||||
5772 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
5773 | } else if (RHSTy->isArrayType()) { | ||||
5774 | // Same as previous, except for 123[f().a] case | ||||
5775 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5776 | << RHSExp->getSourceRange(); | ||||
5777 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||
5778 | CK_ArrayToPointerDecay).get(); | ||||
5779 | RHSTy = RHSExp->getType(); | ||||
5780 | |||||
5781 | BaseExpr = RHSExp; | ||||
5782 | IndexExpr = LHSExp; | ||||
5783 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
5784 | } else { | ||||
5785 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||
5786 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5787 | } | ||||
5788 | // C99 6.5.2.1p1 | ||||
5789 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||
5790 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||
5791 | << IndexExpr->getSourceRange()); | ||||
5792 | |||||
5793 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5794 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5795 | && !IndexExpr->isTypeDependent()) | ||||
5796 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||
5797 | |||||
5798 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5799 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5800 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||
5801 | // incomplete types are not object types. | ||||
5802 | if (ResultType->isFunctionType()) { | ||||
5803 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||
5804 | << ResultType << BaseExpr->getSourceRange(); | ||||
5805 | return ExprError(); | ||||
5806 | } | ||||
5807 | |||||
5808 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||
5809 | // GNU extension: subscripting on pointer to void | ||||
5810 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||
5811 | << BaseExpr->getSourceRange(); | ||||
5812 | |||||
5813 | // C forbids expressions of unqualified void type from being l-values. | ||||
5814 | // See IsCForbiddenLValueType. | ||||
5815 | if (!ResultType.hasQualifiers()) | ||||
5816 | VK = VK_PRValue; | ||||
5817 | } else if (!ResultType->isDependentType() && | ||||
5818 | RequireCompleteSizedType( | ||||
5819 | LLoc, ResultType, | ||||
5820 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||
5821 | return ExprError(); | ||||
5822 | |||||
5823 | assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "clang/lib/Sema/SemaExpr.cpp", 5824, __extension__ __PRETTY_FUNCTION__ )) | ||||
5824 | !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "clang/lib/Sema/SemaExpr.cpp", 5824, __extension__ __PRETTY_FUNCTION__ )); | ||||
5825 | |||||
5826 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||
5827 | FunctionScopes.size() > 1) { | ||||
5828 | if (auto *TT = | ||||
5829 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||
5830 | for (auto I = FunctionScopes.rbegin(), | ||||
5831 | E = std::prev(FunctionScopes.rend()); | ||||
5832 | I != E; ++I) { | ||||
5833 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
5834 | if (CSI == nullptr) | ||||
5835 | break; | ||||
5836 | DeclContext *DC = nullptr; | ||||
5837 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
5838 | DC = LSI->CallOperator; | ||||
5839 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
5840 | DC = CRSI->TheCapturedDecl; | ||||
5841 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
5842 | DC = BSI->TheDecl; | ||||
5843 | if (DC) { | ||||
5844 | if (DC->containsDecl(TT->getDecl())) | ||||
5845 | break; | ||||
5846 | captureVariablyModifiedType( | ||||
5847 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||
5848 | } | ||||
5849 | } | ||||
5850 | } | ||||
5851 | } | ||||
5852 | |||||
5853 | return new (Context) | ||||
5854 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||
5855 | } | ||||
5856 | |||||
5857 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||
5858 | ParmVarDecl *Param) { | ||||
5859 | if (Param->hasUnparsedDefaultArg()) { | ||||
5860 | // If we've already cleared out the location for the default argument, | ||||
5861 | // that means we're parsing it right now. | ||||
5862 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||
5863 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||
5864 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||
5865 | Param->setInvalidDecl(); | ||||
5866 | return true; | ||||
5867 | } | ||||
5868 | |||||
5869 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||
5870 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||
5871 | Diag(UnparsedDefaultArgLocs[Param], | ||||
5872 | diag::note_default_argument_declared_here); | ||||
5873 | return true; | ||||
5874 | } | ||||
5875 | |||||
5876 | if (Param->hasUninstantiatedDefaultArg() && | ||||
5877 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||
5878 | return true; | ||||
5879 | |||||
5880 | assert(Param->hasInit() && "default argument but no initializer?")(static_cast <bool> (Param->hasInit() && "default argument but no initializer?" ) ? void (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "clang/lib/Sema/SemaExpr.cpp", 5880, __extension__ __PRETTY_FUNCTION__ )); | ||||
5881 | |||||
5882 | // If the default expression creates temporaries, we need to | ||||
5883 | // push them to the current stack of expression temporaries so they'll | ||||
5884 | // be properly destroyed. | ||||
5885 | // FIXME: We should really be rebuilding the default argument with new | ||||
5886 | // bound temporaries; see the comment in PR5810. | ||||
5887 | // We don't need to do that with block decls, though, because | ||||
5888 | // blocks in default argument expression can never capture anything. | ||||
5889 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||
5890 | // Set the "needs cleanups" bit regardless of whether there are | ||||
5891 | // any explicit objects. | ||||
5892 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||
5893 | |||||
5894 | // Append all the objects to the cleanup list. Right now, this | ||||
5895 | // should always be a no-op, because blocks in default argument | ||||
5896 | // expressions should never be able to capture anything. | ||||
5897 | assert(!Init->getNumObjects() &&(static_cast <bool> (!Init->getNumObjects() && "default argument expression has capturing blocks?") ? void ( 0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "clang/lib/Sema/SemaExpr.cpp", 5898, __extension__ __PRETTY_FUNCTION__ )) | ||||
5898 | "default argument expression has capturing blocks?")(static_cast <bool> (!Init->getNumObjects() && "default argument expression has capturing blocks?") ? void ( 0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "clang/lib/Sema/SemaExpr.cpp", 5898, __extension__ __PRETTY_FUNCTION__ )); | ||||
5899 | } | ||||
5900 | |||||
5901 | // We already type-checked the argument, so we know it works. | ||||
5902 | // Just mark all of the declarations in this potentially-evaluated expression | ||||
5903 | // as being "referenced". | ||||
5904 | EnterExpressionEvaluationContext EvalContext( | ||||
5905 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||
5906 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||
5907 | /*SkipLocalVariables=*/true); | ||||
5908 | return false; | ||||
5909 | } | ||||
5910 | |||||
5911 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||
5912 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||
5913 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() && "can't build nonexistent default arg") ? void (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "clang/lib/Sema/SemaExpr.cpp", 5913, __extension__ __PRETTY_FUNCTION__ )); | ||||
5914 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||
5915 | return ExprError(); | ||||
5916 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||
5917 | } | ||||
5918 | |||||
5919 | Sema::VariadicCallType | ||||
5920 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||
5921 | Expr *Fn) { | ||||
5922 | if (Proto && Proto->isVariadic()) { | ||||
5923 | if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) | ||||
5924 | return VariadicConstructor; | ||||
5925 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||
5926 | return VariadicBlock; | ||||
5927 | else if (FDecl) { | ||||
5928 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
5929 | if (Method->isInstance()) | ||||
5930 | return VariadicMethod; | ||||
5931 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||
5932 | return VariadicMethod; | ||||
5933 | return VariadicFunction; | ||||
5934 | } | ||||
5935 | return VariadicDoesNotApply; | ||||
5936 | } | ||||
5937 | |||||
5938 | namespace { | ||||
5939 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||
5940 | public: | ||||
5941 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||
5942 | unsigned NumArgs, MemberExpr *ME) | ||||
5943 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||
5944 | FunctionName(FuncName) {} | ||||
5945 | |||||
5946 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
5947 | if (!candidate.getCorrectionSpecifier() || | ||||
5948 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||
5949 | return false; | ||||
5950 | } | ||||
5951 | |||||
5952 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||
5953 | } | ||||
5954 | |||||
5955 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
5956 | return std::make_unique<FunctionCallCCC>(*this); | ||||
5957 | } | ||||
5958 | |||||
5959 | private: | ||||
5960 | const IdentifierInfo *const FunctionName; | ||||
5961 | }; | ||||
5962 | } | ||||
5963 | |||||
5964 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||
5965 | FunctionDecl *FDecl, | ||||
5966 | ArrayRef<Expr *> Args) { | ||||
5967 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||
5968 | DeclarationName FuncName = FDecl->getDeclName(); | ||||
5969 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||
5970 | |||||
5971 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||
5972 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||
5973 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||
5974 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||
5975 | Sema::CTK_ErrorRecovery)) { | ||||
5976 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||
5977 | if (Corrected.isOverloaded()) { | ||||
5978 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||
5979 | OverloadCandidateSet::iterator Best; | ||||
5980 | for (NamedDecl *CD : Corrected) { | ||||
5981 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
5982 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||
5983 | OCS); | ||||
5984 | } | ||||
5985 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||
5986 | case OR_Success: | ||||
5987 | ND = Best->FoundDecl; | ||||
5988 | Corrected.setCorrectionDecl(ND); | ||||
5989 | break; | ||||
5990 | default: | ||||
5991 | break; | ||||
5992 | } | ||||
5993 | } | ||||
5994 | ND = ND->getUnderlyingDecl(); | ||||
5995 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||
5996 | return Corrected; | ||||
5997 | } | ||||
5998 | } | ||||
5999 | return TypoCorrection(); | ||||
6000 | } | ||||
6001 | |||||
6002 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||
6003 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||
6004 | /// function prototype Proto. Call is the call expression itself, and | ||||
6005 | /// Fn is the function expression. For a C++ member function, this | ||||
6006 | /// routine does not attempt to convert the object argument. Returns | ||||
6007 | /// true if the call is ill-formed. | ||||
6008 | bool | ||||
6009 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||
6010 | FunctionDecl *FDecl, | ||||
6011 | const FunctionProtoType *Proto, | ||||
6012 | ArrayRef<Expr *> Args, | ||||
6013 | SourceLocation RParenLoc, | ||||
6014 | bool IsExecConfig) { | ||||
6015 | // Bail out early if calling a builtin with custom typechecking. | ||||
6016 | if (FDecl) | ||||
6017 | if (unsigned ID = FDecl->getBuiltinID()) | ||||
6018 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||
6019 | return false; | ||||
6020 | |||||
6021 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||
6022 | // assignment, to the types of the corresponding parameter, ... | ||||
6023 | unsigned NumParams = Proto->getNumParams(); | ||||
6024 | bool Invalid = false; | ||||
6025 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||
6026 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||
6027 | ? 1 /* block */ | ||||
6028 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||
6029 | : 0 /* function */); | ||||
6030 | |||||
6031 | // If too few arguments are available (and we don't have default | ||||
6032 | // arguments for the remaining parameters), don't make the call. | ||||
6033 | if (Args.size() < NumParams) { | ||||
6034 | if (Args.size() < MinArgs) { | ||||
6035 | TypoCorrection TC; | ||||
6036 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
6037 | unsigned diag_id = | ||||
6038 | MinArgs == NumParams && !Proto->isVariadic() | ||||
6039 | ? diag::err_typecheck_call_too_few_args_suggest | ||||
6040 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||
6041 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||
6042 | << static_cast<unsigned>(Args.size()) | ||||
6043 | << TC.getCorrectionRange()); | ||||
6044 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||
6045 | Diag(RParenLoc, | ||||
6046 | MinArgs == NumParams && !Proto->isVariadic() | ||||
6047 | ? diag::err_typecheck_call_too_few_args_one | ||||
6048 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||
6049 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||
6050 | else | ||||
6051 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||
6052 | ? diag::err_typecheck_call_too_few_args | ||||
6053 | : diag::err_typecheck_call_too_few_args_at_least) | ||||
6054 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||
6055 | << Fn->getSourceRange(); | ||||
6056 | |||||
6057 | // Emit the location of the prototype. | ||||
6058 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
6059 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6060 | |||||
6061 | return true; | ||||
6062 | } | ||||
6063 | // We reserve space for the default arguments when we create | ||||
6064 | // the call expression, before calling ConvertArgumentsForCall. | ||||
6065 | assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "clang/lib/Sema/SemaExpr.cpp", 6066, __extension__ __PRETTY_FUNCTION__ )) | ||||
6066 | "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "clang/lib/Sema/SemaExpr.cpp", 6066, __extension__ __PRETTY_FUNCTION__ )); | ||||
6067 | } | ||||
6068 | |||||
6069 | // If too many are passed and not variadic, error on the extras and drop | ||||
6070 | // them. | ||||
6071 | if (Args.size() > NumParams) { | ||||
6072 | if (!Proto->isVariadic()) { | ||||
6073 | TypoCorrection TC; | ||||
6074 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
6075 | unsigned diag_id = | ||||
6076 | MinArgs == NumParams && !Proto->isVariadic() | ||||
6077 | ? diag::err_typecheck_call_too_many_args_suggest | ||||
6078 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||
6079 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||
6080 | << static_cast<unsigned>(Args.size()) | ||||
6081 | << TC.getCorrectionRange()); | ||||
6082 | } else if (NumParams == 1 && FDecl && | ||||
6083 | FDecl->getParamDecl(0)->getDeclName()) | ||||
6084 | Diag(Args[NumParams]->getBeginLoc(), | ||||
6085 | MinArgs == NumParams | ||||
6086 | ? diag::err_typecheck_call_too_many_args_one | ||||
6087 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||
6088 | << FnKind << FDecl->getParamDecl(0) | ||||
6089 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||
6090 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
6091 | Args.back()->getEndLoc()); | ||||
6092 | else | ||||
6093 | Diag(Args[NumParams]->getBeginLoc(), | ||||
6094 | MinArgs == NumParams | ||||
6095 | ? diag::err_typecheck_call_too_many_args | ||||
6096 | : diag::err_typecheck_call_too_many_args_at_most) | ||||
6097 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||
6098 | << Fn->getSourceRange() | ||||
6099 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
6100 | Args.back()->getEndLoc()); | ||||
6101 | |||||
6102 | // Emit the location of the prototype. | ||||
6103 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
6104 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6105 | |||||
6106 | // This deletes the extra arguments. | ||||
6107 | Call->shrinkNumArgs(NumParams); | ||||
6108 | return true; | ||||
6109 | } | ||||
6110 | } | ||||
6111 | SmallVector<Expr *, 8> AllArgs; | ||||
6112 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||
6113 | |||||
6114 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||
6115 | AllArgs, CallType); | ||||
6116 | if (Invalid) | ||||
6117 | return true; | ||||
6118 | unsigned TotalNumArgs = AllArgs.size(); | ||||
6119 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||
6120 | Call->setArg(i, AllArgs[i]); | ||||
6121 | |||||
6122 | Call->computeDependence(); | ||||
6123 | return false; | ||||
6124 | } | ||||
6125 | |||||
6126 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||
6127 | const FunctionProtoType *Proto, | ||||
6128 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||
6129 | SmallVectorImpl<Expr *> &AllArgs, | ||||
6130 | VariadicCallType CallType, bool AllowExplicit, | ||||
6131 | bool IsListInitialization) { | ||||
6132 | unsigned NumParams = Proto->getNumParams(); | ||||
6133 | bool Invalid = false; | ||||
6134 | size_t ArgIx = 0; | ||||
6135 | // Continue to check argument types (even if we have too few/many args). | ||||
6136 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||
6137 | QualType ProtoArgType = Proto->getParamType(i); | ||||
6138 | |||||
6139 | Expr *Arg; | ||||
6140 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||
6141 | if (ArgIx < Args.size()) { | ||||
6142 | Arg = Args[ArgIx++]; | ||||
6143 | |||||
6144 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||
6145 | diag::err_call_incomplete_argument, Arg)) | ||||
6146 | return true; | ||||
6147 | |||||
6148 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
6149 | bool CFAudited = false; | ||||
6150 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||
6151 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
6152 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
6153 | Arg = stripARCUnbridgedCast(Arg); | ||||
6154 | else if (getLangOpts().ObjCAutoRefCount && | ||||
6155 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
6156 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
6157 | CFAudited = true; | ||||
6158 | |||||
6159 | if (Proto->getExtParameterInfo(i).isNoEscape() && | ||||
6160 | ProtoArgType->isBlockPointerType()) | ||||
6161 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||
6162 | BE->getBlockDecl()->setDoesNotEscape(); | ||||
6163 | |||||
6164 | InitializedEntity Entity = | ||||
6165 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||
6166 | ProtoArgType) | ||||
6167 | : InitializedEntity::InitializeParameter( | ||||
6168 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||
6169 | |||||
6170 | // Remember that parameter belongs to a CF audited API. | ||||
6171 | if (CFAudited) | ||||
6172 | Entity.setParameterCFAudited(); | ||||
6173 | |||||
6174 | ExprResult ArgE = PerformCopyInitialization( | ||||
6175 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||
6176 | if (ArgE.isInvalid()) | ||||
6177 | return true; | ||||
6178 | |||||
6179 | Arg = ArgE.getAs<Expr>(); | ||||
6180 | } else { | ||||
6181 | assert(Param && "can't use default arguments without a known callee")(static_cast <bool> (Param && "can't use default arguments without a known callee" ) ? void (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "clang/lib/Sema/SemaExpr.cpp", 6181, __extension__ __PRETTY_FUNCTION__ )); | ||||
6182 | |||||
6183 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||
6184 | if (ArgExpr.isInvalid()) | ||||
6185 | return true; | ||||
6186 | |||||
6187 | Arg = ArgExpr.getAs<Expr>(); | ||||
6188 | } | ||||
6189 | |||||
6190 | // Check for array bounds violations for each argument to the call. This | ||||
6191 | // check only triggers warnings when the argument isn't a more complex Expr | ||||
6192 | // with its own checking, such as a BinaryOperator. | ||||
6193 | CheckArrayAccess(Arg); | ||||
6194 | |||||
6195 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||
6196 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||
6197 | |||||
6198 | AllArgs.push_back(Arg); | ||||
6199 | } | ||||
6200 | |||||
6201 | // If this is a variadic call, handle args passed through "...". | ||||
6202 | if (CallType != VariadicDoesNotApply) { | ||||
6203 | // Assume that extern "C" functions with variadic arguments that | ||||
6204 | // return __unknown_anytype aren't *really* variadic. | ||||
6205 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||
6206 | FDecl->isExternC()) { | ||||
6207 | for (Expr *A : Args.slice(ArgIx)) { | ||||
6208 | QualType paramType; // ignored | ||||
6209 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | ||||
6210 | Invalid |= arg.isInvalid(); | ||||
6211 | AllArgs.push_back(arg.get()); | ||||
6212 | } | ||||
6213 | |||||
6214 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | ||||
6215 | } else { | ||||
6216 | for (Expr *A : Args.slice(ArgIx)) { | ||||
6217 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | ||||
6218 | Invalid |= Arg.isInvalid(); | ||||
6219 | AllArgs.push_back(Arg.get()); | ||||
6220 | } | ||||
6221 | } | ||||
6222 | |||||
6223 | // Check for array bounds violations. | ||||
6224 | for (Expr *A : Args.slice(ArgIx)) | ||||
6225 | CheckArrayAccess(A); | ||||
6226 | } | ||||
6227 | return Invalid; | ||||
6228 | } | ||||
6229 | |||||
6230 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | ||||
6231 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | ||||
6232 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | ||||
6233 | TL = DTL.getOriginalLoc(); | ||||
6234 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | ||||
6235 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | ||||
6236 | << ATL.getLocalSourceRange(); | ||||
6237 | } | ||||
6238 | |||||
6239 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | ||||
6240 | /// array parameter, check that it is non-null, and that if it is formed by | ||||
6241 | /// array-to-pointer decay, the underlying array is sufficiently large. | ||||
6242 | /// | ||||
6243 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | ||||
6244 | /// array type derivation, then for each call to the function, the value of the | ||||
6245 | /// corresponding actual argument shall provide access to the first element of | ||||
6246 | /// an array with at least as many elements as specified by the size expression. | ||||
6247 | void | ||||
6248 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | ||||
6249 | ParmVarDecl *Param, | ||||
6250 | const Expr *ArgExpr) { | ||||
6251 | // Static array parameters are not supported in C++. | ||||
6252 | if (!Param || getLangOpts().CPlusPlus) | ||||
6253 | return; | ||||
6254 | |||||
6255 | QualType OrigTy = Param->getOriginalType(); | ||||
6256 | |||||
6257 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | ||||
6258 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | ||||
6259 | return; | ||||
6260 | |||||
6261 | if (ArgExpr->isNullPointerConstant(Context, | ||||
6262 | Expr::NPC_NeverValueDependent)) { | ||||
6263 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | ||||
6264 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6265 | return; | ||||
6266 | } | ||||
6267 | |||||
6268 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | ||||
6269 | if (!CAT) | ||||
6270 | return; | ||||
6271 | |||||
6272 | const ConstantArrayType *ArgCAT = | ||||
6273 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | ||||
6274 | if (!ArgCAT) | ||||
6275 | return; | ||||
6276 | |||||
6277 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | ||||
6278 | ArgCAT->getElementType())) { | ||||
6279 | if (ArgCAT->getSize().ult(CAT->getSize())) { | ||||
6280 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6281 | << ArgExpr->getSourceRange() | ||||
6282 | << (unsigned)ArgCAT->getSize().getZExtValue() | ||||
6283 | << (unsigned)CAT->getSize().getZExtValue() << 0; | ||||
6284 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6285 | } | ||||
6286 | return; | ||||
6287 | } | ||||
6288 | |||||
6289 | Optional<CharUnits> ArgSize = | ||||
6290 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | ||||
6291 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | ||||
6292 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | ||||
6293 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6294 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | ||||
6295 | << (unsigned)ParmSize->getQuantity() << 1; | ||||
6296 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6297 | } | ||||
6298 | } | ||||
6299 | |||||
6300 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
6301 | /// to have a function type. | ||||
6302 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | ||||
6303 | |||||
6304 | /// Is the given type a placeholder that we need to lower out | ||||
6305 | /// immediately during argument processing? | ||||
6306 | static bool isPlaceholderToRemoveAsArg(QualType type) { | ||||
6307 | // Placeholders are never sugared. | ||||
6308 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | ||||
6309 | if (!placeholder) return false; | ||||
6310 | |||||
6311 | switch (placeholder->getKind()) { | ||||
6312 | // Ignore all the non-placeholder types. | ||||
6313 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
6314 | case BuiltinType::Id: | ||||
6315 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
6316 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
6317 | case BuiltinType::Id: | ||||
6318 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
6319 | // In practice we'll never use this, since all SVE types are sugared | ||||
6320 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | ||||
6321 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
6322 | case BuiltinType::Id: | ||||
6323 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
6324 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
6325 | case BuiltinType::Id: | ||||
6326 | #include "clang/Basic/PPCTypes.def" | ||||
6327 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
6328 | #include "clang/Basic/RISCVVTypes.def" | ||||
6329 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | ||||
6330 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | ||||
6331 | #include "clang/AST/BuiltinTypes.def" | ||||
6332 | return false; | ||||
6333 | |||||
6334 | // We cannot lower out overload sets; they might validly be resolved | ||||
6335 | // by the call machinery. | ||||
6336 | case BuiltinType::Overload: | ||||
6337 | return false; | ||||
6338 | |||||
6339 | // Unbridged casts in ARC can be handled in some call positions and | ||||
6340 | // should be left in place. | ||||
6341 | case BuiltinType::ARCUnbridgedCast: | ||||
6342 | return false; | ||||
6343 | |||||
6344 | // Pseudo-objects should be converted as soon as possible. | ||||
6345 | case BuiltinType::PseudoObject: | ||||
6346 | return true; | ||||
6347 | |||||
6348 | // The debugger mode could theoretically but currently does not try | ||||
6349 | // to resolve unknown-typed arguments based on known parameter types. | ||||
6350 | case BuiltinType::UnknownAny: | ||||
6351 | return true; | ||||
6352 | |||||
6353 | // These are always invalid as call arguments and should be reported. | ||||
6354 | case BuiltinType::BoundMember: | ||||
6355 | case BuiltinType::BuiltinFn: | ||||
6356 | case BuiltinType::IncompleteMatrixIdx: | ||||
6357 | case BuiltinType::OMPArraySection: | ||||
6358 | case BuiltinType::OMPArrayShaping: | ||||
6359 | case BuiltinType::OMPIterator: | ||||
6360 | return true; | ||||
6361 | |||||
6362 | } | ||||
6363 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "clang/lib/Sema/SemaExpr.cpp" , 6363); | ||||
6364 | } | ||||
6365 | |||||
6366 | /// Check an argument list for placeholders that we won't try to | ||||
6367 | /// handle later. | ||||
6368 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | ||||
6369 | // Apply this processing to all the arguments at once instead of | ||||
6370 | // dying at the first failure. | ||||
6371 | bool hasInvalid = false; | ||||
6372 | for (size_t i = 0, e = args.size(); i != e; i++) { | ||||
6373 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | ||||
6374 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | ||||
6375 | if (result.isInvalid()) hasInvalid = true; | ||||
6376 | else args[i] = result.get(); | ||||
6377 | } | ||||
6378 | } | ||||
6379 | return hasInvalid; | ||||
6380 | } | ||||
6381 | |||||
6382 | /// If a builtin function has a pointer argument with no explicit address | ||||
6383 | /// space, then it should be able to accept a pointer to any address | ||||
6384 | /// space as input. In order to do this, we need to replace the | ||||
6385 | /// standard builtin declaration with one that uses the same address space | ||||
6386 | /// as the call. | ||||
6387 | /// | ||||
6388 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | ||||
6389 | /// it does not contain any pointer arguments without | ||||
6390 | /// an address space qualifer. Otherwise the rewritten | ||||
6391 | /// FunctionDecl is returned. | ||||
6392 | /// TODO: Handle pointer return types. | ||||
6393 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | ||||
6394 | FunctionDecl *FDecl, | ||||
6395 | MultiExprArg ArgExprs) { | ||||
6396 | |||||
6397 | QualType DeclType = FDecl->getType(); | ||||
6398 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | ||||
6399 | |||||
6400 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | ||||
6401 | ArgExprs.size() < FT->getNumParams()) | ||||
6402 | return nullptr; | ||||
6403 | |||||
6404 | bool NeedsNewDecl = false; | ||||
6405 | unsigned i = 0; | ||||
6406 | SmallVector<QualType, 8> OverloadParams; | ||||
6407 | |||||
6408 | for (QualType ParamType : FT->param_types()) { | ||||
6409 | |||||
6410 | // Convert array arguments to pointer to simplify type lookup. | ||||
6411 | ExprResult ArgRes = | ||||
6412 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | ||||
6413 | if (ArgRes.isInvalid()) | ||||
6414 | return nullptr; | ||||
6415 | Expr *Arg = ArgRes.get(); | ||||
6416 | QualType ArgType = Arg->getType(); | ||||
6417 | if (!ParamType->isPointerType() || | ||||
6418 | ParamType.hasAddressSpace() || | ||||
6419 | !ArgType->isPointerType() || | ||||
6420 | !ArgType->getPointeeType().hasAddressSpace()) { | ||||
6421 | OverloadParams.push_back(ParamType); | ||||
6422 | continue; | ||||
6423 | } | ||||
6424 | |||||
6425 | QualType PointeeType = ParamType->getPointeeType(); | ||||
6426 | if (PointeeType.hasAddressSpace()) | ||||
6427 | continue; | ||||
6428 | |||||
6429 | NeedsNewDecl = true; | ||||
6430 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | ||||
6431 | |||||
6432 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | ||||
6433 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | ||||
6434 | } | ||||
6435 | |||||
6436 | if (!NeedsNewDecl) | ||||
6437 | return nullptr; | ||||
6438 | |||||
6439 | FunctionProtoType::ExtProtoInfo EPI; | ||||
6440 | EPI.Variadic = FT->isVariadic(); | ||||
6441 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | ||||
6442 | OverloadParams, EPI); | ||||
6443 | DeclContext *Parent = FDecl->getParent(); | ||||
6444 | FunctionDecl *OverloadDecl = FunctionDecl::Create( | ||||
6445 | Context, Parent, FDecl->getLocation(), FDecl->getLocation(), | ||||
6446 | FDecl->getIdentifier(), OverloadTy, | ||||
6447 | /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), | ||||
6448 | false, | ||||
6449 | /*hasPrototype=*/true); | ||||
6450 | SmallVector<ParmVarDecl*, 16> Params; | ||||
6451 | FT = cast<FunctionProtoType>(OverloadTy); | ||||
6452 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
6453 | QualType ParamType = FT->getParamType(i); | ||||
6454 | ParmVarDecl *Parm = | ||||
6455 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | ||||
6456 | SourceLocation(), nullptr, ParamType, | ||||
6457 | /*TInfo=*/nullptr, SC_None, nullptr); | ||||
6458 | Parm->setScopeInfo(0, i); | ||||
6459 | Params.push_back(Parm); | ||||
6460 | } | ||||
6461 | OverloadDecl->setParams(Params); | ||||
6462 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | ||||
6463 | return OverloadDecl; | ||||
6464 | } | ||||
6465 | |||||
6466 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | ||||
6467 | FunctionDecl *Callee, | ||||
6468 | MultiExprArg ArgExprs) { | ||||
6469 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | ||||
6470 | // similar attributes) really don't like it when functions are called with an | ||||
6471 | // invalid number of args. | ||||
6472 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | ||||
6473 | /*PartialOverloading=*/false) && | ||||
6474 | !Callee->isVariadic()) | ||||
6475 | return; | ||||
6476 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | ||||
6477 | return; | ||||
6478 | |||||
6479 | if (const EnableIfAttr *Attr = | ||||
6480 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | ||||
6481 | S.Diag(Fn->getBeginLoc(), | ||||
6482 | isa<CXXMethodDecl>(Callee) | ||||
6483 | ? diag::err_ovl_no_viable_member_function_in_call | ||||
6484 | : diag::err_ovl_no_viable_function_in_call) | ||||
6485 | << Callee << Callee->getSourceRange(); | ||||
6486 | S.Diag(Callee->getLocation(), | ||||
6487 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | ||||
6488 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | ||||
6489 | return; | ||||
6490 | } | ||||
6491 | } | ||||
6492 | |||||
6493 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | ||||
6494 | const UnresolvedMemberExpr *const UME, Sema &S) { | ||||
6495 | |||||
6496 | const auto GetFunctionLevelDCIfCXXClass = | ||||
6497 | [](Sema &S) -> const CXXRecordDecl * { | ||||
6498 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | ||||
6499 | if (!DC || !DC->getParent()) | ||||
6500 | return nullptr; | ||||
6501 | |||||
6502 | // If the call to some member function was made from within a member | ||||
6503 | // function body 'M' return return 'M's parent. | ||||
6504 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
6505 | return MD->getParent()->getCanonicalDecl(); | ||||
6506 | // else the call was made from within a default member initializer of a | ||||
6507 | // class, so return the class. | ||||
6508 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
6509 | return RD->getCanonicalDecl(); | ||||
6510 | return nullptr; | ||||
6511 | }; | ||||
6512 | // If our DeclContext is neither a member function nor a class (in the | ||||
6513 | // case of a lambda in a default member initializer), we can't have an | ||||
6514 | // enclosing 'this'. | ||||
6515 | |||||
6516 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | ||||
6517 | if (!CurParentClass) | ||||
6518 | return false; | ||||
6519 | |||||
6520 | // The naming class for implicit member functions call is the class in which | ||||
6521 | // name lookup starts. | ||||
6522 | const CXXRecordDecl *const NamingClass = | ||||
6523 | UME->getNamingClass()->getCanonicalDecl(); | ||||
6524 | assert(NamingClass && "Must have naming class even for implicit access")(static_cast <bool> (NamingClass && "Must have naming class even for implicit access" ) ? void (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "clang/lib/Sema/SemaExpr.cpp", 6524, __extension__ __PRETTY_FUNCTION__ )); | ||||
6525 | |||||
6526 | // If the unresolved member functions were found in a 'naming class' that is | ||||
6527 | // related (either the same or derived from) to the class that contains the | ||||
6528 | // member function that itself contained the implicit member access. | ||||
6529 | |||||
6530 | return CurParentClass == NamingClass || | ||||
6531 | CurParentClass->isDerivedFrom(NamingClass); | ||||
6532 | } | ||||
6533 | |||||
6534 | static void | ||||
6535 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6536 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | ||||
6537 | |||||
6538 | if (!UME) | ||||
6539 | return; | ||||
6540 | |||||
6541 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | ||||
6542 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | ||||
6543 | // already been captured, or if this is an implicit member function call (if | ||||
6544 | // it isn't, an attempt to capture 'this' should already have been made). | ||||
6545 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | ||||
6546 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | ||||
6547 | return; | ||||
6548 | |||||
6549 | // Check if the naming class in which the unresolved members were found is | ||||
6550 | // related (same as or is a base of) to the enclosing class. | ||||
6551 | |||||
6552 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | ||||
6553 | return; | ||||
6554 | |||||
6555 | |||||
6556 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | ||||
6557 | // If the enclosing function is not dependent, then this lambda is | ||||
6558 | // capture ready, so if we can capture this, do so. | ||||
6559 | if (!EnclosingFunctionCtx->isDependentContext()) { | ||||
6560 | // If the current lambda and all enclosing lambdas can capture 'this' - | ||||
6561 | // then go ahead and capture 'this' (since our unresolved overload set | ||||
6562 | // contains at least one non-static member function). | ||||
6563 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | ||||
6564 | S.CheckCXXThisCapture(CallLoc); | ||||
6565 | } else if (S.CurContext->isDependentContext()) { | ||||
6566 | // ... since this is an implicit member reference, that might potentially | ||||
6567 | // involve a 'this' capture, mark 'this' for potential capture in | ||||
6568 | // enclosing lambdas. | ||||
6569 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | ||||
6570 | CurLSI->addPotentialThisCapture(CallLoc); | ||||
6571 | } | ||||
6572 | } | ||||
6573 | |||||
6574 | // Once a call is fully resolved, warn for unqualified calls to specific | ||||
6575 | // C++ standard functions, like move and forward. | ||||
6576 | static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { | ||||
6577 | // We are only checking unary move and forward so exit early here. | ||||
6578 | if (Call->getNumArgs() != 1) | ||||
6579 | return; | ||||
6580 | |||||
6581 | Expr *E = Call->getCallee()->IgnoreParenImpCasts(); | ||||
6582 | if (!E || isa<UnresolvedLookupExpr>(E)) | ||||
6583 | return; | ||||
6584 | DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); | ||||
6585 | if (!DRE || !DRE->getLocation().isValid()) | ||||
6586 | return; | ||||
6587 | |||||
6588 | if (DRE->getQualifier()) | ||||
6589 | return; | ||||
6590 | |||||
6591 | const FunctionDecl *FD = Call->getDirectCallee(); | ||||
6592 | if (!FD) | ||||
6593 | return; | ||||
6594 | |||||
6595 | // Only warn for some functions deemed more frequent or problematic. | ||||
6596 | unsigned BuiltinID = FD->getBuiltinID(); | ||||
6597 | if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) | ||||
6598 | return; | ||||
6599 | |||||
6600 | S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) | ||||
6601 | << FD->getQualifiedNameAsString() | ||||
6602 | << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); | ||||
6603 | } | ||||
6604 | |||||
6605 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6606 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6607 | Expr *ExecConfig) { | ||||
6608 | ExprResult Call = | ||||
6609 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6610 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); | ||||
6611 | if (Call.isInvalid()) | ||||
6612 | return Call; | ||||
6613 | |||||
6614 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | ||||
6615 | // language modes. | ||||
6616 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | ||||
6617 | if (ULE->hasExplicitTemplateArgs() && | ||||
6618 | ULE->decls_begin() == ULE->decls_end()) { | ||||
6619 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | ||||
6620 | ? diag::warn_cxx17_compat_adl_only_template_id | ||||
6621 | : diag::ext_adl_only_template_id) | ||||
6622 | << ULE->getName(); | ||||
6623 | } | ||||
6624 | } | ||||
6625 | |||||
6626 | if (LangOpts.OpenMP) | ||||
6627 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | ||||
6628 | ExecConfig); | ||||
6629 | if (LangOpts.CPlusPlus) { | ||||
6630 | CallExpr *CE = dyn_cast<CallExpr>(Call.get()); | ||||
6631 | if (CE) | ||||
6632 | DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); | ||||
6633 | } | ||||
6634 | return Call; | ||||
6635 | } | ||||
6636 | |||||
6637 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | ||||
6638 | /// This provides the location of the left/right parens and a list of comma | ||||
6639 | /// locations. | ||||
6640 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6641 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6642 | Expr *ExecConfig, bool IsExecConfig, | ||||
6643 | bool AllowRecovery) { | ||||
6644 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
6645 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | ||||
6646 | if (Result.isInvalid()) return ExprError(); | ||||
6647 | Fn = Result.get(); | ||||
6648 | |||||
6649 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
6650 | return ExprError(); | ||||
6651 | |||||
6652 | if (getLangOpts().CPlusPlus) { | ||||
6653 | // If this is a pseudo-destructor expression, build the call immediately. | ||||
6654 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | ||||
6655 | if (!ArgExprs.empty()) { | ||||
6656 | // Pseudo-destructor calls should not have any arguments. | ||||
6657 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | ||||
6658 | << FixItHint::CreateRemoval( | ||||
6659 | SourceRange(ArgExprs.front()->getBeginLoc(), | ||||
6660 | ArgExprs.back()->getEndLoc())); | ||||
6661 | } | ||||
6662 | |||||
6663 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | ||||
6664 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6665 | } | ||||
6666 | if (Fn->getType() == Context.PseudoObjectTy) { | ||||
6667 | ExprResult result = CheckPlaceholderExpr(Fn); | ||||
6668 | if (result.isInvalid()) return ExprError(); | ||||
6669 | Fn = result.get(); | ||||
6670 | } | ||||
6671 | |||||
6672 | // Determine whether this is a dependent call inside a C++ template, | ||||
6673 | // in which case we won't do any semantic analysis now. | ||||
6674 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | ||||
6675 | if (ExecConfig) { | ||||
6676 | return CUDAKernelCallExpr::Create(Context, Fn, | ||||
6677 | cast<CallExpr>(ExecConfig), ArgExprs, | ||||
6678 | Context.DependentTy, VK_PRValue, | ||||
6679 | RParenLoc, CurFPFeatureOverrides()); | ||||
6680 | } else { | ||||
6681 | |||||
6682 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6683 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | ||||
6684 | Fn->getBeginLoc()); | ||||
6685 | |||||
6686 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6687 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6688 | } | ||||
6689 | } | ||||
6690 | |||||
6691 | // Determine whether this is a call to an object (C++ [over.call.object]). | ||||
6692 | if (Fn->getType()->isRecordType()) | ||||
6693 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | ||||
6694 | RParenLoc); | ||||
6695 | |||||
6696 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6697 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6698 | if (result.isInvalid()) return ExprError(); | ||||
6699 | Fn = result.get(); | ||||
6700 | } | ||||
6701 | |||||
6702 | if (Fn->getType() == Context.BoundMemberTy) { | ||||
6703 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6704 | RParenLoc, ExecConfig, IsExecConfig, | ||||
6705 | AllowRecovery); | ||||
6706 | } | ||||
6707 | } | ||||
6708 | |||||
6709 | // Check for overloaded calls. This can happen even in C due to extensions. | ||||
6710 | if (Fn->getType() == Context.OverloadTy) { | ||||
6711 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | ||||
6712 | |||||
6713 | // We aren't supposed to apply this logic if there's an '&' involved. | ||||
6714 | if (!find.HasFormOfMemberPointer) { | ||||
6715 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | ||||
6716 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6717 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6718 | OverloadExpr *ovl = find.Expression; | ||||
6719 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | ||||
6720 | return BuildOverloadedCallExpr( | ||||
6721 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6722 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | ||||
6723 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6724 | RParenLoc, ExecConfig, IsExecConfig, | ||||
6725 | AllowRecovery); | ||||
6726 | } | ||||
6727 | } | ||||
6728 | |||||
6729 | // If we're directly calling a function, get the appropriate declaration. | ||||
6730 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6731 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6732 | if (result.isInvalid()) return ExprError(); | ||||
6733 | Fn = result.get(); | ||||
6734 | } | ||||
6735 | |||||
6736 | Expr *NakedFn = Fn->IgnoreParens(); | ||||
6737 | |||||
6738 | bool CallingNDeclIndirectly = false; | ||||
6739 | NamedDecl *NDecl = nullptr; | ||||
6740 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | ||||
6741 | if (UnOp->getOpcode() == UO_AddrOf) { | ||||
6742 | CallingNDeclIndirectly = true; | ||||
6743 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | ||||
6744 | } | ||||
6745 | } | ||||
6746 | |||||
6747 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | ||||
6748 | NDecl = DRE->getDecl(); | ||||
6749 | |||||
6750 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | ||||
6751 | if (FDecl && FDecl->getBuiltinID()) { | ||||
6752 | // Rewrite the function decl for this builtin by replacing parameters | ||||
6753 | // with no explicit address space with the address space of the arguments | ||||
6754 | // in ArgExprs. | ||||
6755 | if ((FDecl = | ||||
6756 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | ||||
6757 | NDecl = FDecl; | ||||
6758 | Fn = DeclRefExpr::Create( | ||||
6759 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | ||||
6760 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | ||||
6761 | nullptr, DRE->isNonOdrUse()); | ||||
6762 | } | ||||
6763 | } | ||||
6764 | } else if (isa<MemberExpr>(NakedFn)) | ||||
6765 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | ||||
6766 | |||||
6767 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | ||||
6768 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | ||||
6769 | FD, /*Complain=*/true, Fn->getBeginLoc())) | ||||
6770 | return ExprError(); | ||||
6771 | |||||
6772 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | ||||
6773 | |||||
6774 | // If this expression is a call to a builtin function in HIP device | ||||
6775 | // compilation, allow a pointer-type argument to default address space to be | ||||
6776 | // passed as a pointer-type parameter to a non-default address space. | ||||
6777 | // If Arg is declared in the default address space and Param is declared | ||||
6778 | // in a non-default address space, perform an implicit address space cast to | ||||
6779 | // the parameter type. | ||||
6780 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && | ||||
6781 | FD->getBuiltinID()) { | ||||
6782 | for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { | ||||
6783 | ParmVarDecl *Param = FD->getParamDecl(Idx); | ||||
6784 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || | ||||
6785 | !ArgExprs[Idx]->getType()->isPointerType()) | ||||
6786 | continue; | ||||
6787 | |||||
6788 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); | ||||
6789 | auto ArgTy = ArgExprs[Idx]->getType(); | ||||
6790 | auto ArgPtTy = ArgTy->getPointeeType(); | ||||
6791 | auto ArgAS = ArgPtTy.getAddressSpace(); | ||||
6792 | |||||
6793 | // Add address space cast if target address spaces are different | ||||
6794 | bool NeedImplicitASC = | ||||
6795 | ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. | ||||
6796 | ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS | ||||
6797 | // or from specific AS which has target AS matching that of Param. | ||||
6798 | getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); | ||||
6799 | if (!NeedImplicitASC) | ||||
6800 | continue; | ||||
6801 | |||||
6802 | // First, ensure that the Arg is an RValue. | ||||
6803 | if (ArgExprs[Idx]->isGLValue()) { | ||||
6804 | ArgExprs[Idx] = ImplicitCastExpr::Create( | ||||
6805 | Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], | ||||
6806 | nullptr, VK_PRValue, FPOptionsOverride()); | ||||
6807 | } | ||||
6808 | |||||
6809 | // Construct a new arg type with address space of Param | ||||
6810 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); | ||||
6811 | ArgPtQuals.setAddressSpace(ParamAS); | ||||
6812 | auto NewArgPtTy = | ||||
6813 | Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); | ||||
6814 | auto NewArgTy = | ||||
6815 | Context.getQualifiedType(Context.getPointerType(NewArgPtTy), | ||||
6816 | ArgTy.getQualifiers()); | ||||
6817 | |||||
6818 | // Finally perform an implicit address space cast | ||||
6819 | ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, | ||||
6820 | CK_AddressSpaceConversion) | ||||
6821 | .get(); | ||||
6822 | } | ||||
6823 | } | ||||
6824 | } | ||||
6825 | |||||
6826 | if (Context.isDependenceAllowed() && | ||||
6827 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
6828 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 6828, __extension__ __PRETTY_FUNCTION__)); | ||||
6829 | assert((Fn->containsErrors() ||(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6832, __extension__ __PRETTY_FUNCTION__ )) | ||||
6830 | llvm::any_of(ArgExprs,(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6832, __extension__ __PRETTY_FUNCTION__ )) | ||||
6831 | [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6832, __extension__ __PRETTY_FUNCTION__ )) | ||||
6832 | "should only occur in error-recovery path.")(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 6832, __extension__ __PRETTY_FUNCTION__ )); | ||||
6833 | QualType ReturnType = | ||||
6834 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | ||||
6835 | ? cast<FunctionDecl>(NDecl)->getCallResultType() | ||||
6836 | : Context.DependentTy; | ||||
6837 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | ||||
6838 | Expr::getValueKindForType(ReturnType), RParenLoc, | ||||
6839 | CurFPFeatureOverrides()); | ||||
6840 | } | ||||
6841 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | ||||
6842 | ExecConfig, IsExecConfig); | ||||
6843 | } | ||||
6844 | |||||
6845 | /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id | ||||
6846 | // with the specified CallArgs | ||||
6847 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, | ||||
6848 | MultiExprArg CallArgs) { | ||||
6849 | StringRef Name = Context.BuiltinInfo.getName(Id); | ||||
6850 | LookupResult R(*this, &Context.Idents.get(Name), Loc, | ||||
6851 | Sema::LookupOrdinaryName); | ||||
6852 | LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); | ||||
6853 | |||||
6854 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); | ||||
6855 | assert(BuiltInDecl && "failed to find builtin declaration")(static_cast <bool> (BuiltInDecl && "failed to find builtin declaration" ) ? void (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\"" , "clang/lib/Sema/SemaExpr.cpp", 6855, __extension__ __PRETTY_FUNCTION__ )); | ||||
6856 | |||||
6857 | ExprResult DeclRef = | ||||
6858 | BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); | ||||
6859 | assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (DeclRef.isUsable() && "Builtin reference cannot fail" ) ? void (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\"" , "clang/lib/Sema/SemaExpr.cpp", 6859, __extension__ __PRETTY_FUNCTION__ )); | ||||
6860 | |||||
6861 | ExprResult Call = | ||||
6862 | BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); | ||||
6863 | |||||
6864 | assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to builtin cannot fail!" ) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\"" , "clang/lib/Sema/SemaExpr.cpp", 6864, __extension__ __PRETTY_FUNCTION__ )); | ||||
6865 | return Call.get(); | ||||
6866 | } | ||||
6867 | |||||
6868 | /// Parse a __builtin_astype expression. | ||||
6869 | /// | ||||
6870 | /// __builtin_astype( value, dst type ) | ||||
6871 | /// | ||||
6872 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6873 | SourceLocation BuiltinLoc, | ||||
6874 | SourceLocation RParenLoc) { | ||||
6875 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | ||||
6876 | return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); | ||||
6877 | } | ||||
6878 | |||||
6879 | /// Create a new AsTypeExpr node (bitcast) from the arguments. | ||||
6880 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, | ||||
6881 | SourceLocation BuiltinLoc, | ||||
6882 | SourceLocation RParenLoc) { | ||||
6883 | ExprValueKind VK = VK_PRValue; | ||||
6884 | ExprObjectKind OK = OK_Ordinary; | ||||
6885 | QualType SrcTy = E->getType(); | ||||
6886 | if (!SrcTy->isDependentType() && | ||||
6887 | Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) | ||||
6888 | return ExprError( | ||||
6889 | Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) | ||||
6890 | << DestTy << SrcTy << E->getSourceRange()); | ||||
6891 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); | ||||
6892 | } | ||||
6893 | |||||
6894 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | ||||
6895 | /// provided arguments. | ||||
6896 | /// | ||||
6897 | /// __builtin_convertvector( value, dst type ) | ||||
6898 | /// | ||||
6899 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6900 | SourceLocation BuiltinLoc, | ||||
6901 | SourceLocation RParenLoc) { | ||||
6902 | TypeSourceInfo *TInfo; | ||||
6903 | GetTypeFromParser(ParsedDestTy, &TInfo); | ||||
6904 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | ||||
6905 | } | ||||
6906 | |||||
6907 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | ||||
6908 | /// i.e. an expression not of \p OverloadTy. The expression should | ||||
6909 | /// unary-convert to an expression of function-pointer or | ||||
6910 | /// block-pointer type. | ||||
6911 | /// | ||||
6912 | /// \param NDecl the declaration being called, if available | ||||
6913 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | ||||
6914 | SourceLocation LParenLoc, | ||||
6915 | ArrayRef<Expr *> Args, | ||||
6916 | SourceLocation RParenLoc, Expr *Config, | ||||
6917 | bool IsExecConfig, ADLCallKind UsesADL) { | ||||
6918 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | ||||
6919 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | ||||
6920 | |||||
6921 | // Functions with 'interrupt' attribute cannot be called directly. | ||||
6922 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | ||||
6923 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | ||||
6924 | return ExprError(); | ||||
6925 | } | ||||
6926 | |||||
6927 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | ||||
6928 | // so there's some risk when calling out to non-interrupt handler functions | ||||
6929 | // that the callee might not preserve them. This is easy to diagnose here, | ||||
6930 | // but can be very challenging to debug. | ||||
6931 | // Likewise, X86 interrupt handlers may only call routines with attribute | ||||
6932 | // no_caller_saved_registers since there is no efficient way to | ||||
6933 | // save and restore the non-GPR state. | ||||
6934 | if (auto *Caller = getCurFunctionDecl()) { | ||||
6935 | if (Caller->hasAttr<ARMInterruptAttr>()) { | ||||
6936 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | ||||
6937 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { | ||||
6938 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | ||||
6939 | if (FDecl) | ||||
6940 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6941 | } | ||||
6942 | } | ||||
6943 | if (Caller->hasAttr<AnyX86InterruptAttr>() && | ||||
6944 | ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { | ||||
6945 | Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); | ||||
6946 | if (FDecl) | ||||
6947 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6948 | } | ||||
6949 | } | ||||
6950 | |||||
6951 | // Promote the function operand. | ||||
6952 | // We special-case function promotion here because we only allow promoting | ||||
6953 | // builtin functions to function pointers in the callee of a call. | ||||
6954 | ExprResult Result; | ||||
6955 | QualType ResultTy; | ||||
6956 | if (BuiltinID && | ||||
6957 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | ||||
6958 | // Extract the return type from the (builtin) function pointer type. | ||||
6959 | // FIXME Several builtins still have setType in | ||||
6960 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | ||||
6961 | // Builtins.def to ensure they are correct before removing setType calls. | ||||
6962 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | ||||
6963 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | ||||
6964 | ResultTy = FDecl->getCallResultType(); | ||||
6965 | } else { | ||||
6966 | Result = CallExprUnaryConversions(Fn); | ||||
6967 | ResultTy = Context.BoolTy; | ||||
6968 | } | ||||
6969 | if (Result.isInvalid()) | ||||
6970 | return ExprError(); | ||||
6971 | Fn = Result.get(); | ||||
6972 | |||||
6973 | // Check for a valid function type, but only if it is not a builtin which | ||||
6974 | // requires custom type checking. These will be handled by | ||||
6975 | // CheckBuiltinFunctionCall below just after creation of the call expression. | ||||
6976 | const FunctionType *FuncT = nullptr; | ||||
6977 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | ||||
6978 | retry: | ||||
6979 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | ||||
6980 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | ||||
6981 | // have type pointer to function". | ||||
6982 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | ||||
6983 | if (!FuncT) | ||||
6984 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6985 | << Fn->getType() << Fn->getSourceRange()); | ||||
6986 | } else if (const BlockPointerType *BPT = | ||||
6987 | Fn->getType()->getAs<BlockPointerType>()) { | ||||
6988 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | ||||
6989 | } else { | ||||
6990 | // Handle calls to expressions of unknown-any type. | ||||
6991 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6992 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | ||||
6993 | if (rewrite.isInvalid()) | ||||
6994 | return ExprError(); | ||||
6995 | Fn = rewrite.get(); | ||||
6996 | goto retry; | ||||
6997 | } | ||||
6998 | |||||
6999 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
7000 | << Fn->getType() << Fn->getSourceRange()); | ||||
7001 | } | ||||
7002 | } | ||||
7003 | |||||
7004 | // Get the number of parameters in the function prototype, if any. | ||||
7005 | // We will allocate space for max(Args.size(), NumParams) arguments | ||||
7006 | // in the call expression. | ||||
7007 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | ||||
7008 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; | ||||
7009 | |||||
7010 | CallExpr *TheCall; | ||||
7011 | if (Config) { | ||||
7012 | assert(UsesADL == ADLCallKind::NotADL &&(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "clang/lib/Sema/SemaExpr.cpp", 7013, __extension__ __PRETTY_FUNCTION__ )) | ||||
7013 | "CUDAKernelCallExpr should not use ADL")(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "clang/lib/Sema/SemaExpr.cpp", 7013, __extension__ __PRETTY_FUNCTION__ )); | ||||
7014 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | ||||
7015 | Args, ResultTy, VK_PRValue, RParenLoc, | ||||
7016 | CurFPFeatureOverrides(), NumParams); | ||||
7017 | } else { | ||||
7018 | TheCall = | ||||
7019 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | ||||
7020 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
7021 | } | ||||
7022 | |||||
7023 | if (!Context.isDependenceAllowed()) { | ||||
7024 | // Forget about the nulled arguments since typo correction | ||||
7025 | // do not handle them well. | ||||
7026 | TheCall->shrinkNumArgs(Args.size()); | ||||
7027 | // C cannot always handle TypoExpr nodes in builtin calls and direct | ||||
7028 | // function calls as their argument checking don't necessarily handle | ||||
7029 | // dependent types properly, so make sure any TypoExprs have been | ||||
7030 | // dealt with. | ||||
7031 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | ||||
7032 | if (!Result.isUsable()) return ExprError(); | ||||
7033 | CallExpr *TheOldCall = TheCall; | ||||
7034 | TheCall = dyn_cast<CallExpr>(Result.get()); | ||||
7035 | bool CorrectedTypos = TheCall != TheOldCall; | ||||
7036 | if (!TheCall) return Result; | ||||
7037 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | ||||
7038 | |||||
7039 | // A new call expression node was created if some typos were corrected. | ||||
7040 | // However it may not have been constructed with enough storage. In this | ||||
7041 | // case, rebuild the node with enough storage. The waste of space is | ||||
7042 | // immaterial since this only happens when some typos were corrected. | ||||
7043 | if (CorrectedTypos && Args.size() < NumParams) { | ||||
7044 | if (Config) | ||||
7045 | TheCall = CUDAKernelCallExpr::Create( | ||||
7046 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, | ||||
7047 | RParenLoc, CurFPFeatureOverrides(), NumParams); | ||||
7048 | else | ||||
7049 | TheCall = | ||||
7050 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | ||||
7051 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
7052 | } | ||||
7053 | // We can now handle the nulled arguments for the default arguments. | ||||
7054 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | ||||
7055 | } | ||||
7056 | |||||
7057 | // Bail out early if calling a builtin with custom type checking. | ||||
7058 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | ||||
7059 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
7060 | |||||
7061 | if (getLangOpts().CUDA) { | ||||
7062 | if (Config) { | ||||
7063 | // CUDA: Kernel calls must be to global functions | ||||
7064 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
7065 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | ||||
7066 | << FDecl << Fn->getSourceRange()); | ||||
7067 | |||||
7068 | // CUDA: Kernel function must have 'void' return type | ||||
7069 | if (!FuncT->getReturnType()->isVoidType() && | ||||
7070 | !FuncT->getReturnType()->getAs<AutoType>() && | ||||
7071 | !FuncT->getReturnType()->isInstantiationDependentType()) | ||||
7072 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | ||||
7073 | << Fn->getType() << Fn->getSourceRange()); | ||||
7074 | } else { | ||||
7075 | // CUDA: Calls to global functions must be configured | ||||
7076 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
7077 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | ||||
7078 | << FDecl << Fn->getSourceRange()); | ||||
7079 | } | ||||
7080 | } | ||||
7081 | |||||
7082 | // Check for a valid return type | ||||
7083 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | ||||
7084 | FDecl)) | ||||
7085 | return ExprError(); | ||||
7086 | |||||
7087 | // We know the result type of the call, set it. | ||||
7088 | TheCall->setType(FuncT->getCallResultType(Context)); | ||||
7089 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | ||||
7090 | |||||
7091 | if (Proto) { | ||||
7092 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | ||||
7093 | IsExecConfig)) | ||||
7094 | return ExprError(); | ||||
7095 | } else { | ||||
7096 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT ) && "Unknown FunctionType!") ? void (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "clang/lib/Sema/SemaExpr.cpp", 7096, __extension__ __PRETTY_FUNCTION__ )); | ||||
7097 | |||||
7098 | if (FDecl) { | ||||
7099 | // Check if we have too few/too many template arguments, based | ||||
7100 | // on our knowledge of the function definition. | ||||
7101 | const FunctionDecl *Def = nullptr; | ||||
7102 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | ||||
7103 | Proto = Def->getType()->getAs<FunctionProtoType>(); | ||||
7104 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | ||||
7105 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | ||||
7106 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | ||||
7107 | } | ||||
7108 | |||||
7109 | // If the function we're calling isn't a function prototype, but we have | ||||
7110 | // a function prototype from a prior declaratiom, use that prototype. | ||||
7111 | if (!FDecl->hasPrototype()) | ||||
7112 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | ||||
7113 | } | ||||
7114 | |||||
7115 | // If we still haven't found a prototype to use but there are arguments to | ||||
7116 | // the call, diagnose this as calling a function without a prototype. | ||||
7117 | // However, if we found a function declaration, check to see if | ||||
7118 | // -Wdeprecated-non-prototype was disabled where the function was declared. | ||||
7119 | // If so, we will silence the diagnostic here on the assumption that this | ||||
7120 | // interface is intentional and the user knows what they're doing. We will | ||||
7121 | // also silence the diagnostic if there is a function declaration but it | ||||
7122 | // was implicitly defined (the user already gets diagnostics about the | ||||
7123 | // creation of the implicit function declaration, so the additional warning | ||||
7124 | // is not helpful). | ||||
7125 | if (!Proto && !Args.empty() && | ||||
7126 | (!FDecl || (!FDecl->isImplicit() && | ||||
7127 | !Diags.isIgnored(diag::warn_strict_uses_without_prototype, | ||||
7128 | FDecl->getLocation())))) | ||||
7129 | Diag(LParenLoc, diag::warn_strict_uses_without_prototype) | ||||
7130 | << (FDecl != nullptr) << FDecl; | ||||
7131 | |||||
7132 | // Promote the arguments (C99 6.5.2.2p6). | ||||
7133 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
7134 | Expr *Arg = Args[i]; | ||||
7135 | |||||
7136 | if (Proto && i < Proto->getNumParams()) { | ||||
7137 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
7138 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | ||||
7139 | ExprResult ArgE = | ||||
7140 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | ||||
7141 | if (ArgE.isInvalid()) | ||||
7142 | return true; | ||||
7143 | |||||
7144 | Arg = ArgE.getAs<Expr>(); | ||||
7145 | |||||
7146 | } else { | ||||
7147 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | ||||
7148 | |||||
7149 | if (ArgE.isInvalid()) | ||||
7150 | return true; | ||||
7151 | |||||
7152 | Arg = ArgE.getAs<Expr>(); | ||||
7153 | } | ||||
7154 | |||||
7155 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | ||||
7156 | diag::err_call_incomplete_argument, Arg)) | ||||
7157 | return ExprError(); | ||||
7158 | |||||
7159 | TheCall->setArg(i, Arg); | ||||
7160 | } | ||||
7161 | TheCall->computeDependence(); | ||||
7162 | } | ||||
7163 | |||||
7164 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
7165 | if (!Method->isStatic()) | ||||
7166 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | ||||
7167 | << Fn->getSourceRange()); | ||||
7168 | |||||
7169 | // Check for sentinels | ||||
7170 | if (NDecl) | ||||
7171 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | ||||
7172 | |||||
7173 | // Warn for unions passing across security boundary (CMSE). | ||||
7174 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | ||||
7175 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
7176 | if (const auto *RT = | ||||
7177 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | ||||
7178 | if (RT->getDecl()->isOrContainsUnion()) | ||||
7179 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | ||||
7180 | << 0 << i; | ||||
7181 | } | ||||
7182 | } | ||||
7183 | } | ||||
7184 | |||||
7185 | // Do special checking on direct calls to functions. | ||||
7186 | if (FDecl) { | ||||
7187 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | ||||
7188 | return ExprError(); | ||||
7189 | |||||
7190 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | ||||
7191 | |||||
7192 | if (BuiltinID) | ||||
7193 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
7194 | } else if (NDecl) { | ||||
7195 | if (CheckPointerCall(NDecl, TheCall, Proto)) | ||||
7196 | return ExprError(); | ||||
7197 | } else { | ||||
7198 | if (CheckOtherCall(TheCall, Proto)) | ||||
7199 | return ExprError(); | ||||
7200 | } | ||||
7201 | |||||
7202 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | ||||
7203 | } | ||||
7204 | |||||
7205 | ExprResult | ||||
7206 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | ||||
7207 | SourceLocation RParenLoc, Expr *InitExpr) { | ||||
7208 | assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type" ) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "clang/lib/Sema/SemaExpr.cpp", 7208, __extension__ __PRETTY_FUNCTION__ )); | ||||
7209 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "clang/lib/Sema/SemaExpr.cpp", 7209, __extension__ __PRETTY_FUNCTION__ )); | ||||
7210 | |||||
7211 | TypeSourceInfo *TInfo; | ||||
7212 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | ||||
7213 | if (!TInfo) | ||||
7214 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | ||||
7215 | |||||
7216 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | ||||
7217 | } | ||||
7218 | |||||
7219 | ExprResult | ||||
7220 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | ||||
7221 | SourceLocation RParenLoc, Expr *LiteralExpr) { | ||||
7222 | QualType literalType = TInfo->getType(); | ||||
7223 | |||||
7224 | if (literalType->isArrayType()) { | ||||
7225 | if (RequireCompleteSizedType( | ||||
7226 | LParenLoc, Context.getBaseElementType(literalType), | ||||
7227 | diag::err_array_incomplete_or_sizeless_type, | ||||
7228 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
7229 | return ExprError(); | ||||
7230 | if (literalType->isVariableArrayType()) { | ||||
7231 | if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, | ||||
7232 | diag::err_variable_object_no_init)) { | ||||
7233 | return ExprError(); | ||||
7234 | } | ||||
7235 | } | ||||
7236 | } else if (!literalType->isDependentType() && | ||||
7237 | RequireCompleteType(LParenLoc, literalType, | ||||
7238 | diag::err_typecheck_decl_incomplete_type, | ||||
7239 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
7240 | return ExprError(); | ||||
7241 | |||||
7242 | InitializedEntity Entity | ||||
7243 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | ||||
7244 | InitializationKind Kind | ||||
7245 | = InitializationKind::CreateCStyleCast(LParenLoc, | ||||
7246 | SourceRange(LParenLoc, RParenLoc), | ||||
7247 | /*InitList=*/true); | ||||
7248 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | ||||
7249 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | ||||
7250 | &literalType); | ||||
7251 | if (Result.isInvalid()) | ||||
7252 | return ExprError(); | ||||
7253 | LiteralExpr = Result.get(); | ||||
7254 | |||||
7255 | bool isFileScope = !CurContext->isFunctionOrMethod(); | ||||
7256 | |||||
7257 | // In C, compound literals are l-values for some reason. | ||||
7258 | // For GCC compatibility, in C++, file-scope array compound literals with | ||||
7259 | // constant initializers are also l-values, and compound literals are | ||||
7260 | // otherwise prvalues. | ||||
7261 | // | ||||
7262 | // (GCC also treats C++ list-initialized file-scope array prvalues with | ||||
7263 | // constant initializers as l-values, but that's non-conforming, so we don't | ||||
7264 | // follow it there.) | ||||
7265 | // | ||||
7266 | // FIXME: It would be better to handle the lvalue cases as materializing and | ||||
7267 | // lifetime-extending a temporary object, but our materialized temporaries | ||||
7268 | // representation only supports lifetime extension from a variable, not "out | ||||
7269 | // of thin air". | ||||
7270 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | ||||
7271 | // is bound to the result of applying array-to-pointer decay to the compound | ||||
7272 | // literal. | ||||
7273 | // FIXME: GCC supports compound literals of reference type, which should | ||||
7274 | // obviously have a value kind derived from the kind of reference involved. | ||||
7275 | ExprValueKind VK = | ||||
7276 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | ||||
7277 | ? VK_PRValue | ||||
7278 | : VK_LValue; | ||||
7279 | |||||
7280 | if (isFileScope) | ||||
7281 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | ||||
7282 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | ||||
7283 | Expr *Init = ILE->getInit(i); | ||||
7284 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | ||||
7285 | } | ||||
7286 | |||||
7287 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | ||||
7288 | VK, LiteralExpr, isFileScope); | ||||
7289 | if (isFileScope) { | ||||
7290 | if (!LiteralExpr->isTypeDependent() && | ||||
7291 | !LiteralExpr->isValueDependent() && | ||||
7292 | !literalType->isDependentType()) // C99 6.5.2.5p3 | ||||
7293 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | ||||
7294 | return ExprError(); | ||||
7295 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | ||||
7296 | literalType.getAddressSpace() != LangAS::Default) { | ||||
7297 | // Embedded-C extensions to C99 6.5.2.5: | ||||
7298 | // "If the compound literal occurs inside the body of a function, the | ||||
7299 | // type name shall not be qualified by an address-space qualifier." | ||||
7300 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | ||||
7301 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | ||||
7302 | return ExprError(); | ||||
7303 | } | ||||
7304 | |||||
7305 | if (!isFileScope && !getLangOpts().CPlusPlus) { | ||||
7306 | // Compound literals that have automatic storage duration are destroyed at | ||||
7307 | // the end of the scope in C; in C++, they're just temporaries. | ||||
7308 | |||||
7309 | // Emit diagnostics if it is or contains a C union type that is non-trivial | ||||
7310 | // to destruct. | ||||
7311 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | ||||
7312 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
7313 | NTCUC_CompoundLiteral, NTCUK_Destruct); | ||||
7314 | |||||
7315 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | ||||
7316 | if (literalType.isDestructedType()) { | ||||
7317 | Cleanup.setExprNeedsCleanups(true); | ||||
7318 | ExprCleanupObjects.push_back(E); | ||||
7319 | getCurFunction()->setHasBranchProtectedScope(); | ||||
7320 | } | ||||
7321 | } | ||||
7322 | |||||
7323 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
7324 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
7325 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | ||||
7326 | E->getInitializer()->getExprLoc()); | ||||
7327 | |||||
7328 | return MaybeBindToTemporary(E); | ||||
7329 | } | ||||
7330 | |||||
7331 | ExprResult | ||||
7332 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7333 | SourceLocation RBraceLoc) { | ||||
7334 | // Only produce each kind of designated initialization diagnostic once. | ||||
7335 | SourceLocation FirstDesignator; | ||||
7336 | bool DiagnosedArrayDesignator = false; | ||||
7337 | bool DiagnosedNestedDesignator = false; | ||||
7338 | bool DiagnosedMixedDesignator = false; | ||||
7339 | |||||
7340 | // Check that any designated initializers are syntactically valid in the | ||||
7341 | // current language mode. | ||||
7342 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7343 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | ||||
7344 | if (FirstDesignator.isInvalid()) | ||||
7345 | FirstDesignator = DIE->getBeginLoc(); | ||||
7346 | |||||
7347 | if (!getLangOpts().CPlusPlus) | ||||
7348 | break; | ||||
7349 | |||||
7350 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | ||||
7351 | DiagnosedNestedDesignator = true; | ||||
7352 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | ||||
7353 | << DIE->getDesignatorsSourceRange(); | ||||
7354 | } | ||||
7355 | |||||
7356 | for (auto &Desig : DIE->designators()) { | ||||
7357 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | ||||
7358 | DiagnosedArrayDesignator = true; | ||||
7359 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | ||||
7360 | << Desig.getSourceRange(); | ||||
7361 | } | ||||
7362 | } | ||||
7363 | |||||
7364 | if (!DiagnosedMixedDesignator && | ||||
7365 | !isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7366 | DiagnosedMixedDesignator = true; | ||||
7367 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7368 | << DIE->getSourceRange(); | ||||
7369 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7370 | << InitArgList[0]->getSourceRange(); | ||||
7371 | } | ||||
7372 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | ||||
7373 | isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7374 | DiagnosedMixedDesignator = true; | ||||
7375 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | ||||
7376 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7377 | << DIE->getSourceRange(); | ||||
7378 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7379 | << InitArgList[I]->getSourceRange(); | ||||
7380 | } | ||||
7381 | } | ||||
7382 | |||||
7383 | if (FirstDesignator.isValid()) { | ||||
7384 | // Only diagnose designated initiaization as a C++20 extension if we didn't | ||||
7385 | // already diagnose use of (non-C++20) C99 designator syntax. | ||||
7386 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | ||||
7387 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | ||||
7388 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | ||||
7389 | ? diag::warn_cxx17_compat_designated_init | ||||
7390 | : diag::ext_cxx_designated_init); | ||||
7391 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | ||||
7392 | Diag(FirstDesignator, diag::ext_designated_init); | ||||
7393 | } | ||||
7394 | } | ||||
7395 | |||||
7396 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | ||||
7397 | } | ||||
7398 | |||||
7399 | ExprResult | ||||
7400 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7401 | SourceLocation RBraceLoc) { | ||||
7402 | // Semantic analysis for initializers is done by ActOnDeclarator() and | ||||
7403 | // CheckInitializer() - it requires knowledge of the object being initialized. | ||||
7404 | |||||
7405 | // Immediately handle non-overload placeholders. Overloads can be | ||||
7406 | // resolved contextually, but everything else here can't. | ||||
7407 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7408 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | ||||
7409 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | ||||
7410 | |||||
7411 | // Ignore failures; dropping the entire initializer list because | ||||
7412 | // of one failure would be terrible for indexing/etc. | ||||
7413 | if (result.isInvalid()) continue; | ||||
7414 | |||||
7415 | InitArgList[I] = result.get(); | ||||
7416 | } | ||||
7417 | } | ||||
7418 | |||||
7419 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | ||||
7420 | RBraceLoc); | ||||
7421 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | ||||
7422 | return E; | ||||
7423 | } | ||||
7424 | |||||
7425 | /// Do an explicit extend of the given block pointer if we're in ARC. | ||||
7426 | void Sema::maybeExtendBlockObject(ExprResult &E) { | ||||
7427 | assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType ()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 7427, __extension__ __PRETTY_FUNCTION__ )); | ||||
7428 | assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0 ) : __assert_fail ("E.get()->isPRValue()", "clang/lib/Sema/SemaExpr.cpp" , 7428, __extension__ __PRETTY_FUNCTION__)); | ||||
7429 | |||||
7430 | // Only do this in an r-value context. | ||||
7431 | if (!getLangOpts().ObjCAutoRefCount) return; | ||||
7432 | |||||
7433 | E = ImplicitCastExpr::Create( | ||||
7434 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | ||||
7435 | /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); | ||||
7436 | Cleanup.setExprNeedsCleanups(true); | ||||
7437 | } | ||||
7438 | |||||
7439 | /// Prepare a conversion of the given expression to an ObjC object | ||||
7440 | /// pointer type. | ||||
7441 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | ||||
7442 | QualType type = E.get()->getType(); | ||||
7443 | if (type->isObjCObjectPointerType()) { | ||||
7444 | return CK_BitCast; | ||||
7445 | } else if (type->isBlockPointerType()) { | ||||
7446 | maybeExtendBlockObject(E); | ||||
7447 | return CK_BlockPointerToObjCPointerCast; | ||||
7448 | } else { | ||||
7449 | assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void ( 0) : __assert_fail ("type->isPointerType()", "clang/lib/Sema/SemaExpr.cpp" , 7449, __extension__ __PRETTY_FUNCTION__)); | ||||
7450 | return CK_CPointerToObjCPointerCast; | ||||
7451 | } | ||||
7452 | } | ||||
7453 | |||||
7454 | /// Prepares for a scalar cast, performing all the necessary stages | ||||
7455 | /// except the final cast and returning the kind required. | ||||
7456 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | ||||
7457 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | ||||
7458 | // Also, callers should have filtered out the invalid cases with | ||||
7459 | // pointers. Everything else should be possible. | ||||
7460 | |||||
7461 | QualType SrcTy = Src.get()->getType(); | ||||
7462 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | ||||
7463 | return CK_NoOp; | ||||
7464 | |||||
7465 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | ||||
7466 | case Type::STK_MemberPointer: | ||||
7467 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7467); | ||||
7468 | |||||
7469 | case Type::STK_CPointer: | ||||
7470 | case Type::STK_BlockPointer: | ||||
7471 | case Type::STK_ObjCObjectPointer: | ||||
7472 | switch (DestTy->getScalarTypeKind()) { | ||||
7473 | case Type::STK_CPointer: { | ||||
7474 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | ||||
7475 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | ||||
7476 | if (SrcAS != DestAS) | ||||
7477 | return CK_AddressSpaceConversion; | ||||
7478 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | ||||
7479 | return CK_NoOp; | ||||
7480 | return CK_BitCast; | ||||
7481 | } | ||||
7482 | case Type::STK_BlockPointer: | ||||
7483 | return (SrcKind == Type::STK_BlockPointer | ||||
7484 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | ||||
7485 | case Type::STK_ObjCObjectPointer: | ||||
7486 | if (SrcKind == Type::STK_ObjCObjectPointer) | ||||
7487 | return CK_BitCast; | ||||
7488 | if (SrcKind == Type::STK_CPointer) | ||||
7489 | return CK_CPointerToObjCPointerCast; | ||||
7490 | maybeExtendBlockObject(Src); | ||||
7491 | return CK_BlockPointerToObjCPointerCast; | ||||
7492 | case Type::STK_Bool: | ||||
7493 | return CK_PointerToBoolean; | ||||
7494 | case Type::STK_Integral: | ||||
7495 | return CK_PointerToIntegral; | ||||
7496 | case Type::STK_Floating: | ||||
7497 | case Type::STK_FloatingComplex: | ||||
7498 | case Type::STK_IntegralComplex: | ||||
7499 | case Type::STK_MemberPointer: | ||||
7500 | case Type::STK_FixedPoint: | ||||
7501 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "clang/lib/Sema/SemaExpr.cpp", 7501); | ||||
7502 | } | ||||
7503 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7503); | ||||
7504 | |||||
7505 | case Type::STK_FixedPoint: | ||||
7506 | switch (DestTy->getScalarTypeKind()) { | ||||
7507 | case Type::STK_FixedPoint: | ||||
7508 | return CK_FixedPointCast; | ||||
7509 | case Type::STK_Bool: | ||||
7510 | return CK_FixedPointToBoolean; | ||||
7511 | case Type::STK_Integral: | ||||
7512 | return CK_FixedPointToIntegral; | ||||
7513 | case Type::STK_Floating: | ||||
7514 | return CK_FixedPointToFloating; | ||||
7515 | case Type::STK_IntegralComplex: | ||||
7516 | case Type::STK_FloatingComplex: | ||||
7517 | Diag(Src.get()->getExprLoc(), | ||||
7518 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7519 | << DestTy; | ||||
7520 | return CK_IntegralCast; | ||||
7521 | case Type::STK_CPointer: | ||||
7522 | case Type::STK_ObjCObjectPointer: | ||||
7523 | case Type::STK_BlockPointer: | ||||
7524 | case Type::STK_MemberPointer: | ||||
7525 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "clang/lib/Sema/SemaExpr.cpp", 7525); | ||||
7526 | } | ||||
7527 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7527); | ||||
7528 | |||||
7529 | case Type::STK_Bool: // casting from bool is like casting from an integer | ||||
7530 | case Type::STK_Integral: | ||||
7531 | switch (DestTy->getScalarTypeKind()) { | ||||
7532 | case Type::STK_CPointer: | ||||
7533 | case Type::STK_ObjCObjectPointer: | ||||
7534 | case Type::STK_BlockPointer: | ||||
7535 | if (Src.get()->isNullPointerConstant(Context, | ||||
7536 | Expr::NPC_ValueDependentIsNull)) | ||||
7537 | return CK_NullToPointer; | ||||
7538 | return CK_IntegralToPointer; | ||||
7539 | case Type::STK_Bool: | ||||
7540 | return CK_IntegralToBoolean; | ||||
7541 | case Type::STK_Integral: | ||||
7542 | return CK_IntegralCast; | ||||
7543 | case Type::STK_Floating: | ||||
7544 | return CK_IntegralToFloating; | ||||
7545 | case Type::STK_IntegralComplex: | ||||
7546 | Src = ImpCastExprToType(Src.get(), | ||||
7547 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7548 | CK_IntegralCast); | ||||
7549 | return CK_IntegralRealToComplex; | ||||
7550 | case Type::STK_FloatingComplex: | ||||
7551 | Src = ImpCastExprToType(Src.get(), | ||||
7552 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7553 | CK_IntegralToFloating); | ||||
7554 | return CK_FloatingRealToComplex; | ||||
7555 | case Type::STK_MemberPointer: | ||||
7556 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7556); | ||||
7557 | case Type::STK_FixedPoint: | ||||
7558 | return CK_IntegralToFixedPoint; | ||||
7559 | } | ||||
7560 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7560); | ||||
7561 | |||||
7562 | case Type::STK_Floating: | ||||
7563 | switch (DestTy->getScalarTypeKind()) { | ||||
7564 | case Type::STK_Floating: | ||||
7565 | return CK_FloatingCast; | ||||
7566 | case Type::STK_Bool: | ||||
7567 | return CK_FloatingToBoolean; | ||||
7568 | case Type::STK_Integral: | ||||
7569 | return CK_FloatingToIntegral; | ||||
7570 | case Type::STK_FloatingComplex: | ||||
7571 | Src = ImpCastExprToType(Src.get(), | ||||
7572 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7573 | CK_FloatingCast); | ||||
7574 | return CK_FloatingRealToComplex; | ||||
7575 | case Type::STK_IntegralComplex: | ||||
7576 | Src = ImpCastExprToType(Src.get(), | ||||
7577 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7578 | CK_FloatingToIntegral); | ||||
7579 | return CK_IntegralRealToComplex; | ||||
7580 | case Type::STK_CPointer: | ||||
7581 | case Type::STK_ObjCObjectPointer: | ||||
7582 | case Type::STK_BlockPointer: | ||||
7583 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7583); | ||||
7584 | case Type::STK_MemberPointer: | ||||
7585 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7585); | ||||
7586 | case Type::STK_FixedPoint: | ||||
7587 | return CK_FloatingToFixedPoint; | ||||
7588 | } | ||||
7589 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7589); | ||||
7590 | |||||
7591 | case Type::STK_FloatingComplex: | ||||
7592 | switch (DestTy->getScalarTypeKind()) { | ||||
7593 | case Type::STK_FloatingComplex: | ||||
7594 | return CK_FloatingComplexCast; | ||||
7595 | case Type::STK_IntegralComplex: | ||||
7596 | return CK_FloatingComplexToIntegralComplex; | ||||
7597 | case Type::STK_Floating: { | ||||
7598 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7599 | if (Context.hasSameType(ET, DestTy)) | ||||
7600 | return CK_FloatingComplexToReal; | ||||
7601 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | ||||
7602 | return CK_FloatingCast; | ||||
7603 | } | ||||
7604 | case Type::STK_Bool: | ||||
7605 | return CK_FloatingComplexToBoolean; | ||||
7606 | case Type::STK_Integral: | ||||
7607 | Src = ImpCastExprToType(Src.get(), | ||||
7608 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7609 | CK_FloatingComplexToReal); | ||||
7610 | return CK_FloatingToIntegral; | ||||
7611 | case Type::STK_CPointer: | ||||
7612 | case Type::STK_ObjCObjectPointer: | ||||
7613 | case Type::STK_BlockPointer: | ||||
7614 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7614); | ||||
7615 | case Type::STK_MemberPointer: | ||||
7616 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7616); | ||||
7617 | case Type::STK_FixedPoint: | ||||
7618 | Diag(Src.get()->getExprLoc(), | ||||
7619 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7620 | << SrcTy; | ||||
7621 | return CK_IntegralCast; | ||||
7622 | } | ||||
7623 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7623); | ||||
7624 | |||||
7625 | case Type::STK_IntegralComplex: | ||||
7626 | switch (DestTy->getScalarTypeKind()) { | ||||
7627 | case Type::STK_FloatingComplex: | ||||
7628 | return CK_IntegralComplexToFloatingComplex; | ||||
7629 | case Type::STK_IntegralComplex: | ||||
7630 | return CK_IntegralComplexCast; | ||||
7631 | case Type::STK_Integral: { | ||||
7632 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7633 | if (Context.hasSameType(ET, DestTy)) | ||||
7634 | return CK_IntegralComplexToReal; | ||||
7635 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | ||||
7636 | return CK_IntegralCast; | ||||
7637 | } | ||||
7638 | case Type::STK_Bool: | ||||
7639 | return CK_IntegralComplexToBoolean; | ||||
7640 | case Type::STK_Floating: | ||||
7641 | Src = ImpCastExprToType(Src.get(), | ||||
7642 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7643 | CK_IntegralComplexToReal); | ||||
7644 | return CK_IntegralToFloating; | ||||
7645 | case Type::STK_CPointer: | ||||
7646 | case Type::STK_ObjCObjectPointer: | ||||
7647 | case Type::STK_BlockPointer: | ||||
7648 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "clang/lib/Sema/SemaExpr.cpp", 7648); | ||||
7649 | case Type::STK_MemberPointer: | ||||
7650 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "clang/lib/Sema/SemaExpr.cpp", 7650); | ||||
7651 | case Type::STK_FixedPoint: | ||||
7652 | Diag(Src.get()->getExprLoc(), | ||||
7653 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7654 | << SrcTy; | ||||
7655 | return CK_IntegralCast; | ||||
7656 | } | ||||
7657 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "clang/lib/Sema/SemaExpr.cpp", 7657); | ||||
7658 | } | ||||
7659 | |||||
7660 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "clang/lib/Sema/SemaExpr.cpp" , 7660); | ||||
7661 | } | ||||
7662 | |||||
7663 | static bool breakDownVectorType(QualType type, uint64_t &len, | ||||
7664 | QualType &eltType) { | ||||
7665 | // Vectors are simple. | ||||
7666 | if (const VectorType *vecType = type->getAs<VectorType>()) { | ||||
7667 | len = vecType->getNumElements(); | ||||
7668 | eltType = vecType->getElementType(); | ||||
7669 | assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void (0) : __assert_fail ("eltType->isScalarType()", "clang/lib/Sema/SemaExpr.cpp" , 7669, __extension__ __PRETTY_FUNCTION__)); | ||||
7670 | return true; | ||||
7671 | } | ||||
7672 | |||||
7673 | // We allow lax conversion to and from non-vector types, but only if | ||||
7674 | // they're real types (i.e. non-complex, non-pointer scalar types). | ||||
7675 | if (!type->isRealType()) return false; | ||||
7676 | |||||
7677 | len = 1; | ||||
7678 | eltType = type; | ||||
7679 | return true; | ||||
7680 | } | ||||
7681 | |||||
7682 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | ||||
7683 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | ||||
7684 | /// allowed? | ||||
7685 | /// | ||||
7686 | /// This will also return false if the two given types do not make sense from | ||||
7687 | /// the perspective of SVE bitcasts. | ||||
7688 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | ||||
7689 | assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy ->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7689, __extension__ __PRETTY_FUNCTION__ )); | ||||
7690 | |||||
7691 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | ||||
7692 | if (!FirstType->isSizelessBuiltinType()) | ||||
7693 | return false; | ||||
7694 | |||||
7695 | const auto *VecTy = SecondType->getAs<VectorType>(); | ||||
7696 | return VecTy && | ||||
7697 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | ||||
7698 | }; | ||||
7699 | |||||
7700 | return ValidScalableConversion(srcTy, destTy) || | ||||
7701 | ValidScalableConversion(destTy, srcTy); | ||||
7702 | } | ||||
7703 | |||||
7704 | /// Are the two types matrix types and do they have the same dimensions i.e. | ||||
7705 | /// do they have the same number of rows and the same number of columns? | ||||
7706 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { | ||||
7707 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) | ||||
7708 | return false; | ||||
7709 | |||||
7710 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); | ||||
7711 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); | ||||
7712 | |||||
7713 | return matSrcType->getNumRows() == matDestType->getNumRows() && | ||||
7714 | matSrcType->getNumColumns() == matDestType->getNumColumns(); | ||||
7715 | } | ||||
7716 | |||||
7717 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { | ||||
7718 | assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast <bool> (DestTy->isVectorType() || SrcTy ->isVectorType()) ? void (0) : __assert_fail ("DestTy->isVectorType() || SrcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7718, __extension__ __PRETTY_FUNCTION__ )); | ||||
7719 | |||||
7720 | uint64_t SrcLen, DestLen; | ||||
7721 | QualType SrcEltTy, DestEltTy; | ||||
7722 | if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) | ||||
7723 | return false; | ||||
7724 | if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) | ||||
7725 | return false; | ||||
7726 | |||||
7727 | // ASTContext::getTypeSize will return the size rounded up to a | ||||
7728 | // power of 2, so instead of using that, we need to use the raw | ||||
7729 | // element size multiplied by the element count. | ||||
7730 | uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); | ||||
7731 | uint64_t DestEltSize = Context.getTypeSize(DestEltTy); | ||||
7732 | |||||
7733 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); | ||||
7734 | } | ||||
7735 | |||||
7736 | // This returns true if at least one of the types is an altivec vector. | ||||
7737 | bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { | ||||
7738 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 7739, __extension__ __PRETTY_FUNCTION__ )) | ||||
7739 | "expected at least one type to be a vector here")(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 7739, __extension__ __PRETTY_FUNCTION__ )); | ||||
7740 | |||||
7741 | bool IsSrcTyAltivec = | ||||
7742 | SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() == | ||||
7743 | VectorType::AltiVecVector); | ||||
7744 | bool IsDestTyAltivec = DestTy->isVectorType() && | ||||
7745 | (DestTy->castAs<VectorType>()->getVectorKind() == | ||||
7746 | VectorType::AltiVecVector); | ||||
7747 | |||||
7748 | return (IsSrcTyAltivec || IsDestTyAltivec); | ||||
7749 | } | ||||
7750 | |||||
7751 | // This returns true if both vectors have the same element type. | ||||
7752 | bool Sema::areSameVectorElemTypes(QualType SrcTy, QualType DestTy) { | ||||
7753 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 7754, __extension__ __PRETTY_FUNCTION__ )) | ||||
7754 | "expected at least one type to be a vector here")(static_cast <bool> ((DestTy->isVectorType() || SrcTy ->isVectorType()) && "expected at least one type to be a vector here" ) ? void (0) : __assert_fail ("(DestTy->isVectorType() || SrcTy->isVectorType()) && \"expected at least one type to be a vector here\"" , "clang/lib/Sema/SemaExpr.cpp", 7754, __extension__ __PRETTY_FUNCTION__ )); | ||||
7755 | |||||
7756 | uint64_t SrcLen, DestLen; | ||||
7757 | QualType SrcEltTy, DestEltTy; | ||||
7758 | if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) | ||||
7759 | return false; | ||||
7760 | if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) | ||||
7761 | return false; | ||||
7762 | |||||
7763 | return (SrcEltTy == DestEltTy); | ||||
7764 | } | ||||
7765 | |||||
7766 | /// Are the two types lax-compatible vector types? That is, given | ||||
7767 | /// that one of them is a vector, do they have equal storage sizes, | ||||
7768 | /// where the storage size is the number of elements times the element | ||||
7769 | /// size? | ||||
7770 | /// | ||||
7771 | /// This will also return false if either of the types is neither a | ||||
7772 | /// vector nor a real type. | ||||
7773 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | ||||
7774 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7774, __extension__ __PRETTY_FUNCTION__ )); | ||||
7775 | |||||
7776 | // Disallow lax conversions between scalars and ExtVectors (these | ||||
7777 | // conversions are allowed for other vector types because common headers | ||||
7778 | // depend on them). Most scalar OP ExtVector cases are handled by the | ||||
7779 | // splat path anyway, which does what we want (convert, not bitcast). | ||||
7780 | // What this rules out for ExtVectors is crazy things like char4*float. | ||||
7781 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | ||||
7782 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | ||||
7783 | |||||
7784 | return areVectorTypesSameSize(srcTy, destTy); | ||||
7785 | } | ||||
7786 | |||||
7787 | /// Is this a legal conversion between two types, one of which is | ||||
7788 | /// known to be a vector type? | ||||
7789 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | ||||
7790 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "clang/lib/Sema/SemaExpr.cpp", 7790, __extension__ __PRETTY_FUNCTION__ )); | ||||
7791 | |||||
7792 | switch (Context.getLangOpts().getLaxVectorConversions()) { | ||||
7793 | case LangOptions::LaxVectorConversionKind::None: | ||||
7794 | return false; | ||||
7795 | |||||
7796 | case LangOptions::LaxVectorConversionKind::Integer: | ||||
7797 | if (!srcTy->isIntegralOrEnumerationType()) { | ||||
7798 | auto *Vec = srcTy->getAs<VectorType>(); | ||||
7799 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7800 | return false; | ||||
7801 | } | ||||
7802 | if (!destTy->isIntegralOrEnumerationType()) { | ||||
7803 | auto *Vec = destTy->getAs<VectorType>(); | ||||
7804 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7805 | return false; | ||||
7806 | } | ||||
7807 | // OK, integer (vector) -> integer (vector) bitcast. | ||||
7808 | break; | ||||
7809 | |||||
7810 | case LangOptions::LaxVectorConversionKind::All: | ||||
7811 | break; | ||||
7812 | } | ||||
7813 | |||||
7814 | return areLaxCompatibleVectorTypes(srcTy, destTy); | ||||
7815 | } | ||||
7816 | |||||
7817 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, | ||||
7818 | CastKind &Kind) { | ||||
7819 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { | ||||
7820 | if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { | ||||
7821 | return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) | ||||
7822 | << DestTy << SrcTy << R; | ||||
7823 | } | ||||
7824 | } else if (SrcTy->isMatrixType()) { | ||||
7825 | return Diag(R.getBegin(), | ||||
7826 | diag::err_invalid_conversion_between_matrix_and_type) | ||||
7827 | << SrcTy << DestTy << R; | ||||
7828 | } else if (DestTy->isMatrixType()) { | ||||
7829 | return Diag(R.getBegin(), | ||||
7830 | diag::err_invalid_conversion_between_matrix_and_type) | ||||
7831 | << DestTy << SrcTy << R; | ||||
7832 | } | ||||
7833 | |||||
7834 | Kind = CK_MatrixCast; | ||||
7835 | return false; | ||||
7836 | } | ||||
7837 | |||||
7838 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | ||||
7839 | CastKind &Kind) { | ||||
7840 | assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast <bool> (VectorTy->isVectorType() && "Not a vector type!") ? void (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "clang/lib/Sema/SemaExpr.cpp", 7840, __extension__ __PRETTY_FUNCTION__ )); | ||||
7841 | |||||
7842 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | ||||
7843 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | ||||
7844 | return Diag(R.getBegin(), | ||||
7845 | Ty->isVectorType() ? | ||||
7846 | diag::err_invalid_conversion_between_vectors : | ||||
7847 | diag::err_invalid_conversion_between_vector_and_integer) | ||||
7848 | << VectorTy << Ty << R; | ||||
7849 | } else | ||||
7850 | return Diag(R.getBegin(), | ||||
7851 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7852 | << VectorTy << Ty << R; | ||||
7853 | |||||
7854 | Kind = CK_BitCast; | ||||
7855 | return false; | ||||
7856 | } | ||||
7857 | |||||
7858 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | ||||
7859 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | ||||
7860 | |||||
7861 | if (DestElemTy == SplattedExpr->getType()) | ||||
7862 | return SplattedExpr; | ||||
7863 | |||||
7864 | assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaExpr.cpp", 7865, __extension__ __PRETTY_FUNCTION__ )) | ||||
7865 | DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "clang/lib/Sema/SemaExpr.cpp", 7865, __extension__ __PRETTY_FUNCTION__ )); | ||||
7866 | |||||
7867 | CastKind CK; | ||||
7868 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | ||||
7869 | // OpenCL requires that we convert `true` boolean expressions to -1, but | ||||
7870 | // only when splatting vectors. | ||||
7871 | if (DestElemTy->isFloatingType()) { | ||||
7872 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | ||||
7873 | // in two steps: boolean to signed integral, then to floating. | ||||
7874 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | ||||
7875 | CK_BooleanToSignedIntegral); | ||||
7876 | SplattedExpr = CastExprRes.get(); | ||||
7877 | CK = CK_IntegralToFloating; | ||||
7878 | } else { | ||||
7879 | CK = CK_BooleanToSignedIntegral; | ||||
7880 | } | ||||
7881 | } else { | ||||
7882 | ExprResult CastExprRes = SplattedExpr; | ||||
7883 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | ||||
7884 | if (CastExprRes.isInvalid()) | ||||
7885 | return ExprError(); | ||||
7886 | SplattedExpr = CastExprRes.get(); | ||||
7887 | } | ||||
7888 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | ||||
7889 | } | ||||
7890 | |||||
7891 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | ||||
7892 | Expr *CastExpr, CastKind &Kind) { | ||||
7893 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast <bool> (DestTy->isExtVectorType() && "Not an extended vector type!") ? void (0) : __assert_fail ( "DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "clang/lib/Sema/SemaExpr.cpp", 7893, __extension__ __PRETTY_FUNCTION__ )); | ||||
7894 | |||||
7895 | QualType SrcTy = CastExpr->getType(); | ||||
7896 | |||||
7897 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | ||||
7898 | // an ExtVectorType. | ||||
7899 | // In OpenCL, casts between vectors of different types are not allowed. | ||||
7900 | // (See OpenCL 6.2). | ||||
7901 | if (SrcTy->isVectorType()) { | ||||
7902 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | ||||
7903 | (getLangOpts().OpenCL && | ||||
7904 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | ||||
7905 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | ||||
7906 | << DestTy << SrcTy << R; | ||||
7907 | return ExprError(); | ||||
7908 | } | ||||
7909 | Kind = CK_BitCast; | ||||
7910 | return CastExpr; | ||||
7911 | } | ||||
7912 | |||||
7913 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | ||||
7914 | // conversion will take place first from scalar to elt type, and then | ||||
7915 | // splat from elt type to vector. | ||||
7916 | if (SrcTy->isPointerType()) | ||||
7917 | return Diag(R.getBegin(), | ||||
7918 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7919 | << DestTy << SrcTy << R; | ||||
7920 | |||||
7921 | Kind = CK_VectorSplat; | ||||
7922 | return prepareVectorSplat(DestTy, CastExpr); | ||||
7923 | } | ||||
7924 | |||||
7925 | ExprResult | ||||
7926 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | ||||
7927 | Declarator &D, ParsedType &Ty, | ||||
7928 | SourceLocation RParenLoc, Expr *CastExpr) { | ||||
7929 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "clang/lib/Sema/SemaExpr.cpp", 7930, __extension__ __PRETTY_FUNCTION__ )) | ||||
7930 | "ActOnCastExpr(): missing type or expr")(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "clang/lib/Sema/SemaExpr.cpp", 7930, __extension__ __PRETTY_FUNCTION__ )); | ||||
7931 | |||||
7932 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | ||||
7933 | if (D.isInvalidType()) | ||||
7934 | return ExprError(); | ||||
7935 | |||||
7936 | if (getLangOpts().CPlusPlus) { | ||||
7937 | // Check that there are no default arguments (C++ only). | ||||
7938 | CheckExtraCXXDefaultArguments(D); | ||||
7939 | } else { | ||||
7940 | // Make sure any TypoExprs have been dealt with. | ||||
7941 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | ||||
7942 | if (!Res.isUsable()) | ||||
7943 | return ExprError(); | ||||
7944 | CastExpr = Res.get(); | ||||
7945 | } | ||||
7946 | |||||
7947 | checkUnusedDeclAttributes(D); | ||||
7948 | |||||
7949 | QualType castType = castTInfo->getType(); | ||||
7950 | Ty = CreateParsedType(castType, castTInfo); | ||||
7951 | |||||
7952 | bool isVectorLiteral = false; | ||||
7953 | |||||
7954 | // Check for an altivec or OpenCL literal, | ||||
7955 | // i.e. all the elements are integer constants. | ||||
7956 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | ||||
7957 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | ||||
7958 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | ||||
7959 | && castType->isVectorType() && (PE || PLE)) { | ||||
7960 | if (PLE && PLE->getNumExprs() == 0) { | ||||
7961 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | ||||
7962 | return ExprError(); | ||||
7963 | } | ||||
7964 | if (PE || PLE->getNumExprs() == 1) { | ||||
7965 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | ||||
7966 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | ||||
7967 | isVectorLiteral = true; | ||||
7968 | } | ||||
7969 | else | ||||
7970 | isVectorLiteral = true; | ||||
7971 | } | ||||
7972 | |||||
7973 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | ||||
7974 | // then handle it as such. | ||||
7975 | if (isVectorLiteral) | ||||
7976 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | ||||
7977 | |||||
7978 | // If the Expr being casted is a ParenListExpr, handle it specially. | ||||
7979 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | ||||
7980 | // sequence of BinOp comma operators. | ||||
7981 | if (isa<ParenListExpr>(CastExpr)) { | ||||
7982 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | ||||
7983 | if (Result.isInvalid()) return ExprError(); | ||||
7984 | CastExpr = Result.get(); | ||||
7985 | } | ||||
7986 | |||||
7987 | if (getLangOpts().CPlusPlus && !castType->isVoidType()) | ||||
7988 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | ||||
7989 | |||||
7990 | CheckTollFreeBridgeCast(castType, CastExpr); | ||||
7991 | |||||
7992 | CheckObjCBridgeRelatedCast(castType, CastExpr); | ||||
7993 | |||||
7994 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | ||||
7995 | |||||
7996 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | ||||
7997 | } | ||||
7998 | |||||
7999 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | ||||
8000 | SourceLocation RParenLoc, Expr *E, | ||||
8001 | TypeSourceInfo *TInfo) { | ||||
8002 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "clang/lib/Sema/SemaExpr.cpp", 8003, __extension__ __PRETTY_FUNCTION__ )) | ||||
8003 | "Expected paren or paren list expression")(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "clang/lib/Sema/SemaExpr.cpp", 8003, __extension__ __PRETTY_FUNCTION__ )); | ||||
8004 | |||||
8005 | Expr **exprs; | ||||
8006 | unsigned numExprs; | ||||
8007 | Expr *subExpr; | ||||
8008 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | ||||
8009 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | ||||
8010 | LiteralLParenLoc = PE->getLParenLoc(); | ||||
8011 | LiteralRParenLoc = PE->getRParenLoc(); | ||||
8012 | exprs = PE->getExprs(); | ||||
8013 | numExprs = PE->getNumExprs(); | ||||
8014 | } else { // isa<ParenExpr> by assertion at function entrance | ||||
8015 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | ||||
8016 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | ||||
8017 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | ||||
8018 | exprs = &subExpr; | ||||
8019 | numExprs = 1; | ||||
8020 | } | ||||
8021 | |||||
8022 | QualType Ty = TInfo->getType(); | ||||
8023 | assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type" ) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "clang/lib/Sema/SemaExpr.cpp", 8023, __extension__ __PRETTY_FUNCTION__ )); | ||||
8024 | |||||
8025 | SmallVector<Expr *, 8> initExprs; | ||||
8026 | const VectorType *VTy = Ty->castAs<VectorType>(); | ||||
8027 | unsigned numElems = VTy->getNumElements(); | ||||
8028 | |||||
8029 | // '(...)' form of vector initialization in AltiVec: the number of | ||||
8030 | // initializers must be one or must match the size of the vector. | ||||
8031 | // If a single value is specified in the initializer then it will be | ||||
8032 | // replicated to all the components of the vector | ||||
8033 | if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, | ||||
8034 | VTy->getElementType())) | ||||
8035 | return ExprError(); | ||||
8036 | if (ShouldSplatAltivecScalarInCast(VTy)) { | ||||
8037 | // The number of initializers must be one or must match the size of the | ||||
8038 | // vector. If a single value is specified in the initializer then it will | ||||
8039 | // be replicated to all the components of the vector | ||||
8040 | if (numExprs == 1) { | ||||
8041 | QualType ElemTy = VTy->getElementType(); | ||||
8042 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
8043 | if (Literal.isInvalid()) | ||||
8044 | return ExprError(); | ||||
8045 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
8046 | PrepareScalarCast(Literal, ElemTy)); | ||||
8047 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
8048 | } | ||||
8049 | else if (numExprs < numElems) { | ||||
8050 | Diag(E->getExprLoc(), | ||||
8051 | diag::err_incorrect_number_of_vector_initializers); | ||||
8052 | return ExprError(); | ||||
8053 | } | ||||
8054 | else | ||||
8055 | initExprs.append(exprs, exprs + numExprs); | ||||
8056 | } | ||||
8057 | else { | ||||
8058 | // For OpenCL, when the number of initializers is a single value, | ||||
8059 | // it will be replicated to all components of the vector. | ||||
8060 | if (getLangOpts().OpenCL && | ||||
8061 | VTy->getVectorKind() == VectorType::GenericVector && | ||||
8062 | numExprs == 1) { | ||||
8063 | QualType ElemTy = VTy->getElementType(); | ||||
8064 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
8065 | if (Literal.isInvalid()) | ||||
8066 | return ExprError(); | ||||
8067 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
8068 | PrepareScalarCast(Literal, ElemTy)); | ||||
8069 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
8070 | } | ||||
8071 | |||||
8072 | initExprs.append(exprs, exprs + numExprs); | ||||
8073 | } | ||||
8074 | // FIXME: This means that pretty-printing the final AST will produce curly | ||||
8075 | // braces instead of the original commas. | ||||
8076 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | ||||
8077 | initExprs, LiteralRParenLoc); | ||||
8078 | initE->setType(Ty); | ||||
8079 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | ||||
8080 | } | ||||
8081 | |||||
8082 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | ||||
8083 | /// the ParenListExpr into a sequence of comma binary operators. | ||||
8084 | ExprResult | ||||
8085 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | ||||
8086 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | ||||
8087 | if (!E) | ||||
8088 | return OrigExpr; | ||||
8089 | |||||
8090 | ExprResult Result(E->getExpr(0)); | ||||
8091 | |||||
8092 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | ||||
8093 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | ||||
8094 | E->getExpr(i)); | ||||
8095 | |||||
8096 | if (Result.isInvalid()) return ExprError(); | ||||
8097 | |||||
8098 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | ||||
8099 | } | ||||
8100 | |||||
8101 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | ||||
8102 | SourceLocation R, | ||||
8103 | MultiExprArg Val) { | ||||
8104 | return ParenListExpr::Create(Context, L, Val, R); | ||||
8105 | } | ||||
8106 | |||||
8107 | /// Emit a specialized diagnostic when one expression is a null pointer | ||||
8108 | /// constant and the other is not a pointer. Returns true if a diagnostic is | ||||
8109 | /// emitted. | ||||
8110 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | ||||
8111 | SourceLocation QuestionLoc) { | ||||
8112 | Expr *NullExpr = LHSExpr; | ||||
8113 | Expr *NonPointerExpr = RHSExpr; | ||||
8114 | Expr::NullPointerConstantKind NullKind = | ||||
8115 | NullExpr->isNullPointerConstant(Context, | ||||
8116 | Expr::NPC_ValueDependentIsNotNull); | ||||
8117 | |||||
8118 | if (NullKind == Expr::NPCK_NotNull) { | ||||
8119 | NullExpr = RHSExpr; | ||||
8120 | NonPointerExpr = LHSExpr; | ||||
8121 | NullKind = | ||||
8122 | NullExpr->isNullPointerConstant(Context, | ||||
8123 | Expr::NPC_ValueDependentIsNotNull); | ||||
8124 | } | ||||
8125 | |||||
8126 | if (NullKind == Expr::NPCK_NotNull) | ||||
8127 | return false; | ||||
8128 | |||||
8129 | if (NullKind == Expr::NPCK_ZeroExpression) | ||||
8130 | return false; | ||||
8131 | |||||
8132 | if (NullKind == Expr::NPCK_ZeroLiteral) { | ||||
8133 | // In this case, check to make sure that we got here from a "NULL" | ||||
8134 | // string in the source code. | ||||
8135 | NullExpr = NullExpr->IgnoreParenImpCasts(); | ||||
8136 | SourceLocation loc = NullExpr->getExprLoc(); | ||||
8137 | if (!findMacroSpelling(loc, "NULL")) | ||||
8138 | return false; | ||||
8139 | } | ||||
8140 | |||||
8141 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | ||||
8142 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | ||||
8143 | << NonPointerExpr->getType() << DiagType | ||||
8144 | << NonPointerExpr->getSourceRange(); | ||||
8145 | return true; | ||||
8146 | } | ||||
8147 | |||||
8148 | /// Return false if the condition expression is valid, true otherwise. | ||||
8149 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | ||||
8150 | QualType CondTy = Cond->getType(); | ||||
8151 | |||||
8152 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | ||||
8153 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | ||||
8154 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8155 | << CondTy << Cond->getSourceRange(); | ||||
8156 | return true; | ||||
8157 | } | ||||
8158 | |||||
8159 | // C99 6.5.15p2 | ||||
8160 | if (CondTy->isScalarType()) return false; | ||||
8161 | |||||
8162 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | ||||
8163 | << CondTy << Cond->getSourceRange(); | ||||
8164 | return true; | ||||
8165 | } | ||||
8166 | |||||
8167 | /// Return false if the NullExpr can be promoted to PointerTy, | ||||
8168 | /// true otherwise. | ||||
8169 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | ||||
8170 | QualType PointerTy) { | ||||
8171 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | ||||
8172 | !NullExpr.get()->isNullPointerConstant(S.Context, | ||||
8173 | Expr::NPC_ValueDependentIsNull)) | ||||
8174 | return true; | ||||
8175 | |||||
8176 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | ||||
8177 | return false; | ||||
8178 | } | ||||
8179 | |||||
8180 | /// Checks compatibility between two pointers and return the resulting | ||||
8181 | /// type. | ||||
8182 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | ||||
8183 | ExprResult &RHS, | ||||
8184 | SourceLocation Loc) { | ||||
8185 | QualType LHSTy = LHS.get()->getType(); | ||||
8186 | QualType RHSTy = RHS.get()->getType(); | ||||
8187 | |||||
8188 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | ||||
8189 | // Two identical pointers types are always compatible. | ||||
8190 | return S.Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8191 | } | ||||
8192 | |||||
8193 | QualType lhptee, rhptee; | ||||
8194 | |||||
8195 | // Get the pointee types. | ||||
8196 | bool IsBlockPointer = false; | ||||
8197 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | ||||
8198 | lhptee = LHSBTy->getPointeeType(); | ||||
8199 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | ||||
8200 | IsBlockPointer = true; | ||||
8201 | } else { | ||||
8202 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8203 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8204 | } | ||||
8205 | |||||
8206 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | ||||
8207 | // differently qualified versions of compatible types, the result type is | ||||
8208 | // a pointer to an appropriately qualified version of the composite | ||||
8209 | // type. | ||||
8210 | |||||
8211 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | ||||
8212 | // clause doesn't make sense for our extensions. E.g. address space 2 should | ||||
8213 | // be incompatible with address space 3: they may live on different devices or | ||||
8214 | // anything. | ||||
8215 | Qualifiers lhQual = lhptee.getQualifiers(); | ||||
8216 | Qualifiers rhQual = rhptee.getQualifiers(); | ||||
8217 | |||||
8218 | LangAS ResultAddrSpace = LangAS::Default; | ||||
8219 | LangAS LAddrSpace = lhQual.getAddressSpace(); | ||||
8220 | LangAS RAddrSpace = rhQual.getAddressSpace(); | ||||
8221 | |||||
8222 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | ||||
8223 | // spaces is disallowed. | ||||
8224 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | ||||
8225 | ResultAddrSpace = LAddrSpace; | ||||
8226 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | ||||
8227 | ResultAddrSpace = RAddrSpace; | ||||
8228 | else { | ||||
8229 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
8230 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | ||||
8231 | << RHS.get()->getSourceRange(); | ||||
8232 | return QualType(); | ||||
8233 | } | ||||
8234 | |||||
8235 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | ||||
8236 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | ||||
8237 | lhQual.removeCVRQualifiers(); | ||||
8238 | rhQual.removeCVRQualifiers(); | ||||
8239 | |||||
8240 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | ||||
8241 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | ||||
8242 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | ||||
8243 | // qual types are compatible iff | ||||
8244 | // * corresponded types are compatible | ||||
8245 | // * CVR qualifiers are equal | ||||
8246 | // * address spaces are equal | ||||
8247 | // Thus for conditional operator we merge CVR and address space unqualified | ||||
8248 | // pointees and if there is a composite type we return a pointer to it with | ||||
8249 | // merged qualifiers. | ||||
8250 | LHSCastKind = | ||||
8251 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
8252 | RHSCastKind = | ||||
8253 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
8254 | lhQual.removeAddressSpace(); | ||||
8255 | rhQual.removeAddressSpace(); | ||||
8256 | |||||
8257 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | ||||
8258 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | ||||
8259 | |||||
8260 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | ||||
8261 | |||||
8262 | if (CompositeTy.isNull()) { | ||||
8263 | // In this situation, we assume void* type. No especially good | ||||
8264 | // reason, but this is what gcc does, and we do have to pick | ||||
8265 | // to get a consistent AST. | ||||
8266 | QualType incompatTy; | ||||
8267 | incompatTy = S.Context.getPointerType( | ||||
8268 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | ||||
8269 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | ||||
8270 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | ||||
8271 | |||||
8272 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | ||||
8273 | // for casts between types with incompatible address space qualifiers. | ||||
8274 | // For the following code the compiler produces casts between global and | ||||
8275 | // local address spaces of the corresponded innermost pointees: | ||||
8276 | // local int *global *a; | ||||
8277 | // global int *global *b; | ||||
8278 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | ||||
8279 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | ||||
8280 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8281 | << RHS.get()->getSourceRange(); | ||||
8282 | |||||
8283 | return incompatTy; | ||||
8284 | } | ||||
8285 | |||||
8286 | // The pointer types are compatible. | ||||
8287 | // In case of OpenCL ResultTy should have the address space qualifier | ||||
8288 | // which is a superset of address spaces of both the 2nd and the 3rd | ||||
8289 | // operands of the conditional operator. | ||||
8290 | QualType ResultTy = [&, ResultAddrSpace]() { | ||||
8291 | if (S.getLangOpts().OpenCL) { | ||||
8292 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | ||||
8293 | CompositeQuals.setAddressSpace(ResultAddrSpace); | ||||
8294 | return S.Context | ||||
8295 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | ||||
8296 | .withCVRQualifiers(MergedCVRQual); | ||||
8297 | } | ||||
8298 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | ||||
8299 | }(); | ||||
8300 | if (IsBlockPointer) | ||||
8301 | ResultTy = S.Context.getBlockPointerType(ResultTy); | ||||
8302 | else | ||||
8303 | ResultTy = S.Context.getPointerType(ResultTy); | ||||
8304 | |||||
8305 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | ||||
8306 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | ||||
8307 | return ResultTy; | ||||
8308 | } | ||||
8309 | |||||
8310 | /// Return the resulting type when the operands are both block pointers. | ||||
8311 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | ||||
8312 | ExprResult &LHS, | ||||
8313 | ExprResult &RHS, | ||||
8314 | SourceLocation Loc) { | ||||
8315 | QualType LHSTy = LHS.get()->getType(); | ||||
8316 | QualType RHSTy = RHS.get()->getType(); | ||||
8317 | |||||
8318 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | ||||
8319 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | ||||
8320 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | ||||
8321 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8322 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8323 | return destType; | ||||
8324 | } | ||||
8325 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | ||||
8326 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8327 | << RHS.get()->getSourceRange(); | ||||
8328 | return QualType(); | ||||
8329 | } | ||||
8330 | |||||
8331 | // We have 2 block pointer types. | ||||
8332 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
8333 | } | ||||
8334 | |||||
8335 | /// Return the resulting type when the operands are both pointers. | ||||
8336 | static QualType | ||||
8337 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | ||||
8338 | ExprResult &RHS, | ||||
8339 | SourceLocation Loc) { | ||||
8340 | // get the pointer types | ||||
8341 | QualType LHSTy = LHS.get()->getType(); | ||||
8342 | QualType RHSTy = RHS.get()->getType(); | ||||
8343 | |||||
8344 | // get the "pointed to" types | ||||
8345 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8346 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8347 | |||||
8348 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | ||||
8349 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | ||||
8350 | // Figure out necessary qualifiers (C99 6.5.15p6) | ||||
8351 | QualType destPointee | ||||
8352 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8353 | QualType destType = S.Context.getPointerType(destPointee); | ||||
8354 | // Add qualifiers if necessary. | ||||
8355 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8356 | // Promote to void*. | ||||
8357 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8358 | return destType; | ||||
8359 | } | ||||
8360 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | ||||
8361 | QualType destPointee | ||||
8362 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8363 | QualType destType = S.Context.getPointerType(destPointee); | ||||
8364 | // Add qualifiers if necessary. | ||||
8365 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8366 | // Promote to void*. | ||||
8367 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8368 | return destType; | ||||
8369 | } | ||||
8370 | |||||
8371 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
8372 | } | ||||
8373 | |||||
8374 | /// Return false if the first expression is not an integer and the second | ||||
8375 | /// expression is not a pointer, true otherwise. | ||||
8376 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | ||||
8377 | Expr* PointerExpr, SourceLocation Loc, | ||||
8378 | bool IsIntFirstExpr) { | ||||
8379 | if (!PointerExpr->getType()->isPointerType() || | ||||
8380 | !Int.get()->getType()->isIntegerType()) | ||||
8381 | return false; | ||||
8382 | |||||
8383 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | ||||
8384 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | ||||
8385 | |||||
8386 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | ||||
8387 | << Expr1->getType() << Expr2->getType() | ||||
8388 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | ||||
8389 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | ||||
8390 | CK_IntegralToPointer); | ||||
8391 | return true; | ||||
8392 | } | ||||
8393 | |||||
8394 | /// Simple conversion between integer and floating point types. | ||||
8395 | /// | ||||
8396 | /// Used when handling the OpenCL conditional operator where the | ||||
8397 | /// condition is a vector while the other operands are scalar. | ||||
8398 | /// | ||||
8399 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | ||||
8400 | /// types are either integer or floating type. Between the two | ||||
8401 | /// operands, the type with the higher rank is defined as the "result | ||||
8402 | /// type". The other operand needs to be promoted to the same type. No | ||||
8403 | /// other type promotion is allowed. We cannot use | ||||
8404 | /// UsualArithmeticConversions() for this purpose, since it always | ||||
8405 | /// promotes promotable types. | ||||
8406 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | ||||
8407 | ExprResult &RHS, | ||||
8408 | SourceLocation QuestionLoc) { | ||||
8409 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
8410 | if (LHS.isInvalid()) | ||||
8411 | return QualType(); | ||||
8412 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
8413 | if (RHS.isInvalid()) | ||||
8414 | return QualType(); | ||||
8415 | |||||
8416 | // For conversion purposes, we ignore any qualifiers. | ||||
8417 | // For example, "const float" and "float" are equivalent. | ||||
8418 | QualType LHSType = | ||||
8419 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
8420 | QualType RHSType = | ||||
8421 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
8422 | |||||
8423 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | ||||
8424 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8425 | << LHSType << LHS.get()->getSourceRange(); | ||||
8426 | return QualType(); | ||||
8427 | } | ||||
8428 | |||||
8429 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | ||||
8430 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8431 | << RHSType << RHS.get()->getSourceRange(); | ||||
8432 | return QualType(); | ||||
8433 | } | ||||
8434 | |||||
8435 | // If both types are identical, no conversion is needed. | ||||
8436 | if (LHSType == RHSType) | ||||
8437 | return LHSType; | ||||
8438 | |||||
8439 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
8440 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
8441 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
8442 | /*IsCompAssign = */ false); | ||||
8443 | |||||
8444 | // Finally, we have two differing integer types. | ||||
8445 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
8446 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | ||||
8447 | } | ||||
8448 | |||||
8449 | /// Convert scalar operands to a vector that matches the | ||||
8450 | /// condition in length. | ||||
8451 | /// | ||||
8452 | /// Used when handling the OpenCL conditional operator where the | ||||
8453 | /// condition is a vector while the other operands are scalar. | ||||
8454 | /// | ||||
8455 | /// We first compute the "result type" for the scalar operands | ||||
8456 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | ||||
8457 | /// into a vector of that type where the length matches the condition | ||||
8458 | /// vector type. s6.11.6 requires that the element types of the result | ||||
8459 | /// and the condition must have the same number of bits. | ||||
8460 | static QualType | ||||
8461 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
8462 | QualType CondTy, SourceLocation QuestionLoc) { | ||||
8463 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | ||||
8464 | if (ResTy.isNull()) return QualType(); | ||||
8465 | |||||
8466 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8467 | assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV" , "clang/lib/Sema/SemaExpr.cpp", 8467, __extension__ __PRETTY_FUNCTION__ )); | ||||
8468 | |||||
8469 | // Determine the vector result type | ||||
8470 | unsigned NumElements = CV->getNumElements(); | ||||
8471 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | ||||
8472 | |||||
8473 | // Ensure that all types have the same number of bits | ||||
8474 | if (S.Context.getTypeSize(CV->getElementType()) | ||||
8475 | != S.Context.getTypeSize(ResTy)) { | ||||
8476 | // Since VectorTy is created internally, it does not pretty print | ||||
8477 | // with an OpenCL name. Instead, we just print a description. | ||||
8478 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | ||||
8479 | SmallString<64> Str; | ||||
8480 | llvm::raw_svector_ostream OS(Str); | ||||
8481 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | ||||
8482 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8483 | << CondTy << OS.str(); | ||||
8484 | return QualType(); | ||||
8485 | } | ||||
8486 | |||||
8487 | // Convert operands to the vector result type | ||||
8488 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | ||||
8489 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | ||||
8490 | |||||
8491 | return VectorTy; | ||||
8492 | } | ||||
8493 | |||||
8494 | /// Return false if this is a valid OpenCL condition vector | ||||
8495 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | ||||
8496 | SourceLocation QuestionLoc) { | ||||
8497 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | ||||
8498 | // integral type. | ||||
8499 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | ||||
8500 | assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail ("CondTy", "clang/lib/Sema/SemaExpr.cpp", 8500, __extension__ __PRETTY_FUNCTION__)); | ||||
8501 | QualType EleTy = CondTy->getElementType(); | ||||
8502 | if (EleTy->isIntegerType()) return false; | ||||
8503 | |||||
8504 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8505 | << Cond->getType() << Cond->getSourceRange(); | ||||
8506 | return true; | ||||
8507 | } | ||||
8508 | |||||
8509 | /// Return false if the vector condition type and the vector | ||||
8510 | /// result type are compatible. | ||||
8511 | /// | ||||
8512 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | ||||
8513 | /// number of elements, and their element types have the same number | ||||
8514 | /// of bits. | ||||
8515 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | ||||
8516 | SourceLocation QuestionLoc) { | ||||
8517 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8518 | const VectorType *RV = VecResTy->getAs<VectorType>(); | ||||
8519 | assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail ("CV && RV", "clang/lib/Sema/SemaExpr.cpp", 8519, __extension__ __PRETTY_FUNCTION__)); | ||||
8520 | |||||
8521 | if (CV->getNumElements() != RV->getNumElements()) { | ||||
8522 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | ||||
8523 | << CondTy << VecResTy; | ||||
8524 | return true; | ||||
8525 | } | ||||
8526 | |||||
8527 | QualType CVE = CV->getElementType(); | ||||
8528 | QualType RVE = RV->getElementType(); | ||||
8529 | |||||
8530 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | ||||
8531 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8532 | << CondTy << VecResTy; | ||||
8533 | return true; | ||||
8534 | } | ||||
8535 | |||||
8536 | return false; | ||||
8537 | } | ||||
8538 | |||||
8539 | /// Return the resulting type for the conditional operator in | ||||
8540 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | ||||
8541 | /// s6.3.i) when the condition is a vector type. | ||||
8542 | static QualType | ||||
8543 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | ||||
8544 | ExprResult &LHS, ExprResult &RHS, | ||||
8545 | SourceLocation QuestionLoc) { | ||||
8546 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | ||||
8547 | if (Cond.isInvalid()) | ||||
8548 | return QualType(); | ||||
8549 | QualType CondTy = Cond.get()->getType(); | ||||
8550 | |||||
8551 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | ||||
8552 | return QualType(); | ||||
8553 | |||||
8554 | // If either operand is a vector then find the vector type of the | ||||
8555 | // result as specified in OpenCL v1.1 s6.3.i. | ||||
8556 | if (LHS.get()->getType()->isVectorType() || | ||||
8557 | RHS.get()->getType()->isVectorType()) { | ||||
8558 | bool IsBoolVecLang = | ||||
8559 | !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; | ||||
8560 | QualType VecResTy = | ||||
8561 | S.CheckVectorOperands(LHS, RHS, QuestionLoc, | ||||
8562 | /*isCompAssign*/ false, | ||||
8563 | /*AllowBothBool*/ true, | ||||
8564 | /*AllowBoolConversions*/ false, | ||||
8565 | /*AllowBooleanOperation*/ IsBoolVecLang, | ||||
8566 | /*ReportInvalid*/ true); | ||||
8567 | if (VecResTy.isNull()) | ||||
8568 | return QualType(); | ||||
8569 | // The result type must match the condition type as specified in | ||||
8570 | // OpenCL v1.1 s6.11.6. | ||||
8571 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | ||||
8572 | return QualType(); | ||||
8573 | return VecResTy; | ||||
8574 | } | ||||
8575 | |||||
8576 | // Both operands are scalar. | ||||
8577 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | ||||
8578 | } | ||||
8579 | |||||
8580 | /// Return true if the Expr is block type | ||||
8581 | static bool checkBlockType(Sema &S, const Expr *E) { | ||||
8582 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
8583 | QualType Ty = CE->getCallee()->getType(); | ||||
8584 | if (Ty->isBlockPointerType()) { | ||||
8585 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | ||||
8586 | return true; | ||||
8587 | } | ||||
8588 | } | ||||
8589 | return false; | ||||
8590 | } | ||||
8591 | |||||
8592 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | ||||
8593 | /// In that case, LHS = cond. | ||||
8594 | /// C99 6.5.15 | ||||
8595 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | ||||
8596 | ExprResult &RHS, ExprValueKind &VK, | ||||
8597 | ExprObjectKind &OK, | ||||
8598 | SourceLocation QuestionLoc) { | ||||
8599 | |||||
8600 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | ||||
8601 | if (!LHSResult.isUsable()) return QualType(); | ||||
8602 | LHS = LHSResult; | ||||
8603 | |||||
8604 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | ||||
8605 | if (!RHSResult.isUsable()) return QualType(); | ||||
8606 | RHS = RHSResult; | ||||
8607 | |||||
8608 | // C++ is sufficiently different to merit its own checker. | ||||
8609 | if (getLangOpts().CPlusPlus) | ||||
8610 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | ||||
8611 | |||||
8612 | VK = VK_PRValue; | ||||
8613 | OK = OK_Ordinary; | ||||
8614 | |||||
8615 | if (Context.isDependenceAllowed() && | ||||
8616 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | ||||
8617 | RHS.get()->isTypeDependent())) { | ||||
8618 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 8618, __extension__ __PRETTY_FUNCTION__)); | ||||
8619 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8621, __extension__ __PRETTY_FUNCTION__ )) | ||||
8620 | RHS.get()->containsErrors()) &&(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8621, __extension__ __PRETTY_FUNCTION__ )) | ||||
8621 | "should only occur in error-recovery path.")(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 8621, __extension__ __PRETTY_FUNCTION__ )); | ||||
8622 | return Context.DependentTy; | ||||
8623 | } | ||||
8624 | |||||
8625 | // The OpenCL operator with a vector condition is sufficiently | ||||
8626 | // different to merit its own checker. | ||||
8627 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | ||||
8628 | Cond.get()->getType()->isExtVectorType()) | ||||
8629 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | ||||
8630 | |||||
8631 | // First, check the condition. | ||||
8632 | Cond = UsualUnaryConversions(Cond.get()); | ||||
8633 | if (Cond.isInvalid()) | ||||
8634 | return QualType(); | ||||
8635 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | ||||
8636 | return QualType(); | ||||
8637 | |||||
8638 | // Now check the two expressions. | ||||
8639 | if (LHS.get()->getType()->isVectorType() || | ||||
8640 | RHS.get()->getType()->isVectorType()) | ||||
8641 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, | ||||
8642 | /*AllowBothBool*/ true, | ||||
8643 | /*AllowBoolConversions*/ false, | ||||
8644 | /*AllowBooleanOperation*/ false, | ||||
8645 | /*ReportInvalid*/ true); | ||||
8646 | |||||
8647 | QualType ResTy = | ||||
8648 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | ||||
8649 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8650 | return QualType(); | ||||
8651 | |||||
8652 | QualType LHSTy = LHS.get()->getType(); | ||||
8653 | QualType RHSTy = RHS.get()->getType(); | ||||
8654 | |||||
8655 | // Diagnose attempts to convert between __ibm128, __float128 and long double | ||||
8656 | // where such conversions currently can't be handled. | ||||
8657 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | ||||
8658 | Diag(QuestionLoc, | ||||
8659 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | ||||
8660 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8661 | return QualType(); | ||||
8662 | } | ||||
8663 | |||||
8664 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | ||||
8665 | // selection operator (?:). | ||||
8666 | if (getLangOpts().OpenCL && | ||||
8667 | ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { | ||||
8668 | return QualType(); | ||||
8669 | } | ||||
8670 | |||||
8671 | // If both operands have arithmetic type, do the usual arithmetic conversions | ||||
8672 | // to find a common type: C99 6.5.15p3,5. | ||||
8673 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | ||||
8674 | // Disallow invalid arithmetic conversions, such as those between bit- | ||||
8675 | // precise integers types of different sizes, or between a bit-precise | ||||
8676 | // integer and another type. | ||||
8677 | if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { | ||||
8678 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8679 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8680 | << RHS.get()->getSourceRange(); | ||||
8681 | return QualType(); | ||||
8682 | } | ||||
8683 | |||||
8684 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | ||||
8685 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | ||||
8686 | |||||
8687 | return ResTy; | ||||
8688 | } | ||||
8689 | |||||
8690 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | ||||
8691 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | ||||
8692 | return Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8693 | } | ||||
8694 | |||||
8695 | // If both operands are the same structure or union type, the result is that | ||||
8696 | // type. | ||||
8697 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | ||||
8698 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | ||||
8699 | if (LHSRT->getDecl() == RHSRT->getDecl()) | ||||
8700 | // "If both the operands have structure or union type, the result has | ||||
8701 | // that type." This implies that CV qualifiers are dropped. | ||||
8702 | return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(), | ||||
8703 | RHSTy.getUnqualifiedType()); | ||||
8704 | // FIXME: Type of conditional expression must be complete in C mode. | ||||
8705 | } | ||||
8706 | |||||
8707 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | ||||
8708 | // The following || allows only one side to be void (a GCC-ism). | ||||
8709 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | ||||
8710 | QualType ResTy; | ||||
8711 | if (LHSTy->isVoidType() && RHSTy->isVoidType()) { | ||||
8712 | ResTy = Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8713 | } else if (RHSTy->isVoidType()) { | ||||
8714 | ResTy = RHSTy; | ||||
8715 | Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
8716 | << RHS.get()->getSourceRange(); | ||||
8717 | } else { | ||||
8718 | ResTy = LHSTy; | ||||
8719 | Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
8720 | << LHS.get()->getSourceRange(); | ||||
8721 | } | ||||
8722 | LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid); | ||||
8723 | RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid); | ||||
8724 | return ResTy; | ||||
8725 | } | ||||
8726 | |||||
8727 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | ||||
8728 | // the type of the other operand." | ||||
8729 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | ||||
8730 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | ||||
8731 | |||||
8732 | // All objective-c pointer type analysis is done here. | ||||
8733 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | ||||
8734 | QuestionLoc); | ||||
8735 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8736 | return QualType(); | ||||
8737 | if (!compositeType.isNull()) | ||||
8738 | return compositeType; | ||||
8739 | |||||
8740 | |||||
8741 | // Handle block pointer types. | ||||
8742 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | ||||
8743 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | ||||
8744 | QuestionLoc); | ||||
8745 | |||||
8746 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | ||||
8747 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | ||||
8748 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | ||||
8749 | QuestionLoc); | ||||
8750 | |||||
8751 | // GCC compatibility: soften pointer/integer mismatch. Note that | ||||
8752 | // null pointers have been filtered out by this point. | ||||
8753 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | ||||
8754 | /*IsIntFirstExpr=*/true)) | ||||
8755 | return RHSTy; | ||||
8756 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | ||||
8757 | /*IsIntFirstExpr=*/false)) | ||||
8758 | return LHSTy; | ||||
8759 | |||||
8760 | // Allow ?: operations in which both operands have the same | ||||
8761 | // built-in sizeless type. | ||||
8762 | if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) | ||||
8763 | return Context.getCommonSugaredType(LHSTy, RHSTy); | ||||
8764 | |||||
8765 | // Emit a better diagnostic if one of the expressions is a null pointer | ||||
8766 | // constant and the other is not a pointer type. In this case, the user most | ||||
8767 | // likely forgot to take the address of the other expression. | ||||
8768 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | ||||
8769 | return QualType(); | ||||
8770 | |||||
8771 | // Otherwise, the operands are not compatible. | ||||
8772 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8773 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8774 | << RHS.get()->getSourceRange(); | ||||
8775 | return QualType(); | ||||
8776 | } | ||||
8777 | |||||
8778 | /// FindCompositeObjCPointerType - Helper method to find composite type of | ||||
8779 | /// two objective-c pointer types of the two input expressions. | ||||
8780 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | ||||
8781 | SourceLocation QuestionLoc) { | ||||
8782 | QualType LHSTy = LHS.get()->getType(); | ||||
8783 | QualType RHSTy = RHS.get()->getType(); | ||||
8784 | |||||
8785 | // Handle things like Class and struct objc_class*. Here we case the result | ||||
8786 | // to the pseudo-builtin, because that will be implicitly cast back to the | ||||
8787 | // redefinition type if an attempt is made to access its fields. | ||||
8788 | if (LHSTy->isObjCClassType() && | ||||
8789 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8790 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8791 | return LHSTy; | ||||
8792 | } | ||||
8793 | if (RHSTy->isObjCClassType() && | ||||
8794 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8795 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8796 | return RHSTy; | ||||
8797 | } | ||||
8798 | // And the same for struct objc_object* / id | ||||
8799 | if (LHSTy->isObjCIdType() && | ||||
8800 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8801 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8802 | return LHSTy; | ||||
8803 | } | ||||
8804 | if (RHSTy->isObjCIdType() && | ||||
8805 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8806 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8807 | return RHSTy; | ||||
8808 | } | ||||
8809 | // And the same for struct objc_selector* / SEL | ||||
8810 | if (Context.isObjCSelType(LHSTy) && | ||||
8811 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8812 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | ||||
8813 | return LHSTy; | ||||
8814 | } | ||||
8815 | if (Context.isObjCSelType(RHSTy) && | ||||
8816 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8817 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | ||||
8818 | return RHSTy; | ||||
8819 | } | ||||
8820 | // Check constraints for Objective-C object pointers types. | ||||
8821 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8822 | |||||
8823 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | ||||
8824 | // Two identical object pointer types are always compatible. | ||||
8825 | return LHSTy; | ||||
8826 | } | ||||
8827 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | ||||
8828 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | ||||
8829 | QualType compositeType = LHSTy; | ||||
8830 | |||||
8831 | // If both operands are interfaces and either operand can be | ||||
8832 | // assigned to the other, use that type as the composite | ||||
8833 | // type. This allows | ||||
8834 | // xxx ? (A*) a : (B*) b | ||||
8835 | // where B is a subclass of A. | ||||
8836 | // | ||||
8837 | // Additionally, as for assignment, if either type is 'id' | ||||
8838 | // allow silent coercion. Finally, if the types are | ||||
8839 | // incompatible then make sure to use 'id' as the composite | ||||
8840 | // type so the result is acceptable for sending messages to. | ||||
8841 | |||||
8842 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | ||||
8843 | // It could return the composite type. | ||||
8844 | if (!(compositeType = | ||||
8845 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | ||||
8846 | // Nothing more to do. | ||||
8847 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | ||||
8848 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | ||||
8849 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | ||||
8850 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | ||||
8851 | } else if ((LHSOPT->isObjCQualifiedIdType() || | ||||
8852 | RHSOPT->isObjCQualifiedIdType()) && | ||||
8853 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | ||||
8854 | true)) { | ||||
8855 | // Need to handle "id<xx>" explicitly. | ||||
8856 | // GCC allows qualified id and any Objective-C type to devolve to | ||||
8857 | // id. Currently localizing to here until clear this should be | ||||
8858 | // part of ObjCQualifiedIdTypesAreCompatible. | ||||
8859 | compositeType = Context.getObjCIdType(); | ||||
8860 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | ||||
8861 | compositeType = Context.getObjCIdType(); | ||||
8862 | } else { | ||||
8863 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | ||||
8864 | << LHSTy << RHSTy | ||||
8865 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8866 | QualType incompatTy = Context.getObjCIdType(); | ||||
8867 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | ||||
8868 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | ||||
8869 | return incompatTy; | ||||
8870 | } | ||||
8871 | // The object pointer types are compatible. | ||||
8872 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | ||||
8873 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | ||||
8874 | return compositeType; | ||||
8875 | } | ||||
8876 | // Check Objective-C object pointer types and 'void *' | ||||
8877 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8878 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8879 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8880 | // so these types are not compatible. | ||||
8881 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8882 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8883 | LHS = RHS = true; | ||||
8884 | return QualType(); | ||||
8885 | } | ||||
8886 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8887 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8888 | QualType destPointee | ||||
8889 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8890 | QualType destType = Context.getPointerType(destPointee); | ||||
8891 | // Add qualifiers if necessary. | ||||
8892 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8893 | // Promote to void*. | ||||
8894 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8895 | return destType; | ||||
8896 | } | ||||
8897 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | ||||
8898 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8899 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8900 | // so these types are not compatible. | ||||
8901 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8902 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8903 | LHS = RHS = true; | ||||
8904 | return QualType(); | ||||
8905 | } | ||||
8906 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8907 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8908 | QualType destPointee | ||||
8909 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8910 | QualType destType = Context.getPointerType(destPointee); | ||||
8911 | // Add qualifiers if necessary. | ||||
8912 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8913 | // Promote to void*. | ||||
8914 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8915 | return destType; | ||||
8916 | } | ||||
8917 | return QualType(); | ||||
8918 | } | ||||
8919 | |||||
8920 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | ||||
8921 | /// ParenRange in parentheses. | ||||
8922 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | ||||
8923 | const PartialDiagnostic &Note, | ||||
8924 | SourceRange ParenRange) { | ||||
8925 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | ||||
8926 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | ||||
8927 | EndLoc.isValid()) { | ||||
8928 | Self.Diag(Loc, Note) | ||||
8929 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | ||||
8930 | << FixItHint::CreateInsertion(EndLoc, ")"); | ||||
8931 | } else { | ||||
8932 | // We can't display the parentheses, so just show the bare note. | ||||
8933 | Self.Diag(Loc, Note) << ParenRange; | ||||
8934 | } | ||||
8935 | } | ||||
8936 | |||||
8937 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | ||||
8938 | return BinaryOperator::isAdditiveOp(Opc) || | ||||
8939 | BinaryOperator::isMultiplicativeOp(Opc) || | ||||
8940 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | ||||
8941 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | ||||
8942 | // not any of the logical operators. Bitwise-xor is commonly used as a | ||||
8943 | // logical-xor because there is no logical-xor operator. The logical | ||||
8944 | // operators, including uses of xor, have a high false positive rate for | ||||
8945 | // precedence warnings. | ||||
8946 | } | ||||
8947 | |||||
8948 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | ||||
8949 | /// expression, either using a built-in or overloaded operator, | ||||
8950 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | ||||
8951 | /// expression. | ||||
8952 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | ||||
8953 | Expr **RHSExprs) { | ||||
8954 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | ||||
8955 | E = E->IgnoreImpCasts(); | ||||
8956 | E = E->IgnoreConversionOperatorSingleStep(); | ||||
8957 | E = E->IgnoreImpCasts(); | ||||
8958 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | ||||
8959 | E = MTE->getSubExpr(); | ||||
8960 | E = E->IgnoreImpCasts(); | ||||
8961 | } | ||||
8962 | |||||
8963 | // Built-in binary operator. | ||||
8964 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | ||||
8965 | if (IsArithmeticOp(OP->getOpcode())) { | ||||
8966 | *Opcode = OP->getOpcode(); | ||||
8967 | *RHSExprs = OP->getRHS(); | ||||
8968 | return true; | ||||
8969 | } | ||||
8970 | } | ||||
8971 | |||||
8972 | // Overloaded operator. | ||||
8973 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
8974 | if (Call->getNumArgs() != 2) | ||||
8975 | return false; | ||||
8976 | |||||
8977 | // Make sure this is really a binary operator that is safe to pass into | ||||
8978 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | ||||
8979 | OverloadedOperatorKind OO = Call->getOperator(); | ||||
8980 | if (OO < OO_Plus || OO > OO_Arrow || | ||||
8981 | OO == OO_PlusPlus || OO == OO_MinusMinus) | ||||
8982 | return false; | ||||
8983 | |||||
8984 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | ||||
8985 | if (IsArithmeticOp(OpKind)) { | ||||
8986 | *Opcode = OpKind; | ||||
8987 | *RHSExprs = Call->getArg(1); | ||||
8988 | return true; | ||||
8989 | } | ||||
8990 | } | ||||
8991 | |||||
8992 | return false; | ||||
8993 | } | ||||
8994 | |||||
8995 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | ||||
8996 | /// or is a logical expression such as (x==y) which has int type, but is | ||||
8997 | /// commonly interpreted as boolean. | ||||
8998 | static bool ExprLooksBoolean(Expr *E) { | ||||
8999 | E = E->IgnoreParenImpCasts(); | ||||
9000 | |||||
9001 | if (E->getType()->isBooleanType()) | ||||
9002 | return true; | ||||
9003 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | ||||
9004 | return OP->isComparisonOp() || OP->isLogicalOp(); | ||||
9005 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | ||||
9006 | return OP->getOpcode() == UO_LNot; | ||||
9007 | if (E->getType()->isPointerType()) | ||||
9008 | return true; | ||||
9009 | // FIXME: What about overloaded operator calls returning "unspecified boolean | ||||
9010 | // type"s (commonly pointer-to-members)? | ||||
9011 | |||||
9012 | return false; | ||||
9013 | } | ||||
9014 | |||||
9015 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | ||||
9016 | /// and binary operator are mixed in a way that suggests the programmer assumed | ||||
9017 | /// the conditional operator has higher precedence, for example: | ||||
9018 | /// "int x = a + someBinaryCondition ? 1 : 2". | ||||
9019 | static void DiagnoseConditionalPrecedence(Sema &Self, | ||||
9020 | SourceLocation OpLoc, | ||||
9021 | Expr *Condition, | ||||
9022 | Expr *LHSExpr, | ||||
9023 | Expr *RHSExpr) { | ||||
9024 | BinaryOperatorKind CondOpcode; | ||||
9025 | Expr *CondRHS; | ||||
9026 | |||||
9027 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | ||||
9028 | return; | ||||
9029 | if (!ExprLooksBoolean(CondRHS)) | ||||
9030 | return; | ||||
9031 | |||||
9032 | // The condition is an arithmetic binary expression, with a right- | ||||
9033 | // hand side that looks boolean, so warn. | ||||
9034 | |||||
9035 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | ||||
9036 | ? diag::warn_precedence_bitwise_conditional | ||||
9037 | : diag::warn_precedence_conditional; | ||||
9038 | |||||
9039 | Self.Diag(OpLoc, DiagID) | ||||
9040 | << Condition->getSourceRange() | ||||
9041 | << BinaryOperator::getOpcodeStr(CondOpcode); | ||||
9042 | |||||
9043 | SuggestParentheses( | ||||
9044 | Self, OpLoc, | ||||
9045 | Self.PDiag(diag::note_precedence_silence) | ||||
9046 | << BinaryOperator::getOpcodeStr(CondOpcode), | ||||
9047 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | ||||
9048 | |||||
9049 | SuggestParentheses(Self, OpLoc, | ||||
9050 | Self.PDiag(diag::note_precedence_conditional_first), | ||||
9051 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
9052 | } | ||||
9053 | |||||
9054 | /// Compute the nullability of a conditional expression. | ||||
9055 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | ||||
9056 | QualType LHSTy, QualType RHSTy, | ||||
9057 | ASTContext &Ctx) { | ||||
9058 | if (!ResTy->isAnyPointerType()) | ||||
9059 | return ResTy; | ||||
9060 | |||||
9061 | auto GetNullability = [&Ctx](QualType Ty) { | ||||
9062 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | ||||
9063 | if (Kind) { | ||||
9064 | // For our purposes, treat _Nullable_result as _Nullable. | ||||
9065 | if (*Kind == NullabilityKind::NullableResult) | ||||
9066 | return NullabilityKind::Nullable; | ||||
9067 | return *Kind; | ||||
9068 | } | ||||
9069 | return NullabilityKind::Unspecified; | ||||
9070 | }; | ||||
9071 | |||||
9072 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | ||||
9073 | NullabilityKind MergedKind; | ||||
9074 | |||||
9075 | // Compute nullability of a binary conditional expression. | ||||
9076 | if (IsBin) { | ||||
9077 | if (LHSKind == NullabilityKind::NonNull) | ||||
9078 | MergedKind = NullabilityKind::NonNull; | ||||
9079 | else | ||||
9080 | MergedKind = RHSKind; | ||||
9081 | // Compute nullability of a normal conditional expression. | ||||
9082 | } else { | ||||
9083 | if (LHSKind == NullabilityKind::Nullable || | ||||
9084 | RHSKind == NullabilityKind::Nullable) | ||||
9085 | MergedKind = NullabilityKind::Nullable; | ||||
9086 | else if (LHSKind == NullabilityKind::NonNull) | ||||
9087 | MergedKind = RHSKind; | ||||
9088 | else if (RHSKind == NullabilityKind::NonNull) | ||||
9089 | MergedKind = LHSKind; | ||||
9090 | else | ||||
9091 | MergedKind = NullabilityKind::Unspecified; | ||||
9092 | } | ||||
9093 | |||||
9094 | // Return if ResTy already has the correct nullability. | ||||
9095 | if (GetNullability(ResTy) == MergedKind) | ||||
9096 | return ResTy; | ||||
9097 | |||||
9098 | // Strip all nullability from ResTy. | ||||
9099 | while (ResTy->getNullability(Ctx)) | ||||
9100 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | ||||
9101 | |||||
9102 | // Create a new AttributedType with the new nullability kind. | ||||
9103 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | ||||
9104 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | ||||
9105 | } | ||||
9106 | |||||
9107 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | ||||
9108 | /// in the case of a the GNU conditional expr extension. | ||||
9109 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | ||||
9110 | SourceLocation ColonLoc, | ||||
9111 | Expr *CondExpr, Expr *LHSExpr, | ||||
9112 | Expr *RHSExpr) { | ||||
9113 | if (!Context.isDependenceAllowed()) { | ||||
9114 | // C cannot handle TypoExpr nodes in the condition because it | ||||
9115 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
9116 | // been dealt with before checking the operands. | ||||
9117 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | ||||
9118 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | ||||
9119 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | ||||
9120 | |||||
9121 | if (!CondResult.isUsable()) | ||||
9122 | return ExprError(); | ||||
9123 | |||||
9124 | if (LHSExpr) { | ||||
9125 | if (!LHSResult.isUsable()) | ||||
9126 | return ExprError(); | ||||
9127 | } | ||||
9128 | |||||
9129 | if (!RHSResult.isUsable()) | ||||
9130 | return ExprError(); | ||||
9131 | |||||
9132 | CondExpr = CondResult.get(); | ||||
9133 | LHSExpr = LHSResult.get(); | ||||
9134 | RHSExpr = RHSResult.get(); | ||||
9135 | } | ||||
9136 | |||||
9137 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | ||||
9138 | // was the condition. | ||||
9139 | OpaqueValueExpr *opaqueValue = nullptr; | ||||
9140 | Expr *commonExpr = nullptr; | ||||
9141 | if (!LHSExpr) { | ||||
9142 | commonExpr = CondExpr; | ||||
9143 | // Lower out placeholder types first. This is important so that we don't | ||||
9144 | // try to capture a placeholder. This happens in few cases in C++; such | ||||
9145 | // as Objective-C++'s dictionary subscripting syntax. | ||||
9146 | if (commonExpr->hasPlaceholderType()) { | ||||
9147 | ExprResult result = CheckPlaceholderExpr(commonExpr); | ||||
9148 | if (!result.isUsable()) return ExprError(); | ||||
9149 | commonExpr = result.get(); | ||||
9150 | } | ||||
9151 | // We usually want to apply unary conversions *before* saving, except | ||||
9152 | // in the special case of a C++ l-value conditional. | ||||
9153 | if (!(getLangOpts().CPlusPlus | ||||
9154 | && !commonExpr->isTypeDependent() | ||||
9155 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | ||||
9156 | && commonExpr->isGLValue() | ||||
9157 | && commonExpr->isOrdinaryOrBitFieldObject() | ||||
9158 | && RHSExpr->isOrdinaryOrBitFieldObject() | ||||
9159 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | ||||
9160 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | ||||
9161 | if (commonRes.isInvalid()) | ||||
9162 | return ExprError(); | ||||
9163 | commonExpr = commonRes.get(); | ||||
9164 | } | ||||
9165 | |||||
9166 | // If the common expression is a class or array prvalue, materialize it | ||||
9167 | // so that we can safely refer to it multiple times. | ||||
9168 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || | ||||
9169 | commonExpr->getType()->isArrayType())) { | ||||
9170 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | ||||
9171 | if (MatExpr.isInvalid()) | ||||
9172 | return ExprError(); | ||||
9173 | commonExpr = MatExpr.get(); | ||||
9174 | } | ||||
9175 | |||||
9176 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | ||||
9177 | commonExpr->getType(), | ||||
9178 | commonExpr->getValueKind(), | ||||
9179 | commonExpr->getObjectKind(), | ||||
9180 | commonExpr); | ||||
9181 | LHSExpr = CondExpr = opaqueValue; | ||||
9182 | } | ||||
9183 | |||||
9184 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | ||||
9185 | ExprValueKind VK = VK_PRValue; | ||||
9186 | ExprObjectKind OK = OK_Ordinary; | ||||
9187 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | ||||
9188 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | ||||
9189 | VK, OK, QuestionLoc); | ||||
9190 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | ||||
9191 | RHS.isInvalid()) | ||||
9192 | return ExprError(); | ||||
9193 | |||||
9194 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | ||||
9195 | RHS.get()); | ||||
9196 | |||||
9197 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | ||||
9198 | |||||
9199 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | ||||
9200 | Context); | ||||
9201 | |||||
9202 | if (!commonExpr) | ||||
9203 | return new (Context) | ||||
9204 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | ||||
9205 | RHS.get(), result, VK, OK); | ||||
9206 | |||||
9207 | return new (Context) BinaryConditionalOperator( | ||||
9208 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | ||||
9209 | ColonLoc, result, VK, OK); | ||||
9210 | } | ||||
9211 | |||||
9212 | // Check if we have a conversion between incompatible cmse function pointer | ||||
9213 | // types, that is, a conversion between a function pointer with the | ||||
9214 | // cmse_nonsecure_call attribute and one without. | ||||
9215 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | ||||
9216 | QualType ToType) { | ||||
9217 | if (const auto *ToFn = | ||||
9218 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | ||||
9219 | if (const auto *FromFn = | ||||
9220 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | ||||
9221 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | ||||
9222 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | ||||
9223 | |||||
9224 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | ||||
9225 | } | ||||
9226 | } | ||||
9227 | return false; | ||||
9228 | } | ||||
9229 | |||||
9230 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | ||||
9231 | // being closely modeled after the C99 spec:-). The odd characteristic of this | ||||
9232 | // routine is it effectively iqnores the qualifiers on the top level pointee. | ||||
9233 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | ||||
9234 | // FIXME: add a couple examples in this comment. | ||||
9235 | static Sema::AssignConvertType | ||||
9236 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | ||||
9237 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9237, __extension__ __PRETTY_FUNCTION__ )); | ||||
9238 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9238, __extension__ __PRETTY_FUNCTION__ )); | ||||
9239 | |||||
9240 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
9241 | const Type *lhptee, *rhptee; | ||||
9242 | Qualifiers lhq, rhq; | ||||
9243 | std::tie(lhptee, lhq) = | ||||
9244 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | ||||
9245 | std::tie(rhptee, rhq) = | ||||
9246 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | ||||
9247 | |||||
9248 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
9249 | |||||
9250 | // C99 6.5.16.1p1: This following citation is common to constraints | ||||
9251 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | ||||
9252 | // qualifiers of the type *pointed to* by the right; | ||||
9253 | |||||
9254 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | ||||
9255 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | ||||
9256 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | ||||
9257 | // Ignore lifetime for further calculation. | ||||
9258 | lhq.removeObjCLifetime(); | ||||
9259 | rhq.removeObjCLifetime(); | ||||
9260 | } | ||||
9261 | |||||
9262 | if (!lhq.compatiblyIncludes(rhq)) { | ||||
9263 | // Treat address-space mismatches as fatal. | ||||
9264 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | ||||
9265 | return Sema::IncompatiblePointerDiscardsQualifiers; | ||||
9266 | |||||
9267 | // It's okay to add or remove GC or lifetime qualifiers when converting to | ||||
9268 | // and from void*. | ||||
9269 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | ||||
9270 | .compatiblyIncludes( | ||||
9271 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | ||||
9272 | && (lhptee->isVoidType() || rhptee->isVoidType())) | ||||
9273 | ; // keep old | ||||
9274 | |||||
9275 | // Treat lifetime mismatches as fatal. | ||||
9276 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | ||||
9277 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | ||||
9278 | |||||
9279 | // For GCC/MS compatibility, other qualifier mismatches are treated | ||||
9280 | // as still compatible in C. | ||||
9281 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
9282 | } | ||||
9283 | |||||
9284 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | ||||
9285 | // incomplete type and the other is a pointer to a qualified or unqualified | ||||
9286 | // version of void... | ||||
9287 | if (lhptee->isVoidType()) { | ||||
9288 | if (rhptee->isIncompleteOrObjectType()) | ||||
9289 | return ConvTy; | ||||
9290 | |||||
9291 | // As an extension, we allow cast to/from void* to function pointer. | ||||
9292 | assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void (0) : __assert_fail ("rhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp" , 9292, __extension__ __PRETTY_FUNCTION__)); | ||||
9293 | return Sema::FunctionVoidPointer; | ||||
9294 | } | ||||
9295 | |||||
9296 | if (rhptee->isVoidType()) { | ||||
9297 | if (lhptee->isIncompleteOrObjectType()) | ||||
9298 | return ConvTy; | ||||
9299 | |||||
9300 | // As an extension, we allow cast to/from void* to function pointer. | ||||
9301 | assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void (0) : __assert_fail ("lhptee->isFunctionType()", "clang/lib/Sema/SemaExpr.cpp" , 9301, __extension__ __PRETTY_FUNCTION__)); | ||||
9302 | return Sema::FunctionVoidPointer; | ||||
9303 | } | ||||
9304 | |||||
9305 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | ||||
9306 | // unqualified versions of compatible types, ... | ||||
9307 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | ||||
9308 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | ||||
9309 | // Check if the pointee types are compatible ignoring the sign. | ||||
9310 | // We explicitly check for char so that we catch "char" vs | ||||
9311 | // "unsigned char" on systems where "char" is unsigned. | ||||
9312 | if (lhptee->isCharType()) | ||||
9313 | ltrans = S.Context.UnsignedCharTy; | ||||
9314 | else if (lhptee->hasSignedIntegerRepresentation()) | ||||
9315 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | ||||
9316 | |||||
9317 | if (rhptee->isCharType()) | ||||
9318 | rtrans = S.Context.UnsignedCharTy; | ||||
9319 | else if (rhptee->hasSignedIntegerRepresentation()) | ||||
9320 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | ||||
9321 | |||||
9322 | if (ltrans == rtrans) { | ||||
9323 | // Types are compatible ignoring the sign. Qualifier incompatibility | ||||
9324 | // takes priority over sign incompatibility because the sign | ||||
9325 | // warning can be disabled. | ||||
9326 | if (ConvTy != Sema::Compatible) | ||||
9327 | return ConvTy; | ||||
9328 | |||||
9329 | return Sema::IncompatiblePointerSign; | ||||
9330 | } | ||||
9331 | |||||
9332 | // If we are a multi-level pointer, it's possible that our issue is simply | ||||
9333 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | ||||
9334 | // the eventual target type is the same and the pointers have the same | ||||
9335 | // level of indirection, this must be the issue. | ||||
9336 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | ||||
9337 | do { | ||||
9338 | std::tie(lhptee, lhq) = | ||||
9339 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | ||||
9340 | std::tie(rhptee, rhq) = | ||||
9341 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | ||||
9342 | |||||
9343 | // Inconsistent address spaces at this point is invalid, even if the | ||||
9344 | // address spaces would be compatible. | ||||
9345 | // FIXME: This doesn't catch address space mismatches for pointers of | ||||
9346 | // different nesting levels, like: | ||||
9347 | // __local int *** a; | ||||
9348 | // int ** b = a; | ||||
9349 | // It's not clear how to actually determine when such pointers are | ||||
9350 | // invalidly incompatible. | ||||
9351 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | ||||
9352 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | ||||
9353 | |||||
9354 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | ||||
9355 | |||||
9356 | if (lhptee == rhptee) | ||||
9357 | return Sema::IncompatibleNestedPointerQualifiers; | ||||
9358 | } | ||||
9359 | |||||
9360 | // General pointer incompatibility takes priority over qualifiers. | ||||
9361 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | ||||
9362 | return Sema::IncompatibleFunctionPointer; | ||||
9363 | return Sema::IncompatiblePointer; | ||||
9364 | } | ||||
9365 | if (!S.getLangOpts().CPlusPlus && | ||||
9366 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | ||||
9367 | return Sema::IncompatibleFunctionPointer; | ||||
9368 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | ||||
9369 | return Sema::IncompatibleFunctionPointer; | ||||
9370 | return ConvTy; | ||||
9371 | } | ||||
9372 | |||||
9373 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | ||||
9374 | /// block pointer types are compatible or whether a block and normal pointer | ||||
9375 | /// are compatible. It is more restrict than comparing two function pointer | ||||
9376 | // types. | ||||
9377 | static Sema::AssignConvertType | ||||
9378 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
9379 | QualType RHSType) { | ||||
9380 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9380, __extension__ __PRETTY_FUNCTION__ )); | ||||
9381 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9381, __extension__ __PRETTY_FUNCTION__ )); | ||||
9382 | |||||
9383 | QualType lhptee, rhptee; | ||||
9384 | |||||
9385 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
9386 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | ||||
9387 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | ||||
9388 | |||||
9389 | // In C++, the types have to match exactly. | ||||
9390 | if (S.getLangOpts().CPlusPlus) | ||||
9391 | return Sema::IncompatibleBlockPointer; | ||||
9392 | |||||
9393 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
9394 | |||||
9395 | // For blocks we enforce that qualifiers are identical. | ||||
9396 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | ||||
9397 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | ||||
9398 | if (S.getLangOpts().OpenCL) { | ||||
9399 | LQuals.removeAddressSpace(); | ||||
9400 | RQuals.removeAddressSpace(); | ||||
9401 | } | ||||
9402 | if (LQuals != RQuals) | ||||
9403 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
9404 | |||||
9405 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | ||||
9406 | // assignment. | ||||
9407 | // The current behavior is similar to C++ lambdas. A block might be | ||||
9408 | // assigned to a variable iff its return type and parameters are compatible | ||||
9409 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | ||||
9410 | // an assignment. Presumably it should behave in way that a function pointer | ||||
9411 | // assignment does in C, so for each parameter and return type: | ||||
9412 | // * CVR and address space of LHS should be a superset of CVR and address | ||||
9413 | // space of RHS. | ||||
9414 | // * unqualified types should be compatible. | ||||
9415 | if (S.getLangOpts().OpenCL) { | ||||
9416 | if (!S.Context.typesAreBlockPointerCompatible( | ||||
9417 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | ||||
9418 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | ||||
9419 | return Sema::IncompatibleBlockPointer; | ||||
9420 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | ||||
9421 | return Sema::IncompatibleBlockPointer; | ||||
9422 | |||||
9423 | return ConvTy; | ||||
9424 | } | ||||
9425 | |||||
9426 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | ||||
9427 | /// for assignment compatibility. | ||||
9428 | static Sema::AssignConvertType | ||||
9429 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
9430 | QualType RHSType) { | ||||
9431 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS was not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9431, __extension__ __PRETTY_FUNCTION__ )); | ||||
9432 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS was not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "clang/lib/Sema/SemaExpr.cpp", 9432, __extension__ __PRETTY_FUNCTION__ )); | ||||
9433 | |||||
9434 | if (LHSType->isObjCBuiltinType()) { | ||||
9435 | // Class is not compatible with ObjC object pointers. | ||||
9436 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | ||||
9437 | !RHSType->isObjCQualifiedClassType()) | ||||
9438 | return Sema::IncompatiblePointer; | ||||
9439 | return Sema::Compatible; | ||||
9440 | } | ||||
9441 | if (RHSType->isObjCBuiltinType()) { | ||||
9442 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | ||||
9443 | !LHSType->isObjCQualifiedClassType()) | ||||
9444 | return Sema::IncompatiblePointer; | ||||
9445 | return Sema::Compatible; | ||||
9446 | } | ||||
9447 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9448 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9449 | |||||
9450 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | ||||
9451 | // make an exception for id<P> | ||||
9452 | !LHSType->isObjCQualifiedIdType()) | ||||
9453 | return Sema::CompatiblePointerDiscardsQualifiers; | ||||
9454 | |||||
9455 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | ||||
9456 | return Sema::Compatible; | ||||
9457 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | ||||
9458 | return Sema::IncompatibleObjCQualifiedId; | ||||
9459 | return Sema::IncompatiblePointer; | ||||
9460 | } | ||||
9461 | |||||
9462 | Sema::AssignConvertType | ||||
9463 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | ||||
9464 | QualType LHSType, QualType RHSType) { | ||||
9465 | // Fake up an opaque expression. We don't actually care about what | ||||
9466 | // cast operations are required, so if CheckAssignmentConstraints | ||||
9467 | // adds casts to this they'll be wasted, but fortunately that doesn't | ||||
9468 | // usually happen on valid code. | ||||
9469 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); | ||||
9470 | ExprResult RHSPtr = &RHSExpr; | ||||
9471 | CastKind K; | ||||
9472 | |||||
9473 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | ||||
9474 | } | ||||
9475 | |||||
9476 | /// This helper function returns true if QT is a vector type that has element | ||||
9477 | /// type ElementType. | ||||
9478 | static bool isVector(QualType QT, QualType ElementType) { | ||||
9479 | if (const VectorType *VT = QT->getAs<VectorType>()) | ||||
9480 | return VT->getElementType().getCanonicalType() == ElementType; | ||||
9481 | return false; | ||||
9482 | } | ||||
9483 | |||||
9484 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | ||||
9485 | /// has code to accommodate several GCC extensions when type checking | ||||
9486 | /// pointers. Here are some objectionable examples that GCC considers warnings: | ||||
9487 | /// | ||||
9488 | /// int a, *pint; | ||||
9489 | /// short *pshort; | ||||
9490 | /// struct foo *pfoo; | ||||
9491 | /// | ||||
9492 | /// pint = pshort; // warning: assignment from incompatible pointer type | ||||
9493 | /// a = pint; // warning: assignment makes integer from pointer without a cast | ||||
9494 | /// pint = a; // warning: assignment makes pointer from integer without a cast | ||||
9495 | /// pint = pfoo; // warning: assignment from incompatible pointer type | ||||
9496 | /// | ||||
9497 | /// As a result, the code for dealing with pointers is more complex than the | ||||
9498 | /// C99 spec dictates. | ||||
9499 | /// | ||||
9500 | /// Sets 'Kind' for any result kind except Incompatible. | ||||
9501 | Sema::AssignConvertType | ||||
9502 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | ||||
9503 | CastKind &Kind, bool ConvertRHS) { | ||||
9504 | QualType RHSType = RHS.get()->getType(); | ||||
9505 | QualType OrigLHSType = LHSType; | ||||
9506 | |||||
9507 | // Get canonical types. We're not formatting these types, just comparing | ||||
9508 | // them. | ||||
9509 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | ||||
9510 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | ||||
9511 | |||||
9512 | // Common case: no conversion required. | ||||
9513 | if (LHSType == RHSType) { | ||||
| |||||
9514 | Kind = CK_NoOp; | ||||
9515 | return Compatible; | ||||
9516 | } | ||||
9517 | |||||
9518 | // If the LHS has an __auto_type, there are no additional type constraints | ||||
9519 | // to be worried about. | ||||
9520 | if (const auto *AT
| ||||
9521 | if (AT->isGNUAutoType()) { | ||||
9522 | Kind = CK_NoOp; | ||||
9523 | return Compatible; | ||||
9524 | } | ||||
9525 | } | ||||
9526 | |||||
9527 | // If we have an atomic type, try a non-atomic assignment, then just add an | ||||
9528 | // atomic qualification step. | ||||
9529 | if (const AtomicType *AtomicTy
| ||||
9530 | Sema::AssignConvertType result = | ||||
9531 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | ||||
9532 | if (result != Compatible) | ||||
9533 | return result; | ||||
9534 | if (Kind != CK_NoOp && ConvertRHS) | ||||
9535 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | ||||
9536 | Kind = CK_NonAtomicToAtomic; | ||||
9537 | return Compatible; | ||||
9538 | } | ||||
9539 | |||||
9540 | // If the left-hand side is a reference type, then we are in a | ||||
9541 | // (rare!) case where we've allowed the use of references in C, | ||||
9542 | // e.g., as a parameter type in a built-in function. In this case, | ||||
9543 | // just make sure that the type referenced is compatible with the | ||||
9544 | // right-hand side type. The caller is responsible for adjusting | ||||
9545 | // LHSType so that the resulting expression does not have reference | ||||
9546 | // type. | ||||
9547 | if (const ReferenceType *LHSTypeRef
| ||||
9548 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | ||||
9549 | Kind = CK_LValueBitCast; | ||||
9550 | return Compatible; | ||||
9551 | } | ||||
9552 | return Incompatible; | ||||
9553 | } | ||||
9554 | |||||
9555 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | ||||
9556 | // to the same ExtVector type. | ||||
9557 | if (LHSType->isExtVectorType()) { | ||||
9558 | if (RHSType->isExtVectorType()) | ||||
9559 | return Incompatible; | ||||
9560 | if (RHSType->isArithmeticType()) { | ||||
9561 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | ||||
9562 | if (ConvertRHS) | ||||
9563 | RHS = prepareVectorSplat(LHSType, RHS.get()); | ||||
9564 | Kind = CK_VectorSplat; | ||||
9565 | return Compatible; | ||||
9566 | } | ||||
9567 | } | ||||
9568 | |||||
9569 | // Conversions to or from vector type. | ||||
9570 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | ||||
9571 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | ||||
9572 | // Allow assignments of an AltiVec vector type to an equivalent GCC | ||||
9573 | // vector type and vice versa | ||||
9574 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9575 | Kind = CK_BitCast; | ||||
9576 | return Compatible; | ||||
9577 | } | ||||
9578 | |||||
9579 | // If we are allowing lax vector conversions, and LHS and RHS are both | ||||
9580 | // vectors, the total size only needs to be the same. This is a bitcast; | ||||
9581 | // no bits are changed but the result type is different. | ||||
9582 | if (isLaxVectorConversion(RHSType, LHSType)) { | ||||
9583 | // The default for lax vector conversions with Altivec vectors will | ||||
9584 | // change, so if we are converting between vector types where | ||||
9585 | // at least one is an Altivec vector, emit a warning. | ||||
9586 | if (anyAltivecTypes(RHSType, LHSType) && | ||||
9587 | !areSameVectorElemTypes(RHSType, LHSType)) | ||||
9588 | Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) | ||||
9589 | << RHSType << LHSType; | ||||
9590 | Kind = CK_BitCast; | ||||
9591 | return IncompatibleVectors; | ||||
9592 | } | ||||
9593 | } | ||||
9594 | |||||
9595 | // When the RHS comes from another lax conversion (e.g. binops between | ||||
9596 | // scalars and vectors) the result is canonicalized as a vector. When the | ||||
9597 | // LHS is also a vector, the lax is allowed by the condition above. Handle | ||||
9598 | // the case where LHS is a scalar. | ||||
9599 | if (LHSType->isScalarType()) { | ||||
9600 | const VectorType *VecType = RHSType->getAs<VectorType>(); | ||||
9601 | if (VecType && VecType->getNumElements() == 1 && | ||||
9602 | isLaxVectorConversion(RHSType, LHSType)) { | ||||
9603 | if (VecType->getVectorKind() == VectorType::AltiVecVector) | ||||
9604 | Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) | ||||
9605 | << RHSType << LHSType; | ||||
9606 | ExprResult *VecExpr = &RHS; | ||||
9607 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | ||||
9608 | Kind = CK_BitCast; | ||||
9609 | return Compatible; | ||||
9610 | } | ||||
9611 | } | ||||
9612 | |||||
9613 | // Allow assignments between fixed-length and sizeless SVE vectors. | ||||
9614 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | ||||
9615 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | ||||
9616 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | ||||
9617 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | ||||
9618 | Kind = CK_BitCast; | ||||
9619 | return Compatible; | ||||
9620 | } | ||||
9621 | |||||
9622 | return Incompatible; | ||||
9623 | } | ||||
9624 | |||||
9625 | // Diagnose attempts to convert between __ibm128, __float128 and long double | ||||
9626 | // where such conversions currently can't be handled. | ||||
9627 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
9628 | return Incompatible; | ||||
9629 | |||||
9630 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | ||||
9631 | // discards the imaginary part. | ||||
9632 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | ||||
9633 | !LHSType->getAs<ComplexType>()) | ||||
9634 | return Incompatible; | ||||
9635 | |||||
9636 | // Arithmetic conversions. | ||||
9637 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | ||||
9638 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | ||||
9639 | if (ConvertRHS) | ||||
9640 | Kind = PrepareScalarCast(RHS, LHSType); | ||||
9641 | return Compatible; | ||||
9642 | } | ||||
9643 | |||||
9644 | // Conversions to normal pointers. | ||||
9645 | if (const PointerType *LHSPointer
| ||||
9646 | // U* -> T* | ||||
9647 | if (isa<PointerType>(RHSType)) { | ||||
9648 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9649 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | ||||
9650 | if (AddrSpaceL != AddrSpaceR) | ||||
9651 | Kind = CK_AddressSpaceConversion; | ||||
9652 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | ||||
9653 | Kind = CK_NoOp; | ||||
9654 | else | ||||
9655 | Kind = CK_BitCast; | ||||
9656 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9657 | } | ||||
9658 | |||||
9659 | // int -> T* | ||||
9660 | if (RHSType->isIntegerType()) { | ||||
9661 | Kind = CK_IntegralToPointer; // FIXME: null? | ||||
9662 | return IntToPointer; | ||||
9663 | } | ||||
9664 | |||||
9665 | // C pointers are not compatible with ObjC object pointers, | ||||
9666 | // with two exceptions: | ||||
9667 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9668 | // - conversions to void* | ||||
9669 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9670 | Kind = CK_BitCast; | ||||
9671 | return Compatible; | ||||
9672 | } | ||||
9673 | |||||
9674 | // - conversions from 'Class' to the redefinition type | ||||
9675 | if (RHSType->isObjCClassType() && | ||||
9676 | Context.hasSameType(LHSType, | ||||
9677 | Context.getObjCClassRedefinitionType())) { | ||||
9678 | Kind = CK_BitCast; | ||||
9679 | return Compatible; | ||||
9680 | } | ||||
9681 | |||||
9682 | Kind = CK_BitCast; | ||||
9683 | return IncompatiblePointer; | ||||
9684 | } | ||||
9685 | |||||
9686 | // U^ -> void* | ||||
9687 | if (RHSType->getAs<BlockPointerType>()) { | ||||
9688 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9689 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9690 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9691 | ->getPointeeType() | ||||
9692 | .getAddressSpace(); | ||||
9693 | Kind = | ||||
9694 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9695 | return Compatible; | ||||
9696 | } | ||||
9697 | } | ||||
9698 | |||||
9699 | return Incompatible; | ||||
9700 | } | ||||
9701 | |||||
9702 | // Conversions to block pointers. | ||||
9703 | if (isa<BlockPointerType>(LHSType)) { | ||||
9704 | // U^ -> T^ | ||||
9705 | if (RHSType->isBlockPointerType()) { | ||||
9706 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | ||||
9707 | ->getPointeeType() | ||||
9708 | .getAddressSpace(); | ||||
9709 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
| |||||
9710 | ->getPointeeType() | ||||
9711 | .getAddressSpace(); | ||||
9712 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9713 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9714 | } | ||||
9715 | |||||
9716 | // int or null -> T^ | ||||
9717 | if (RHSType->isIntegerType()) { | ||||
9718 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9719 | return IntToBlockPointer; | ||||
9720 | } | ||||
9721 | |||||
9722 | // id -> T^ | ||||
9723 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | ||||
9724 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9725 | return Compatible; | ||||
9726 | } | ||||
9727 | |||||
9728 | // void* -> T^ | ||||
9729 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | ||||
9730 | if (RHSPT->getPointeeType()->isVoidType()) { | ||||
9731 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9732 | return Compatible; | ||||
9733 | } | ||||
9734 | |||||
9735 | return Incompatible; | ||||
9736 | } | ||||
9737 | |||||
9738 | // Conversions to Objective-C pointers. | ||||
9739 | if (isa<ObjCObjectPointerType>(LHSType)) { | ||||
9740 | // A* -> B* | ||||
9741 | if (RHSType->isObjCObjectPointerType()) { | ||||
9742 | Kind = CK_BitCast; | ||||
9743 | Sema::AssignConvertType result = | ||||
9744 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9745 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9746 | result == Compatible && | ||||
9747 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | ||||
9748 | result = IncompatibleObjCWeakRef; | ||||
9749 | return result; | ||||
9750 | } | ||||
9751 | |||||
9752 | // int or null -> A* | ||||
9753 | if (RHSType->isIntegerType()) { | ||||
9754 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9755 | return IntToPointer; | ||||
9756 | } | ||||
9757 | |||||
9758 | // In general, C pointers are not compatible with ObjC object pointers, | ||||
9759 | // with two exceptions: | ||||
9760 | if (isa<PointerType>(RHSType)) { | ||||
9761 | Kind = CK_CPointerToObjCPointerCast; | ||||
9762 | |||||
9763 | // - conversions from 'void*' | ||||
9764 | if (RHSType->isVoidPointerType()) { | ||||
9765 | return Compatible; | ||||
9766 | } | ||||
9767 | |||||
9768 | // - conversions to 'Class' from its redefinition type | ||||
9769 | if (LHSType->isObjCClassType() && | ||||
9770 | Context.hasSameType(RHSType, | ||||
9771 | Context.getObjCClassRedefinitionType())) { | ||||
9772 | return Compatible; | ||||
9773 | } | ||||
9774 | |||||
9775 | return IncompatiblePointer; | ||||
9776 | } | ||||
9777 | |||||
9778 | // Only under strict condition T^ is compatible with an Objective-C pointer. | ||||
9779 | if (RHSType->isBlockPointerType() && | ||||
9780 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
9781 | if (ConvertRHS) | ||||
9782 | maybeExtendBlockObject(RHS); | ||||
9783 | Kind = CK_BlockPointerToObjCPointerCast; | ||||
9784 | return Compatible; | ||||
9785 | } | ||||
9786 | |||||
9787 | return Incompatible; | ||||
9788 | } | ||||
9789 | |||||
9790 | // Conversions from pointers that are not covered by the above. | ||||
9791 | if (isa<PointerType>(RHSType)) { | ||||
9792 | // T* -> _Bool | ||||
9793 | if (LHSType == Context.BoolTy) { | ||||
9794 | Kind = CK_PointerToBoolean; | ||||
9795 | return Compatible; | ||||
9796 | } | ||||
9797 | |||||
9798 | // T* -> int | ||||
9799 | if (LHSType->isIntegerType()) { | ||||
9800 | Kind = CK_PointerToIntegral; | ||||
9801 | return PointerToInt; | ||||
9802 | } | ||||
9803 | |||||
9804 | return Incompatible; | ||||
9805 | } | ||||
9806 | |||||
9807 | // Conversions from Objective-C pointers that are not covered by the above. | ||||
9808 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9809 | // T* -> _Bool | ||||
9810 | if (LHSType == Context.BoolTy) { | ||||
9811 | Kind = CK_PointerToBoolean; | ||||
9812 | return Compatible; | ||||
9813 | } | ||||
9814 | |||||
9815 | // T* -> int | ||||
9816 | if (LHSType->isIntegerType()) { | ||||
9817 | Kind = CK_PointerToIntegral; | ||||
9818 | return PointerToInt; | ||||
9819 | } | ||||
9820 | |||||
9821 | return Incompatible; | ||||
9822 | } | ||||
9823 | |||||
9824 | // struct A -> struct B | ||||
9825 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | ||||
9826 | if (Context.typesAreCompatible(LHSType, RHSType)) { | ||||
9827 | Kind = CK_NoOp; | ||||
9828 | return Compatible; | ||||
9829 | } | ||||
9830 | } | ||||
9831 | |||||
9832 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | ||||
9833 | Kind = CK_IntToOCLSampler; | ||||
9834 | return Compatible; | ||||
9835 | } | ||||
9836 | |||||
9837 | return Incompatible; | ||||
9838 | } | ||||
9839 | |||||
9840 | /// Constructs a transparent union from an expression that is | ||||
9841 | /// used to initialize the transparent union. | ||||
9842 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | ||||
9843 | ExprResult &EResult, QualType UnionType, | ||||
9844 | FieldDecl *Field) { | ||||
9845 | // Build an initializer list that designates the appropriate member | ||||
9846 | // of the transparent union. | ||||
9847 | Expr *E = EResult.get(); | ||||
9848 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | ||||
9849 | E, SourceLocation()); | ||||
9850 | Initializer->setType(UnionType); | ||||
9851 | Initializer->setInitializedFieldInUnion(Field); | ||||
9852 | |||||
9853 | // Build a compound literal constructing a value of the transparent | ||||
9854 | // union type from this initializer list. | ||||
9855 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | ||||
9856 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | ||||
9857 | VK_PRValue, Initializer, false); | ||||
9858 | } | ||||
9859 | |||||
9860 | Sema::AssignConvertType | ||||
9861 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | ||||
9862 | ExprResult &RHS) { | ||||
9863 | QualType RHSType = RHS.get()->getType(); | ||||
9864 | |||||
9865 | // If the ArgType is a Union type, we want to handle a potential | ||||
9866 | // transparent_union GCC extension. | ||||
9867 | const RecordType *UT = ArgType->getAsUnionType(); | ||||
9868 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | ||||
9869 | return Incompatible; | ||||
9870 | |||||
9871 | // The field to initialize within the transparent union. | ||||
9872 | RecordDecl *UD = UT->getDecl(); | ||||
9873 | FieldDecl *InitField = nullptr; | ||||
9874 | // It's compatible if the expression matches any of the fields. | ||||
9875 | for (auto *it : UD->fields()) { | ||||
9876 | if (it->getType()->isPointerType()) { | ||||
9877 | // If the transparent union contains a pointer type, we allow: | ||||
9878 | // 1) void pointer | ||||
9879 | // 2) null pointer constant | ||||
9880 | if (RHSType->isPointerType()) | ||||
9881 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | ||||
9882 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | ||||
9883 | InitField = it; | ||||
9884 | break; | ||||
9885 | } | ||||
9886 | |||||
9887 | if (RHS.get()->isNullPointerConstant(Context, | ||||
9888 | Expr::NPC_ValueDependentIsNull)) { | ||||
9889 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | ||||
9890 | CK_NullToPointer); | ||||
9891 | InitField = it; | ||||
9892 | break; | ||||
9893 | } | ||||
9894 | } | ||||
9895 | |||||
9896 | CastKind Kind; | ||||
9897 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | ||||
9898 | == Compatible) { | ||||
9899 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | ||||
9900 | InitField = it; | ||||
9901 | break; | ||||
9902 | } | ||||
9903 | } | ||||
9904 | |||||
9905 | if (!InitField) | ||||
9906 | return Incompatible; | ||||
9907 | |||||
9908 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | ||||
9909 | return Compatible; | ||||
9910 | } | ||||
9911 | |||||
9912 | Sema::AssignConvertType | ||||
9913 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | ||||
9914 | bool Diagnose, | ||||
9915 | bool DiagnoseCFAudited, | ||||
9916 | bool ConvertRHS) { | ||||
9917 | // We need to be able to tell the caller whether we diagnosed a problem, if | ||||
9918 | // they ask us to issue diagnostics. | ||||
9919 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast <bool> ((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed") ? void (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "clang/lib/Sema/SemaExpr.cpp", 9919, __extension__ __PRETTY_FUNCTION__ )); | ||||
9920 | |||||
9921 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | ||||
9922 | // we can't avoid *all* modifications at the moment, so we need some somewhere | ||||
9923 | // to put the updated value. | ||||
9924 | ExprResult LocalRHS = CallerRHS; | ||||
9925 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | ||||
9926 | |||||
9927 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | ||||
9928 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | ||||
9929 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||
9930 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
9931 | Diag(RHS.get()->getExprLoc(), | ||||
9932 | diag::warn_noderef_to_dereferenceable_pointer) | ||||
9933 | << RHS.get()->getSourceRange(); | ||||
9934 | } | ||||
9935 | } | ||||
9936 | } | ||||
9937 | |||||
9938 | if (getLangOpts().CPlusPlus) { | ||||
9939 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | ||||
9940 | // C++ 5.17p3: If the left operand is not of class type, the | ||||
9941 | // expression is implicitly converted (C++ 4) to the | ||||
9942 | // cv-unqualified type of the left operand. | ||||
9943 | QualType RHSType = RHS.get()->getType(); | ||||
9944 | if (Diagnose) { | ||||
9945 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9946 | AA_Assigning); | ||||
9947 | } else { | ||||
9948 | ImplicitConversionSequence ICS = | ||||
9949 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9950 | /*SuppressUserConversions=*/false, | ||||
9951 | AllowedExplicit::None, | ||||
9952 | /*InOverloadResolution=*/false, | ||||
9953 | /*CStyle=*/false, | ||||
9954 | /*AllowObjCWritebackConversion=*/false); | ||||
9955 | if (ICS.isFailure()) | ||||
9956 | return Incompatible; | ||||
9957 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9958 | ICS, AA_Assigning); | ||||
9959 | } | ||||
9960 | if (RHS.isInvalid()) | ||||
9961 | return Incompatible; | ||||
9962 | Sema::AssignConvertType result = Compatible; | ||||
9963 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9964 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | ||||
9965 | result = IncompatibleObjCWeakRef; | ||||
9966 | return result; | ||||
9967 | } | ||||
9968 | |||||
9969 | // FIXME: Currently, we fall through and treat C++ classes like C | ||||
9970 | // structures. | ||||
9971 | // FIXME: We also fall through for atomics; not sure what should | ||||
9972 | // happen there, though. | ||||
9973 | } else if (RHS.get()->getType() == Context.OverloadTy) { | ||||
9974 | // As a set of extensions to C, we support overloading on functions. These | ||||
9975 | // functions need to be resolved here. | ||||
9976 | DeclAccessPair DAP; | ||||
9977 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | ||||
9978 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | ||||
9979 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | ||||
9980 | else | ||||
9981 | return Incompatible; | ||||
9982 | } | ||||
9983 | |||||
9984 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | ||||
9985 | // a null pointer constant. | ||||
9986 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | ||||
9987 | LHSType->isBlockPointerType()) && | ||||
9988 | RHS.get()->isNullPointerConstant(Context, | ||||
9989 | Expr::NPC_ValueDependentIsNull)) { | ||||
9990 | if (Diagnose || ConvertRHS) { | ||||
9991 | CastKind Kind; | ||||
9992 | CXXCastPath Path; | ||||
9993 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | ||||
9994 | /*IgnoreBaseAccess=*/false, Diagnose); | ||||
9995 | if (ConvertRHS) | ||||
9996 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); | ||||
9997 | } | ||||
9998 | return Compatible; | ||||
9999 | } | ||||
10000 | |||||
10001 | // OpenCL queue_t type assignment. | ||||
10002 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | ||||
10003 | Context, Expr::NPC_ValueDependentIsNull)) { | ||||
10004 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
10005 | return Compatible; | ||||
10006 | } | ||||
10007 | |||||
10008 | // This check seems unnatural, however it is necessary to ensure the proper | ||||
10009 | // conversion of functions/arrays. If the conversion were done for all | ||||
10010 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | ||||
10011 | // expressions that suppress this implicit conversion (&, sizeof). | ||||
10012 | // | ||||
10013 | // Suppress this for references: C++ 8.5.3p5. | ||||
10014 | if (!LHSType->isReferenceType()) { | ||||
10015 | // FIXME: We potentially allocate here even if ConvertRHS is false. | ||||
10016 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | ||||
10017 | if (RHS.isInvalid()) | ||||
10018 | return Incompatible; | ||||
10019 | } | ||||
10020 | CastKind Kind; | ||||
10021 | Sema::AssignConvertType result = | ||||
10022 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | ||||
10023 | |||||
10024 | // C99 6.5.16.1p2: The value of the right operand is converted to the | ||||
10025 | // type of the assignment expression. | ||||
10026 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | ||||
10027 | // so that we can use references in built-in functions even in C. | ||||
10028 | // The getNonReferenceType() call makes sure that the resulting expression | ||||
10029 | // does not have reference type. | ||||
10030 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | ||||
10031 | QualType Ty = LHSType.getNonLValueExprType(Context); | ||||
10032 | Expr *E = RHS.get(); | ||||
10033 | |||||
10034 | // Check for various Objective-C errors. If we are not reporting | ||||
10035 | // diagnostics and just checking for errors, e.g., during overload | ||||
10036 | // resolution, return Incompatible to indicate the failure. | ||||
10037 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
10038 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | ||||
10039 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | ||||
10040 | if (!Diagnose) | ||||
10041 | return Incompatible; | ||||
10042 | } | ||||
10043 | if (getLangOpts().ObjC && | ||||
10044 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | ||||
10045 | E->getType(), E, Diagnose) || | ||||
10046 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | ||||
10047 | if (!Diagnose) | ||||
10048 | return Incompatible; | ||||
10049 | // Replace the expression with a corrected version and continue so we | ||||
10050 | // can find further errors. | ||||
10051 | RHS = E; | ||||
10052 | return Compatible; | ||||
10053 | } | ||||
10054 | |||||
10055 | if (ConvertRHS) | ||||
10056 | RHS = ImpCastExprToType(E, Ty, Kind); | ||||
10057 | } | ||||
10058 | |||||
10059 | return result; | ||||
10060 | } | ||||
10061 | |||||
10062 | namespace { | ||||
10063 | /// The original operand to an operator, prior to the application of the usual | ||||
10064 | /// arithmetic conversions and converting the arguments of a builtin operator | ||||
10065 | /// candidate. | ||||
10066 | struct OriginalOperand { | ||||
10067 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | ||||
10068 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | ||||
10069 | Op = MTE->getSubExpr(); | ||||
10070 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | ||||
10071 | Op = BTE->getSubExpr(); | ||||
10072 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | ||||
10073 | Orig = ICE->getSubExprAsWritten(); | ||||
10074 | Conversion = ICE->getConversionFunction(); | ||||
10075 | } | ||||
10076 | } | ||||
10077 | |||||
10078 | QualType getType() const { return Orig->getType(); } | ||||
10079 | |||||
10080 | Expr *Orig; | ||||
10081 | NamedDecl *Conversion; | ||||
10082 | }; | ||||
10083 | } | ||||
10084 | |||||
10085 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | ||||
10086 | ExprResult &RHS) { | ||||
10087 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | ||||
10088 | |||||
10089 | Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
10090 | << OrigLHS.getType() << OrigRHS.getType() | ||||
10091 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10092 | |||||
10093 | // If a user-defined conversion was applied to either of the operands prior | ||||
10094 | // to applying the built-in operator rules, tell the user about it. | ||||
10095 | if (OrigLHS.Conversion) { | ||||
10096 | Diag(OrigLHS.Conversion->getLocation(), | ||||
10097 | diag::note_typecheck_invalid_operands_converted) | ||||
10098 | << 0 << LHS.get()->getType(); | ||||
10099 | } | ||||
10100 | if (OrigRHS.Conversion) { | ||||
10101 | Diag(OrigRHS.Conversion->getLocation(), | ||||
10102 | diag::note_typecheck_invalid_operands_converted) | ||||
10103 | << 1 << RHS.get()->getType(); | ||||
10104 | } | ||||
10105 | |||||
10106 | return QualType(); | ||||
10107 | } | ||||
10108 | |||||
10109 | // Diagnose cases where a scalar was implicitly converted to a vector and | ||||
10110 | // diagnose the underlying types. Otherwise, diagnose the error | ||||
10111 | // as invalid vector logical operands for non-C++ cases. | ||||
10112 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | ||||
10113 | ExprResult &RHS) { | ||||
10114 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | ||||
10115 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | ||||
10116 | |||||
10117 | bool LHSNatVec = LHSType->isVectorType(); | ||||
10118 | bool RHSNatVec = RHSType->isVectorType(); | ||||
10119 | |||||
10120 | if (!(LHSNatVec && RHSNatVec)) { | ||||
10121 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | ||||
10122 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | ||||
10123 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
10124 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | ||||
10125 | << Vector->getSourceRange(); | ||||
10126 | return QualType(); | ||||
10127 | } | ||||
10128 | |||||
10129 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
10130 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10131 | << RHS.get()->getSourceRange(); | ||||
10132 | |||||
10133 | return QualType(); | ||||
10134 | } | ||||
10135 | |||||
10136 | /// Try to convert a value of non-vector type to a vector type by converting | ||||
10137 | /// the type to the element type of the vector and then performing a splat. | ||||
10138 | /// If the language is OpenCL, we only use conversions that promote scalar | ||||
10139 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | ||||
10140 | /// for float->int. | ||||
10141 | /// | ||||
10142 | /// OpenCL V2.0 6.2.6.p2: | ||||
10143 | /// An error shall occur if any scalar operand type has greater rank | ||||
10144 | /// than the type of the vector element. | ||||
10145 | /// | ||||
10146 | /// \param scalar - if non-null, actually perform the conversions | ||||
10147 | /// \return true if the operation fails (but without diagnosing the failure) | ||||
10148 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | ||||
10149 | QualType scalarTy, | ||||
10150 | QualType vectorEltTy, | ||||
10151 | QualType vectorTy, | ||||
10152 | unsigned &DiagID) { | ||||
10153 | // The conversion to apply to the scalar before splatting it, | ||||
10154 | // if necessary. | ||||
10155 | CastKind scalarCast = CK_NoOp; | ||||
10156 | |||||
10157 | if (vectorEltTy->isIntegralType(S.Context)) { | ||||
10158 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | ||||
10159 | (scalarTy->isIntegerType() && | ||||
10160 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | ||||
10161 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
10162 | return true; | ||||
10163 | } | ||||
10164 | if (!scalarTy->isIntegralType(S.Context)) | ||||
10165 | return true; | ||||
10166 | scalarCast = CK_IntegralCast; | ||||
10167 | } else if (vectorEltTy->isRealFloatingType()) { | ||||
10168 | if (scalarTy->isRealFloatingType()) { | ||||
10169 | if (S.getLangOpts().OpenCL && | ||||
10170 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | ||||
10171 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
10172 | return true; | ||||
10173 | } | ||||
10174 | scalarCast = CK_FloatingCast; | ||||
10175 | } | ||||
10176 | else if (scalarTy->isIntegralType(S.Context)) | ||||
10177 | scalarCast = CK_IntegralToFloating; | ||||
10178 | else | ||||
10179 | return true; | ||||
10180 | } else { | ||||
10181 | return true; | ||||
10182 | } | ||||
10183 | |||||
10184 | // Adjust scalar if desired. | ||||
10185 | if (scalar) { | ||||
10186 | if (scalarCast != CK_NoOp) | ||||
10187 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | ||||
10188 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | ||||
10189 | } | ||||
10190 | return false; | ||||
10191 | } | ||||
10192 | |||||
10193 | /// Convert vector E to a vector with the same number of elements but different | ||||
10194 | /// element type. | ||||
10195 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | ||||
10196 | const auto *VecTy = E->getType()->getAs<VectorType>(); | ||||
10197 | assert(VecTy && "Expression E must be a vector")(static_cast <bool> (VecTy && "Expression E must be a vector" ) ? void (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "clang/lib/Sema/SemaExpr.cpp", 10197, __extension__ __PRETTY_FUNCTION__ )); | ||||
10198 | QualType NewVecTy = | ||||
10199 | VecTy->isExtVectorType() | ||||
10200 | ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) | ||||
10201 | : S.Context.getVectorType(ElementType, VecTy->getNumElements(), | ||||
10202 | VecTy->getVectorKind()); | ||||
10203 | |||||
10204 | // Look through the implicit cast. Return the subexpression if its type is | ||||
10205 | // NewVecTy. | ||||
10206 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
10207 | if (ICE->getSubExpr()->getType() == NewVecTy) | ||||
10208 | return ICE->getSubExpr(); | ||||
10209 | |||||
10210 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | ||||
10211 | return S.ImpCastExprToType(E, NewVecTy, Cast); | ||||
10212 | } | ||||
10213 | |||||
10214 | /// Test if a (constant) integer Int can be casted to another integer type | ||||
10215 | /// IntTy without losing precision. | ||||
10216 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | ||||
10217 | QualType OtherIntTy) { | ||||
10218 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
10219 | |||||
10220 | // Reject cases where the value of the Int is unknown as that would | ||||
10221 | // possibly cause truncation, but accept cases where the scalar can be | ||||
10222 | // demoted without loss of precision. | ||||
10223 | Expr::EvalResult EVResult; | ||||
10224 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
10225 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | ||||
10226 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | ||||
10227 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | ||||
10228 | |||||
10229 | if (CstInt) { | ||||
10230 | // If the scalar is constant and is of a higher order and has more active | ||||
10231 | // bits that the vector element type, reject it. | ||||
10232 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
10233 | unsigned NumBits = IntSigned | ||||
10234 | ? (Result.isNegative() ? Result.getMinSignedBits() | ||||
10235 | : Result.getActiveBits()) | ||||
10236 | : Result.getActiveBits(); | ||||
10237 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | ||||
10238 | return true; | ||||
10239 | |||||
10240 | // If the signedness of the scalar type and the vector element type | ||||
10241 | // differs and the number of bits is greater than that of the vector | ||||
10242 | // element reject it. | ||||
10243 | return (IntSigned != OtherIntSigned && | ||||
10244 | NumBits > S.Context.getIntWidth(OtherIntTy)); | ||||
10245 | } | ||||
10246 | |||||
10247 | // Reject cases where the value of the scalar is not constant and it's | ||||
10248 | // order is greater than that of the vector element type. | ||||
10249 | return (Order < 0); | ||||
10250 | } | ||||
10251 | |||||
10252 | /// Test if a (constant) integer Int can be casted to floating point type | ||||
10253 | /// FloatTy without losing precision. | ||||
10254 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | ||||
10255 | QualType FloatTy) { | ||||
10256 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
10257 | |||||
10258 | // Determine if the integer constant can be expressed as a floating point | ||||
10259 | // number of the appropriate type. | ||||
10260 | Expr::EvalResult EVResult; | ||||
10261 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
10262 | |||||
10263 | uint64_t Bits = 0; | ||||
10264 | if (CstInt) { | ||||
10265 | // Reject constants that would be truncated if they were converted to | ||||
10266 | // the floating point type. Test by simple to/from conversion. | ||||
10267 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | ||||
10268 | // could be avoided if there was a convertFromAPInt method | ||||
10269 | // which could signal back if implicit truncation occurred. | ||||
10270 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
10271 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | ||||
10272 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | ||||
10273 | llvm::APFloat::rmTowardZero); | ||||
10274 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | ||||
10275 | !IntTy->hasSignedIntegerRepresentation()); | ||||
10276 | bool Ignored = false; | ||||
10277 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | ||||
10278 | &Ignored); | ||||
10279 | if (Result != ConvertBack) | ||||
10280 | return true; | ||||
10281 | } else { | ||||
10282 | // Reject types that cannot be fully encoded into the mantissa of | ||||
10283 | // the float. | ||||
10284 | Bits = S.Context.getTypeSize(IntTy); | ||||
10285 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | ||||
10286 | S.Context.getFloatTypeSemantics(FloatTy)); | ||||
10287 | if (Bits > FloatPrec) | ||||
10288 | return true; | ||||
10289 | } | ||||
10290 | |||||
10291 | return false; | ||||
10292 | } | ||||
10293 | |||||
10294 | /// Attempt to convert and splat Scalar into a vector whose types matches | ||||
10295 | /// Vector following GCC conversion rules. The rule is that implicit | ||||
10296 | /// conversion can occur when Scalar can be casted to match Vector's element | ||||
10297 | /// type without causing truncation of Scalar. | ||||
10298 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | ||||
10299 | ExprResult *Vector) { | ||||
10300 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | ||||
10301 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | ||||
10302 | QualType VectorEltTy; | ||||
10303 | |||||
10304 | if (const auto *VT = VectorTy->getAs<VectorType>()) { | ||||
10305 | assert(!isa<ExtVectorType>(VT) &&(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "clang/lib/Sema/SemaExpr.cpp", 10306, __extension__ __PRETTY_FUNCTION__ )) | ||||
10306 | "ExtVectorTypes should not be handled here!")(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "clang/lib/Sema/SemaExpr.cpp", 10306, __extension__ __PRETTY_FUNCTION__ )); | ||||
10307 | VectorEltTy = VT->getElementType(); | ||||
10308 | } else if (VectorTy->isVLSTBuiltinType()) { | ||||
10309 | VectorEltTy = | ||||
10310 | VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext()); | ||||
10311 | } else { | ||||
10312 | llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here")::llvm::llvm_unreachable_internal("Only Fixed-Length and SVE Vector types are handled here" , "clang/lib/Sema/SemaExpr.cpp", 10312); | ||||
10313 | } | ||||
10314 | |||||
10315 | // Reject cases where the vector element type or the scalar element type are | ||||
10316 | // not integral or floating point types. | ||||
10317 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | ||||
10318 | return true; | ||||
10319 | |||||
10320 | // The conversion to apply to the scalar before splatting it, | ||||
10321 | // if necessary. | ||||
10322 | CastKind ScalarCast = CK_NoOp; | ||||
10323 | |||||
10324 | // Accept cases where the vector elements are integers and the scalar is | ||||
10325 | // an integer. | ||||
10326 | // FIXME: Notionally if the scalar was a floating point value with a precise | ||||
10327 | // integral representation, we could cast it to an appropriate integer | ||||
10328 | // type and then perform the rest of the checks here. GCC will perform | ||||
10329 | // this conversion in some cases as determined by the input language. | ||||
10330 | // We should accept it on a language independent basis. | ||||
10331 | if (VectorEltTy->isIntegralType(S.Context) && | ||||
10332 | ScalarTy->isIntegralType(S.Context) && | ||||
10333 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | ||||
10334 | |||||
10335 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | ||||
10336 | return true; | ||||
10337 | |||||
10338 | ScalarCast = CK_IntegralCast; | ||||
10339 | } else if (VectorEltTy->isIntegralType(S.Context) && | ||||
10340 | ScalarTy->isRealFloatingType()) { | ||||
10341 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | ||||
10342 | ScalarCast = CK_FloatingToIntegral; | ||||
10343 | else | ||||
10344 | return true; | ||||
10345 | } else if (VectorEltTy->isRealFloatingType()) { | ||||
10346 | if (ScalarTy->isRealFloatingType()) { | ||||
10347 | |||||
10348 | // Reject cases where the scalar type is not a constant and has a higher | ||||
10349 | // Order than the vector element type. | ||||
10350 | llvm::APFloat Result(0.0); | ||||
10351 | |||||
10352 | // Determine whether this is a constant scalar. In the event that the | ||||
10353 | // value is dependent (and thus cannot be evaluated by the constant | ||||
10354 | // evaluator), skip the evaluation. This will then diagnose once the | ||||
10355 | // expression is instantiated. | ||||
10356 | bool CstScalar = Scalar->get()->isValueDependent() || | ||||
10357 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | ||||
10358 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | ||||
10359 | if (!CstScalar && Order < 0) | ||||
10360 | return true; | ||||
10361 | |||||
10362 | // If the scalar cannot be safely casted to the vector element type, | ||||
10363 | // reject it. | ||||
10364 | if (CstScalar) { | ||||
10365 | bool Truncated = false; | ||||
10366 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | ||||
10367 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | ||||
10368 | if (Truncated) | ||||
10369 | return true; | ||||
10370 | } | ||||
10371 | |||||
10372 | ScalarCast = CK_FloatingCast; | ||||
10373 | } else if (ScalarTy->isIntegralType(S.Context)) { | ||||
10374 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | ||||
10375 | return true; | ||||
10376 | |||||
10377 | ScalarCast = CK_IntegralToFloating; | ||||
10378 | } else | ||||
10379 | return true; | ||||
10380 | } else if (ScalarTy->isEnumeralType()) | ||||
10381 | return true; | ||||
10382 | |||||
10383 | // Adjust scalar if desired. | ||||
10384 | if (Scalar) { | ||||
10385 | if (ScalarCast != CK_NoOp) | ||||
10386 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | ||||
10387 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | ||||
10388 | } | ||||
10389 | return false; | ||||
10390 | } | ||||
10391 | |||||
10392 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10393 | SourceLocation Loc, bool IsCompAssign, | ||||
10394 | bool AllowBothBool, | ||||
10395 | bool AllowBoolConversions, | ||||
10396 | bool AllowBoolOperation, | ||||
10397 | bool ReportInvalid) { | ||||
10398 | if (!IsCompAssign) { | ||||
10399 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
10400 | if (LHS.isInvalid()) | ||||
10401 | return QualType(); | ||||
10402 | } | ||||
10403 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
10404 | if (RHS.isInvalid()) | ||||
10405 | return QualType(); | ||||
10406 | |||||
10407 | // For conversion purposes, we ignore any qualifiers. | ||||
10408 | // For example, "const float" and "float" are equivalent. | ||||
10409 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
10410 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
10411 | |||||
10412 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | ||||
10413 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | ||||
10414 | assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void ( 0) : __assert_fail ("LHSVecType || RHSVecType", "clang/lib/Sema/SemaExpr.cpp" , 10414, __extension__ __PRETTY_FUNCTION__)); | ||||
10415 | |||||
10416 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | ||||
10417 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | ||||
10418 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); | ||||
10419 | |||||
10420 | // AltiVec-style "vector bool op vector bool" combinations are allowed | ||||
10421 | // for some operators but not others. | ||||
10422 | if (!AllowBothBool && | ||||
10423 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
10424 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10425 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); | ||||
10426 | |||||
10427 | // This operation may not be performed on boolean vectors. | ||||
10428 | if (!AllowBoolOperation && | ||||
10429 | (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) | ||||
10430 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); | ||||
10431 | |||||
10432 | // If the vector types are identical, return. | ||||
10433 | if (Context.hasSameType(LHSType, RHSType)) | ||||
10434 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
10435 | |||||
10436 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | ||||
10437 | if (LHSVecType && RHSVecType && | ||||
10438 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
10439 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10440 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
10441 | return LHSType; | ||||
10442 | } | ||||
10443 | |||||
10444 | if (!IsCompAssign) | ||||
10445 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
10446 | return RHSType; | ||||
10447 | } | ||||
10448 | |||||
10449 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | ||||
10450 | // can be mixed, with the result being the non-bool type. The non-bool | ||||
10451 | // operand must have integer element type. | ||||
10452 | if (AllowBoolConversions && LHSVecType && RHSVecType && | ||||
10453 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | ||||
10454 | (Context.getTypeSize(LHSVecType->getElementType()) == | ||||
10455 | Context.getTypeSize(RHSVecType->getElementType()))) { | ||||
10456 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
10457 | LHSVecType->getElementType()->isIntegerType() && | ||||
10458 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | ||||
10459 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
10460 | return LHSType; | ||||
10461 | } | ||||
10462 | if (!IsCompAssign && | ||||
10463 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
10464 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
10465 | RHSVecType->getElementType()->isIntegerType()) { | ||||
10466 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
10467 | return RHSType; | ||||
10468 | } | ||||
10469 | } | ||||
10470 | |||||
10471 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | ||||
10472 | // since the ambiguity can affect the ABI. | ||||
10473 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | ||||
10474 | const VectorType *VecType = SecondType->getAs<VectorType>(); | ||||
10475 | return FirstType->isSizelessBuiltinType() && VecType && | ||||
10476 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | ||||
10477 | VecType->getVectorKind() == | ||||
10478 | VectorType::SveFixedLengthPredicateVector); | ||||
10479 | }; | ||||
10480 | |||||
10481 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | ||||
10482 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | ||||
10483 | return QualType(); | ||||
10484 | } | ||||
10485 | |||||
10486 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | ||||
10487 | // since the ambiguity can affect the ABI. | ||||
10488 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | ||||
10489 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | ||||
10490 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | ||||
10491 | |||||
10492 | if (FirstVecType && SecondVecType) | ||||
10493 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | ||||
10494 | (SecondVecType->getVectorKind() == | ||||
10495 | VectorType::SveFixedLengthDataVector || | ||||
10496 | SecondVecType->getVectorKind() == | ||||
10497 | VectorType::SveFixedLengthPredicateVector); | ||||
10498 | |||||
10499 | return FirstType->isSizelessBuiltinType() && SecondVecType && | ||||
10500 | SecondVecType->getVectorKind() == VectorType::GenericVector; | ||||
10501 | }; | ||||
10502 | |||||
10503 | if (IsSveGnuConversion(LHSType, RHSType) || | ||||
10504 | IsSveGnuConversion(RHSType, LHSType)) { | ||||
10505 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | ||||
10506 | return QualType(); | ||||
10507 | } | ||||
10508 | |||||
10509 | // If there's a vector type and a scalar, try to convert the scalar to | ||||
10510 | // the vector element type and splat. | ||||
10511 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | ||||
10512 | if (!RHSVecType) { | ||||
10513 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10514 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | ||||
10515 | LHSVecType->getElementType(), LHSType, | ||||
10516 | DiagID)) | ||||
10517 | return LHSType; | ||||
10518 | } else { | ||||
10519 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
10520 | return LHSType; | ||||
10521 | } | ||||
10522 | } | ||||
10523 | if (!LHSVecType) { | ||||
10524 | if (isa<ExtVectorType>(RHSVecType)) { | ||||
10525 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | ||||
10526 | LHSType, RHSVecType->getElementType(), | ||||
10527 | RHSType, DiagID)) | ||||
10528 | return RHSType; | ||||
10529 | } else { | ||||
10530 | if (LHS.get()->isLValue() || | ||||
10531 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10532 | return RHSType; | ||||
10533 | } | ||||
10534 | } | ||||
10535 | |||||
10536 | // FIXME: The code below also handles conversion between vectors and | ||||
10537 | // non-scalars, we should break this down into fine grained specific checks | ||||
10538 | // and emit proper diagnostics. | ||||
10539 | QualType VecType = LHSVecType ? LHSType : RHSType; | ||||
10540 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | ||||
10541 | QualType OtherType = LHSVecType ? RHSType : LHSType; | ||||
10542 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | ||||
10543 | if (isLaxVectorConversion(OtherType, VecType)) { | ||||
10544 | if (anyAltivecTypes(RHSType, LHSType) && | ||||
10545 | !areSameVectorElemTypes(RHSType, LHSType)) | ||||
10546 | Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; | ||||
10547 | // If we're allowing lax vector conversions, only the total (data) size | ||||
10548 | // needs to be the same. For non compound assignment, if one of the types is | ||||
10549 | // scalar, the result is always the vector type. | ||||
10550 | if (!IsCompAssign) { | ||||
10551 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | ||||
10552 | return VecType; | ||||
10553 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | ||||
10554 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | ||||
10555 | // type. Note that this is already done by non-compound assignments in | ||||
10556 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | ||||
10557 | // <1 x T> -> T. The result is also a vector type. | ||||
10558 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | ||||
10559 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | ||||
10560 | ExprResult *RHSExpr = &RHS; | ||||
10561 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | ||||
10562 | return VecType; | ||||
10563 | } | ||||
10564 | } | ||||
10565 | |||||
10566 | // Okay, the expression is invalid. | ||||
10567 | |||||
10568 | // If there's a non-vector, non-real operand, diagnose that. | ||||
10569 | if ((!RHSVecType && !RHSType->isRealType()) || | ||||
10570 | (!LHSVecType && !LHSType->isRealType())) { | ||||
10571 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10572 | << LHSType << RHSType | ||||
10573 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10574 | return QualType(); | ||||
10575 | } | ||||
10576 | |||||
10577 | // OpenCL V1.1 6.2.6.p1: | ||||
10578 | // If the operands are of more than one vector type, then an error shall | ||||
10579 | // occur. Implicit conversions between vector types are not permitted, per | ||||
10580 | // section 6.2.1. | ||||
10581 | if (getLangOpts().OpenCL && | ||||
10582 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | ||||
10583 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | ||||
10584 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | ||||
10585 | << RHSType; | ||||
10586 | return QualType(); | ||||
10587 | } | ||||
10588 | |||||
10589 | |||||
10590 | // If there is a vector type that is not a ExtVector and a scalar, we reach | ||||
10591 | // this point if scalar could not be converted to the vector's element type | ||||
10592 | // without truncation. | ||||
10593 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | ||||
10594 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | ||||
10595 | QualType Scalar = LHSVecType ? RHSType : LHSType; | ||||
10596 | QualType Vector = LHSVecType ? LHSType : RHSType; | ||||
10597 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | ||||
10598 | Diag(Loc, | ||||
10599 | diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10600 | << ScalarOrVector << Scalar << Vector; | ||||
10601 | |||||
10602 | return QualType(); | ||||
10603 | } | ||||
10604 | |||||
10605 | // Otherwise, use the generic diagnostic. | ||||
10606 | Diag(Loc, DiagID) | ||||
10607 | << LHSType << RHSType | ||||
10608 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10609 | return QualType(); | ||||
10610 | } | ||||
10611 | |||||
10612 | QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10613 | SourceLocation Loc, | ||||
10614 | bool IsCompAssign, | ||||
10615 | ArithConvKind OperationKind) { | ||||
10616 | if (!IsCompAssign) { | ||||
10617 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
10618 | if (LHS.isInvalid()) | ||||
10619 | return QualType(); | ||||
10620 | } | ||||
10621 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
10622 | if (RHS.isInvalid()) | ||||
10623 | return QualType(); | ||||
10624 | |||||
10625 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
10626 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
10627 | |||||
10628 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); | ||||
10629 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); | ||||
10630 | |||||
10631 | unsigned DiagID = diag::err_typecheck_invalid_operands; | ||||
10632 | if ((OperationKind == ACK_Arithmetic) && | ||||
10633 | ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || | ||||
10634 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { | ||||
10635 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10636 | << RHS.get()->getSourceRange(); | ||||
10637 | return QualType(); | ||||
10638 | } | ||||
10639 | |||||
10640 | if (Context.hasSameType(LHSType, RHSType)) | ||||
10641 | return LHSType; | ||||
10642 | |||||
10643 | if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { | ||||
10644 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
10645 | return LHSType; | ||||
10646 | } | ||||
10647 | if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { | ||||
10648 | if (LHS.get()->isLValue() || | ||||
10649 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10650 | return RHSType; | ||||
10651 | } | ||||
10652 | |||||
10653 | if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) || | ||||
10654 | (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) { | ||||
10655 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10656 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10657 | << RHS.get()->getSourceRange(); | ||||
10658 | return QualType(); | ||||
10659 | } | ||||
10660 | |||||
10661 | if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && | ||||
10662 | Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != | ||||
10663 | Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) { | ||||
10664 | Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
10665 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10666 | << RHS.get()->getSourceRange(); | ||||
10667 | return QualType(); | ||||
10668 | } | ||||
10669 | |||||
10670 | if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) { | ||||
10671 | QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType; | ||||
10672 | QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType; | ||||
10673 | bool ScalarOrVector = | ||||
10674 | LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType(); | ||||
10675 | |||||
10676 | Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10677 | << ScalarOrVector << Scalar << Vector; | ||||
10678 | |||||
10679 | return QualType(); | ||||
10680 | } | ||||
10681 | |||||
10682 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
10683 | << RHS.get()->getSourceRange(); | ||||
10684 | return QualType(); | ||||
10685 | } | ||||
10686 | |||||
10687 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | ||||
10688 | // expression. These are mainly cases where the null pointer is used as an | ||||
10689 | // integer instead of a pointer. | ||||
10690 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10691 | SourceLocation Loc, bool IsCompare) { | ||||
10692 | // The canonical way to check for a GNU null is with isNullPointerConstant, | ||||
10693 | // but we use a bit of a hack here for speed; this is a relatively | ||||
10694 | // hot path, and isNullPointerConstant is slow. | ||||
10695 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | ||||
10696 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | ||||
10697 | |||||
10698 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | ||||
10699 | |||||
10700 | // Avoid analyzing cases where the result will either be invalid (and | ||||
10701 | // diagnosed as such) or entirely valid and not something to warn about. | ||||
10702 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | ||||
10703 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | ||||
10704 | return; | ||||
10705 | |||||
10706 | // Comparison operations would not make sense with a null pointer no matter | ||||
10707 | // what the other expression is. | ||||
10708 | if (!IsCompare) { | ||||
10709 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | ||||
10710 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | ||||
10711 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | ||||
10712 | return; | ||||
10713 | } | ||||
10714 | |||||
10715 | // The rest of the operations only make sense with a null pointer | ||||
10716 | // if the other expression is a pointer. | ||||
10717 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | ||||
10718 | NonNullType->canDecayToPointerType()) | ||||
10719 | return; | ||||
10720 | |||||
10721 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | ||||
10722 | << LHSNull /* LHS is NULL */ << NonNullType | ||||
10723 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10724 | } | ||||
10725 | |||||
10726 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | ||||
10727 | SourceLocation Loc) { | ||||
10728 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | ||||
10729 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | ||||
10730 | if (!LUE || !RUE) | ||||
10731 | return; | ||||
10732 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | ||||
10733 | RUE->getKind() != UETT_SizeOf) | ||||
10734 | return; | ||||
10735 | |||||
10736 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | ||||
10737 | QualType LHSTy = LHSArg->getType(); | ||||
10738 | QualType RHSTy; | ||||
10739 | |||||
10740 | if (RUE->isArgumentType()) | ||||
10741 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | ||||
10742 | else | ||||
10743 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | ||||
10744 | |||||
10745 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | ||||
10746 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | ||||
10747 | return; | ||||
10748 | |||||
10749 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | ||||
10750 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10751 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10752 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | ||||
10753 | << LHSArgDecl; | ||||
10754 | } | ||||
10755 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | ||||
10756 | QualType ArrayElemTy = ArrayTy->getElementType(); | ||||
10757 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | ||||
10758 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | ||||
10759 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | ||||
10760 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | ||||
10761 | return; | ||||
10762 | S.Diag(Loc, diag::warn_division_sizeof_array) | ||||
10763 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | ||||
10764 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10765 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10766 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | ||||
10767 | << LHSArgDecl; | ||||
10768 | } | ||||
10769 | |||||
10770 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | ||||
10771 | } | ||||
10772 | } | ||||
10773 | |||||
10774 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | ||||
10775 | ExprResult &RHS, | ||||
10776 | SourceLocation Loc, bool IsDiv) { | ||||
10777 | // Check for division/remainder by zero. | ||||
10778 | Expr::EvalResult RHSValue; | ||||
10779 | if (!RHS.get()->isValueDependent() && | ||||
10780 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | ||||
10781 | RHSValue.Val.getInt() == 0) | ||||
10782 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10783 | S.PDiag(diag::warn_remainder_division_by_zero) | ||||
10784 | << IsDiv << RHS.get()->getSourceRange()); | ||||
10785 | } | ||||
10786 | |||||
10787 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10788 | SourceLocation Loc, | ||||
10789 | bool IsCompAssign, bool IsDiv) { | ||||
10790 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10791 | |||||
10792 | QualType LHSTy = LHS.get()->getType(); | ||||
10793 | QualType RHSTy = RHS.get()->getType(); | ||||
10794 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) | ||||
10795 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10796 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
10797 | /*AllowBoolConversions*/ false, | ||||
10798 | /*AllowBooleanOperation*/ false, | ||||
10799 | /*ReportInvalid*/ true); | ||||
10800 | if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) | ||||
10801 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10802 | ACK_Arithmetic); | ||||
10803 | if (!IsDiv && | ||||
10804 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) | ||||
10805 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10806 | // For division, only matrix-by-scalar is supported. Other combinations with | ||||
10807 | // matrix types are invalid. | ||||
10808 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) | ||||
10809 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10810 | |||||
10811 | QualType compType = UsualArithmeticConversions( | ||||
10812 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10813 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10814 | return QualType(); | ||||
10815 | |||||
10816 | |||||
10817 | if (compType.isNull() || !compType->isArithmeticType()) | ||||
10818 | return InvalidOperands(Loc, LHS, RHS); | ||||
10819 | if (IsDiv) { | ||||
10820 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | ||||
10821 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | ||||
10822 | } | ||||
10823 | return compType; | ||||
10824 | } | ||||
10825 | |||||
10826 | QualType Sema::CheckRemainderOperands( | ||||
10827 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | ||||
10828 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10829 | |||||
10830 | if (LHS.get()->getType()->isVectorType() || | ||||
10831 | RHS.get()->getType()->isVectorType()) { | ||||
10832 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
10833 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
10834 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10835 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
10836 | /*AllowBoolConversions*/ false, | ||||
10837 | /*AllowBooleanOperation*/ false, | ||||
10838 | /*ReportInvalid*/ true); | ||||
10839 | return InvalidOperands(Loc, LHS, RHS); | ||||
10840 | } | ||||
10841 | |||||
10842 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
10843 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
10844 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
10845 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
10846 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10847 | ACK_Arithmetic); | ||||
10848 | |||||
10849 | return InvalidOperands(Loc, LHS, RHS); | ||||
10850 | } | ||||
10851 | |||||
10852 | QualType compType = UsualArithmeticConversions( | ||||
10853 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10854 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10855 | return QualType(); | ||||
10856 | |||||
10857 | if (compType.isNull() || !compType->isIntegerType()) | ||||
10858 | return InvalidOperands(Loc, LHS, RHS); | ||||
10859 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | ||||
10860 | return compType; | ||||
10861 | } | ||||
10862 | |||||
10863 | /// Diagnose invalid arithmetic on two void pointers. | ||||
10864 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | ||||
10865 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10866 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10867 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10868 | : diag::ext_gnu_void_ptr) | ||||
10869 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | ||||
10870 | << RHSExpr->getSourceRange(); | ||||
10871 | } | ||||
10872 | |||||
10873 | /// Diagnose invalid arithmetic on a void pointer. | ||||
10874 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | ||||
10875 | Expr *Pointer) { | ||||
10876 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10877 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10878 | : diag::ext_gnu_void_ptr) | ||||
10879 | << 0 /* one pointer */ << Pointer->getSourceRange(); | ||||
10880 | } | ||||
10881 | |||||
10882 | /// Diagnose invalid arithmetic on a null pointer. | ||||
10883 | /// | ||||
10884 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | ||||
10885 | /// idiom, which we recognize as a GNU extension. | ||||
10886 | /// | ||||
10887 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | ||||
10888 | Expr *Pointer, bool IsGNUIdiom) { | ||||
10889 | if (IsGNUIdiom) | ||||
10890 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | ||||
10891 | << Pointer->getSourceRange(); | ||||
10892 | else | ||||
10893 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | ||||
10894 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||
10895 | } | ||||
10896 | |||||
10897 | /// Diagnose invalid subraction on a null pointer. | ||||
10898 | /// | ||||
10899 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, | ||||
10900 | Expr *Pointer, bool BothNull) { | ||||
10901 | // Null - null is valid in C++ [expr.add]p7 | ||||
10902 | if (BothNull && S.getLangOpts().CPlusPlus) | ||||
10903 | return; | ||||
10904 | |||||
10905 | // Is this s a macro from a system header? | ||||
10906 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) | ||||
10907 | return; | ||||
10908 | |||||
10909 | S.DiagRuntimeBehavior(Loc, Pointer, | ||||
10910 | S.PDiag(diag::warn_pointer_sub_null_ptr) | ||||
10911 | << S.getLangOpts().CPlusPlus | ||||
10912 | << Pointer->getSourceRange()); | ||||
10913 | } | ||||
10914 | |||||
10915 | /// Diagnose invalid arithmetic on two function pointers. | ||||
10916 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | ||||
10917 | Expr *LHS, Expr *RHS) { | ||||
10918 | assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10918, __extension__ __PRETTY_FUNCTION__ )); | ||||
10919 | assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10919, __extension__ __PRETTY_FUNCTION__ )); | ||||
10920 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10921 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10922 | : diag::ext_gnu_ptr_func_arith) | ||||
10923 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | ||||
10924 | // We only show the second type if it differs from the first. | ||||
10925 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | ||||
10926 | RHS->getType()) | ||||
10927 | << RHS->getType()->getPointeeType() | ||||
10928 | << LHS->getSourceRange() << RHS->getSourceRange(); | ||||
10929 | } | ||||
10930 | |||||
10931 | /// Diagnose invalid arithmetic on a function pointer. | ||||
10932 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | ||||
10933 | Expr *Pointer) { | ||||
10934 | assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 10934, __extension__ __PRETTY_FUNCTION__ )); | ||||
10935 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10936 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10937 | : diag::ext_gnu_ptr_func_arith) | ||||
10938 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | ||||
10939 | << 0 /* one pointer, so only one type */ | ||||
10940 | << Pointer->getSourceRange(); | ||||
10941 | } | ||||
10942 | |||||
10943 | /// Emit error if Operand is incomplete pointer type | ||||
10944 | /// | ||||
10945 | /// \returns True if pointer has incomplete type | ||||
10946 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | ||||
10947 | Expr *Operand) { | ||||
10948 | QualType ResType = Operand->getType(); | ||||
10949 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10950 | ResType = ResAtomicType->getValueType(); | ||||
10951 | |||||
10952 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() && !ResType->isDependentType()) ? void (0) : __assert_fail ( "ResType->isAnyPointerType() && !ResType->isDependentType()" , "clang/lib/Sema/SemaExpr.cpp", 10952, __extension__ __PRETTY_FUNCTION__ )); | ||||
10953 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10954 | return S.RequireCompleteSizedType( | ||||
10955 | Loc, PointeeTy, | ||||
10956 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | ||||
10957 | Operand->getSourceRange()); | ||||
10958 | } | ||||
10959 | |||||
10960 | /// Check the validity of an arithmetic pointer operand. | ||||
10961 | /// | ||||
10962 | /// If the operand has pointer type, this code will check for pointer types | ||||
10963 | /// which are invalid in arithmetic operations. These will be diagnosed | ||||
10964 | /// appropriately, including whether or not the use is supported as an | ||||
10965 | /// extension. | ||||
10966 | /// | ||||
10967 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10968 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | ||||
10969 | Expr *Operand) { | ||||
10970 | QualType ResType = Operand->getType(); | ||||
10971 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10972 | ResType = ResAtomicType->getValueType(); | ||||
10973 | |||||
10974 | if (!ResType->isAnyPointerType()) return true; | ||||
10975 | |||||
10976 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10977 | if (PointeeTy->isVoidType()) { | ||||
10978 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | ||||
10979 | return !S.getLangOpts().CPlusPlus; | ||||
10980 | } | ||||
10981 | if (PointeeTy->isFunctionType()) { | ||||
10982 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | ||||
10983 | return !S.getLangOpts().CPlusPlus; | ||||
10984 | } | ||||
10985 | |||||
10986 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | ||||
10987 | |||||
10988 | return true; | ||||
10989 | } | ||||
10990 | |||||
10991 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | ||||
10992 | /// operands. | ||||
10993 | /// | ||||
10994 | /// This routine will diagnose any invalid arithmetic on pointer operands much | ||||
10995 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | ||||
10996 | /// for emitting a single diagnostic even for operations where both LHS and RHS | ||||
10997 | /// are (potentially problematic) pointers. | ||||
10998 | /// | ||||
10999 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
11000 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | ||||
11001 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11002 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | ||||
11003 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | ||||
11004 | if (!isLHSPointer && !isRHSPointer) return true; | ||||
11005 | |||||
11006 | QualType LHSPointeeTy, RHSPointeeTy; | ||||
11007 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | ||||
11008 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | ||||
11009 | |||||
11010 | // if both are pointers check if operation is valid wrt address spaces | ||||
11011 | if (isLHSPointer && isRHSPointer) { | ||||
11012 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | ||||
11013 | S.Diag(Loc, | ||||
11014 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
11015 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | ||||
11016 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | ||||
11017 | return false; | ||||
11018 | } | ||||
11019 | } | ||||
11020 | |||||
11021 | // Check for arithmetic on pointers to incomplete types. | ||||
11022 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | ||||
11023 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | ||||
11024 | if (isLHSVoidPtr || isRHSVoidPtr) { | ||||
11025 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | ||||
11026 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | ||||
11027 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | ||||
11028 | |||||
11029 | return !S.getLangOpts().CPlusPlus; | ||||
11030 | } | ||||
11031 | |||||
11032 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | ||||
11033 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | ||||
11034 | if (isLHSFuncPtr || isRHSFuncPtr) { | ||||
11035 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | ||||
11036 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | ||||
11037 | RHSExpr); | ||||
11038 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | ||||
11039 | |||||
11040 | return !S.getLangOpts().CPlusPlus; | ||||
11041 | } | ||||
11042 | |||||
11043 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | ||||
11044 | return false; | ||||
11045 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | ||||
11046 | return false; | ||||
11047 | |||||
11048 | return true; | ||||
11049 | } | ||||
11050 | |||||
11051 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | ||||
11052 | /// literal. | ||||
11053 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | ||||
11054 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11055 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
11056 | Expr* IndexExpr = RHSExpr; | ||||
11057 | if (!StrExpr) { | ||||
11058 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
11059 | IndexExpr = LHSExpr; | ||||
11060 | } | ||||
11061 | |||||
11062 | bool IsStringPlusInt = StrExpr && | ||||
11063 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | ||||
11064 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | ||||
11065 | return; | ||||
11066 | |||||
11067 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
11068 | Self.Diag(OpLoc, diag::warn_string_plus_int) | ||||
11069 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | ||||
11070 | |||||
11071 | // Only print a fixit for "str" + int, not for int + "str". | ||||
11072 | if (IndexExpr == RHSExpr) { | ||||
11073 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
11074 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
11075 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
11076 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
11077 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
11078 | } else | ||||
11079 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
11080 | } | ||||
11081 | |||||
11082 | /// Emit a warning when adding a char literal to a string. | ||||
11083 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | ||||
11084 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11085 | const Expr *StringRefExpr = LHSExpr; | ||||
11086 | const CharacterLiteral *CharExpr = | ||||
11087 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
11088 | |||||
11089 | if (!CharExpr) { | ||||
11090 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
11091 | StringRefExpr = RHSExpr; | ||||
11092 | } | ||||
11093 | |||||
11094 | if (!CharExpr || !StringRefExpr) | ||||
11095 | return; | ||||
11096 | |||||
11097 | const QualType StringType = StringRefExpr->getType(); | ||||
11098 | |||||
11099 | // Return if not a PointerType. | ||||
11100 | if (!StringType->isAnyPointerType()) | ||||
11101 | return; | ||||
11102 | |||||
11103 | // Return if not a CharacterType. | ||||
11104 | if (!StringType->getPointeeType()->isAnyCharacterType()) | ||||
11105 | return; | ||||
11106 | |||||
11107 | ASTContext &Ctx = Self.getASTContext(); | ||||
11108 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
11109 | |||||
11110 | const QualType CharType = CharExpr->getType(); | ||||
11111 | if (!CharType->isAnyCharacterType() && | ||||
11112 | CharType->isIntegerType() && | ||||
11113 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | ||||
11114 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
11115 | << DiagRange << Ctx.CharTy; | ||||
11116 | } else { | ||||
11117 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
11118 | << DiagRange << CharExpr->getType(); | ||||
11119 | } | ||||
11120 | |||||
11121 | // Only print a fixit for str + char, not for char + str. | ||||
11122 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | ||||
11123 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
11124 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
11125 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
11126 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
11127 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
11128 | } else { | ||||
11129 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
11130 | } | ||||
11131 | } | ||||
11132 | |||||
11133 | /// Emit error when two pointers are incompatible. | ||||
11134 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | ||||
11135 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
11136 | assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11136, __extension__ __PRETTY_FUNCTION__ )); | ||||
11137 | assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11137, __extension__ __PRETTY_FUNCTION__ )); | ||||
11138 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | ||||
11139 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | ||||
11140 | << RHSExpr->getSourceRange(); | ||||
11141 | } | ||||
11142 | |||||
11143 | // C99 6.5.6 | ||||
11144 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11145 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11146 | QualType* CompLHSTy) { | ||||
11147 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11148 | |||||
11149 | if (LHS.get()->getType()->isVectorType() || | ||||
11150 | RHS.get()->getType()->isVectorType()) { | ||||
11151 | QualType compType = | ||||
11152 | CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, | ||||
11153 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
11154 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
11155 | /*AllowBooleanOperation*/ false, | ||||
11156 | /*ReportInvalid*/ true); | ||||
11157 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11158 | return compType; | ||||
11159 | } | ||||
11160 | |||||
11161 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11162 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
11163 | QualType compType = | ||||
11164 | CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); | ||||
11165 | if (CompLHSTy) | ||||
11166 | *CompLHSTy = compType; | ||||
11167 | return compType; | ||||
11168 | } | ||||
11169 | |||||
11170 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
11171 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
11172 | QualType compType = | ||||
11173 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
11174 | if (CompLHSTy) | ||||
11175 | *CompLHSTy = compType; | ||||
11176 | return compType; | ||||
11177 | } | ||||
11178 | |||||
11179 | QualType compType = UsualArithmeticConversions( | ||||
11180 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
11181 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11182 | return QualType(); | ||||
11183 | |||||
11184 | // Diagnose "string literal" '+' int and string '+' "char literal". | ||||
11185 | if (Opc == BO_Add) { | ||||
11186 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | ||||
11187 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | ||||
11188 | } | ||||
11189 | |||||
11190 | // handle the common case first (both operands are arithmetic). | ||||
11191 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
11192 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11193 | return compType; | ||||
11194 | } | ||||
11195 | |||||
11196 | // Type-checking. Ultimately the pointer's going to be in PExp; | ||||
11197 | // note that we bias towards the LHS being the pointer. | ||||
11198 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | ||||
11199 | |||||
11200 | bool isObjCPointer; | ||||
11201 | if (PExp->getType()->isPointerType()) { | ||||
11202 | isObjCPointer = false; | ||||
11203 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
11204 | isObjCPointer = true; | ||||
11205 | } else { | ||||
11206 | std::swap(PExp, IExp); | ||||
11207 | if (PExp->getType()->isPointerType()) { | ||||
11208 | isObjCPointer = false; | ||||
11209 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
11210 | isObjCPointer = true; | ||||
11211 | } else { | ||||
11212 | return InvalidOperands(Loc, LHS, RHS); | ||||
11213 | } | ||||
11214 | } | ||||
11215 | assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11215, __extension__ __PRETTY_FUNCTION__ )); | ||||
11216 | |||||
11217 | if (!IExp->getType()->isIntegerType()) | ||||
11218 | return InvalidOperands(Loc, LHS, RHS); | ||||
11219 | |||||
11220 | // Adding to a null pointer results in undefined behavior. | ||||
11221 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | ||||
11222 | Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||
11223 | // In C++ adding zero to a null pointer is defined. | ||||
11224 | Expr::EvalResult KnownVal; | ||||
11225 | if (!getLangOpts().CPlusPlus || | ||||
11226 | (!IExp->isValueDependent() && | ||||
11227 | (!IExp->EvaluateAsInt(KnownVal, Context) || | ||||
11228 | KnownVal.Val.getInt() != 0))) { | ||||
11229 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | ||||
11230 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | ||||
11231 | Context, BO_Add, PExp, IExp); | ||||
11232 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | ||||
11233 | } | ||||
11234 | } | ||||
11235 | |||||
11236 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | ||||
11237 | return QualType(); | ||||
11238 | |||||
11239 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | ||||
11240 | return QualType(); | ||||
11241 | |||||
11242 | // Check array bounds for pointer arithemtic | ||||
11243 | CheckArrayAccess(PExp, IExp); | ||||
11244 | |||||
11245 | if (CompLHSTy) { | ||||
11246 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | ||||
11247 | if (LHSTy.isNull()) { | ||||
11248 | LHSTy = LHS.get()->getType(); | ||||
11249 | if (LHSTy->isPromotableIntegerType()) | ||||
11250 | LHSTy = Context.getPromotedIntegerType(LHSTy); | ||||
11251 | } | ||||
11252 | *CompLHSTy = LHSTy; | ||||
11253 | } | ||||
11254 | |||||
11255 | return PExp->getType(); | ||||
11256 | } | ||||
11257 | |||||
11258 | // C99 6.5.6 | ||||
11259 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11260 | SourceLocation Loc, | ||||
11261 | QualType* CompLHSTy) { | ||||
11262 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11263 | |||||
11264 | if (LHS.get()->getType()->isVectorType() || | ||||
11265 | RHS.get()->getType()->isVectorType()) { | ||||
11266 | QualType compType = | ||||
11267 | CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, | ||||
11268 | /*AllowBothBool*/ getLangOpts().AltiVec, | ||||
11269 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
11270 | /*AllowBooleanOperation*/ false, | ||||
11271 | /*ReportInvalid*/ true); | ||||
11272 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11273 | return compType; | ||||
11274 | } | ||||
11275 | |||||
11276 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11277 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
11278 | QualType compType = | ||||
11279 | CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); | ||||
11280 | if (CompLHSTy) | ||||
11281 | *CompLHSTy = compType; | ||||
11282 | return compType; | ||||
11283 | } | ||||
11284 | |||||
11285 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
11286 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
11287 | QualType compType = | ||||
11288 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
11289 | if (CompLHSTy) | ||||
11290 | *CompLHSTy = compType; | ||||
11291 | return compType; | ||||
11292 | } | ||||
11293 | |||||
11294 | QualType compType = UsualArithmeticConversions( | ||||
11295 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
11296 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11297 | return QualType(); | ||||
11298 | |||||
11299 | // Enforce type constraints: C99 6.5.6p3. | ||||
11300 | |||||
11301 | // Handle the common case first (both operands are arithmetic). | ||||
11302 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
11303 | if (CompLHSTy) *CompLHSTy = compType; | ||||
11304 | return compType; | ||||
11305 | } | ||||
11306 | |||||
11307 | // Either ptr - int or ptr - ptr. | ||||
11308 | if (LHS.get()->getType()->isAnyPointerType()) { | ||||
11309 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | ||||
11310 | |||||
11311 | // Diagnose bad cases where we step over interface counts. | ||||
11312 | if (LHS.get()->getType()->isObjCObjectPointerType() && | ||||
11313 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | ||||
11314 | return QualType(); | ||||
11315 | |||||
11316 | // The result type of a pointer-int computation is the pointer type. | ||||
11317 | if (RHS.get()->getType()->isIntegerType()) { | ||||
11318 | // Subtracting from a null pointer should produce a warning. | ||||
11319 | // The last argument to the diagnose call says this doesn't match the | ||||
11320 | // GNU int-to-pointer idiom. | ||||
11321 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | ||||
11322 | Expr::NPC_ValueDependentIsNotNull)) { | ||||
11323 | // In C++ adding zero to a null pointer is defined. | ||||
11324 | Expr::EvalResult KnownVal; | ||||
11325 | if (!getLangOpts().CPlusPlus || | ||||
11326 | (!RHS.get()->isValueDependent() && | ||||
11327 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | ||||
11328 | KnownVal.Val.getInt() != 0))) { | ||||
11329 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | ||||
11330 | } | ||||
11331 | } | ||||
11332 | |||||
11333 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | ||||
11334 | return QualType(); | ||||
11335 | |||||
11336 | // Check array bounds for pointer arithemtic | ||||
11337 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | ||||
11338 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | ||||
11339 | |||||
11340 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
11341 | return LHS.get()->getType(); | ||||
11342 | } | ||||
11343 | |||||
11344 | // Handle pointer-pointer subtractions. | ||||
11345 | if (const PointerType *RHSPTy | ||||
11346 | = RHS.get()->getType()->getAs<PointerType>()) { | ||||
11347 | QualType rpointee = RHSPTy->getPointeeType(); | ||||
11348 | |||||
11349 | if (getLangOpts().CPlusPlus) { | ||||
11350 | // Pointee types must be the same: C++ [expr.add] | ||||
11351 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | ||||
11352 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
11353 | } | ||||
11354 | } else { | ||||
11355 | // Pointee types must be compatible C99 6.5.6p3 | ||||
11356 | if (!Context.typesAreCompatible( | ||||
11357 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | ||||
11358 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | ||||
11359 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
11360 | return QualType(); | ||||
11361 | } | ||||
11362 | } | ||||
11363 | |||||
11364 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | ||||
11365 | LHS.get(), RHS.get())) | ||||
11366 | return QualType(); | ||||
11367 | |||||
11368 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( | ||||
11369 | Context, Expr::NPC_ValueDependentIsNotNull); | ||||
11370 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( | ||||
11371 | Context, Expr::NPC_ValueDependentIsNotNull); | ||||
11372 | |||||
11373 | // Subtracting nullptr or from nullptr is suspect | ||||
11374 | if (LHSIsNullPtr) | ||||
11375 | diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); | ||||
11376 | if (RHSIsNullPtr) | ||||
11377 | diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); | ||||
11378 | |||||
11379 | // The pointee type may have zero size. As an extension, a structure or | ||||
11380 | // union may have zero size or an array may have zero length. In this | ||||
11381 | // case subtraction does not make sense. | ||||
11382 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | ||||
11383 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | ||||
11384 | if (ElementSize.isZero()) { | ||||
11385 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | ||||
11386 | << rpointee.getUnqualifiedType() | ||||
11387 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11388 | } | ||||
11389 | } | ||||
11390 | |||||
11391 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
11392 | return Context.getPointerDiffType(); | ||||
11393 | } | ||||
11394 | } | ||||
11395 | |||||
11396 | return InvalidOperands(Loc, LHS, RHS); | ||||
11397 | } | ||||
11398 | |||||
11399 | static bool isScopedEnumerationType(QualType T) { | ||||
11400 | if (const EnumType *ET = T->getAs<EnumType>()) | ||||
11401 | return ET->getDecl()->isScoped(); | ||||
11402 | return false; | ||||
11403 | } | ||||
11404 | |||||
11405 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | ||||
11406 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11407 | QualType LHSType) { | ||||
11408 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | ||||
11409 | // so skip remaining warnings as we don't want to modify values within Sema. | ||||
11410 | if (S.getLangOpts().OpenCL) | ||||
11411 | return; | ||||
11412 | |||||
11413 | // Check right/shifter operand | ||||
11414 | Expr::EvalResult RHSResult; | ||||
11415 | if (RHS.get()->isValueDependent() || | ||||
11416 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | ||||
11417 | return; | ||||
11418 | llvm::APSInt Right = RHSResult.Val.getInt(); | ||||
11419 | |||||
11420 | if (Right.isNegative()) { | ||||
11421 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11422 | S.PDiag(diag::warn_shift_negative) | ||||
11423 | << RHS.get()->getSourceRange()); | ||||
11424 | return; | ||||
11425 | } | ||||
11426 | |||||
11427 | QualType LHSExprType = LHS.get()->getType(); | ||||
11428 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | ||||
11429 | if (LHSExprType->isBitIntType()) | ||||
11430 | LeftSize = S.Context.getIntWidth(LHSExprType); | ||||
11431 | else if (LHSExprType->isFixedPointType()) { | ||||
11432 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | ||||
11433 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | ||||
11434 | } | ||||
11435 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | ||||
11436 | if (Right.uge(LeftBits)) { | ||||
11437 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11438 | S.PDiag(diag::warn_shift_gt_typewidth) | ||||
11439 | << RHS.get()->getSourceRange()); | ||||
11440 | return; | ||||
11441 | } | ||||
11442 | |||||
11443 | // FIXME: We probably need to handle fixed point types specially here. | ||||
11444 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | ||||
11445 | return; | ||||
11446 | |||||
11447 | // When left shifting an ICE which is signed, we can check for overflow which | ||||
11448 | // according to C++ standards prior to C++2a has undefined behavior | ||||
11449 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | ||||
11450 | // more than the maximum value representable in the result type, so never | ||||
11451 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | ||||
11452 | // expression is still probably a bug.) | ||||
11453 | Expr::EvalResult LHSResult; | ||||
11454 | if (LHS.get()->isValueDependent() || | ||||
11455 | LHSType->hasUnsignedIntegerRepresentation() || | ||||
11456 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | ||||
11457 | return; | ||||
11458 | llvm::APSInt Left = LHSResult.Val.getInt(); | ||||
11459 | |||||
11460 | // Don't warn if signed overflow is defined, then all the rest of the | ||||
11461 | // diagnostics will not be triggered because the behavior is defined. | ||||
11462 | // Also don't warn in C++20 mode (and newer), as signed left shifts | ||||
11463 | // always wrap and never overflow. | ||||
11464 | if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) | ||||
11465 | return; | ||||
11466 | |||||
11467 | // If LHS does not have a non-negative value then, the | ||||
11468 | // behavior is undefined before C++2a. Warn about it. | ||||
11469 | if (Left.isNegative()) { | ||||
11470 | S.DiagRuntimeBehavior(Loc, LHS.get(), | ||||
11471 | S.PDiag(diag::warn_shift_lhs_negative) | ||||
11472 | << LHS.get()->getSourceRange()); | ||||
11473 | return; | ||||
11474 | } | ||||
11475 | |||||
11476 | llvm::APInt ResultBits = | ||||
11477 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | ||||
11478 | if (LeftBits.uge(ResultBits)) | ||||
11479 | return; | ||||
11480 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | ||||
11481 | Result = Result.shl(Right); | ||||
11482 | |||||
11483 | // Print the bit representation of the signed integer as an unsigned | ||||
11484 | // hexadecimal number. | ||||
11485 | SmallString<40> HexResult; | ||||
11486 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | ||||
11487 | |||||
11488 | // If we are only missing a sign bit, this is less likely to result in actual | ||||
11489 | // bugs -- if the result is cast back to an unsigned type, it will have the | ||||
11490 | // expected value. Thus we place this behind a different warning that can be | ||||
11491 | // turned off separately if needed. | ||||
11492 | if (LeftBits == ResultBits - 1) { | ||||
11493 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | ||||
11494 | << HexResult << LHSType | ||||
11495 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11496 | return; | ||||
11497 | } | ||||
11498 | |||||
11499 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | ||||
11500 | << HexResult.str() << Result.getMinSignedBits() << LHSType | ||||
11501 | << Left.getBitWidth() << LHS.get()->getSourceRange() | ||||
11502 | << RHS.get()->getSourceRange(); | ||||
11503 | } | ||||
11504 | |||||
11505 | /// Return the resulting type when a vector is shifted | ||||
11506 | /// by a scalar or vector shift amount. | ||||
11507 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
11508 | SourceLocation Loc, bool IsCompAssign) { | ||||
11509 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | ||||
11510 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | ||||
11511 | !LHS.get()->getType()->isVectorType()) { | ||||
11512 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | ||||
11513 | << RHS.get()->getType() << LHS.get()->getType() | ||||
11514 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11515 | return QualType(); | ||||
11516 | } | ||||
11517 | |||||
11518 | if (!IsCompAssign) { | ||||
11519 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
11520 | if (LHS.isInvalid()) return QualType(); | ||||
11521 | } | ||||
11522 | |||||
11523 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
11524 | if (RHS.isInvalid()) return QualType(); | ||||
11525 | |||||
11526 | QualType LHSType = LHS.get()->getType(); | ||||
11527 | // Note that LHS might be a scalar because the routine calls not only in | ||||
11528 | // OpenCL case. | ||||
11529 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | ||||
11530 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | ||||
11531 | |||||
11532 | // Note that RHS might not be a vector. | ||||
11533 | QualType RHSType = RHS.get()->getType(); | ||||
11534 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | ||||
11535 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | ||||
11536 | |||||
11537 | // Do not allow shifts for boolean vectors. | ||||
11538 | if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || | ||||
11539 | (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { | ||||
11540 | S.Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
11541 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11542 | << LHS.get()->getSourceRange(); | ||||
11543 | return QualType(); | ||||
11544 | } | ||||
11545 | |||||
11546 | // The operands need to be integers. | ||||
11547 | if (!LHSEleType->isIntegerType()) { | ||||
11548 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11549 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
11550 | return QualType(); | ||||
11551 | } | ||||
11552 | |||||
11553 | if (!RHSEleType->isIntegerType()) { | ||||
11554 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11555 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
11556 | return QualType(); | ||||
11557 | } | ||||
11558 | |||||
11559 | if (!LHSVecTy) { | ||||
11560 | assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail ("RHSVecTy", "clang/lib/Sema/SemaExpr.cpp", 11560, __extension__ __PRETTY_FUNCTION__)); | ||||
11561 | if (IsCompAssign) | ||||
11562 | return RHSType; | ||||
11563 | if (LHSEleType != RHSEleType) { | ||||
11564 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | ||||
11565 | LHSEleType = RHSEleType; | ||||
11566 | } | ||||
11567 | QualType VecTy = | ||||
11568 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | ||||
11569 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | ||||
11570 | LHSType = VecTy; | ||||
11571 | } else if (RHSVecTy) { | ||||
11572 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | ||||
11573 | // are applied component-wise. So if RHS is a vector, then ensure | ||||
11574 | // that the number of elements is the same as LHS... | ||||
11575 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | ||||
11576 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
11577 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11578 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11579 | return QualType(); | ||||
11580 | } | ||||
11581 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | ||||
11582 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | ||||
11583 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | ||||
11584 | if (LHSBT != RHSBT && | ||||
11585 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | ||||
11586 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | ||||
11587 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11588 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11589 | } | ||||
11590 | } | ||||
11591 | } else { | ||||
11592 | // ...else expand RHS to match the number of elements in LHS. | ||||
11593 | QualType VecTy = | ||||
11594 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | ||||
11595 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
11596 | } | ||||
11597 | |||||
11598 | return LHSType; | ||||
11599 | } | ||||
11600 | |||||
11601 | static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, | ||||
11602 | ExprResult &RHS, SourceLocation Loc, | ||||
11603 | bool IsCompAssign) { | ||||
11604 | if (!IsCompAssign) { | ||||
11605 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
11606 | if (LHS.isInvalid()) | ||||
11607 | return QualType(); | ||||
11608 | } | ||||
11609 | |||||
11610 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
11611 | if (RHS.isInvalid()) | ||||
11612 | return QualType(); | ||||
11613 | |||||
11614 | QualType LHSType = LHS.get()->getType(); | ||||
11615 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); | ||||
11616 | QualType LHSEleType = LHSType->isVLSTBuiltinType() | ||||
11617 | ? LHSBuiltinTy->getSveEltType(S.getASTContext()) | ||||
11618 | : LHSType; | ||||
11619 | |||||
11620 | // Note that RHS might not be a vector | ||||
11621 | QualType RHSType = RHS.get()->getType(); | ||||
11622 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); | ||||
11623 | QualType RHSEleType = RHSType->isVLSTBuiltinType() | ||||
11624 | ? RHSBuiltinTy->getSveEltType(S.getASTContext()) | ||||
11625 | : RHSType; | ||||
11626 | |||||
11627 | if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || | ||||
11628 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { | ||||
11629 | S.Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
11630 | << LHSType << RHSType << LHS.get()->getSourceRange(); | ||||
11631 | return QualType(); | ||||
11632 | } | ||||
11633 | |||||
11634 | if (!LHSEleType->isIntegerType()) { | ||||
11635 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11636 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
11637 | return QualType(); | ||||
11638 | } | ||||
11639 | |||||
11640 | if (!RHSEleType->isIntegerType()) { | ||||
11641 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11642 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
11643 | return QualType(); | ||||
11644 | } | ||||
11645 | |||||
11646 | if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && | ||||
11647 | (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != | ||||
11648 | S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { | ||||
11649 | S.Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
11650 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11651 | << RHS.get()->getSourceRange(); | ||||
11652 | return QualType(); | ||||
11653 | } | ||||
11654 | |||||
11655 | if (!LHSType->isVLSTBuiltinType()) { | ||||
11656 | assert(RHSType->isVLSTBuiltinType())(static_cast <bool> (RHSType->isVLSTBuiltinType()) ? void (0) : __assert_fail ("RHSType->isVLSTBuiltinType()", "clang/lib/Sema/SemaExpr.cpp", 11656, __extension__ __PRETTY_FUNCTION__ )); | ||||
11657 | if (IsCompAssign) | ||||
11658 | return RHSType; | ||||
11659 | if (LHSEleType != RHSEleType) { | ||||
11660 | LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); | ||||
11661 | LHSEleType = RHSEleType; | ||||
11662 | } | ||||
11663 | const llvm::ElementCount VecSize = | ||||
11664 | S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; | ||||
11665 | QualType VecTy = | ||||
11666 | S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); | ||||
11667 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); | ||||
11668 | LHSType = VecTy; | ||||
11669 | } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { | ||||
11670 | if (S.Context.getTypeSize(RHSBuiltinTy) != | ||||
11671 | S.Context.getTypeSize(LHSBuiltinTy)) { | ||||
11672 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
11673 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11674 | << RHS.get()->getSourceRange(); | ||||
11675 | return QualType(); | ||||
11676 | } | ||||
11677 | } else { | ||||
11678 | const llvm::ElementCount VecSize = | ||||
11679 | S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; | ||||
11680 | if (LHSEleType != RHSEleType) { | ||||
11681 | RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); | ||||
11682 | RHSEleType = LHSEleType; | ||||
11683 | } | ||||
11684 | QualType VecTy = | ||||
11685 | S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); | ||||
11686 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
11687 | } | ||||
11688 | |||||
11689 | return LHSType; | ||||
11690 | } | ||||
11691 | |||||
11692 | // C99 6.5.7 | ||||
11693 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11694 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11695 | bool IsCompAssign) { | ||||
11696 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11697 | |||||
11698 | // Vector shifts promote their scalar inputs to vector type. | ||||
11699 | if (LHS.get()->getType()->isVectorType() || | ||||
11700 | RHS.get()->getType()->isVectorType()) { | ||||
11701 | if (LangOpts.ZVector) { | ||||
11702 | // The shift operators for the z vector extensions work basically | ||||
11703 | // like general shifts, except that neither the LHS nor the RHS is | ||||
11704 | // allowed to be a "vector bool". | ||||
11705 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | ||||
11706 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
11707 | return InvalidOperands(Loc, LHS, RHS); | ||||
11708 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | ||||
11709 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
11710 | return InvalidOperands(Loc, LHS, RHS); | ||||
11711 | } | ||||
11712 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
11713 | } | ||||
11714 | |||||
11715 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
11716 | RHS.get()->getType()->isVLSTBuiltinType()) | ||||
11717 | return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
11718 | |||||
11719 | // Shifts don't perform usual arithmetic conversions, they just do integer | ||||
11720 | // promotions on each operand. C99 6.5.7p3 | ||||
11721 | |||||
11722 | // For the LHS, do usual unary conversions, but then reset them away | ||||
11723 | // if this is a compound assignment. | ||||
11724 | ExprResult OldLHS = LHS; | ||||
11725 | LHS = UsualUnaryConversions(LHS.get()); | ||||
11726 | if (LHS.isInvalid()) | ||||
11727 | return QualType(); | ||||
11728 | QualType LHSType = LHS.get()->getType(); | ||||
11729 | if (IsCompAssign) LHS = OldLHS; | ||||
11730 | |||||
11731 | // The RHS is simpler. | ||||
11732 | RHS = UsualUnaryConversions(RHS.get()); | ||||
11733 | if (RHS.isInvalid()) | ||||
11734 | return QualType(); | ||||
11735 | QualType RHSType = RHS.get()->getType(); | ||||
11736 | |||||
11737 | // C99 6.5.7p2: Each of the operands shall have integer type. | ||||
11738 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | ||||
11739 | if ((!LHSType->isFixedPointOrIntegerType() && | ||||
11740 | !LHSType->hasIntegerRepresentation()) || | ||||
11741 | !RHSType->hasIntegerRepresentation()) | ||||
11742 | return InvalidOperands(Loc, LHS, RHS); | ||||
11743 | |||||
11744 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | ||||
11745 | // hasIntegerRepresentation() above instead of this. | ||||
11746 | if (isScopedEnumerationType(LHSType) || | ||||
11747 | isScopedEnumerationType(RHSType)) { | ||||
11748 | return InvalidOperands(Loc, LHS, RHS); | ||||
11749 | } | ||||
11750 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | ||||
11751 | |||||
11752 | // "The type of the result is that of the promoted left operand." | ||||
11753 | return LHSType; | ||||
11754 | } | ||||
11755 | |||||
11756 | /// Diagnose bad pointer comparisons. | ||||
11757 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | ||||
11758 | ExprResult &LHS, ExprResult &RHS, | ||||
11759 | bool IsError) { | ||||
11760 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | ||||
11761 | : diag::ext_typecheck_comparison_of_distinct_pointers) | ||||
11762 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11763 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11764 | } | ||||
11765 | |||||
11766 | /// Returns false if the pointers are converted to a composite type, | ||||
11767 | /// true otherwise. | ||||
11768 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | ||||
11769 | ExprResult &LHS, ExprResult &RHS) { | ||||
11770 | // C++ [expr.rel]p2: | ||||
11771 | // [...] Pointer conversions (4.10) and qualification | ||||
11772 | // conversions (4.4) are performed on pointer operands (or on | ||||
11773 | // a pointer operand and a null pointer constant) to bring | ||||
11774 | // them to their composite pointer type. [...] | ||||
11775 | // | ||||
11776 | // C++ [expr.eq]p1 uses the same notion for (in)equality | ||||
11777 | // comparisons of pointers. | ||||
11778 | |||||
11779 | QualType LHSType = LHS.get()->getType(); | ||||
11780 | QualType RHSType = RHS.get()->getType(); | ||||
11781 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11782, __extension__ __PRETTY_FUNCTION__ )) | ||||
11782 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "clang/lib/Sema/SemaExpr.cpp", 11782, __extension__ __PRETTY_FUNCTION__ )); | ||||
11783 | |||||
11784 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | ||||
11785 | if (T.isNull()) { | ||||
11786 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | ||||
11787 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | ||||
11788 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | ||||
11789 | else | ||||
11790 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11791 | return true; | ||||
11792 | } | ||||
11793 | |||||
11794 | return false; | ||||
11795 | } | ||||
11796 | |||||
11797 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | ||||
11798 | ExprResult &LHS, | ||||
11799 | ExprResult &RHS, | ||||
11800 | bool IsError) { | ||||
11801 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | ||||
11802 | : diag::ext_typecheck_comparison_of_fptr_to_void) | ||||
11803 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11804 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11805 | } | ||||
11806 | |||||
11807 | static bool isObjCObjectLiteral(ExprResult &E) { | ||||
11808 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | ||||
11809 | case Stmt::ObjCArrayLiteralClass: | ||||
11810 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11811 | case Stmt::ObjCStringLiteralClass: | ||||
11812 | case Stmt::ObjCBoxedExprClass: | ||||
11813 | return true; | ||||
11814 | default: | ||||
11815 | // Note that ObjCBoolLiteral is NOT an object literal! | ||||
11816 | return false; | ||||
11817 | } | ||||
11818 | } | ||||
11819 | |||||
11820 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | ||||
11821 | const ObjCObjectPointerType *Type = | ||||
11822 | LHS->getType()->getAs<ObjCObjectPointerType>(); | ||||
11823 | |||||
11824 | // If this is not actually an Objective-C object, bail out. | ||||
11825 | if (!Type) | ||||
11826 | return false; | ||||
11827 | |||||
11828 | // Get the LHS object's interface type. | ||||
11829 | QualType InterfaceType = Type->getPointeeType(); | ||||
11830 | |||||
11831 | // If the RHS isn't an Objective-C object, bail out. | ||||
11832 | if (!RHS->getType()->isObjCObjectPointerType()) | ||||
11833 | return false; | ||||
11834 | |||||
11835 | // Try to find the -isEqual: method. | ||||
11836 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | ||||
11837 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | ||||
11838 | InterfaceType, | ||||
11839 | /*IsInstance=*/true); | ||||
11840 | if (!Method) { | ||||
11841 | if (Type->isObjCIdType()) { | ||||
11842 | // For 'id', just check the global pool. | ||||
11843 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | ||||
11844 | /*receiverId=*/true); | ||||
11845 | } else { | ||||
11846 | // Check protocols. | ||||
11847 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | ||||
11848 | /*IsInstance=*/true); | ||||
11849 | } | ||||
11850 | } | ||||
11851 | |||||
11852 | if (!Method) | ||||
11853 | return false; | ||||
11854 | |||||
11855 | QualType T = Method->parameters()[0]->getType(); | ||||
11856 | if (!T->isObjCObjectPointerType()) | ||||
11857 | return false; | ||||
11858 | |||||
11859 | QualType R = Method->getReturnType(); | ||||
11860 | if (!R->isScalarType()) | ||||
11861 | return false; | ||||
11862 | |||||
11863 | return true; | ||||
11864 | } | ||||
11865 | |||||
11866 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | ||||
11867 | FromE = FromE->IgnoreParenImpCasts(); | ||||
11868 | switch (FromE->getStmtClass()) { | ||||
11869 | default: | ||||
11870 | break; | ||||
11871 | case Stmt::ObjCStringLiteralClass: | ||||
11872 | // "string literal" | ||||
11873 | return LK_String; | ||||
11874 | case Stmt::ObjCArrayLiteralClass: | ||||
11875 | // "array literal" | ||||
11876 | return LK_Array; | ||||
11877 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11878 | // "dictionary literal" | ||||
11879 | return LK_Dictionary; | ||||
11880 | case Stmt::BlockExprClass: | ||||
11881 | return LK_Block; | ||||
11882 | case Stmt::ObjCBoxedExprClass: { | ||||
11883 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | ||||
11884 | switch (Inner->getStmtClass()) { | ||||
11885 | case Stmt::IntegerLiteralClass: | ||||
11886 | case Stmt::FloatingLiteralClass: | ||||
11887 | case Stmt::CharacterLiteralClass: | ||||
11888 | case Stmt::ObjCBoolLiteralExprClass: | ||||
11889 | case Stmt::CXXBoolLiteralExprClass: | ||||
11890 | // "numeric literal" | ||||
11891 | return LK_Numeric; | ||||
11892 | case Stmt::ImplicitCastExprClass: { | ||||
11893 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | ||||
11894 | // Boolean literals can be represented by implicit casts. | ||||
11895 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | ||||
11896 | return LK_Numeric; | ||||
11897 | break; | ||||
11898 | } | ||||
11899 | default: | ||||
11900 | break; | ||||
11901 | } | ||||
11902 | return LK_Boxed; | ||||
11903 | } | ||||
11904 | } | ||||
11905 | return LK_None; | ||||
11906 | } | ||||
11907 | |||||
11908 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | ||||
11909 | ExprResult &LHS, ExprResult &RHS, | ||||
11910 | BinaryOperator::Opcode Opc){ | ||||
11911 | Expr *Literal; | ||||
11912 | Expr *Other; | ||||
11913 | if (isObjCObjectLiteral(LHS)) { | ||||
11914 | Literal = LHS.get(); | ||||
11915 | Other = RHS.get(); | ||||
11916 | } else { | ||||
11917 | Literal = RHS.get(); | ||||
11918 | Other = LHS.get(); | ||||
11919 | } | ||||
11920 | |||||
11921 | // Don't warn on comparisons against nil. | ||||
11922 | Other = Other->IgnoreParenCasts(); | ||||
11923 | if (Other->isNullPointerConstant(S.getASTContext(), | ||||
11924 | Expr::NPC_ValueDependentIsNotNull)) | ||||
11925 | return; | ||||
11926 | |||||
11927 | // This should be kept in sync with warn_objc_literal_comparison. | ||||
11928 | // LK_String should always be after the other literals, since it has its own | ||||
11929 | // warning flag. | ||||
11930 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | ||||
11931 | assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void (0) : __assert_fail ("LiteralKind != Sema::LK_Block", "clang/lib/Sema/SemaExpr.cpp" , 11931, __extension__ __PRETTY_FUNCTION__)); | ||||
11932 | if (LiteralKind == Sema::LK_None) { | ||||
11933 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "clang/lib/Sema/SemaExpr.cpp", 11933); | ||||
11934 | } | ||||
11935 | |||||
11936 | if (LiteralKind == Sema::LK_String) | ||||
11937 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | ||||
11938 | << Literal->getSourceRange(); | ||||
11939 | else | ||||
11940 | S.Diag(Loc, diag::warn_objc_literal_comparison) | ||||
11941 | << LiteralKind << Literal->getSourceRange(); | ||||
11942 | |||||
11943 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
11944 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | ||||
11945 | SourceLocation Start = LHS.get()->getBeginLoc(); | ||||
11946 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
11947 | CharSourceRange OpRange = | ||||
11948 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
11949 | |||||
11950 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | ||||
11951 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | ||||
11952 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | ||||
11953 | << FixItHint::CreateInsertion(End, "]"); | ||||
11954 | } | ||||
11955 | } | ||||
11956 | |||||
11957 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | ||||
11958 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | ||||
11959 | ExprResult &RHS, SourceLocation Loc, | ||||
11960 | BinaryOperatorKind Opc) { | ||||
11961 | // Check that left hand side is !something. | ||||
11962 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | ||||
11963 | if (!UO || UO->getOpcode() != UO_LNot) return; | ||||
11964 | |||||
11965 | // Only check if the right hand side is non-bool arithmetic type. | ||||
11966 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | ||||
11967 | |||||
11968 | // Make sure that the something in !something is not bool. | ||||
11969 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | ||||
11970 | if (SubExpr->isKnownToHaveBooleanValue()) return; | ||||
11971 | |||||
11972 | // Emit warning. | ||||
11973 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | ||||
11974 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | ||||
11975 | << Loc << IsBitwiseOp; | ||||
11976 | |||||
11977 | // First note suggest !(x < y) | ||||
11978 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | ||||
11979 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | ||||
11980 | FirstClose = S.getLocForEndOfToken(FirstClose); | ||||
11981 | if (FirstClose.isInvalid()) | ||||
11982 | FirstOpen = SourceLocation(); | ||||
11983 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | ||||
11984 | << IsBitwiseOp | ||||
11985 | << FixItHint::CreateInsertion(FirstOpen, "(") | ||||
11986 | << FixItHint::CreateInsertion(FirstClose, ")"); | ||||
11987 | |||||
11988 | // Second note suggests (!x) < y | ||||
11989 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | ||||
11990 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | ||||
11991 | SecondClose = S.getLocForEndOfToken(SecondClose); | ||||
11992 | if (SecondClose.isInvalid()) | ||||
11993 | SecondOpen = SourceLocation(); | ||||
11994 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | ||||
11995 | << FixItHint::CreateInsertion(SecondOpen, "(") | ||||
11996 | << FixItHint::CreateInsertion(SecondClose, ")"); | ||||
11997 | } | ||||
11998 | |||||
11999 | // Returns true if E refers to a non-weak array. | ||||
12000 | static bool checkForArray(const Expr *E) { | ||||
12001 | const ValueDecl *D = nullptr; | ||||
12002 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | ||||
12003 | D = DR->getDecl(); | ||||
12004 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | ||||
12005 | if (Mem->isImplicitAccess()) | ||||
12006 | D = Mem->getMemberDecl(); | ||||
12007 | } | ||||
12008 | if (!D) | ||||
12009 | return false; | ||||
12010 | return D->getType()->isArrayType() && !D->isWeak(); | ||||
12011 | } | ||||
12012 | |||||
12013 | /// Diagnose some forms of syntactically-obvious tautological comparison. | ||||
12014 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | ||||
12015 | Expr *LHS, Expr *RHS, | ||||
12016 | BinaryOperatorKind Opc) { | ||||
12017 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | ||||
12018 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | ||||
12019 | |||||
12020 | QualType LHSType = LHS->getType(); | ||||
12021 | QualType RHSType = RHS->getType(); | ||||
12022 | if (LHSType->hasFloatingRepresentation() || | ||||
12023 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | ||||
12024 | S.inTemplateInstantiation()) | ||||
12025 | return; | ||||
12026 | |||||
12027 | // Comparisons between two array types are ill-formed for operator<=>, so | ||||
12028 | // we shouldn't emit any additional warnings about it. | ||||
12029 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | ||||
12030 | return; | ||||
12031 | |||||
12032 | // For non-floating point types, check for self-comparisons of the form | ||||
12033 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12034 | // often indicate logic errors in the program. | ||||
12035 | // | ||||
12036 | // NOTE: Don't warn about comparison expressions resulting from macro | ||||
12037 | // expansion. Also don't warn about comparisons which are only self | ||||
12038 | // comparisons within a template instantiation. The warnings should catch | ||||
12039 | // obvious cases in the definition of the template anyways. The idea is to | ||||
12040 | // warn when the typed comparison operator will always evaluate to the same | ||||
12041 | // result. | ||||
12042 | |||||
12043 | // Used for indexing into %select in warn_comparison_always | ||||
12044 | enum { | ||||
12045 | AlwaysConstant, | ||||
12046 | AlwaysTrue, | ||||
12047 | AlwaysFalse, | ||||
12048 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | ||||
12049 | }; | ||||
12050 | |||||
12051 | // C++2a [depr.array.comp]: | ||||
12052 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | ||||
12053 | // operands of array type are deprecated. | ||||
12054 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | ||||
12055 | RHSStripped->getType()->isArrayType()) { | ||||
12056 | S.Diag(Loc, diag::warn_depr_array_comparison) | ||||
12057 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
12058 | << LHSStripped->getType() << RHSStripped->getType(); | ||||
12059 | // Carry on to produce the tautological comparison warning, if this | ||||
12060 | // expression is potentially-evaluated, we can resolve the array to a | ||||
12061 | // non-weak declaration, and so on. | ||||
12062 | } | ||||
12063 | |||||
12064 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | ||||
12065 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | ||||
12066 | unsigned Result; | ||||
12067 | switch (Opc) { | ||||
12068 | case BO_EQ: | ||||
12069 | case BO_LE: | ||||
12070 | case BO_GE: | ||||
12071 | Result = AlwaysTrue; | ||||
12072 | break; | ||||
12073 | case BO_NE: | ||||
12074 | case BO_LT: | ||||
12075 | case BO_GT: | ||||
12076 | Result = AlwaysFalse; | ||||
12077 | break; | ||||
12078 | case BO_Cmp: | ||||
12079 | Result = AlwaysEqual; | ||||
12080 | break; | ||||
12081 | default: | ||||
12082 | Result = AlwaysConstant; | ||||
12083 | break; | ||||
12084 | } | ||||
12085 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
12086 | S.PDiag(diag::warn_comparison_always) | ||||
12087 | << 0 /*self-comparison*/ | ||||
12088 | << Result); | ||||
12089 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | ||||
12090 | // What is it always going to evaluate to? | ||||
12091 | unsigned Result; | ||||
12092 | switch (Opc) { | ||||
12093 | case BO_EQ: // e.g. array1 == array2 | ||||
12094 | Result = AlwaysFalse; | ||||
12095 | break; | ||||
12096 | case BO_NE: // e.g. array1 != array2 | ||||
12097 | Result = AlwaysTrue; | ||||
12098 | break; | ||||
12099 | default: // e.g. array1 <= array2 | ||||
12100 | // The best we can say is 'a constant' | ||||
12101 | Result = AlwaysConstant; | ||||
12102 | break; | ||||
12103 | } | ||||
12104 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
12105 | S.PDiag(diag::warn_comparison_always) | ||||
12106 | << 1 /*array comparison*/ | ||||
12107 | << Result); | ||||
12108 | } | ||||
12109 | } | ||||
12110 | |||||
12111 | if (isa<CastExpr>(LHSStripped)) | ||||
12112 | LHSStripped = LHSStripped->IgnoreParenCasts(); | ||||
12113 | if (isa<CastExpr>(RHSStripped)) | ||||
12114 | RHSStripped = RHSStripped->IgnoreParenCasts(); | ||||
12115 | |||||
12116 | // Warn about comparisons against a string constant (unless the other | ||||
12117 | // operand is null); the user probably wants string comparison function. | ||||
12118 | Expr *LiteralString = nullptr; | ||||
12119 | Expr *LiteralStringStripped = nullptr; | ||||
12120 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | ||||
12121 | !RHSStripped->isNullPointerConstant(S.Context, | ||||
12122 | Expr::NPC_ValueDependentIsNull)) { | ||||
12123 | LiteralString = LHS; | ||||
12124 | LiteralStringStripped = LHSStripped; | ||||
12125 | } else if ((isa<StringLiteral>(RHSStripped) || | ||||
12126 | isa<ObjCEncodeExpr>(RHSStripped)) && | ||||
12127 | !LHSStripped->isNullPointerConstant(S.Context, | ||||
12128 | Expr::NPC_ValueDependentIsNull)) { | ||||
12129 | LiteralString = RHS; | ||||
12130 | LiteralStringStripped = RHSStripped; | ||||
12131 | } | ||||
12132 | |||||
12133 | if (LiteralString) { | ||||
12134 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
12135 | S.PDiag(diag::warn_stringcompare) | ||||
12136 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | ||||
12137 | << LiteralString->getSourceRange()); | ||||
12138 | } | ||||
12139 | } | ||||
12140 | |||||
12141 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | ||||
12142 | switch (CK) { | ||||
12143 | default: { | ||||
12144 | #ifndef NDEBUG | ||||
12145 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | ||||
12146 | << "\n"; | ||||
12147 | #endif | ||||
12148 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "clang/lib/Sema/SemaExpr.cpp" , 12148); | ||||
12149 | } | ||||
12150 | case CK_UserDefinedConversion: | ||||
12151 | return ICK_Identity; | ||||
12152 | case CK_LValueToRValue: | ||||
12153 | return ICK_Lvalue_To_Rvalue; | ||||
12154 | case CK_ArrayToPointerDecay: | ||||
12155 | return ICK_Array_To_Pointer; | ||||
12156 | case CK_FunctionToPointerDecay: | ||||
12157 | return ICK_Function_To_Pointer; | ||||
12158 | case CK_IntegralCast: | ||||
12159 | return ICK_Integral_Conversion; | ||||
12160 | case CK_FloatingCast: | ||||
12161 | return ICK_Floating_Conversion; | ||||
12162 | case CK_IntegralToFloating: | ||||
12163 | case CK_FloatingToIntegral: | ||||
12164 | return ICK_Floating_Integral; | ||||
12165 | case CK_IntegralComplexCast: | ||||
12166 | case CK_FloatingComplexCast: | ||||
12167 | case CK_FloatingComplexToIntegralComplex: | ||||
12168 | case CK_IntegralComplexToFloatingComplex: | ||||
12169 | return ICK_Complex_Conversion; | ||||
12170 | case CK_FloatingComplexToReal: | ||||
12171 | case CK_FloatingRealToComplex: | ||||
12172 | case CK_IntegralComplexToReal: | ||||
12173 | case CK_IntegralRealToComplex: | ||||
12174 | return ICK_Complex_Real; | ||||
12175 | } | ||||
12176 | } | ||||
12177 | |||||
12178 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | ||||
12179 | QualType FromType, | ||||
12180 | SourceLocation Loc) { | ||||
12181 | // Check for a narrowing implicit conversion. | ||||
12182 | StandardConversionSequence SCS; | ||||
12183 | SCS.setAsIdentityConversion(); | ||||
12184 | SCS.setToType(0, FromType); | ||||
12185 | SCS.setToType(1, ToType); | ||||
12186 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
12187 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | ||||
12188 | |||||
12189 | APValue PreNarrowingValue; | ||||
12190 | QualType PreNarrowingType; | ||||
12191 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | ||||
12192 | PreNarrowingType, | ||||
12193 | /*IgnoreFloatToIntegralConversion*/ true)) { | ||||
12194 | case NK_Dependent_Narrowing: | ||||
12195 | // Implicit conversion to a narrower type, but the expression is | ||||
12196 | // value-dependent so we can't tell whether it's actually narrowing. | ||||
12197 | case NK_Not_Narrowing: | ||||
12198 | return false; | ||||
12199 | |||||
12200 | case NK_Constant_Narrowing: | ||||
12201 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
12202 | // expression. | ||||
12203 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
12204 | << /*Constant*/ 1 | ||||
12205 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | ||||
12206 | return true; | ||||
12207 | |||||
12208 | case NK_Variable_Narrowing: | ||||
12209 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
12210 | // expression. | ||||
12211 | case NK_Type_Narrowing: | ||||
12212 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
12213 | << /*Constant*/ 0 << FromType << ToType; | ||||
12214 | // TODO: It's not a constant expression, but what if the user intended it | ||||
12215 | // to be? Can we produce notes to help them figure out why it isn't? | ||||
12216 | return true; | ||||
12217 | } | ||||
12218 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "clang/lib/Sema/SemaExpr.cpp", 12218); | ||||
12219 | } | ||||
12220 | |||||
12221 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | ||||
12222 | ExprResult &LHS, | ||||
12223 | ExprResult &RHS, | ||||
12224 | SourceLocation Loc) { | ||||
12225 | QualType LHSType = LHS.get()->getType(); | ||||
12226 | QualType RHSType = RHS.get()->getType(); | ||||
12227 | // Dig out the original argument type and expression before implicit casts | ||||
12228 | // were applied. These are the types/expressions we need to check the | ||||
12229 | // [expr.spaceship] requirements against. | ||||
12230 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | ||||
12231 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | ||||
12232 | QualType LHSStrippedType = LHSStripped.get()->getType(); | ||||
12233 | QualType RHSStrippedType = RHSStripped.get()->getType(); | ||||
12234 | |||||
12235 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | ||||
12236 | // other is not, the program is ill-formed. | ||||
12237 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | ||||
12238 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
12239 | return QualType(); | ||||
12240 | } | ||||
12241 | |||||
12242 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | ||||
12243 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | ||||
12244 | RHSStrippedType->isEnumeralType(); | ||||
12245 | if (NumEnumArgs == 1) { | ||||
12246 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | ||||
12247 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | ||||
12248 | if (OtherTy->hasFloatingRepresentation()) { | ||||
12249 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
12250 | return QualType(); | ||||
12251 | } | ||||
12252 | } | ||||
12253 | if (NumEnumArgs == 2) { | ||||
12254 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | ||||
12255 | // type E, the operator yields the result of converting the operands | ||||
12256 | // to the underlying type of E and applying <=> to the converted operands. | ||||
12257 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | ||||
12258 | S.InvalidOperands(Loc, LHS, RHS); | ||||
12259 | return QualType(); | ||||
12260 | } | ||||
12261 | QualType IntType = | ||||
12262 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | ||||
12263 | assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void (0) : __assert_fail ("IntType->isArithmeticType()", "clang/lib/Sema/SemaExpr.cpp" , 12263, __extension__ __PRETTY_FUNCTION__)); | ||||
12264 | |||||
12265 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | ||||
12266 | // promote the boolean type, and all other promotable integer types, to | ||||
12267 | // avoid this. | ||||
12268 | if (IntType->isPromotableIntegerType()) | ||||
12269 | IntType = S.Context.getPromotedIntegerType(IntType); | ||||
12270 | |||||
12271 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | ||||
12272 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | ||||
12273 | LHSType = RHSType = IntType; | ||||
12274 | } | ||||
12275 | |||||
12276 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | ||||
12277 | // usual arithmetic conversions are applied to the operands. | ||||
12278 | QualType Type = | ||||
12279 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
12280 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
12281 | return QualType(); | ||||
12282 | if (Type.isNull()) | ||||
12283 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12284 | |||||
12285 | Optional<ComparisonCategoryType> CCT = | ||||
12286 | getComparisonCategoryForBuiltinCmp(Type); | ||||
12287 | if (!CCT) | ||||
12288 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12289 | |||||
12290 | bool HasNarrowing = checkThreeWayNarrowingConversion( | ||||
12291 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | ||||
12292 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | ||||
12293 | RHS.get()->getBeginLoc()); | ||||
12294 | if (HasNarrowing) | ||||
12295 | return QualType(); | ||||
12296 | |||||
12297 | assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast <bool> (!Type.isNull() && "composite type for <=> has not been set" ) ? void (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "clang/lib/Sema/SemaExpr.cpp", 12297, __extension__ __PRETTY_FUNCTION__ )); | ||||
12298 | |||||
12299 | return S.CheckComparisonCategoryType( | ||||
12300 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | ||||
12301 | } | ||||
12302 | |||||
12303 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | ||||
12304 | ExprResult &RHS, | ||||
12305 | SourceLocation Loc, | ||||
12306 | BinaryOperatorKind Opc) { | ||||
12307 | if (Opc == BO_Cmp) | ||||
12308 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | ||||
12309 | |||||
12310 | // C99 6.5.8p3 / C99 6.5.9p4 | ||||
12311 | QualType Type = | ||||
12312 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
12313 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
12314 | return QualType(); | ||||
12315 | if (Type.isNull()) | ||||
12316 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12317 | assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type ->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "clang/lib/Sema/SemaExpr.cpp", 12317, __extension__ __PRETTY_FUNCTION__ )); | ||||
12318 | |||||
12319 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | ||||
12320 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
12321 | |||||
12322 | // Check for comparisons of floating point operands using != and ==. | ||||
12323 | if (Type->hasFloatingRepresentation()) | ||||
12324 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); | ||||
12325 | |||||
12326 | // The result of comparisons is 'bool' in C++, 'int' in C. | ||||
12327 | return S.Context.getLogicalOperationType(); | ||||
12328 | } | ||||
12329 | |||||
12330 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | ||||
12331 | if (!NullE.get()->getType()->isAnyPointerType()) | ||||
12332 | return; | ||||
12333 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | ||||
12334 | if (!E.get()->getType()->isAnyPointerType() && | ||||
12335 | E.get()->isNullPointerConstant(Context, | ||||
12336 | Expr::NPC_ValueDependentIsNotNull) == | ||||
12337 | Expr::NPCK_ZeroExpression) { | ||||
12338 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | ||||
12339 | if (CL->getValue() == 0) | ||||
12340 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
12341 | << NullValue | ||||
12342 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
12343 | NullValue ? "NULL" : "(void *)0"); | ||||
12344 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | ||||
12345 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | ||||
12346 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | ||||
12347 | if (T == Context.CharTy) | ||||
12348 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
12349 | << NullValue | ||||
12350 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
12351 | NullValue ? "NULL" : "(void *)0"); | ||||
12352 | } | ||||
12353 | } | ||||
12354 | } | ||||
12355 | |||||
12356 | // C99 6.5.8, C++ [expr.rel] | ||||
12357 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12358 | SourceLocation Loc, | ||||
12359 | BinaryOperatorKind Opc) { | ||||
12360 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | ||||
12361 | bool IsThreeWay = Opc == BO_Cmp; | ||||
12362 | bool IsOrdered = IsRelational || IsThreeWay; | ||||
12363 | auto IsAnyPointerType = [](ExprResult E) { | ||||
12364 | QualType Ty = E.get()->getType(); | ||||
12365 | return Ty->isPointerType() || Ty->isMemberPointerType(); | ||||
12366 | }; | ||||
12367 | |||||
12368 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | ||||
12369 | // type, array-to-pointer, ..., conversions are performed on both operands to | ||||
12370 | // bring them to their composite type. | ||||
12371 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | ||||
12372 | // any type-related checks. | ||||
12373 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | ||||
12374 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12375 | if (LHS.isInvalid()) | ||||
12376 | return QualType(); | ||||
12377 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12378 | if (RHS.isInvalid()) | ||||
12379 | return QualType(); | ||||
12380 | } else { | ||||
12381 | LHS = DefaultLvalueConversion(LHS.get()); | ||||
12382 | if (LHS.isInvalid()) | ||||
12383 | return QualType(); | ||||
12384 | RHS = DefaultLvalueConversion(RHS.get()); | ||||
12385 | if (RHS.isInvalid()) | ||||
12386 | return QualType(); | ||||
12387 | } | ||||
12388 | |||||
12389 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | ||||
12390 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | ||||
12391 | CheckPtrComparisonWithNullChar(LHS, RHS); | ||||
12392 | CheckPtrComparisonWithNullChar(RHS, LHS); | ||||
12393 | } | ||||
12394 | |||||
12395 | // Handle vector comparisons separately. | ||||
12396 | if (LHS.get()->getType()->isVectorType() || | ||||
12397 | RHS.get()->getType()->isVectorType()) | ||||
12398 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
12399 | |||||
12400 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
12401 | RHS.get()->getType()->isVLSTBuiltinType()) | ||||
12402 | return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
12403 | |||||
12404 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
12405 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12406 | |||||
12407 | QualType LHSType = LHS.get()->getType(); | ||||
12408 | QualType RHSType = RHS.get()->getType(); | ||||
12409 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | ||||
12410 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | ||||
12411 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | ||||
12412 | |||||
12413 | const Expr::NullPointerConstantKind LHSNullKind = | ||||
12414 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
12415 | const Expr::NullPointerConstantKind RHSNullKind = | ||||
12416 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
12417 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | ||||
12418 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | ||||
12419 | |||||
12420 | auto computeResultTy = [&]() { | ||||
12421 | if (Opc != BO_Cmp) | ||||
12422 | return Context.getLogicalOperationType(); | ||||
12423 | assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0 ) : __assert_fail ("getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 12423, __extension__ __PRETTY_FUNCTION__)); | ||||
12424 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast <bool> (Context.hasSameType(LHS.get()-> getType(), RHS.get()->getType())) ? void (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "clang/lib/Sema/SemaExpr.cpp", 12424, __extension__ __PRETTY_FUNCTION__ )); | ||||
12425 | |||||
12426 | QualType CompositeTy = LHS.get()->getType(); | ||||
12427 | assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType() ) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()" , "clang/lib/Sema/SemaExpr.cpp", 12427, __extension__ __PRETTY_FUNCTION__ )); | ||||
12428 | |||||
12429 | Optional<ComparisonCategoryType> CCT = | ||||
12430 | getComparisonCategoryForBuiltinCmp(CompositeTy); | ||||
12431 | if (!CCT) | ||||
12432 | return InvalidOperands(Loc, LHS, RHS); | ||||
12433 | |||||
12434 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | ||||
12435 | // P0946R0: Comparisons between a null pointer constant and an object | ||||
12436 | // pointer result in std::strong_equality, which is ill-formed under | ||||
12437 | // P1959R0. | ||||
12438 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | ||||
12439 | << (LHSIsNull ? LHS.get()->getSourceRange() | ||||
12440 | : RHS.get()->getSourceRange()); | ||||
12441 | return QualType(); | ||||
12442 | } | ||||
12443 | |||||
12444 | return CheckComparisonCategoryType( | ||||
12445 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | ||||
12446 | }; | ||||
12447 | |||||
12448 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | ||||
12449 | bool IsEquality = Opc == BO_EQ; | ||||
12450 | if (RHSIsNull) | ||||
12451 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | ||||
12452 | RHS.get()->getSourceRange()); | ||||
12453 | else | ||||
12454 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | ||||
12455 | LHS.get()->getSourceRange()); | ||||
12456 | } | ||||
12457 | |||||
12458 | if (IsOrdered && LHSType->isFunctionPointerType() && | ||||
12459 | RHSType->isFunctionPointerType()) { | ||||
12460 | // Valid unless a relational comparison of function pointers | ||||
12461 | bool IsError = Opc == BO_Cmp; | ||||
12462 | auto DiagID = | ||||
12463 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers | ||||
12464 | : getLangOpts().CPlusPlus | ||||
12465 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers | ||||
12466 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; | ||||
12467 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12468 | << RHS.get()->getSourceRange(); | ||||
12469 | if (IsError) | ||||
12470 | return QualType(); | ||||
12471 | } | ||||
12472 | |||||
12473 | if ((LHSType->isIntegerType() && !LHSIsNull) || | ||||
12474 | (RHSType->isIntegerType() && !RHSIsNull)) { | ||||
12475 | // Skip normal pointer conversion checks in this case; we have better | ||||
12476 | // diagnostics for this below. | ||||
12477 | } else if (getLangOpts().CPlusPlus) { | ||||
12478 | // Equality comparison of a function pointer to a void pointer is invalid, | ||||
12479 | // but we allow it as an extension. | ||||
12480 | // FIXME: If we really want to allow this, should it be part of composite | ||||
12481 | // pointer type computation so it works in conditionals too? | ||||
12482 | if (!IsOrdered && | ||||
12483 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | ||||
12484 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | ||||
12485 | // This is a gcc extension compatibility comparison. | ||||
12486 | // In a SFINAE context, we treat this as a hard error to maintain | ||||
12487 | // conformance with the C++ standard. | ||||
12488 | diagnoseFunctionPointerToVoidComparison( | ||||
12489 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | ||||
12490 | |||||
12491 | if (isSFINAEContext()) | ||||
12492 | return QualType(); | ||||
12493 | |||||
12494 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12495 | return computeResultTy(); | ||||
12496 | } | ||||
12497 | |||||
12498 | // C++ [expr.eq]p2: | ||||
12499 | // If at least one operand is a pointer [...] bring them to their | ||||
12500 | // composite pointer type. | ||||
12501 | // C++ [expr.spaceship]p6 | ||||
12502 | // If at least one of the operands is of pointer type, [...] bring them | ||||
12503 | // to their composite pointer type. | ||||
12504 | // C++ [expr.rel]p2: | ||||
12505 | // If both operands are pointers, [...] bring them to their composite | ||||
12506 | // pointer type. | ||||
12507 | // For <=>, the only valid non-pointer types are arrays and functions, and | ||||
12508 | // we already decayed those, so this is really the same as the relational | ||||
12509 | // comparison rule. | ||||
12510 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | ||||
12511 | (IsOrdered ? 2 : 1) && | ||||
12512 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | ||||
12513 | RHSType->isObjCObjectPointerType()))) { | ||||
12514 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
12515 | return QualType(); | ||||
12516 | return computeResultTy(); | ||||
12517 | } | ||||
12518 | } else if (LHSType->isPointerType() && | ||||
12519 | RHSType->isPointerType()) { // C99 6.5.8p2 | ||||
12520 | // All of the following pointer-related warnings are GCC extensions, except | ||||
12521 | // when handling null pointer constants. | ||||
12522 | QualType LCanPointeeTy = | ||||
12523 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
12524 | QualType RCanPointeeTy = | ||||
12525 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
12526 | |||||
12527 | // C99 6.5.9p2 and C99 6.5.8p2 | ||||
12528 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | ||||
12529 | RCanPointeeTy.getUnqualifiedType())) { | ||||
12530 | if (IsRelational) { | ||||
12531 | // Pointers both need to point to complete or incomplete types | ||||
12532 | if ((LCanPointeeTy->isIncompleteType() != | ||||
12533 | RCanPointeeTy->isIncompleteType()) && | ||||
12534 | !getLangOpts().C11) { | ||||
12535 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | ||||
12536 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | ||||
12537 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | ||||
12538 | << RCanPointeeTy->isIncompleteType(); | ||||
12539 | } | ||||
12540 | } | ||||
12541 | } else if (!IsRelational && | ||||
12542 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | ||||
12543 | // Valid unless comparison between non-null pointer and function pointer | ||||
12544 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | ||||
12545 | && !LHSIsNull && !RHSIsNull) | ||||
12546 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | ||||
12547 | /*isError*/false); | ||||
12548 | } else { | ||||
12549 | // Invalid | ||||
12550 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | ||||
12551 | } | ||||
12552 | if (LCanPointeeTy != RCanPointeeTy) { | ||||
12553 | // Treat NULL constant as a special case in OpenCL. | ||||
12554 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | ||||
12555 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | ||||
12556 | Diag(Loc, | ||||
12557 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
12558 | << LHSType << RHSType << 0 /* comparison */ | ||||
12559 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
12560 | } | ||||
12561 | } | ||||
12562 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | ||||
12563 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | ||||
12564 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | ||||
12565 | : CK_BitCast; | ||||
12566 | if (LHSIsNull && !RHSIsNull) | ||||
12567 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | ||||
12568 | else | ||||
12569 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | ||||
12570 | } | ||||
12571 | return computeResultTy(); | ||||
12572 | } | ||||
12573 | |||||
12574 | if (getLangOpts().CPlusPlus) { | ||||
12575 | // C++ [expr.eq]p4: | ||||
12576 | // Two operands of type std::nullptr_t or one operand of type | ||||
12577 | // std::nullptr_t and the other a null pointer constant compare equal. | ||||
12578 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | ||||
12579 | if (LHSType->isNullPtrType()) { | ||||
12580 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12581 | return computeResultTy(); | ||||
12582 | } | ||||
12583 | if (RHSType->isNullPtrType()) { | ||||
12584 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12585 | return computeResultTy(); | ||||
12586 | } | ||||
12587 | } | ||||
12588 | |||||
12589 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | ||||
12590 | // These aren't covered by the composite pointer type rules. | ||||
12591 | if (!IsOrdered && RHSType->isNullPtrType() && | ||||
12592 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | ||||
12593 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12594 | return computeResultTy(); | ||||
12595 | } | ||||
12596 | if (!IsOrdered && LHSType->isNullPtrType() && | ||||
12597 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | ||||
12598 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12599 | return computeResultTy(); | ||||
12600 | } | ||||
12601 | |||||
12602 | if (IsRelational && | ||||
12603 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | ||||
12604 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | ||||
12605 | // HACK: Relational comparison of nullptr_t against a pointer type is | ||||
12606 | // invalid per DR583, but we allow it within std::less<> and friends, | ||||
12607 | // since otherwise common uses of it break. | ||||
12608 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | ||||
12609 | // friends to have std::nullptr_t overload candidates. | ||||
12610 | DeclContext *DC = CurContext; | ||||
12611 | if (isa<FunctionDecl>(DC)) | ||||
12612 | DC = DC->getParent(); | ||||
12613 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | ||||
12614 | if (CTSD->isInStdNamespace() && | ||||
12615 | llvm::StringSwitch<bool>(CTSD->getName()) | ||||
12616 | .Cases("less", "less_equal", "greater", "greater_equal", true) | ||||
12617 | .Default(false)) { | ||||
12618 | if (RHSType->isNullPtrType()) | ||||
12619 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12620 | else | ||||
12621 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12622 | return computeResultTy(); | ||||
12623 | } | ||||
12624 | } | ||||
12625 | } | ||||
12626 | |||||
12627 | // C++ [expr.eq]p2: | ||||
12628 | // If at least one operand is a pointer to member, [...] bring them to | ||||
12629 | // their composite pointer type. | ||||
12630 | if (!IsOrdered && | ||||
12631 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | ||||
12632 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
12633 | return QualType(); | ||||
12634 | else | ||||
12635 | return computeResultTy(); | ||||
12636 | } | ||||
12637 | } | ||||
12638 | |||||
12639 | // Handle block pointer types. | ||||
12640 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
12641 | RHSType->isBlockPointerType()) { | ||||
12642 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
12643 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
12644 | |||||
12645 | if (!LHSIsNull && !RHSIsNull && | ||||
12646 | !Context.typesAreCompatible(lpointee, rpointee)) { | ||||
12647 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
12648 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12649 | << RHS.get()->getSourceRange(); | ||||
12650 | } | ||||
12651 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12652 | return computeResultTy(); | ||||
12653 | } | ||||
12654 | |||||
12655 | // Allow block pointers to be compared with null pointer constants. | ||||
12656 | if (!IsOrdered | ||||
12657 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | ||||
12658 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | ||||
12659 | if (!LHSIsNull && !RHSIsNull) { | ||||
12660 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | ||||
12661 | ->getPointeeType()->isVoidType()) | ||||
12662 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | ||||
12663 | ->getPointeeType()->isVoidType()))) | ||||
12664 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
12665 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12666 | << RHS.get()->getSourceRange(); | ||||
12667 | } | ||||
12668 | if (LHSIsNull && !RHSIsNull) | ||||
12669 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12670 | RHSType->isPointerType() ? CK_BitCast | ||||
12671 | : CK_AnyPointerToBlockPointerCast); | ||||
12672 | else | ||||
12673 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12674 | LHSType->isPointerType() ? CK_BitCast | ||||
12675 | : CK_AnyPointerToBlockPointerCast); | ||||
12676 | return computeResultTy(); | ||||
12677 | } | ||||
12678 | |||||
12679 | if (LHSType->isObjCObjectPointerType() || | ||||
12680 | RHSType->isObjCObjectPointerType()) { | ||||
12681 | const PointerType *LPT = LHSType->getAs<PointerType>(); | ||||
12682 | const PointerType *RPT = RHSType->getAs<PointerType>(); | ||||
12683 | if (LPT || RPT) { | ||||
12684 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | ||||
12685 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | ||||
12686 | |||||
12687 | if (!LPtrToVoid && !RPtrToVoid && | ||||
12688 | !Context.typesAreCompatible(LHSType, RHSType)) { | ||||
12689 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
12690 | /*isError*/false); | ||||
12691 | } | ||||
12692 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | ||||
12693 | // the RHS, but we have test coverage for this behavior. | ||||
12694 | // FIXME: Consider using convertPointersToCompositeType in C++. | ||||
12695 | if (LHSIsNull && !RHSIsNull) { | ||||
12696 | Expr *E = LHS.get(); | ||||
12697 | if (getLangOpts().ObjCAutoRefCount) | ||||
12698 | CheckObjCConversion(SourceRange(), RHSType, E, | ||||
12699 | CCK_ImplicitConversion); | ||||
12700 | LHS = ImpCastExprToType(E, RHSType, | ||||
12701 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
12702 | } | ||||
12703 | else { | ||||
12704 | Expr *E = RHS.get(); | ||||
12705 | if (getLangOpts().ObjCAutoRefCount) | ||||
12706 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | ||||
12707 | /*Diagnose=*/true, | ||||
12708 | /*DiagnoseCFAudited=*/false, Opc); | ||||
12709 | RHS = ImpCastExprToType(E, LHSType, | ||||
12710 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
12711 | } | ||||
12712 | return computeResultTy(); | ||||
12713 | } | ||||
12714 | if (LHSType->isObjCObjectPointerType() && | ||||
12715 | RHSType->isObjCObjectPointerType()) { | ||||
12716 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | ||||
12717 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
12718 | /*isError*/false); | ||||
12719 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | ||||
12720 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | ||||
12721 | |||||
12722 | if (LHSIsNull && !RHSIsNull) | ||||
12723 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
12724 | else | ||||
12725 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12726 | return computeResultTy(); | ||||
12727 | } | ||||
12728 | |||||
12729 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
12730 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
12731 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12732 | CK_BlockPointerToObjCPointerCast); | ||||
12733 | return computeResultTy(); | ||||
12734 | } else if (!IsOrdered && | ||||
12735 | LHSType->isBlockCompatibleObjCPointerType(Context) && | ||||
12736 | RHSType->isBlockPointerType()) { | ||||
12737 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12738 | CK_BlockPointerToObjCPointerCast); | ||||
12739 | return computeResultTy(); | ||||
12740 | } | ||||
12741 | } | ||||
12742 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | ||||
12743 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | ||||
12744 | unsigned DiagID = 0; | ||||
12745 | bool isError = false; | ||||
12746 | if (LangOpts.DebuggerSupport) { | ||||
12747 | // Under a debugger, allow the comparison of pointers to integers, | ||||
12748 | // since users tend to want to compare addresses. | ||||
12749 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | ||||
12750 | (RHSIsNull && RHSType->isIntegerType())) { | ||||
12751 | if (IsOrdered) { | ||||
12752 | isError = getLangOpts().CPlusPlus; | ||||
12753 | DiagID = | ||||
12754 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | ||||
12755 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | ||||
12756 | } | ||||
12757 | } else if (getLangOpts().CPlusPlus) { | ||||
12758 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | ||||
12759 | isError = true; | ||||
12760 | } else if (IsOrdered) | ||||
12761 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | ||||
12762 | else | ||||
12763 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | ||||
12764 | |||||
12765 | if (DiagID) { | ||||
12766 | Diag(Loc, DiagID) | ||||
12767 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12768 | << RHS.get()->getSourceRange(); | ||||
12769 | if (isError) | ||||
12770 | return QualType(); | ||||
12771 | } | ||||
12772 | |||||
12773 | if (LHSType->isIntegerType()) | ||||
12774 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12775 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
12776 | else | ||||
12777 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12778 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
12779 | return computeResultTy(); | ||||
12780 | } | ||||
12781 | |||||
12782 | // Handle block pointers. | ||||
12783 | if (!IsOrdered && RHSIsNull | ||||
12784 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | ||||
12785 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12786 | return computeResultTy(); | ||||
12787 | } | ||||
12788 | if (!IsOrdered && LHSIsNull | ||||
12789 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | ||||
12790 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12791 | return computeResultTy(); | ||||
12792 | } | ||||
12793 | |||||
12794 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { | ||||
12795 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | ||||
12796 | return computeResultTy(); | ||||
12797 | } | ||||
12798 | |||||
12799 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | ||||
12800 | return computeResultTy(); | ||||
12801 | } | ||||
12802 | |||||
12803 | if (LHSIsNull && RHSType->isQueueT()) { | ||||
12804 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12805 | return computeResultTy(); | ||||
12806 | } | ||||
12807 | |||||
12808 | if (LHSType->isQueueT() && RHSIsNull) { | ||||
12809 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12810 | return computeResultTy(); | ||||
12811 | } | ||||
12812 | } | ||||
12813 | |||||
12814 | return InvalidOperands(Loc, LHS, RHS); | ||||
12815 | } | ||||
12816 | |||||
12817 | // Return a signed ext_vector_type that is of identical size and number of | ||||
12818 | // elements. For floating point vectors, return an integer type of identical | ||||
12819 | // size and number of elements. In the non ext_vector_type case, search from | ||||
12820 | // the largest type to the smallest type to avoid cases where long long == long, | ||||
12821 | // where long gets picked over long long. | ||||
12822 | QualType Sema::GetSignedVectorType(QualType V) { | ||||
12823 | const VectorType *VTy = V->castAs<VectorType>(); | ||||
12824 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | ||||
12825 | |||||
12826 | if (isa<ExtVectorType>(VTy)) { | ||||
12827 | if (VTy->isExtVectorBoolType()) | ||||
12828 | return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); | ||||
12829 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | ||||
12830 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | ||||
12831 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12832 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | ||||
12833 | if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12834 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | ||||
12835 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) | ||||
12836 | return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); | ||||
12837 | if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12838 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | ||||
12839 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12840, __extension__ __PRETTY_FUNCTION__ )) | ||||
12840 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12840, __extension__ __PRETTY_FUNCTION__ )); | ||||
12841 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | ||||
12842 | } | ||||
12843 | |||||
12844 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) | ||||
12845 | return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), | ||||
12846 | VectorType::GenericVector); | ||||
12847 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | ||||
12848 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | ||||
12849 | VectorType::GenericVector); | ||||
12850 | if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12851 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | ||||
12852 | VectorType::GenericVector); | ||||
12853 | if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12854 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | ||||
12855 | VectorType::GenericVector); | ||||
12856 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12857 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | ||||
12858 | VectorType::GenericVector); | ||||
12859 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12860, __extension__ __PRETTY_FUNCTION__ )) | ||||
12860 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "clang/lib/Sema/SemaExpr.cpp", 12860, __extension__ __PRETTY_FUNCTION__ )); | ||||
12861 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | ||||
12862 | VectorType::GenericVector); | ||||
12863 | } | ||||
12864 | |||||
12865 | QualType Sema::GetSignedSizelessVectorType(QualType V) { | ||||
12866 | const BuiltinType *VTy = V->castAs<BuiltinType>(); | ||||
12867 | assert(VTy->isSizelessBuiltinType() && "expected sizeless type")(static_cast <bool> (VTy->isSizelessBuiltinType() && "expected sizeless type") ? void (0) : __assert_fail ("VTy->isSizelessBuiltinType() && \"expected sizeless type\"" , "clang/lib/Sema/SemaExpr.cpp", 12867, __extension__ __PRETTY_FUNCTION__ )); | ||||
12868 | |||||
12869 | const QualType ETy = V->getSveEltType(Context); | ||||
12870 | const auto TypeSize = Context.getTypeSize(ETy); | ||||
12871 | |||||
12872 | const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); | ||||
12873 | const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; | ||||
12874 | return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); | ||||
12875 | } | ||||
12876 | |||||
12877 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | ||||
12878 | /// operates on extended vector types. Instead of producing an IntTy result, | ||||
12879 | /// like a scalar comparison, a vector comparison produces a vector of integer | ||||
12880 | /// types. | ||||
12881 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12882 | SourceLocation Loc, | ||||
12883 | BinaryOperatorKind Opc) { | ||||
12884 | if (Opc == BO_Cmp) { | ||||
12885 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
12886 | return QualType(); | ||||
12887 | } | ||||
12888 | |||||
12889 | // Check to make sure we're operating on vectors of the same type and width, | ||||
12890 | // Allowing one side to be a scalar of element type. | ||||
12891 | QualType vType = | ||||
12892 | CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, | ||||
12893 | /*AllowBothBool*/ true, | ||||
12894 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
12895 | /*AllowBooleanOperation*/ true, | ||||
12896 | /*ReportInvalid*/ true); | ||||
12897 | if (vType.isNull()) | ||||
12898 | return vType; | ||||
12899 | |||||
12900 | QualType LHSType = LHS.get()->getType(); | ||||
12901 | |||||
12902 | // Determine the return type of a vector compare. By default clang will return | ||||
12903 | // a scalar for all vector compares except vector bool and vector pixel. | ||||
12904 | // With the gcc compiler we will always return a vector type and with the xl | ||||
12905 | // compiler we will always return a scalar type. This switch allows choosing | ||||
12906 | // which behavior is prefered. | ||||
12907 | if (getLangOpts().AltiVec) { | ||||
12908 | switch (getLangOpts().getAltivecSrcCompat()) { | ||||
12909 | case LangOptions::AltivecSrcCompatKind::Mixed: | ||||
12910 | // If AltiVec, the comparison results in a numeric type, i.e. | ||||
12911 | // bool for C++, int for C | ||||
12912 | if (vType->castAs<VectorType>()->getVectorKind() == | ||||
12913 | VectorType::AltiVecVector) | ||||
12914 | return Context.getLogicalOperationType(); | ||||
12915 | else | ||||
12916 | Diag(Loc, diag::warn_deprecated_altivec_src_compat); | ||||
12917 | break; | ||||
12918 | case LangOptions::AltivecSrcCompatKind::GCC: | ||||
12919 | // For GCC we always return the vector type. | ||||
12920 | break; | ||||
12921 | case LangOptions::AltivecSrcCompatKind::XL: | ||||
12922 | return Context.getLogicalOperationType(); | ||||
12923 | break; | ||||
12924 | } | ||||
12925 | } | ||||
12926 | |||||
12927 | // For non-floating point types, check for self-comparisons of the form | ||||
12928 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12929 | // often indicate logic errors in the program. | ||||
12930 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12931 | |||||
12932 | // Check for comparisons of floating point operands using != and ==. | ||||
12933 | if (LHSType->hasFloatingRepresentation()) { | ||||
12934 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "clang/lib/Sema/SemaExpr.cpp", 12934, __extension__ __PRETTY_FUNCTION__ )); | ||||
12935 | CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); | ||||
12936 | } | ||||
12937 | |||||
12938 | // Return a signed type for the vector. | ||||
12939 | return GetSignedVectorType(vType); | ||||
12940 | } | ||||
12941 | |||||
12942 | QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, | ||||
12943 | ExprResult &RHS, | ||||
12944 | SourceLocation Loc, | ||||
12945 | BinaryOperatorKind Opc) { | ||||
12946 | if (Opc == BO_Cmp) { | ||||
12947 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
12948 | return QualType(); | ||||
12949 | } | ||||
12950 | |||||
12951 | // Check to make sure we're operating on vectors of the same type and width, | ||||
12952 | // Allowing one side to be a scalar of element type. | ||||
12953 | QualType vType = CheckSizelessVectorOperands( | ||||
12954 | LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); | ||||
12955 | |||||
12956 | if (vType.isNull()) | ||||
12957 | return vType; | ||||
12958 | |||||
12959 | QualType LHSType = LHS.get()->getType(); | ||||
12960 | |||||
12961 | // For non-floating point types, check for self-comparisons of the form | ||||
12962 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12963 | // often indicate logic errors in the program. | ||||
12964 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12965 | |||||
12966 | // Check for comparisons of floating point operands using != and ==. | ||||
12967 | if (LHSType->hasFloatingRepresentation()) { | ||||
12968 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "clang/lib/Sema/SemaExpr.cpp", 12968, __extension__ __PRETTY_FUNCTION__ )); | ||||
12969 | CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); | ||||
12970 | } | ||||
12971 | |||||
12972 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); | ||||
12973 | const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); | ||||
12974 | |||||
12975 | if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && | ||||
12976 | RHSBuiltinTy->isSVEBool()) | ||||
12977 | return LHSType; | ||||
12978 | |||||
12979 | // Return a signed type for the vector. | ||||
12980 | return GetSignedSizelessVectorType(vType); | ||||
12981 | } | ||||
12982 | |||||
12983 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | ||||
12984 | const ExprResult &XorRHS, | ||||
12985 | const SourceLocation Loc) { | ||||
12986 | // Do not diagnose macros. | ||||
12987 | if (Loc.isMacroID()) | ||||
12988 | return; | ||||
12989 | |||||
12990 | // Do not diagnose if both LHS and RHS are macros. | ||||
12991 | if (XorLHS.get()->getExprLoc().isMacroID() && | ||||
12992 | XorRHS.get()->getExprLoc().isMacroID()) | ||||
12993 | return; | ||||
12994 | |||||
12995 | bool Negative = false; | ||||
12996 | bool ExplicitPlus = false; | ||||
12997 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | ||||
12998 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | ||||
12999 | |||||
13000 | if (!LHSInt) | ||||
13001 | return; | ||||
13002 | if (!RHSInt) { | ||||
13003 | // Check negative literals. | ||||
13004 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | ||||
13005 | UnaryOperatorKind Opc = UO->getOpcode(); | ||||
13006 | if (Opc != UO_Minus && Opc != UO_Plus) | ||||
13007 | return; | ||||
13008 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | ||||
13009 | if (!RHSInt) | ||||
13010 | return; | ||||
13011 | Negative = (Opc == UO_Minus); | ||||
13012 | ExplicitPlus = !Negative; | ||||
13013 | } else { | ||||
13014 | return; | ||||
13015 | } | ||||
13016 | } | ||||
13017 | |||||
13018 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | ||||
13019 | llvm::APInt RightSideValue = RHSInt->getValue(); | ||||
13020 | if (LeftSideValue != 2 && LeftSideValue != 10) | ||||
13021 | return; | ||||
13022 | |||||
13023 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | ||||
13024 | return; | ||||
13025 | |||||
13026 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | ||||
13027 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | ||||
13028 | llvm::StringRef ExprStr = | ||||
13029 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | ||||
13030 | |||||
13031 | CharSourceRange XorRange = | ||||
13032 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
13033 | llvm::StringRef XorStr = | ||||
13034 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | ||||
13035 | // Do not diagnose if xor keyword/macro is used. | ||||
13036 | if (XorStr == "xor") | ||||
13037 | return; | ||||
13038 | |||||
13039 | std::string LHSStr = std::string(Lexer::getSourceText( | ||||
13040 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | ||||
13041 | S.getSourceManager(), S.getLangOpts())); | ||||
13042 | std::string RHSStr = std::string(Lexer::getSourceText( | ||||
13043 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | ||||
13044 | S.getSourceManager(), S.getLangOpts())); | ||||
13045 | |||||
13046 | if (Negative) { | ||||
13047 | RightSideValue = -RightSideValue; | ||||
13048 | RHSStr = "-" + RHSStr; | ||||
13049 | } else if (ExplicitPlus) { | ||||
13050 | RHSStr = "+" + RHSStr; | ||||
13051 | } | ||||
13052 | |||||
13053 | StringRef LHSStrRef = LHSStr; | ||||
13054 | StringRef RHSStrRef = RHSStr; | ||||
13055 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | ||||
13056 | // literals. | ||||
13057 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | ||||
13058 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | ||||
13059 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | ||||
13060 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | ||||
13061 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | ||||
13062 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | ||||
13063 | LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) | ||||
13064 | return; | ||||
13065 | |||||
13066 | bool SuggestXor = | ||||
13067 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | ||||
13068 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | ||||
13069 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | ||||
13070 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | ||||
13071 | std::string SuggestedExpr = "1 << " + RHSStr; | ||||
13072 | bool Overflow = false; | ||||
13073 | llvm::APInt One = (LeftSideValue - 1); | ||||
13074 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | ||||
13075 | if (Overflow) { | ||||
13076 | if (RightSideIntValue < 64) | ||||
13077 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
13078 | << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) | ||||
13079 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | ||||
13080 | else if (RightSideIntValue == 64) | ||||
13081 | S.Diag(Loc, diag::warn_xor_used_as_pow) | ||||
13082 | << ExprStr << toString(XorValue, 10, true); | ||||
13083 | else | ||||
13084 | return; | ||||
13085 | } else { | ||||
13086 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | ||||
13087 | << ExprStr << toString(XorValue, 10, true) << SuggestedExpr | ||||
13088 | << toString(PowValue, 10, true) | ||||
13089 | << FixItHint::CreateReplacement( | ||||
13090 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | ||||
13091 | } | ||||
13092 | |||||
13093 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | ||||
13094 | << ("0x2 ^ " + RHSStr) << SuggestXor; | ||||
13095 | } else if (LeftSideValue == 10) { | ||||
13096 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | ||||
13097 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
13098 | << ExprStr << toString(XorValue, 10, true) << SuggestedValue | ||||
13099 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | ||||
13100 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | ||||
13101 | << ("0xA ^ " + RHSStr) << SuggestXor; | ||||
13102 | } | ||||
13103 | } | ||||
13104 | |||||
13105 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13106 | SourceLocation Loc) { | ||||
13107 | // Ensure that either both operands are of the same vector type, or | ||||
13108 | // one operand is of a vector type and the other is of its element type. | ||||
13109 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | ||||
13110 | /*AllowBothBool*/ true, | ||||
13111 | /*AllowBoolConversions*/ false, | ||||
13112 | /*AllowBooleanOperation*/ false, | ||||
13113 | /*ReportInvalid*/ false); | ||||
13114 | if (vType.isNull()) | ||||
13115 | return InvalidOperands(Loc, LHS, RHS); | ||||
13116 | if (getLangOpts().OpenCL && | ||||
13117 | getLangOpts().getOpenCLCompatibleVersion() < 120 && | ||||
13118 | vType->hasFloatingRepresentation()) | ||||
13119 | return InvalidOperands(Loc, LHS, RHS); | ||||
13120 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | ||||
13121 | // usage of the logical operators && and || with vectors in C. This | ||||
13122 | // check could be notionally dropped. | ||||
13123 | if (!getLangOpts().CPlusPlus && | ||||
13124 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | ||||
13125 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | ||||
13126 | |||||
13127 | return GetSignedVectorType(LHS.get()->getType()); | ||||
13128 | } | ||||
13129 | |||||
13130 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13131 | SourceLocation Loc, | ||||
13132 | bool IsCompAssign) { | ||||
13133 | if (!IsCompAssign) { | ||||
13134 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
13135 | if (LHS.isInvalid()) | ||||
13136 | return QualType(); | ||||
13137 | } | ||||
13138 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13139 | if (RHS.isInvalid()) | ||||
13140 | return QualType(); | ||||
13141 | |||||
13142 | // For conversion purposes, we ignore any qualifiers. | ||||
13143 | // For example, "const float" and "float" are equivalent. | ||||
13144 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
13145 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
13146 | |||||
13147 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | ||||
13148 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | ||||
13149 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "clang/lib/Sema/SemaExpr.cpp", 13149, __extension__ __PRETTY_FUNCTION__ )); | ||||
13150 | |||||
13151 | if (Context.hasSameType(LHSType, RHSType)) | ||||
13152 | return Context.getCommonSugaredType(LHSType, RHSType); | ||||
13153 | |||||
13154 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | ||||
13155 | // case we have to return InvalidOperands. | ||||
13156 | ExprResult OriginalLHS = LHS; | ||||
13157 | ExprResult OriginalRHS = RHS; | ||||
13158 | if (LHSMatType && !RHSMatType) { | ||||
13159 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | ||||
13160 | if (!RHS.isInvalid()) | ||||
13161 | return LHSType; | ||||
13162 | |||||
13163 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
13164 | } | ||||
13165 | |||||
13166 | if (!LHSMatType && RHSMatType) { | ||||
13167 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | ||||
13168 | if (!LHS.isInvalid()) | ||||
13169 | return RHSType; | ||||
13170 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
13171 | } | ||||
13172 | |||||
13173 | return InvalidOperands(Loc, LHS, RHS); | ||||
13174 | } | ||||
13175 | |||||
13176 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13177 | SourceLocation Loc, | ||||
13178 | bool IsCompAssign) { | ||||
13179 | if (!IsCompAssign) { | ||||
13180 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
13181 | if (LHS.isInvalid()) | ||||
13182 | return QualType(); | ||||
13183 | } | ||||
13184 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13185 | if (RHS.isInvalid()) | ||||
13186 | return QualType(); | ||||
13187 | |||||
13188 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
13189 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
13190 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "clang/lib/Sema/SemaExpr.cpp", 13190, __extension__ __PRETTY_FUNCTION__ )); | ||||
13191 | |||||
13192 | if (LHSMatType && RHSMatType) { | ||||
13193 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | ||||
13194 | return InvalidOperands(Loc, LHS, RHS); | ||||
13195 | |||||
13196 | if (Context.hasSameType(LHSMatType, RHSMatType)) | ||||
13197 | return Context.getCommonSugaredType( | ||||
13198 | LHS.get()->getType().getUnqualifiedType(), | ||||
13199 | RHS.get()->getType().getUnqualifiedType()); | ||||
13200 | |||||
13201 | QualType LHSELTy = LHSMatType->getElementType(), | ||||
13202 | RHSELTy = RHSMatType->getElementType(); | ||||
13203 | if (!Context.hasSameType(LHSELTy, RHSELTy)) | ||||
13204 | return InvalidOperands(Loc, LHS, RHS); | ||||
13205 | |||||
13206 | return Context.getConstantMatrixType( | ||||
13207 | Context.getCommonSugaredType(LHSELTy, RHSELTy), | ||||
13208 | LHSMatType->getNumRows(), RHSMatType->getNumColumns()); | ||||
13209 | } | ||||
13210 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
13211 | } | ||||
13212 | |||||
13213 | static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { | ||||
13214 | switch (Opc) { | ||||
13215 | default: | ||||
13216 | return false; | ||||
13217 | case BO_And: | ||||
13218 | case BO_AndAssign: | ||||
13219 | case BO_Or: | ||||
13220 | case BO_OrAssign: | ||||
13221 | case BO_Xor: | ||||
13222 | case BO_XorAssign: | ||||
13223 | return true; | ||||
13224 | } | ||||
13225 | } | ||||
13226 | |||||
13227 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13228 | SourceLocation Loc, | ||||
13229 | BinaryOperatorKind Opc) { | ||||
13230 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
13231 | |||||
13232 | bool IsCompAssign = | ||||
13233 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | ||||
13234 | |||||
13235 | bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); | ||||
13236 | |||||
13237 | if (LHS.get()->getType()->isVectorType() || | ||||
13238 | RHS.get()->getType()->isVectorType()) { | ||||
13239 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
13240 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
13241 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
13242 | /*AllowBothBool*/ true, | ||||
13243 | /*AllowBoolConversions*/ getLangOpts().ZVector, | ||||
13244 | /*AllowBooleanOperation*/ LegalBoolVecOperator, | ||||
13245 | /*ReportInvalid*/ true); | ||||
13246 | return InvalidOperands(Loc, LHS, RHS); | ||||
13247 | } | ||||
13248 | |||||
13249 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
13250 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
13251 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
13252 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
13253 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
13254 | ACK_BitwiseOp); | ||||
13255 | return InvalidOperands(Loc, LHS, RHS); | ||||
13256 | } | ||||
13257 | |||||
13258 | if (LHS.get()->getType()->isVLSTBuiltinType() || | ||||
13259 | RHS.get()->getType()->isVLSTBuiltinType()) { | ||||
13260 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
13261 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
13262 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
13263 | ACK_BitwiseOp); | ||||
13264 | return InvalidOperands(Loc, LHS, RHS); | ||||
13265 | } | ||||
13266 | |||||
13267 | if (Opc == BO_And) | ||||
13268 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
13269 | |||||
13270 | if (LHS.get()->getType()->hasFloatingRepresentation() || | ||||
13271 | RHS.get()->getType()->hasFloatingRepresentation()) | ||||
13272 | return InvalidOperands(Loc, LHS, RHS); | ||||
13273 | |||||
13274 | ExprResult LHSResult = LHS, RHSResult = RHS; | ||||
13275 | QualType compType = UsualArithmeticConversions( | ||||
13276 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | ||||
13277 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | ||||
13278 | return QualType(); | ||||
13279 | LHS = LHSResult.get(); | ||||
13280 | RHS = RHSResult.get(); | ||||
13281 | |||||
13282 | if (Opc == BO_Xor) | ||||
13283 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | ||||
13284 | |||||
13285 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | ||||
13286 | return compType; | ||||
13287 | return InvalidOperands(Loc, LHS, RHS); | ||||
13288 | } | ||||
13289 | |||||
13290 | // C99 6.5.[13,14] | ||||
13291 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
13292 | SourceLocation Loc, | ||||
13293 | BinaryOperatorKind Opc) { | ||||
13294 | // Check vector operands differently. | ||||
13295 | if (LHS.get()->getType()->isVectorType() || | ||||
13296 | RHS.get()->getType()->isVectorType()) | ||||
13297 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | ||||
13298 | |||||
13299 | bool EnumConstantInBoolContext = false; | ||||
13300 | for (const ExprResult &HS : {LHS, RHS}) { | ||||
13301 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | ||||
13302 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | ||||
13303 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | ||||
13304 | EnumConstantInBoolContext = true; | ||||
13305 | } | ||||
13306 | } | ||||
13307 | |||||
13308 | if (EnumConstantInBoolContext) | ||||
13309 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | ||||
13310 | |||||
13311 | // Diagnose cases where the user write a logical and/or but probably meant a | ||||
13312 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | ||||
13313 | // is a constant. | ||||
13314 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | ||||
13315 | !LHS.get()->getType()->isBooleanType() && | ||||
13316 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | ||||
13317 | // Don't warn in macros or template instantiations. | ||||
13318 | !Loc.isMacroID() && !inTemplateInstantiation()) { | ||||
13319 | // If the RHS can be constant folded, and if it constant folds to something | ||||
13320 | // that isn't 0 or 1 (which indicate a potential logical operation that | ||||
13321 | // happened to fold to true/false) then warn. | ||||
13322 | // Parens on the RHS are ignored. | ||||
13323 | Expr::EvalResult EVResult; | ||||
13324 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | ||||
13325 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
13326 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | ||||
13327 | !RHS.get()->getExprLoc().isMacroID()) || | ||||
13328 | (Result != 0 && Result != 1)) { | ||||
13329 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | ||||
13330 | << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); | ||||
13331 | // Suggest replacing the logical operator with the bitwise version | ||||
13332 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | ||||
13333 | << (Opc == BO_LAnd ? "&" : "|") | ||||
13334 | << FixItHint::CreateReplacement( | ||||
13335 | SourceRange(Loc, getLocForEndOfToken(Loc)), | ||||
13336 | Opc == BO_LAnd ? "&" : "|"); | ||||
13337 | if (Opc == BO_LAnd) | ||||
13338 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | ||||
13339 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | ||||
13340 | << FixItHint::CreateRemoval( | ||||
13341 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | ||||
13342 | RHS.get()->getEndLoc())); | ||||
13343 | } | ||||
13344 | } | ||||
13345 | } | ||||
13346 | |||||
13347 | if (!Context.getLangOpts().CPlusPlus) { | ||||
13348 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | ||||
13349 | // not operate on the built-in scalar and vector float types. | ||||
13350 | if (Context.getLangOpts().OpenCL && | ||||
13351 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
13352 | if (LHS.get()->getType()->isFloatingType() || | ||||
13353 | RHS.get()->getType()->isFloatingType()) | ||||
13354 | return InvalidOperands(Loc, LHS, RHS); | ||||
13355 | } | ||||
13356 | |||||
13357 | LHS = UsualUnaryConversions(LHS.get()); | ||||
13358 | if (LHS.isInvalid()) | ||||
13359 | return QualType(); | ||||
13360 | |||||
13361 | RHS = UsualUnaryConversions(RHS.get()); | ||||
13362 | if (RHS.isInvalid()) | ||||
13363 | return QualType(); | ||||
13364 | |||||
13365 | if (!LHS.get()->getType()->isScalarType() || | ||||
13366 | !RHS.get()->getType()->isScalarType()) | ||||
13367 | return InvalidOperands(Loc, LHS, RHS); | ||||
13368 | |||||
13369 | return Context.IntTy; | ||||
13370 | } | ||||
13371 | |||||
13372 | // The following is safe because we only use this method for | ||||
13373 | // non-overloadable operands. | ||||
13374 | |||||
13375 | // C++ [expr.log.and]p1 | ||||
13376 | // C++ [expr.log.or]p1 | ||||
13377 | // The operands are both contextually converted to type bool. | ||||
13378 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | ||||
13379 | if (LHSRes.isInvalid()) | ||||
13380 | return InvalidOperands(Loc, LHS, RHS); | ||||
13381 | LHS = LHSRes; | ||||
13382 | |||||
13383 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | ||||
13384 | if (RHSRes.isInvalid()) | ||||
13385 | return InvalidOperands(Loc, LHS, RHS); | ||||
13386 | RHS = RHSRes; | ||||
13387 | |||||
13388 | // C++ [expr.log.and]p2 | ||||
13389 | // C++ [expr.log.or]p2 | ||||
13390 | // The result is a bool. | ||||
13391 | return Context.BoolTy; | ||||
13392 | } | ||||
13393 | |||||
13394 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | ||||
13395 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
13396 | if (!ME) return false; | ||||
13397 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | ||||
13398 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | ||||
13399 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | ||||
13400 | if (!Base) return false; | ||||
13401 | return Base->getMethodDecl() != nullptr; | ||||
13402 | } | ||||
13403 | |||||
13404 | /// Is the given expression (which must be 'const') a reference to a | ||||
13405 | /// variable which was originally non-const, but which has become | ||||
13406 | /// 'const' due to being captured within a block? | ||||
13407 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | ||||
13408 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | ||||
13409 | assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E-> getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "clang/lib/Sema/SemaExpr.cpp", 13409, __extension__ __PRETTY_FUNCTION__ )); | ||||
13410 | E = E->IgnoreParens(); | ||||
13411 | |||||
13412 | // Must be a reference to a declaration from an enclosing scope. | ||||
13413 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
13414 | if (!DRE) return NCCK_None; | ||||
13415 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | ||||
13416 | |||||
13417 | // The declaration must be a variable which is not declared 'const'. | ||||
13418 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
13419 | if (!var) return NCCK_None; | ||||
13420 | if (var->getType().isConstQualified()) return NCCK_None; | ||||
13421 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast <bool> (var->hasLocalStorage() && "capture added 'const' to non-local?") ? void (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "clang/lib/Sema/SemaExpr.cpp", 13421, __extension__ __PRETTY_FUNCTION__ )); | ||||
13422 | |||||
13423 | // Decide whether the first capture was for a block or a lambda. | ||||
13424 | DeclContext *DC = S.CurContext, *Prev = nullptr; | ||||
13425 | // Decide whether the first capture was for a block or a lambda. | ||||
13426 | while (DC) { | ||||
13427 | // For init-capture, it is possible that the variable belongs to the | ||||
13428 | // template pattern of the current context. | ||||
13429 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | ||||
13430 | if (var->isInitCapture() && | ||||
13431 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | ||||
13432 | break; | ||||
13433 | if (DC == var->getDeclContext()) | ||||
13434 | break; | ||||
13435 | Prev = DC; | ||||
13436 | DC = DC->getParent(); | ||||
13437 | } | ||||
13438 | // Unless we have an init-capture, we've gone one step too far. | ||||
13439 | if (!var->isInitCapture()) | ||||
13440 | DC = Prev; | ||||
13441 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | ||||
13442 | } | ||||
13443 | |||||
13444 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | ||||
13445 | Ty = Ty.getNonReferenceType(); | ||||
13446 | if (IsDereference && Ty->isPointerType()) | ||||
13447 | Ty = Ty->getPointeeType(); | ||||
13448 | return !Ty.isConstQualified(); | ||||
13449 | } | ||||
13450 | |||||
13451 | // Update err_typecheck_assign_const and note_typecheck_assign_const | ||||
13452 | // when this enum is changed. | ||||
13453 | enum { | ||||
13454 | ConstFunction, | ||||
13455 | ConstVariable, | ||||
13456 | ConstMember, | ||||
13457 | ConstMethod, | ||||
13458 | NestedConstMember, | ||||
13459 | ConstUnknown, // Keep as last element | ||||
13460 | }; | ||||
13461 | |||||
13462 | /// Emit the "read-only variable not assignable" error and print notes to give | ||||
13463 | /// more information about why the variable is not assignable, such as pointing | ||||
13464 | /// to the declaration of a const variable, showing that a method is const, or | ||||
13465 | /// that the function is returning a const reference. | ||||
13466 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | ||||
13467 | SourceLocation Loc) { | ||||
13468 | SourceRange ExprRange = E->getSourceRange(); | ||||
13469 | |||||
13470 | // Only emit one error on the first const found. All other consts will emit | ||||
13471 | // a note to the error. | ||||
13472 | bool DiagnosticEmitted = false; | ||||
13473 | |||||
13474 | // Track if the current expression is the result of a dereference, and if the | ||||
13475 | // next checked expression is the result of a dereference. | ||||
13476 | bool IsDereference = false; | ||||
13477 | bool NextIsDereference = false; | ||||
13478 | |||||
13479 | // Loop to process MemberExpr chains. | ||||
13480 | while (true) { | ||||
13481 | IsDereference = NextIsDereference; | ||||
13482 | |||||
13483 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | ||||
13484 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
13485 | NextIsDereference = ME->isArrow(); | ||||
13486 | const ValueDecl *VD = ME->getMemberDecl(); | ||||
13487 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | ||||
13488 | // Mutable fields can be modified even if the class is const. | ||||
13489 | if (Field->isMutable()) { | ||||
13490 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted." ) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "clang/lib/Sema/SemaExpr.cpp", 13490, __extension__ __PRETTY_FUNCTION__ )); | ||||
13491 | break; | ||||
13492 | } | ||||
13493 | |||||
13494 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | ||||
13495 | if (!DiagnosticEmitted) { | ||||
13496 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13497 | << ExprRange << ConstMember << false /*static*/ << Field | ||||
13498 | << Field->getType(); | ||||
13499 | DiagnosticEmitted = true; | ||||
13500 | } | ||||
13501 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
13502 | << ConstMember << false /*static*/ << Field << Field->getType() | ||||
13503 | << Field->getSourceRange(); | ||||
13504 | } | ||||
13505 | E = ME->getBase(); | ||||
13506 | continue; | ||||
13507 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | ||||
13508 | if (VDecl->getType().isConstQualified()) { | ||||
13509 | if (!DiagnosticEmitted) { | ||||
13510 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13511 | << ExprRange << ConstMember << true /*static*/ << VDecl | ||||
13512 | << VDecl->getType(); | ||||
13513 | DiagnosticEmitted = true; | ||||
13514 | } | ||||
13515 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
13516 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | ||||
13517 | << VDecl->getSourceRange(); | ||||
13518 | } | ||||
13519 | // Static fields do not inherit constness from parents. | ||||
13520 | break; | ||||
13521 | } | ||||
13522 | break; // End MemberExpr | ||||
13523 | } else if (const ArraySubscriptExpr *ASE = | ||||
13524 | dyn_cast<ArraySubscriptExpr>(E)) { | ||||
13525 | E = ASE->getBase()->IgnoreParenImpCasts(); | ||||
13526 | continue; | ||||
13527 | } else if (const ExtVectorElementExpr *EVE = | ||||
13528 | dyn_cast<ExtVectorElementExpr>(E)) { | ||||
13529 | E = EVE->getBase()->IgnoreParenImpCasts(); | ||||
13530 | continue; | ||||
13531 | } | ||||
13532 | break; | ||||
13533 | } | ||||
13534 | |||||
13535 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
13536 | // Function calls | ||||
13537 | const FunctionDecl *FD = CE->getDirectCallee(); | ||||
13538 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | ||||
13539 | if (!DiagnosticEmitted) { | ||||
13540 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
13541 | << ConstFunction << FD; | ||||
13542 | DiagnosticEmitted = true; | ||||
13543 | } | ||||
13544 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | ||||
13545 | diag::note_typecheck_assign_const) | ||||
13546 | << ConstFunction << FD << FD->getReturnType() | ||||
13547 | << FD->getReturnTypeSourceRange(); | ||||
13548 | } | ||||
13549 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
13550 | // Point to variable declaration. | ||||
13551 | if (const ValueDecl *VD = DRE->getDecl()) { | ||||
13552 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | ||||
13553 | if (!DiagnosticEmitted) { | ||||
13554 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13555 | << ExprRange << ConstVariable << VD << VD->getType(); | ||||
13556 | DiagnosticEmitted = true; | ||||
13557 | } | ||||
13558 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
13559 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | ||||
13560 | } | ||||
13561 | } | ||||
13562 | } else if (isa<CXXThisExpr>(E)) { | ||||
13563 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | ||||
13564 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | ||||
13565 | if (MD->isConst()) { | ||||
13566 | if (!DiagnosticEmitted) { | ||||
13567 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
13568 | << ConstMethod << MD; | ||||
13569 | DiagnosticEmitted = true; | ||||
13570 | } | ||||
13571 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | ||||
13572 | << ConstMethod << MD << MD->getSourceRange(); | ||||
13573 | } | ||||
13574 | } | ||||
13575 | } | ||||
13576 | } | ||||
13577 | |||||
13578 | if (DiagnosticEmitted) | ||||
13579 | return; | ||||
13580 | |||||
13581 | // Can't determine a more specific message, so display the generic error. | ||||
13582 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | ||||
13583 | } | ||||
13584 | |||||
13585 | enum OriginalExprKind { | ||||
13586 | OEK_Variable, | ||||
13587 | OEK_Member, | ||||
13588 | OEK_LValue | ||||
13589 | }; | ||||
13590 | |||||
13591 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | ||||
13592 | const RecordType *Ty, | ||||
13593 | SourceLocation Loc, SourceRange Range, | ||||
13594 | OriginalExprKind OEK, | ||||
13595 | bool &DiagnosticEmitted) { | ||||
13596 | std::vector<const RecordType *> RecordTypeList; | ||||
13597 | RecordTypeList.push_back(Ty); | ||||
13598 | unsigned NextToCheckIndex = 0; | ||||
13599 | // We walk the record hierarchy breadth-first to ensure that we print | ||||
13600 | // diagnostics in field nesting order. | ||||
13601 | while (RecordTypeList.size() > NextToCheckIndex) { | ||||
13602 | bool IsNested = NextToCheckIndex > 0; | ||||
13603 | for (const FieldDecl *Field : | ||||
13604 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | ||||
13605 | // First, check every field for constness. | ||||
13606 | QualType FieldTy = Field->getType(); | ||||
13607 | if (FieldTy.isConstQualified()) { | ||||
13608 | if (!DiagnosticEmitted) { | ||||
13609 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
13610 | << Range << NestedConstMember << OEK << VD | ||||
13611 | << IsNested << Field; | ||||
13612 | DiagnosticEmitted = true; | ||||
13613 | } | ||||
13614 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | ||||
13615 | << NestedConstMember << IsNested << Field | ||||
13616 | << FieldTy << Field->getSourceRange(); | ||||
13617 | } | ||||
13618 | |||||
13619 | // Then we append it to the list to check next in order. | ||||
13620 | FieldTy = FieldTy.getCanonicalType(); | ||||
13621 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | ||||
13622 | if (!llvm::is_contained(RecordTypeList, FieldRecTy)) | ||||
13623 | RecordTypeList.push_back(FieldRecTy); | ||||
13624 | } | ||||
13625 | } | ||||
13626 | ++NextToCheckIndex; | ||||
13627 | } | ||||
13628 | } | ||||
13629 | |||||
13630 | /// Emit an error for the case where a record we are trying to assign to has a | ||||
13631 | /// const-qualified field somewhere in its hierarchy. | ||||
13632 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | ||||
13633 | SourceLocation Loc) { | ||||
13634 | QualType Ty = E->getType(); | ||||
13635 | assert(Ty->isRecordType() && "lvalue was not record?")(static_cast <bool> (Ty->isRecordType() && "lvalue was not record?" ) ? void (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "clang/lib/Sema/SemaExpr.cpp", 13635, __extension__ __PRETTY_FUNCTION__ )); | ||||
13636 | SourceRange Range = E->getSourceRange(); | ||||
13637 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | ||||
13638 | bool DiagEmitted = false; | ||||
13639 | |||||
13640 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
13641 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | ||||
13642 | Range, OEK_Member, DiagEmitted); | ||||
13643 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
13644 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | ||||
13645 | Range, OEK_Variable, DiagEmitted); | ||||
13646 | else | ||||
13647 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | ||||
13648 | Range, OEK_LValue, DiagEmitted); | ||||
13649 | if (!DiagEmitted) | ||||
13650 | DiagnoseConstAssignment(S, E, Loc); | ||||
13651 | } | ||||
13652 | |||||
13653 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | ||||
13654 | /// emit an error and return true. If so, return false. | ||||
13655 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | ||||
13656 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "clang/lib/Sema/SemaExpr.cpp", 13656, __extension__ __PRETTY_FUNCTION__ )); | ||||
13657 | |||||
13658 | S.CheckShadowingDeclModification(E, Loc); | ||||
13659 | |||||
13660 | SourceLocation OrigLoc = Loc; | ||||
13661 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | ||||
13662 | &Loc); | ||||
13663 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | ||||
13664 | IsLV = Expr::MLV_InvalidMessageExpression; | ||||
13665 | if (IsLV == Expr::MLV_Valid) | ||||
13666 | return false; | ||||
13667 | |||||
13668 | unsigned DiagID = 0; | ||||
13669 | bool NeedType = false; | ||||
13670 | switch (IsLV) { // C99 6.5.16p2 | ||||
13671 | case Expr::MLV_ConstQualified: | ||||
13672 | // Use a specialized diagnostic when we're assigning to an object | ||||
13673 | // from an enclosing function or block. | ||||
13674 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | ||||
13675 | if (NCCK == NCCK_Block) | ||||
13676 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | ||||
13677 | else | ||||
13678 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | ||||
13679 | break; | ||||
13680 | } | ||||
13681 | |||||
13682 | // In ARC, use some specialized diagnostics for occasions where we | ||||
13683 | // infer 'const'. These are always pseudo-strong variables. | ||||
13684 | if (S.getLangOpts().ObjCAutoRefCount) { | ||||
13685 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | ||||
13686 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | ||||
13687 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | ||||
13688 | |||||
13689 | // Use the normal diagnostic if it's pseudo-__strong but the | ||||
13690 | // user actually wrote 'const'. | ||||
13691 | if (var->isARCPseudoStrong() && | ||||
13692 | (!var->getTypeSourceInfo() || | ||||
13693 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | ||||
13694 | // There are three pseudo-strong cases: | ||||
13695 | // - self | ||||
13696 | ObjCMethodDecl *method = S.getCurMethodDecl(); | ||||
13697 | if (method && var == method->getSelfDecl()) { | ||||
13698 | DiagID = method->isClassMethod() | ||||
13699 | ? diag::err_typecheck_arc_assign_self_class_method | ||||
13700 | : diag::err_typecheck_arc_assign_self; | ||||
13701 | |||||
13702 | // - Objective-C externally_retained attribute. | ||||
13703 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | ||||
13704 | isa<ParmVarDecl>(var)) { | ||||
13705 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | ||||
13706 | |||||
13707 | // - fast enumeration variables | ||||
13708 | } else { | ||||
13709 | DiagID = diag::err_typecheck_arr_assign_enumeration; | ||||
13710 | } | ||||
13711 | |||||
13712 | SourceRange Assign; | ||||
13713 | if (Loc != OrigLoc) | ||||
13714 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
13715 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
13716 | // We need to preserve the AST regardless, so migration tool | ||||
13717 | // can do its job. | ||||
13718 | return false; | ||||
13719 | } | ||||
13720 | } | ||||
13721 | } | ||||
13722 | |||||
13723 | // If none of the special cases above are triggered, then this is a | ||||
13724 | // simple const assignment. | ||||
13725 | if (DiagID == 0) { | ||||
13726 | DiagnoseConstAssignment(S, E, Loc); | ||||
13727 | return true; | ||||
13728 | } | ||||
13729 | |||||
13730 | break; | ||||
13731 | case Expr::MLV_ConstAddrSpace: | ||||
13732 | DiagnoseConstAssignment(S, E, Loc); | ||||
13733 | return true; | ||||
13734 | case Expr::MLV_ConstQualifiedField: | ||||
13735 | DiagnoseRecursiveConstFields(S, E, Loc); | ||||
13736 | return true; | ||||
13737 | case Expr::MLV_ArrayType: | ||||
13738 | case Expr::MLV_ArrayTemporary: | ||||
13739 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | ||||
13740 | NeedType = true; | ||||
13741 | break; | ||||
13742 | case Expr::MLV_NotObjectType: | ||||
13743 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | ||||
13744 | NeedType = true; | ||||
13745 | break; | ||||
13746 | case Expr::MLV_LValueCast: | ||||
13747 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | ||||
13748 | break; | ||||
13749 | case Expr::MLV_Valid: | ||||
13750 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "clang/lib/Sema/SemaExpr.cpp", 13750); | ||||
13751 | case Expr::MLV_InvalidExpression: | ||||
13752 | case Expr::MLV_MemberFunction: | ||||
13753 | case Expr::MLV_ClassTemporary: | ||||
13754 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | ||||
13755 | break; | ||||
13756 | case Expr::MLV_IncompleteType: | ||||
13757 | case Expr::MLV_IncompleteVoidType: | ||||
13758 | return S.RequireCompleteType(Loc, E->getType(), | ||||
13759 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | ||||
13760 | case Expr::MLV_DuplicateVectorComponents: | ||||
13761 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | ||||
13762 | break; | ||||
13763 | case Expr::MLV_NoSetterProperty: | ||||
13764 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "clang/lib/Sema/SemaExpr.cpp", 13764); | ||||
13765 | case Expr::MLV_InvalidMessageExpression: | ||||
13766 | DiagID = diag::err_readonly_message_assignment; | ||||
13767 | break; | ||||
13768 | case Expr::MLV_SubObjCPropertySetting: | ||||
13769 | DiagID = diag::err_no_subobject_property_setting; | ||||
13770 | break; | ||||
13771 | } | ||||
13772 | |||||
13773 | SourceRange Assign; | ||||
13774 | if (Loc != OrigLoc) | ||||
13775 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
13776 | if (NeedType) | ||||
13777 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | ||||
13778 | else | ||||
13779 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
13780 | return true; | ||||
13781 | } | ||||
13782 | |||||
13783 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | ||||
13784 | SourceLocation Loc, | ||||
13785 | Sema &Sema) { | ||||
13786 | if (Sema.inTemplateInstantiation()) | ||||
13787 | return; | ||||
13788 | if (Sema.isUnevaluatedContext()) | ||||
13789 | return; | ||||
13790 | if (Loc.isInvalid() || Loc.isMacroID()) | ||||
13791 | return; | ||||
13792 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | ||||
13793 | return; | ||||
13794 | |||||
13795 | // C / C++ fields | ||||
13796 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | ||||
13797 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | ||||
13798 | if (ML && MR) { | ||||
13799 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | ||||
13800 | return; | ||||
13801 | const ValueDecl *LHSDecl = | ||||
13802 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | ||||
13803 | const ValueDecl *RHSDecl = | ||||
13804 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | ||||
13805 | if (LHSDecl != RHSDecl) | ||||
13806 | return; | ||||
13807 | if (LHSDecl->getType().isVolatileQualified()) | ||||
13808 | return; | ||||
13809 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
13810 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
13811 | return; | ||||
13812 | |||||
13813 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | ||||
13814 | } | ||||
13815 | |||||
13816 | // Objective-C instance variables | ||||
13817 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | ||||
13818 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | ||||
13819 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | ||||
13820 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | ||||
13821 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | ||||
13822 | if (RL && RR && RL->getDecl() == RR->getDecl()) | ||||
13823 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | ||||
13824 | } | ||||
13825 | } | ||||
13826 | |||||
13827 | // C99 6.5.16.1 | ||||
13828 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | ||||
13829 | SourceLocation Loc, | ||||
13830 | QualType CompoundType, | ||||
13831 | BinaryOperatorKind Opc) { | ||||
13832 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "clang/lib/Sema/SemaExpr.cpp", 13832, __extension__ __PRETTY_FUNCTION__ )); | ||||
13833 | |||||
13834 | // Verify that LHS is a modifiable lvalue, and emit error if not. | ||||
13835 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | ||||
13836 | return QualType(); | ||||
13837 | |||||
13838 | QualType LHSType = LHSExpr->getType(); | ||||
13839 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | ||||
13840 | CompoundType; | ||||
13841 | // OpenCL v1.2 s6.1.1.1 p2: | ||||
13842 | // The half data type can only be used to declare a pointer to a buffer that | ||||
13843 | // contains half values | ||||
13844 | if (getLangOpts().OpenCL && | ||||
13845 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
13846 | LHSType->isHalfType()) { | ||||
13847 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | ||||
13848 | << LHSType.getUnqualifiedType(); | ||||
13849 | return QualType(); | ||||
13850 | } | ||||
13851 | |||||
13852 | AssignConvertType ConvTy; | ||||
13853 | if (CompoundType.isNull()) { | ||||
13854 | Expr *RHSCheck = RHS.get(); | ||||
13855 | |||||
13856 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | ||||
13857 | |||||
13858 | QualType LHSTy(LHSType); | ||||
13859 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | ||||
13860 | if (RHS.isInvalid()) | ||||
13861 | return QualType(); | ||||
13862 | // Special case of NSObject attributes on c-style pointer types. | ||||
13863 | if (ConvTy == IncompatiblePointer && | ||||
13864 | ((Context.isObjCNSObjectType(LHSType) && | ||||
13865 | RHSType->isObjCObjectPointerType()) || | ||||
13866 | (Context.isObjCNSObjectType(RHSType) && | ||||
13867 | LHSType->isObjCObjectPointerType()))) | ||||
13868 | ConvTy = Compatible; | ||||
13869 | |||||
13870 | if (ConvTy == Compatible && | ||||
13871 | LHSType->isObjCObjectType()) | ||||
13872 | Diag(Loc, diag::err_objc_object_assignment) | ||||
13873 | << LHSType; | ||||
13874 | |||||
13875 | // If the RHS is a unary plus or minus, check to see if they = and + are | ||||
13876 | // right next to each other. If so, the user may have typo'd "x =+ 4" | ||||
13877 | // instead of "x += 4". | ||||
13878 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | ||||
13879 | RHSCheck = ICE->getSubExpr(); | ||||
13880 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | ||||
13881 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | ||||
13882 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | ||||
13883 | // Only if the two operators are exactly adjacent. | ||||
13884 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | ||||
13885 | // And there is a space or other character before the subexpr of the | ||||
13886 | // unary +/-. We don't want to warn on "x=-1". | ||||
13887 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | ||||
13888 | UO->getSubExpr()->getBeginLoc().isFileID()) { | ||||
13889 | Diag(Loc, diag::warn_not_compound_assign) | ||||
13890 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | ||||
13891 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | ||||
13892 | } | ||||
13893 | } | ||||
13894 | |||||
13895 | if (ConvTy == Compatible) { | ||||
13896 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | ||||
13897 | // Warn about retain cycles where a block captures the LHS, but | ||||
13898 | // not if the LHS is a simple variable into which the block is | ||||
13899 | // being stored...unless that variable can be captured by reference! | ||||
13900 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | ||||
13901 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | ||||
13902 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | ||||
13903 | checkRetainCycles(LHSExpr, RHS.get()); | ||||
13904 | } | ||||
13905 | |||||
13906 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | ||||
13907 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | ||||
13908 | // It is safe to assign a weak reference into a strong variable. | ||||
13909 | // Although this code can still have problems: | ||||
13910 | // id x = self.weakProp; | ||||
13911 | // id y = self.weakProp; | ||||
13912 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||
13913 | // paths through the function. This should be revisited if | ||||
13914 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||
13915 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | ||||
13916 | // variable, which will be valid for the current autorelease scope. | ||||
13917 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||
13918 | RHS.get()->getBeginLoc())) | ||||
13919 | getCurFunction()->markSafeWeakUse(RHS.get()); | ||||
13920 | |||||
13921 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | ||||
13922 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | ||||
13923 | } | ||||
13924 | } | ||||
13925 | } else { | ||||
13926 | // Compound assignment "x += y" | ||||
13927 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | ||||
13928 | } | ||||
13929 | |||||
13930 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | ||||
13931 | RHS.get(), AA_Assigning)) | ||||
13932 | return QualType(); | ||||
13933 | |||||
13934 | CheckForNullPointerDereference(*this, LHSExpr); | ||||
13935 | |||||
13936 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | ||||
13937 | if (CompoundType.isNull()) { | ||||
13938 | // C++2a [expr.ass]p5: | ||||
13939 | // A simple-assignment whose left operand is of a volatile-qualified | ||||
13940 | // type is deprecated unless the assignment is either a discarded-value | ||||
13941 | // expression or an unevaluated operand | ||||
13942 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | ||||
13943 | } else { | ||||
13944 | // C++20 [expr.ass]p6: | ||||
13945 | // [Compound-assignment] expressions are deprecated if E1 has | ||||
13946 | // volatile-qualified type and op is not one of the bitwise | ||||
13947 | // operators |, &, ˆ. | ||||
13948 | switch (Opc) { | ||||
13949 | case BO_OrAssign: | ||||
13950 | case BO_AndAssign: | ||||
13951 | case BO_XorAssign: | ||||
13952 | break; | ||||
13953 | default: | ||||
13954 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | ||||
13955 | } | ||||
13956 | } | ||||
13957 | } | ||||
13958 | |||||
13959 | // C11 6.5.16p3: The type of an assignment expression is the type of the | ||||
13960 | // left operand would have after lvalue conversion. | ||||
13961 | // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has | ||||
13962 | // qualified type, the value has the unqualified version of the type of the | ||||
13963 | // lvalue; additionally, if the lvalue has atomic type, the value has the | ||||
13964 | // non-atomic version of the type of the lvalue. | ||||
13965 | // C++ 5.17p1: the type of the assignment expression is that of its left | ||||
13966 | // operand. | ||||
13967 | return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); | ||||
13968 | } | ||||
13969 | |||||
13970 | // Scenarios to ignore if expression E is: | ||||
13971 | // 1. an explicit cast expression into void | ||||
13972 | // 2. a function call expression that returns void | ||||
13973 | static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { | ||||
13974 | E = E->IgnoreParens(); | ||||
13975 | |||||
13976 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | ||||
13977 | if (CE->getCastKind() == CK_ToVoid) { | ||||
13978 | return true; | ||||
13979 | } | ||||
13980 | |||||
13981 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | ||||
13982 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | ||||
13983 | CE->getSubExpr()->getType()->isDependentType()) { | ||||
13984 | return true; | ||||
13985 | } | ||||
13986 | } | ||||
13987 | |||||
13988 | if (const auto *CE = dyn_cast<CallExpr>(E)) | ||||
13989 | return CE->getCallReturnType(Context)->isVoidType(); | ||||
13990 | return false; | ||||
13991 | } | ||||
13992 | |||||
13993 | // Look for instances where it is likely the comma operator is confused with | ||||
13994 | // another operator. There is an explicit list of acceptable expressions for | ||||
13995 | // the left hand side of the comma operator, otherwise emit a warning. | ||||
13996 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | ||||
13997 | // No warnings in macros | ||||
13998 | if (Loc.isMacroID()) | ||||
13999 | return; | ||||
14000 | |||||
14001 | // Don't warn in template instantiations. | ||||
14002 | if (inTemplateInstantiation()) | ||||
14003 | return; | ||||
14004 | |||||
14005 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | ||||
14006 | // instead, skip more than needed, then call back into here with the | ||||
14007 | // CommaVisitor in SemaStmt.cpp. | ||||
14008 | // The listed locations are the initialization and increment portions | ||||
14009 | // of a for loop. The additional checks are on the condition of | ||||
14010 | // if statements, do/while loops, and for loops. | ||||
14011 | // Differences in scope flags for C89 mode requires the extra logic. | ||||
14012 | const unsigned ForIncrementFlags = | ||||
14013 | getLangOpts().C99 || getLangOpts().CPlusPlus | ||||
14014 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | ||||
14015 | : Scope::ContinueScope | Scope::BreakScope; | ||||
14016 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | ||||
14017 | const unsigned ScopeFlags = getCurScope()->getFlags(); | ||||
14018 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | ||||
14019 | (ScopeFlags & ForInitFlags) == ForInitFlags) | ||||
14020 | return; | ||||
14021 | |||||
14022 | // If there are multiple comma operators used together, get the RHS of the | ||||
14023 | // of the comma operator as the LHS. | ||||
14024 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | ||||
14025 | if (BO->getOpcode() != BO_Comma) | ||||
14026 | break; | ||||
14027 | LHS = BO->getRHS(); | ||||
14028 | } | ||||
14029 | |||||
14030 | // Only allow some expressions on LHS to not warn. | ||||
14031 | if (IgnoreCommaOperand(LHS, Context)) | ||||
14032 | return; | ||||
14033 | |||||
14034 | Diag(Loc, diag::warn_comma_operator); | ||||
14035 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | ||||
14036 | << LHS->getSourceRange() | ||||
14037 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | ||||
14038 | LangOpts.CPlusPlus ? "static_cast<void>(" | ||||
14039 | : "(void)(") | ||||
14040 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | ||||
14041 | ")"); | ||||
14042 | } | ||||
14043 | |||||
14044 | // C99 6.5.17 | ||||
14045 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
14046 | SourceLocation Loc) { | ||||
14047 | LHS = S.CheckPlaceholderExpr(LHS.get()); | ||||
14048 | RHS = S.CheckPlaceholderExpr(RHS.get()); | ||||
14049 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
14050 | return QualType(); | ||||
14051 | |||||
14052 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | ||||
14053 | // operands, but not unary promotions. | ||||
14054 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | ||||
14055 | |||||
14056 | // So we treat the LHS as a ignored value, and in C++ we allow the | ||||
14057 | // containing site to determine what should be done with the RHS. | ||||
14058 | LHS = S.IgnoredValueConversions(LHS.get()); | ||||
14059 | if (LHS.isInvalid()) | ||||
14060 | return QualType(); | ||||
14061 | |||||
14062 | S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); | ||||
14063 | |||||
14064 | if (!S.getLangOpts().CPlusPlus) { | ||||
14065 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
14066 | if (RHS.isInvalid()) | ||||
14067 | return QualType(); | ||||
14068 | if (!RHS.get()->getType()->isVoidType()) | ||||
14069 | S.RequireCompleteType(Loc, RHS.get()->getType(), | ||||
14070 | diag::err_incomplete_type); | ||||
14071 | } | ||||
14072 | |||||
14073 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | ||||
14074 | S.DiagnoseCommaOperator(LHS.get(), Loc); | ||||
14075 | |||||
14076 | return RHS.get()->getType(); | ||||
14077 | } | ||||
14078 | |||||
14079 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | ||||
14080 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | ||||
14081 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | ||||
14082 | ExprValueKind &VK, | ||||
14083 | ExprObjectKind &OK, | ||||
14084 | SourceLocation OpLoc, | ||||
14085 | bool IsInc, bool IsPrefix) { | ||||
14086 | if (Op->isTypeDependent()) | ||||
14087 | return S.Context.DependentTy; | ||||
14088 | |||||
14089 | QualType ResType = Op->getType(); | ||||
14090 | // Atomic types can be used for increment / decrement where the non-atomic | ||||
14091 | // versions can, so ignore the _Atomic() specifier for the purpose of | ||||
14092 | // checking. | ||||
14093 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
14094 | ResType = ResAtomicType->getValueType(); | ||||
14095 | |||||
14096 | assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast <bool> (!ResType.isNull() && "no type for increment/decrement expression" ) ? void (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "clang/lib/Sema/SemaExpr.cpp", 14096, __extension__ __PRETTY_FUNCTION__ )); | ||||
14097 | |||||
14098 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | ||||
14099 | // Decrement of bool is not allowed. | ||||
14100 | if (!IsInc) { | ||||
14101 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | ||||
14102 | return QualType(); | ||||
14103 | } | ||||
14104 | // Increment of bool sets it to true, but is deprecated. | ||||
14105 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | ||||
14106 | : diag::warn_increment_bool) | ||||
14107 | << Op->getSourceRange(); | ||||
14108 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | ||||
14109 | // Error on enum increments and decrements in C++ mode | ||||
14110 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | ||||
14111 | return QualType(); | ||||
14112 | } else if (ResType->isRealType()) { | ||||
14113 | // OK! | ||||
14114 | } else if (ResType->isPointerType()) { | ||||
14115 | // C99 6.5.2.4p2, 6.5.6p2 | ||||
14116 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | ||||
14117 | return QualType(); | ||||
14118 | } else if (ResType->isObjCObjectPointerType()) { | ||||
14119 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | ||||
14120 | // Otherwise, we just need a complete type. | ||||
14121 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | ||||
14122 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | ||||
14123 | return QualType(); | ||||
14124 | } else if (ResType->isAnyComplexType()) { | ||||
14125 | // C99 does not support ++/-- on complex types, we allow as an extension. | ||||
14126 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | ||||
14127 | << ResType << Op->getSourceRange(); | ||||
14128 | } else if (ResType->isPlaceholderType()) { | ||||
14129 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
14130 | if (PR.isInvalid()) return QualType(); | ||||
14131 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | ||||
14132 | IsInc, IsPrefix); | ||||
14133 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | ||||
14134 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | ||||
14135 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | ||||
14136 | (ResType->castAs<VectorType>()->getVectorKind() != | ||||
14137 | VectorType::AltiVecBool)) { | ||||
14138 | // The z vector extensions allow ++ and -- for non-bool vectors. | ||||
14139 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | ||||
14140 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | ||||
14141 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | ||||
14142 | } else { | ||||
14143 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | ||||
14144 | << ResType << int(IsInc) << Op->getSourceRange(); | ||||
14145 | return QualType(); | ||||
14146 | } | ||||
14147 | // At this point, we know we have a real, complex or pointer type. | ||||
14148 | // Now make sure the operand is a modifiable lvalue. | ||||
14149 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | ||||
14150 | return QualType(); | ||||
14151 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | ||||
14152 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | ||||
14153 | // An operand with volatile-qualified type is deprecated | ||||
14154 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | ||||
14155 | << IsInc << ResType; | ||||
14156 | } | ||||
14157 | // In C++, a prefix increment is the same type as the operand. Otherwise | ||||
14158 | // (in C or with postfix), the increment is the unqualified type of the | ||||
14159 | // operand. | ||||
14160 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | ||||
14161 | VK = VK_LValue; | ||||
14162 | OK = Op->getObjectKind(); | ||||
14163 | return ResType; | ||||
14164 | } else { | ||||
14165 | VK = VK_PRValue; | ||||
14166 | return ResType.getUnqualifiedType(); | ||||
14167 | } | ||||
14168 | } | ||||
14169 | |||||
14170 | |||||
14171 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | ||||
14172 | /// This routine allows us to typecheck complex/recursive expressions | ||||
14173 | /// where the declaration is needed for type checking. We only need to | ||||
14174 | /// handle cases when the expression references a function designator | ||||
14175 | /// or is an lvalue. Here are some examples: | ||||
14176 | /// - &(x) => x | ||||
14177 | /// - &*****f => f for f a function designator. | ||||
14178 | /// - &s.xx => s | ||||
14179 | /// - &s.zz[1].yy -> s, if zz is an array | ||||
14180 | /// - *(x + 1) -> x, if x is an array | ||||
14181 | /// - &"123"[2] -> 0 | ||||
14182 | /// - & __real__ x -> x | ||||
14183 | /// | ||||
14184 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | ||||
14185 | /// members. | ||||
14186 | static ValueDecl *getPrimaryDecl(Expr *E) { | ||||
14187 | switch (E->getStmtClass()) { | ||||
14188 | case Stmt::DeclRefExprClass: | ||||
14189 | return cast<DeclRefExpr>(E)->getDecl(); | ||||
14190 | case Stmt::MemberExprClass: | ||||
14191 | // If this is an arrow operator, the address is an offset from | ||||
14192 | // the base's value, so the object the base refers to is | ||||
14193 | // irrelevant. | ||||
14194 | if (cast<MemberExpr>(E)->isArrow()) | ||||
14195 | return nullptr; | ||||
14196 | // Otherwise, the expression refers to a part of the base | ||||
14197 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | ||||
14198 | case Stmt::ArraySubscriptExprClass: { | ||||
14199 | // FIXME: This code shouldn't be necessary! We should catch the implicit | ||||
14200 | // promotion of register arrays earlier. | ||||
14201 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | ||||
14202 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | ||||
14203 | if (ICE->getSubExpr()->getType()->isArrayType()) | ||||
14204 | return getPrimaryDecl(ICE->getSubExpr()); | ||||
14205 | } | ||||
14206 | return nullptr; | ||||
14207 | } | ||||
14208 | case Stmt::UnaryOperatorClass: { | ||||
14209 | UnaryOperator *UO = cast<UnaryOperator>(E); | ||||
14210 | |||||
14211 | switch(UO->getOpcode()) { | ||||
14212 | case UO_Real: | ||||
14213 | case UO_Imag: | ||||
14214 | case UO_Extension: | ||||
14215 | return getPrimaryDecl(UO->getSubExpr()); | ||||
14216 | default: | ||||
14217 | return nullptr; | ||||
14218 | } | ||||
14219 | } | ||||
14220 | case Stmt::ParenExprClass: | ||||
14221 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | ||||
14222 | case Stmt::ImplicitCastExprClass: | ||||
14223 | // If the result of an implicit cast is an l-value, we care about | ||||
14224 | // the sub-expression; otherwise, the result here doesn't matter. | ||||
14225 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | ||||
14226 | case Stmt::CXXUuidofExprClass: | ||||
14227 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | ||||
14228 | default: | ||||
14229 | return nullptr; | ||||
14230 | } | ||||
14231 | } | ||||
14232 | |||||
14233 | namespace { | ||||
14234 | enum { | ||||
14235 | AO_Bit_Field = 0, | ||||
14236 | AO_Vector_Element = 1, | ||||
14237 | AO_Property_Expansion = 2, | ||||
14238 | AO_Register_Variable = 3, | ||||
14239 | AO_Matrix_Element = 4, | ||||
14240 | AO_No_Error = 5 | ||||
14241 | }; | ||||
14242 | } | ||||
14243 | /// Diagnose invalid operand for address of operations. | ||||
14244 | /// | ||||
14245 | /// \param Type The type of operand which cannot have its address taken. | ||||
14246 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | ||||
14247 | Expr *E, unsigned Type) { | ||||
14248 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | ||||
14249 | } | ||||
14250 | |||||
14251 | /// CheckAddressOfOperand - The operand of & must be either a function | ||||
14252 | /// designator or an lvalue designating an object. If it is an lvalue, the | ||||
14253 | /// object cannot be declared with storage class register or be a bit field. | ||||
14254 | /// Note: The usual conversions are *not* applied to the operand of the & | ||||
14255 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | ||||
14256 | /// In C++, the operand might be an overloaded function name, in which case | ||||
14257 | /// we allow the '&' but retain the overloaded-function type. | ||||
14258 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | ||||
14259 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | ||||
14260 | if (PTy->getKind() == BuiltinType::Overload) { | ||||
14261 | Expr *E = OrigOp.get()->IgnoreParens(); | ||||
14262 | if (!isa<OverloadExpr>(E)) { | ||||
14263 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode () == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "clang/lib/Sema/SemaExpr.cpp", 14263, __extension__ __PRETTY_FUNCTION__ )); | ||||
14264 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | ||||
14265 | << OrigOp.get()->getSourceRange(); | ||||
14266 | return QualType(); | ||||
14267 | } | ||||
14268 | |||||
14269 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | ||||
14270 | if (isa<UnresolvedMemberExpr>(Ovl)) | ||||
14271 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | ||||
14272 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
14273 | << OrigOp.get()->getSourceRange(); | ||||
14274 | return QualType(); | ||||
14275 | } | ||||
14276 | |||||
14277 | return Context.OverloadTy; | ||||
14278 | } | ||||
14279 | |||||
14280 | if (PTy->getKind() == BuiltinType::UnknownAny) | ||||
14281 | return Context.UnknownAnyTy; | ||||
14282 | |||||
14283 | if (PTy->getKind() == BuiltinType::BoundMember) { | ||||
14284 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
14285 | << OrigOp.get()->getSourceRange(); | ||||
14286 | return QualType(); | ||||
14287 | } | ||||
14288 | |||||
14289 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | ||||
14290 | if (OrigOp.isInvalid()) return QualType(); | ||||
14291 | } | ||||
14292 | |||||
14293 | if (OrigOp.get()->isTypeDependent()) | ||||
14294 | return Context.DependentTy; | ||||
14295 | |||||
14296 | assert(!OrigOp.get()->hasPlaceholderType())(static_cast <bool> (!OrigOp.get()->hasPlaceholderType ()) ? void (0) : __assert_fail ("!OrigOp.get()->hasPlaceholderType()" , "clang/lib/Sema/SemaExpr.cpp", 14296, __extension__ __PRETTY_FUNCTION__ )); | ||||
14297 | |||||
14298 | // Make sure to ignore parentheses in subsequent checks | ||||
14299 | Expr *op = OrigOp.get()->IgnoreParens(); | ||||
14300 | |||||
14301 | // In OpenCL captures for blocks called as lambda functions | ||||
14302 | // are located in the private address space. Blocks used in | ||||
14303 | // enqueue_kernel can be located in a different address space | ||||
14304 | // depending on a vendor implementation. Thus preventing | ||||
14305 | // taking an address of the capture to avoid invalid AS casts. | ||||
14306 | if (LangOpts.OpenCL) { | ||||
14307 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | ||||
14308 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | ||||
14309 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | ||||
14310 | return QualType(); | ||||
14311 | } | ||||
14312 | } | ||||
14313 | |||||
14314 | if (getLangOpts().C99) { | ||||
14315 | // Implement C99-only parts of addressof rules. | ||||
14316 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | ||||
14317 | if (uOp->getOpcode() == UO_Deref) | ||||
14318 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | ||||
14319 | // (assuming the deref expression is valid). | ||||
14320 | return uOp->getSubExpr()->getType(); | ||||
14321 | } | ||||
14322 | // Technically, there should be a check for array subscript | ||||
14323 | // expressions here, but the result of one is always an lvalue anyway. | ||||
14324 | } | ||||
14325 | ValueDecl *dcl = getPrimaryDecl(op); | ||||
14326 | |||||
14327 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | ||||
14328 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
14329 | op->getBeginLoc())) | ||||
14330 | return QualType(); | ||||
14331 | |||||
14332 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | ||||
14333 | unsigned AddressOfError = AO_No_Error; | ||||
14334 | |||||
14335 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | ||||
14336 | bool sfinae = (bool)isSFINAEContext(); | ||||
14337 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | ||||
14338 | : diag::ext_typecheck_addrof_temporary) | ||||
14339 | << op->getType() << op->getSourceRange(); | ||||
14340 | if (sfinae) | ||||
14341 | return QualType(); | ||||
14342 | // Materialize the temporary as an lvalue so that we can take its address. | ||||
14343 | OrigOp = op = | ||||
14344 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | ||||
14345 | } else if (isa<ObjCSelectorExpr>(op)) { | ||||
14346 | return Context.getPointerType(op->getType()); | ||||
14347 | } else if (lval == Expr::LV_MemberFunction) { | ||||
14348 | // If it's an instance method, make a member pointer. | ||||
14349 | // The expression must have exactly the form &A::foo. | ||||
14350 | |||||
14351 | // If the underlying expression isn't a decl ref, give up. | ||||
14352 | if (!isa<DeclRefExpr>(op)) { | ||||
14353 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
14354 | << OrigOp.get()->getSourceRange(); | ||||
14355 | return QualType(); | ||||
14356 | } | ||||
14357 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | ||||
14358 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | ||||
14359 | |||||
14360 | // The id-expression was parenthesized. | ||||
14361 | if (OrigOp.get() != DRE) { | ||||
14362 | Diag(OpLoc, diag::err_parens_pointer_member_function) | ||||
14363 | << OrigOp.get()->getSourceRange(); | ||||
14364 | |||||
14365 | // The method was named without a qualifier. | ||||
14366 | } else if (!DRE->getQualifier()) { | ||||
14367 | if (MD->getParent()->getName().empty()) | ||||
14368 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
14369 | << op->getSourceRange(); | ||||
14370 | else { | ||||
14371 | SmallString<32> Str; | ||||
14372 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | ||||
14373 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
14374 | << op->getSourceRange() | ||||
14375 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | ||||
14376 | } | ||||
14377 | } | ||||
14378 | |||||
14379 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | ||||
14380 | if (isa<CXXDestructorDecl>(MD)) | ||||
14381 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | ||||
14382 | |||||
14383 | QualType MPTy = Context.getMemberPointerType( | ||||
14384 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | ||||
14385 | // Under the MS ABI, lock down the inheritance model now. | ||||
14386 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
14387 | (void)isCompleteType(OpLoc, MPTy); | ||||
14388 | return MPTy; | ||||
14389 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | ||||
14390 | // C99 6.5.3.2p1 | ||||
14391 | // The operand must be either an l-value or a function designator | ||||
14392 | if (!op->getType()->isFunctionType()) { | ||||
14393 | // Use a special diagnostic for loads from property references. | ||||
14394 | if (isa<PseudoObjectExpr>(op)) { | ||||
14395 | AddressOfError = AO_Property_Expansion; | ||||
14396 | } else { | ||||
14397 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | ||||
14398 | << op->getType() << op->getSourceRange(); | ||||
14399 | return QualType(); | ||||
14400 | } | ||||
14401 | } | ||||
14402 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | ||||
14403 | // The operand cannot be a bit-field | ||||
14404 | AddressOfError = AO_Bit_Field; | ||||
14405 | } else if (op->getObjectKind() == OK_VectorComponent) { | ||||
14406 | // The operand cannot be an element of a vector | ||||
14407 | AddressOfError = AO_Vector_Element; | ||||
14408 | } else if (op->getObjectKind() == OK_MatrixComponent) { | ||||
14409 | // The operand cannot be an element of a matrix. | ||||
14410 | AddressOfError = AO_Matrix_Element; | ||||
14411 | } else if (dcl) { // C99 6.5.3.2p1 | ||||
14412 | // We have an lvalue with a decl. Make sure the decl is not declared | ||||
14413 | // with the register storage-class specifier. | ||||
14414 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | ||||
14415 | // in C++ it is not error to take address of a register | ||||
14416 | // variable (c++03 7.1.1P3) | ||||
14417 | if (vd->getStorageClass() == SC_Register && | ||||
14418 | !getLangOpts().CPlusPlus) { | ||||
14419 | AddressOfError = AO_Register_Variable; | ||||
14420 | } | ||||
14421 | } else if (isa<MSPropertyDecl>(dcl)) { | ||||
14422 | AddressOfError = AO_Property_Expansion; | ||||
14423 | } else if (isa<FunctionTemplateDecl>(dcl)) { | ||||
14424 | return Context.OverloadTy; | ||||
14425 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | ||||
14426 | // Okay: we can take the address of a field. | ||||
14427 | // Could be a pointer to member, though, if there is an explicit | ||||
14428 | // scope qualifier for the class. | ||||
14429 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | ||||
14430 | DeclContext *Ctx = dcl->getDeclContext(); | ||||
14431 | if (Ctx && Ctx->isRecord()) { | ||||
14432 | if (dcl->getType()->isReferenceType()) { | ||||
14433 | Diag(OpLoc, | ||||
14434 | diag::err_cannot_form_pointer_to_member_of_reference_type) | ||||
14435 | << dcl->getDeclName() << dcl->getType(); | ||||
14436 | return QualType(); | ||||
14437 | } | ||||
14438 | |||||
14439 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | ||||
14440 | Ctx = Ctx->getParent(); | ||||
14441 | |||||
14442 | QualType MPTy = Context.getMemberPointerType( | ||||
14443 | op->getType(), | ||||
14444 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | ||||
14445 | // Under the MS ABI, lock down the inheritance model now. | ||||
14446 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
14447 | (void)isCompleteType(OpLoc, MPTy); | ||||
14448 | return MPTy; | ||||
14449 | } | ||||
14450 | } | ||||
14451 | } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, | ||||
14452 | MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) | ||||
14453 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "clang/lib/Sema/SemaExpr.cpp", 14453); | ||||
14454 | } | ||||
14455 | |||||
14456 | if (AddressOfError != AO_No_Error) { | ||||
14457 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | ||||
14458 | return QualType(); | ||||
14459 | } | ||||
14460 | |||||
14461 | if (lval == Expr::LV_IncompleteVoidType) { | ||||
14462 | // Taking the address of a void variable is technically illegal, but we | ||||
14463 | // allow it in cases which are otherwise valid. | ||||
14464 | // Example: "extern void x; void* y = &x;". | ||||
14465 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | ||||
14466 | } | ||||
14467 | |||||
14468 | // If the operand has type "type", the result has type "pointer to type". | ||||
14469 | if (op->getType()->isObjCObjectType()) | ||||
14470 | return Context.getObjCObjectPointerType(op->getType()); | ||||
14471 | |||||
14472 | CheckAddressOfPackedMember(op); | ||||
14473 | |||||
14474 | return Context.getPointerType(op->getType()); | ||||
14475 | } | ||||
14476 | |||||
14477 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | ||||
14478 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | ||||
14479 | if (!DRE) | ||||
14480 | return; | ||||
14481 | const Decl *D = DRE->getDecl(); | ||||
14482 | if (!D) | ||||
14483 | return; | ||||
14484 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | ||||
14485 | if (!Param) | ||||
14486 | return; | ||||
14487 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | ||||
14488 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | ||||
14489 | return; | ||||
14490 | if (FunctionScopeInfo *FD = S.getCurFunction()) | ||||
14491 | FD->ModifiedNonNullParams.insert(Param); | ||||
14492 | } | ||||
14493 | |||||
14494 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | ||||
14495 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | ||||
14496 | SourceLocation OpLoc, | ||||
14497 | bool IsAfterAmp = false) { | ||||
14498 | if (Op->isTypeDependent()) | ||||
14499 | return S.Context.DependentTy; | ||||
14500 | |||||
14501 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | ||||
14502 | if (ConvResult.isInvalid()) | ||||
14503 | return QualType(); | ||||
14504 | Op = ConvResult.get(); | ||||
14505 | QualType OpTy = Op->getType(); | ||||
14506 | QualType Result; | ||||
14507 | |||||
14508 | if (isa<CXXReinterpretCastExpr>(Op)) { | ||||
14509 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | ||||
14510 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | ||||
14511 | Op->getSourceRange()); | ||||
14512 | } | ||||
14513 | |||||
14514 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | ||||
14515 | { | ||||
14516 | Result = PT->getPointeeType(); | ||||
14517 | } | ||||
14518 | else if (const ObjCObjectPointerType *OPT = | ||||
14519 | OpTy->getAs<ObjCObjectPointerType>()) | ||||
14520 | Result = OPT->getPointeeType(); | ||||
14521 | else { | ||||
14522 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
14523 | if (PR.isInvalid()) return QualType(); | ||||
14524 | if (PR.get() != Op) | ||||
14525 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | ||||
14526 | } | ||||
14527 | |||||
14528 | if (Result.isNull()) { | ||||
14529 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | ||||
14530 | << OpTy << Op->getSourceRange(); | ||||
14531 | return QualType(); | ||||
14532 | } | ||||
14533 | |||||
14534 | if (Result->isVoidType()) { | ||||
14535 | // C++ [expr.unary.op]p1: | ||||
14536 | // [...] the expression to which [the unary * operator] is applied shall | ||||
14537 | // be a pointer to an object type, or a pointer to a function type | ||||
14538 | LangOptions LO = S.getLangOpts(); | ||||
14539 | if (LO.CPlusPlus || !(LO.C99 && (IsAfterAmp || S.isUnevaluatedContext()))) | ||||
14540 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | ||||
14541 | << LO.CPlusPlus << OpTy << Op->getSourceRange(); | ||||
14542 | } | ||||
14543 | |||||
14544 | // Dereferences are usually l-values... | ||||
14545 | VK = VK_LValue; | ||||
14546 | |||||
14547 | // ...except that certain expressions are never l-values in C. | ||||
14548 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | ||||
14549 | VK = VK_PRValue; | ||||
14550 | |||||
14551 | return Result; | ||||
14552 | } | ||||
14553 | |||||
14554 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | ||||
14555 | BinaryOperatorKind Opc; | ||||
14556 | switch (Kind) { | ||||
14557 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "clang/lib/Sema/SemaExpr.cpp" , 14557); | ||||
14558 | case tok::periodstar: Opc = BO_PtrMemD; break; | ||||
14559 | case tok::arrowstar: Opc = BO_PtrMemI; break; | ||||
14560 | case tok::star: Opc = BO_Mul; break; | ||||
14561 | case tok::slash: Opc = BO_Div; break; | ||||
14562 | case tok::percent: Opc = BO_Rem; break; | ||||
14563 | case tok::plus: Opc = BO_Add; break; | ||||
14564 | case tok::minus: Opc = BO_Sub; break; | ||||
14565 | case tok::lessless: Opc = BO_Shl; break; | ||||
14566 | case tok::greatergreater: Opc = BO_Shr; break; | ||||
14567 | case tok::lessequal: Opc = BO_LE; break; | ||||
14568 | case tok::less: Opc = BO_LT; break; | ||||
14569 | case tok::greaterequal: Opc = BO_GE; break; | ||||
14570 | case tok::greater: Opc = BO_GT; break; | ||||
14571 | case tok::exclaimequal: Opc = BO_NE; break; | ||||
14572 | case tok::equalequal: Opc = BO_EQ; break; | ||||
14573 | case tok::spaceship: Opc = BO_Cmp; break; | ||||
14574 | case tok::amp: Opc = BO_And; break; | ||||
14575 | case tok::caret: Opc = BO_Xor; break; | ||||
14576 | case tok::pipe: Opc = BO_Or; break; | ||||
14577 | case tok::ampamp: Opc = BO_LAnd; break; | ||||
14578 | case tok::pipepipe: Opc = BO_LOr; break; | ||||
14579 | case tok::equal: Opc = BO_Assign; break; | ||||
14580 | case tok::starequal: Opc = BO_MulAssign; break; | ||||
14581 | case tok::slashequal: Opc = BO_DivAssign; break; | ||||
14582 | case tok::percentequal: Opc = BO_RemAssign; break; | ||||
14583 | case tok::plusequal: Opc = BO_AddAssign; break; | ||||
14584 | case tok::minusequal: Opc = BO_SubAssign; break; | ||||
14585 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | ||||
14586 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | ||||
14587 | case tok::ampequal: Opc = BO_AndAssign; break; | ||||
14588 | case tok::caretequal: Opc = BO_XorAssign; break; | ||||
14589 | case tok::pipeequal: Opc = BO_OrAssign; break; | ||||
14590 | case tok::comma: Opc = BO_Comma; break; | ||||
14591 | } | ||||
14592 | return Opc; | ||||
14593 | } | ||||
14594 | |||||
14595 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | ||||
14596 | tok::TokenKind Kind) { | ||||
14597 | UnaryOperatorKind Opc; | ||||
14598 | switch (Kind) { | ||||
14599 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "clang/lib/Sema/SemaExpr.cpp" , 14599); | ||||
14600 | case tok::plusplus: Opc = UO_PreInc; break; | ||||
14601 | case tok::minusminus: Opc = UO_PreDec; break; | ||||
14602 | case tok::amp: Opc = UO_AddrOf; break; | ||||
14603 | case tok::star: Opc = UO_Deref; break; | ||||
14604 | case tok::plus: Opc = UO_Plus; break; | ||||
14605 | case tok::minus: Opc = UO_Minus; break; | ||||
14606 | case tok::tilde: Opc = UO_Not; break; | ||||
14607 | case tok::exclaim: Opc = UO_LNot; break; | ||||
14608 | case tok::kw___real: Opc = UO_Real; break; | ||||
14609 | case tok::kw___imag: Opc = UO_Imag; break; | ||||
14610 | case tok::kw___extension__: Opc = UO_Extension; break; | ||||
14611 | } | ||||
14612 | return Opc; | ||||
14613 | } | ||||
14614 | |||||
14615 | const FieldDecl * | ||||
14616 | Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { | ||||
14617 | // Explore the case for adding 'this->' to the LHS of a self assignment, very | ||||
14618 | // common for setters. | ||||
14619 | // struct A { | ||||
14620 | // int X; | ||||
14621 | // -void setX(int X) { X = X; } | ||||
14622 | // +void setX(int X) { this->X = X; } | ||||
14623 | // }; | ||||
14624 | |||||
14625 | // Only consider parameters for self assignment fixes. | ||||
14626 | if (!isa<ParmVarDecl>(SelfAssigned)) | ||||
14627 | return nullptr; | ||||
14628 | const auto *Method = | ||||
14629 | dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true)); | ||||
14630 | if (!Method) | ||||
14631 | return nullptr; | ||||
14632 | |||||
14633 | const CXXRecordDecl *Parent = Method->getParent(); | ||||
14634 | // In theory this is fixable if the lambda explicitly captures this, but | ||||
14635 | // that's added complexity that's rarely going to be used. | ||||
14636 | if (Parent->isLambda()) | ||||
14637 | return nullptr; | ||||
14638 | |||||
14639 | // FIXME: Use an actual Lookup operation instead of just traversing fields | ||||
14640 | // in order to get base class fields. | ||||
14641 | auto Field = | ||||
14642 | llvm::find_if(Parent->fields(), | ||||
14643 | [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { | ||||
14644 | return F->getDeclName() == Name; | ||||
14645 | }); | ||||
14646 | return (Field != Parent->field_end()) ? *Field : nullptr; | ||||
14647 | } | ||||
14648 | |||||
14649 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | ||||
14650 | /// This warning suppressed in the event of macro expansions. | ||||
14651 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | ||||
14652 | SourceLocation OpLoc, bool IsBuiltin) { | ||||
14653 | if (S.inTemplateInstantiation()) | ||||
14654 | return; | ||||
14655 | if (S.isUnevaluatedContext()) | ||||
14656 | return; | ||||
14657 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | ||||
14658 | return; | ||||
14659 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | ||||
14660 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | ||||
14661 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | ||||
14662 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | ||||
14663 | if (!LHSDeclRef || !RHSDeclRef || | ||||
14664 | LHSDeclRef->getLocation().isMacroID() || | ||||
14665 | RHSDeclRef->getLocation().isMacroID()) | ||||
14666 | return; | ||||
14667 | const ValueDecl *LHSDecl = | ||||
14668 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
14669 | const ValueDecl *RHSDecl = | ||||
14670 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
14671 | if (LHSDecl != RHSDecl) | ||||
14672 | return; | ||||
14673 | if (LHSDecl->getType().isVolatileQualified()) | ||||
14674 | return; | ||||
14675 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
14676 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
14677 | return; | ||||
14678 | |||||
14679 | auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | ||||
14680 | : diag::warn_self_assignment_overloaded) | ||||
14681 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | ||||
14682 | << RHSExpr->getSourceRange(); | ||||
14683 | if (const FieldDecl *SelfAssignField = | ||||
14684 | S.getSelfAssignmentClassMemberCandidate(RHSDecl)) | ||||
14685 | Diag << 1 << SelfAssignField | ||||
14686 | << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); | ||||
14687 | else | ||||
14688 | Diag << 0; | ||||
14689 | } | ||||
14690 | |||||
14691 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | ||||
14692 | /// is usually indicative of introspection within the Objective-C pointer. | ||||
14693 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | ||||
14694 | SourceLocation OpLoc) { | ||||
14695 | if (!S.getLangOpts().ObjC) | ||||
14696 | return; | ||||
14697 | |||||
14698 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | ||||
14699 | const Expr *LHS = L.get(); | ||||
14700 | const Expr *RHS = R.get(); | ||||
14701 | |||||
14702 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
14703 | ObjCPointerExpr = LHS; | ||||
14704 | OtherExpr = RHS; | ||||
14705 | } | ||||
14706 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
14707 | ObjCPointerExpr = RHS; | ||||
14708 | OtherExpr = LHS; | ||||
14709 | } | ||||
14710 | |||||
14711 | // This warning is deliberately made very specific to reduce false | ||||
14712 | // positives with logic that uses '&' for hashing. This logic mainly | ||||
14713 | // looks for code trying to introspect into tagged pointers, which | ||||
14714 | // code should generally never do. | ||||
14715 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | ||||
14716 | unsigned Diag = diag::warn_objc_pointer_masking; | ||||
14717 | // Determine if we are introspecting the result of performSelectorXXX. | ||||
14718 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | ||||
14719 | // Special case messages to -performSelector and friends, which | ||||
14720 | // can return non-pointer values boxed in a pointer value. | ||||
14721 | // Some clients may wish to silence warnings in this subcase. | ||||
14722 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | ||||
14723 | Selector S = ME->getSelector(); | ||||
14724 | StringRef SelArg0 = S.getNameForSlot(0); | ||||
14725 | if (SelArg0.startswith("performSelector")) | ||||
14726 | Diag = diag::warn_objc_pointer_masking_performSelector; | ||||
14727 | } | ||||
14728 | |||||
14729 | S.Diag(OpLoc, Diag) | ||||
14730 | << ObjCPointerExpr->getSourceRange(); | ||||
14731 | } | ||||
14732 | } | ||||
14733 | |||||
14734 | static NamedDecl *getDeclFromExpr(Expr *E) { | ||||
14735 | if (!E) | ||||
14736 | return nullptr; | ||||
14737 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
14738 | return DRE->getDecl(); | ||||
14739 | if (auto *ME = dyn_cast<MemberExpr>(E)) | ||||
14740 | return ME->getMemberDecl(); | ||||
14741 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | ||||
14742 | return IRE->getDecl(); | ||||
14743 | return nullptr; | ||||
14744 | } | ||||
14745 | |||||
14746 | // This helper function promotes a binary operator's operands (which are of a | ||||
14747 | // half vector type) to a vector of floats and then truncates the result to | ||||
14748 | // a vector of either half or short. | ||||
14749 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | ||||
14750 | BinaryOperatorKind Opc, QualType ResultTy, | ||||
14751 | ExprValueKind VK, ExprObjectKind OK, | ||||
14752 | bool IsCompAssign, SourceLocation OpLoc, | ||||
14753 | FPOptionsOverride FPFeatures) { | ||||
14754 | auto &Context = S.getASTContext(); | ||||
14755 | assert((isVector(ResultTy, Context.HalfTy) ||(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 14757, __extension__ __PRETTY_FUNCTION__ )) | ||||
14756 | isVector(ResultTy, Context.ShortTy)) &&(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 14757, __extension__ __PRETTY_FUNCTION__ )) | ||||
14757 | "Result must be a vector of half or short")(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "clang/lib/Sema/SemaExpr.cpp", 14757, __extension__ __PRETTY_FUNCTION__ )); | ||||
14758 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 14760, __extension__ __PRETTY_FUNCTION__ )) | ||||
14759 | isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 14760, __extension__ __PRETTY_FUNCTION__ )) | ||||
14760 | "both operands expected to be a half vector")(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "clang/lib/Sema/SemaExpr.cpp", 14760, __extension__ __PRETTY_FUNCTION__ )); | ||||
14761 | |||||
14762 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | ||||
14763 | QualType BinOpResTy = RHS.get()->getType(); | ||||
14764 | |||||
14765 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | ||||
14766 | // change BinOpResTy to a vector of ints. | ||||
14767 | if (isVector(ResultTy, Context.ShortTy)) | ||||
14768 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | ||||
14769 | |||||
14770 | if (IsCompAssign) | ||||
14771 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
14772 | ResultTy, VK, OK, OpLoc, FPFeatures, | ||||
14773 | BinOpResTy, BinOpResTy); | ||||
14774 | |||||
14775 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | ||||
14776 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
14777 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | ||||
14778 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | ||||
14779 | } | ||||
14780 | |||||
14781 | static std::pair<ExprResult, ExprResult> | ||||
14782 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | ||||
14783 | Expr *RHSExpr) { | ||||
14784 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
14785 | if (!S.Context.isDependenceAllowed()) { | ||||
14786 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
14787 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
14788 | // been dealt with before checking the operands. | ||||
14789 | LHS = S.CorrectDelayedTyposInExpr(LHS); | ||||
14790 | RHS = S.CorrectDelayedTyposInExpr( | ||||
14791 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | ||||
14792 | [Opc, LHS](Expr *E) { | ||||
14793 | if (Opc != BO_Assign) | ||||
14794 | return ExprResult(E); | ||||
14795 | // Avoid correcting the RHS to the same Expr as the LHS. | ||||
14796 | Decl *D = getDeclFromExpr(E); | ||||
14797 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | ||||
14798 | }); | ||||
14799 | } | ||||
14800 | return std::make_pair(LHS, RHS); | ||||
14801 | } | ||||
14802 | |||||
14803 | /// Returns true if conversion between vectors of halfs and vectors of floats | ||||
14804 | /// is needed. | ||||
14805 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | ||||
14806 | Expr *E0, Expr *E1 = nullptr) { | ||||
14807 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | ||||
14808 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | ||||
14809 | return false; | ||||
14810 | |||||
14811 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | ||||
14812 | QualType Ty = E->IgnoreImplicit()->getType(); | ||||
14813 | |||||
14814 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | ||||
14815 | // to vectors of floats. Although the element type of the vectors is __fp16, | ||||
14816 | // the vectors shouldn't be treated as storage-only types. See the | ||||
14817 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | ||||
14818 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | ||||
14819 | if (VT->getVectorKind() == VectorType::NeonVector) | ||||
14820 | return false; | ||||
14821 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | ||||
14822 | } | ||||
14823 | return false; | ||||
14824 | }; | ||||
14825 | |||||
14826 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | ||||
14827 | } | ||||
14828 | |||||
14829 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | ||||
14830 | /// operator @p Opc at location @c TokLoc. This routine only supports | ||||
14831 | /// built-in operations; ActOnBinOp handles overloaded operators. | ||||
14832 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | ||||
14833 | BinaryOperatorKind Opc, | ||||
14834 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14835 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | ||||
14836 | // The syntax only allows initializer lists on the RHS of assignment, | ||||
14837 | // so we don't need to worry about accepting invalid code for | ||||
14838 | // non-assignment operators. | ||||
14839 | // C++11 5.17p9: | ||||
14840 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | ||||
14841 | // of x = {} is x = T(). | ||||
14842 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
14843 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
14844 | InitializedEntity Entity = | ||||
14845 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | ||||
14846 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | ||||
14847 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | ||||
14848 | if (Init.isInvalid()) | ||||
14849 | return Init; | ||||
14850 | RHSExpr = Init.get(); | ||||
14851 | } | ||||
14852 | |||||
14853 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
14854 | QualType ResultTy; // Result type of the binary operator. | ||||
14855 | // The following two variables are used for compound assignment operators | ||||
14856 | QualType CompLHSTy; // Type of LHS after promotions for computation | ||||
14857 | QualType CompResultTy; // Type of computation result | ||||
14858 | ExprValueKind VK = VK_PRValue; | ||||
14859 | ExprObjectKind OK = OK_Ordinary; | ||||
14860 | bool ConvertHalfVec = false; | ||||
14861 | |||||
14862 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
14863 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
14864 | return ExprError(); | ||||
14865 | |||||
14866 | if (getLangOpts().OpenCL) { | ||||
14867 | QualType LHSTy = LHSExpr->getType(); | ||||
14868 | QualType RHSTy = RHSExpr->getType(); | ||||
14869 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | ||||
14870 | // the ATOMIC_VAR_INIT macro. | ||||
14871 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | ||||
14872 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
14873 | if (BO_Assign == Opc) | ||||
14874 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | ||||
14875 | else | ||||
14876 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
14877 | return ExprError(); | ||||
14878 | } | ||||
14879 | |||||
14880 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
14881 | // only with a builtin functions and therefore should be disallowed here. | ||||
14882 | if (LHSTy->isImageType() || RHSTy->isImageType() || | ||||
14883 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | ||||
14884 | LHSTy->isPipeType() || RHSTy->isPipeType() || | ||||
14885 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | ||||
14886 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
14887 | return ExprError(); | ||||
14888 | } | ||||
14889 | } | ||||
14890 | |||||
14891 | checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); | ||||
14892 | checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); | ||||
14893 | |||||
14894 | switch (Opc) { | ||||
14895 | case BO_Assign: | ||||
14896 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc); | ||||
14897 | if (getLangOpts().CPlusPlus && | ||||
14898 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | ||||
14899 | VK = LHS.get()->getValueKind(); | ||||
14900 | OK = LHS.get()->getObjectKind(); | ||||
14901 | } | ||||
14902 | if (!ResultTy.isNull()) { | ||||
14903 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
14904 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | ||||
14905 | |||||
14906 | // Avoid copying a block to the heap if the block is assigned to a local | ||||
14907 | // auto variable that is declared in the same scope as the block. This | ||||
14908 | // optimization is unsafe if the local variable is declared in an outer | ||||
14909 | // scope. For example: | ||||
14910 | // | ||||
14911 | // BlockTy b; | ||||
14912 | // { | ||||
14913 | // b = ^{...}; | ||||
14914 | // } | ||||
14915 | // // It is unsafe to invoke the block here if it wasn't copied to the | ||||
14916 | // // heap. | ||||
14917 | // b(); | ||||
14918 | |||||
14919 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | ||||
14920 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | ||||
14921 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | ||||
14922 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | ||||
14923 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||
14924 | |||||
14925 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
14926 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | ||||
14927 | NTCUC_Assignment, NTCUK_Copy); | ||||
14928 | } | ||||
14929 | RecordModifiableNonNullParam(*this, LHS.get()); | ||||
14930 | break; | ||||
14931 | case BO_PtrMemD: | ||||
14932 | case BO_PtrMemI: | ||||
14933 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | ||||
14934 | Opc == BO_PtrMemI); | ||||
14935 | break; | ||||
14936 | case BO_Mul: | ||||
14937 | case BO_Div: | ||||
14938 | ConvertHalfVec = true; | ||||
14939 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | ||||
14940 | Opc == BO_Div); | ||||
14941 | break; | ||||
14942 | case BO_Rem: | ||||
14943 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | ||||
14944 | break; | ||||
14945 | case BO_Add: | ||||
14946 | ConvertHalfVec = true; | ||||
14947 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | ||||
14948 | break; | ||||
14949 | case BO_Sub: | ||||
14950 | ConvertHalfVec = true; | ||||
14951 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | ||||
14952 | break; | ||||
14953 | case BO_Shl: | ||||
14954 | case BO_Shr: | ||||
14955 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | ||||
14956 | break; | ||||
14957 | case BO_LE: | ||||
14958 | case BO_LT: | ||||
14959 | case BO_GE: | ||||
14960 | case BO_GT: | ||||
14961 | ConvertHalfVec = true; | ||||
14962 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14963 | break; | ||||
14964 | case BO_EQ: | ||||
14965 | case BO_NE: | ||||
14966 | ConvertHalfVec = true; | ||||
14967 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14968 | break; | ||||
14969 | case BO_Cmp: | ||||
14970 | ConvertHalfVec = true; | ||||
14971 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14972 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast <bool> (ResultTy.isNull() || ResultTy-> getAsCXXRecordDecl()) ? void (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "clang/lib/Sema/SemaExpr.cpp", 14972, __extension__ __PRETTY_FUNCTION__ )); | ||||
14973 | break; | ||||
14974 | case BO_And: | ||||
14975 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | ||||
14976 | [[fallthrough]]; | ||||
14977 | case BO_Xor: | ||||
14978 | case BO_Or: | ||||
14979 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
14980 | break; | ||||
14981 | case BO_LAnd: | ||||
14982 | case BO_LOr: | ||||
14983 | ConvertHalfVec = true; | ||||
14984 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | ||||
14985 | break; | ||||
14986 | case BO_MulAssign: | ||||
14987 | case BO_DivAssign: | ||||
14988 | ConvertHalfVec = true; | ||||
14989 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | ||||
14990 | Opc == BO_DivAssign); | ||||
14991 | CompLHSTy = CompResultTy; | ||||
14992 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14993 | ResultTy = | ||||
14994 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
14995 | break; | ||||
14996 | case BO_RemAssign: | ||||
14997 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | ||||
14998 | CompLHSTy = CompResultTy; | ||||
14999 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15000 | ResultTy = | ||||
15001 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15002 | break; | ||||
15003 | case BO_AddAssign: | ||||
15004 | ConvertHalfVec = true; | ||||
15005 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | ||||
15006 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15007 | ResultTy = | ||||
15008 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15009 | break; | ||||
15010 | case BO_SubAssign: | ||||
15011 | ConvertHalfVec = true; | ||||
15012 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | ||||
15013 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15014 | ResultTy = | ||||
15015 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15016 | break; | ||||
15017 | case BO_ShlAssign: | ||||
15018 | case BO_ShrAssign: | ||||
15019 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | ||||
15020 | CompLHSTy = CompResultTy; | ||||
15021 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15022 | ResultTy = | ||||
15023 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15024 | break; | ||||
15025 | case BO_AndAssign: | ||||
15026 | case BO_OrAssign: // fallthrough | ||||
15027 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
15028 | [[fallthrough]]; | ||||
15029 | case BO_XorAssign: | ||||
15030 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
15031 | CompLHSTy = CompResultTy; | ||||
15032 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
15033 | ResultTy = | ||||
15034 | CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); | ||||
15035 | break; | ||||
15036 | case BO_Comma: | ||||
15037 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | ||||
15038 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | ||||
15039 | VK = RHS.get()->getValueKind(); | ||||
15040 | OK = RHS.get()->getObjectKind(); | ||||
15041 | } | ||||
15042 | break; | ||||
15043 | } | ||||
15044 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | ||||
15045 | return ExprError(); | ||||
15046 | |||||
15047 | // Some of the binary operations require promoting operands of half vector to | ||||
15048 | // float vectors and truncating the result back to half vector. For now, we do | ||||
15049 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | ||||
15050 | // arm64). | ||||
15051 | assert((static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? 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\"" , "clang/lib/Sema/SemaExpr.cpp", 15054, __extension__ __PRETTY_FUNCTION__ )) | ||||
15052 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? 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\"" , "clang/lib/Sema/SemaExpr.cpp", 15054, __extension__ __PRETTY_FUNCTION__ )) | ||||
15053 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? 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\"" , "clang/lib/Sema/SemaExpr.cpp", 15054, __extension__ __PRETTY_FUNCTION__ )) | ||||
15054 | "both sides are half vectors or neither sides are")(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? 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\"" , "clang/lib/Sema/SemaExpr.cpp", 15054, __extension__ __PRETTY_FUNCTION__ )); | ||||
15055 | ConvertHalfVec = | ||||
15056 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | ||||
15057 | |||||
15058 | // Check for array bounds violations for both sides of the BinaryOperator | ||||
15059 | CheckArrayAccess(LHS.get()); | ||||
15060 | CheckArrayAccess(RHS.get()); | ||||
15061 | |||||
15062 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | ||||
15063 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | ||||
15064 | &Context.Idents.get("object_setClass"), | ||||
15065 | SourceLocation(), LookupOrdinaryName); | ||||
15066 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | ||||
15067 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
15068 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | ||||
15069 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | ||||
15070 | "object_setClass(") | ||||
15071 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | ||||
15072 | ",") | ||||
15073 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
15074 | } | ||||
15075 | else | ||||
15076 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | ||||
15077 | } | ||||
15078 | else if (const ObjCIvarRefExpr *OIRE = | ||||
15079 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | ||||
15080 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | ||||
15081 | |||||
15082 | // Opc is not a compound assignment if CompResultTy is null. | ||||
15083 | if (CompResultTy.isNull()) { | ||||
15084 | if (ConvertHalfVec) | ||||
15085 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | ||||
15086 | OpLoc, CurFPFeatureOverrides()); | ||||
15087 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | ||||
15088 | VK, OK, OpLoc, CurFPFeatureOverrides()); | ||||
15089 | } | ||||
15090 | |||||
15091 | // Handle compound assignments. | ||||
15092 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | ||||
15093 | OK_ObjCProperty) { | ||||
15094 | VK = VK_LValue; | ||||
15095 | OK = LHS.get()->getObjectKind(); | ||||
15096 | } | ||||
15097 | |||||
15098 | // The LHS is not converted to the result type for fixed-point compound | ||||
15099 | // assignment as the common type is computed on demand. Reset the CompLHSTy | ||||
15100 | // to the LHS type we would have gotten after unary conversions. | ||||
15101 | if (CompResultTy->isFixedPointType()) | ||||
15102 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | ||||
15103 | |||||
15104 | if (ConvertHalfVec) | ||||
15105 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | ||||
15106 | OpLoc, CurFPFeatureOverrides()); | ||||
15107 | |||||
15108 | return CompoundAssignOperator::Create( | ||||
15109 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | ||||
15110 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | ||||
15111 | } | ||||
15112 | |||||
15113 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | ||||
15114 | /// operators are mixed in a way that suggests that the programmer forgot that | ||||
15115 | /// comparison operators have higher precedence. The most typical example of | ||||
15116 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | ||||
15117 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
15118 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
15119 | Expr *RHSExpr) { | ||||
15120 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | ||||
15121 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | ||||
15122 | |||||
15123 | // Check that one of the sides is a comparison operator and the other isn't. | ||||
15124 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | ||||
15125 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | ||||
15126 | if (isLeftComp == isRightComp) | ||||
15127 | return; | ||||
15128 | |||||
15129 | // Bitwise operations are sometimes used as eager logical ops. | ||||
15130 | // Don't diagnose this. | ||||
15131 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | ||||
15132 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | ||||
15133 | if (isLeftBitwise || isRightBitwise) | ||||
15134 | return; | ||||
15135 | |||||
15136 | SourceRange DiagRange = isLeftComp | ||||
15137 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | ||||
15138 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | ||||
15139 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | ||||
15140 | SourceRange ParensRange = | ||||
15141 | isLeftComp | ||||
15142 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | ||||
15143 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | ||||
15144 | |||||
15145 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | ||||
15146 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | ||||
15147 | SuggestParentheses(Self, OpLoc, | ||||
15148 | Self.PDiag(diag::note_precedence_silence) << OpStr, | ||||
15149 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | ||||
15150 | SuggestParentheses(Self, OpLoc, | ||||
15151 | Self.PDiag(diag::note_precedence_bitwise_first) | ||||
15152 | << BinaryOperator::getOpcodeStr(Opc), | ||||
15153 | ParensRange); | ||||
15154 | } | ||||
15155 | |||||
15156 | /// It accepts a '&&' expr that is inside a '||' one. | ||||
15157 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | ||||
15158 | /// in parentheses. | ||||
15159 | static void | ||||
15160 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | ||||
15161 | BinaryOperator *Bop) { | ||||
15162 | assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void (0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "clang/lib/Sema/SemaExpr.cpp" , 15162, __extension__ __PRETTY_FUNCTION__)); | ||||
15163 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | ||||
15164 | << Bop->getSourceRange() << OpLoc; | ||||
15165 | SuggestParentheses(Self, Bop->getOperatorLoc(), | ||||
15166 | Self.PDiag(diag::note_precedence_silence) | ||||
15167 | << Bop->getOpcodeStr(), | ||||
15168 | Bop->getSourceRange()); | ||||
15169 | } | ||||
15170 | |||||
15171 | /// Returns true if the given expression can be evaluated as a constant | ||||
15172 | /// 'true'. | ||||
15173 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | ||||
15174 | bool Res; | ||||
15175 | return !E->isValueDependent() && | ||||
15176 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | ||||
15177 | } | ||||
15178 | |||||
15179 | /// Returns true if the given expression can be evaluated as a constant | ||||
15180 | /// 'false'. | ||||
15181 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | ||||
15182 | bool Res; | ||||
15183 | return !E->isValueDependent() && | ||||
15184 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | ||||
15185 | } | ||||
15186 | |||||
15187 | /// Look for '&&' in the left hand of a '||' expr. | ||||
15188 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | ||||
15189 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15190 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | ||||
15191 | if (Bop->getOpcode() == BO_LAnd) { | ||||
15192 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | ||||
15193 | if (EvaluatesAsFalse(S, RHSExpr)) | ||||
15194 | return; | ||||
15195 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | ||||
15196 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | ||||
15197 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
15198 | } else if (Bop->getOpcode() == BO_LOr) { | ||||
15199 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | ||||
15200 | // If it's "a || b && 1 || c" we didn't warn earlier for | ||||
15201 | // "a || b && 1", but warn now. | ||||
15202 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | ||||
15203 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | ||||
15204 | } | ||||
15205 | } | ||||
15206 | } | ||||
15207 | } | ||||
15208 | |||||
15209 | /// Look for '&&' in the right hand of a '||' expr. | ||||
15210 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | ||||
15211 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15212 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | ||||
15213 | if (Bop->getOpcode() == BO_LAnd) { | ||||
15214 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | ||||
15215 | if (EvaluatesAsFalse(S, LHSExpr)) | ||||
15216 | return; | ||||
15217 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | ||||
15218 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | ||||
15219 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
15220 | } | ||||
15221 | } | ||||
15222 | } | ||||
15223 | |||||
15224 | /// Look for bitwise op in the left or right hand of a bitwise op with | ||||
15225 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | ||||
15226 | /// the '&' expression in parentheses. | ||||
15227 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | ||||
15228 | SourceLocation OpLoc, Expr *SubExpr) { | ||||
15229 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
15230 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | ||||
15231 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | ||||
15232 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | ||||
15233 | << Bop->getSourceRange() << OpLoc; | ||||
15234 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
15235 | S.PDiag(diag::note_precedence_silence) | ||||
15236 | << Bop->getOpcodeStr(), | ||||
15237 | Bop->getSourceRange()); | ||||
15238 | } | ||||
15239 | } | ||||
15240 | } | ||||
15241 | |||||
15242 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | ||||
15243 | Expr *SubExpr, StringRef Shift) { | ||||
15244 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
15245 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | ||||
15246 | StringRef Op = Bop->getOpcodeStr(); | ||||
15247 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | ||||
15248 | << Bop->getSourceRange() << OpLoc << Shift << Op; | ||||
15249 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
15250 | S.PDiag(diag::note_precedence_silence) << Op, | ||||
15251 | Bop->getSourceRange()); | ||||
15252 | } | ||||
15253 | } | ||||
15254 | } | ||||
15255 | |||||
15256 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | ||||
15257 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15258 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | ||||
15259 | if (!OCE) | ||||
15260 | return; | ||||
15261 | |||||
15262 | FunctionDecl *FD = OCE->getDirectCallee(); | ||||
15263 | if (!FD || !FD->isOverloadedOperator()) | ||||
15264 | return; | ||||
15265 | |||||
15266 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | ||||
15267 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | ||||
15268 | return; | ||||
15269 | |||||
15270 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | ||||
15271 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | ||||
15272 | << (Kind == OO_LessLess); | ||||
15273 | SuggestParentheses(S, OCE->getOperatorLoc(), | ||||
15274 | S.PDiag(diag::note_precedence_silence) | ||||
15275 | << (Kind == OO_LessLess ? "<<" : ">>"), | ||||
15276 | OCE->getSourceRange()); | ||||
15277 | SuggestParentheses( | ||||
15278 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | ||||
15279 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
15280 | } | ||||
15281 | |||||
15282 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | ||||
15283 | /// precedence. | ||||
15284 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
15285 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
15286 | Expr *RHSExpr){ | ||||
15287 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | ||||
15288 | if (BinaryOperator::isBitwiseOp(Opc)) | ||||
15289 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | ||||
15290 | |||||
15291 | // Diagnose "arg1 & arg2 | arg3" | ||||
15292 | if ((Opc == BO_Or || Opc == BO_Xor) && | ||||
15293 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
15294 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | ||||
15295 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | ||||
15296 | } | ||||
15297 | |||||
15298 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | ||||
15299 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | ||||
15300 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
15301 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
15302 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
15303 | } | ||||
15304 | |||||
15305 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | ||||
15306 | || Opc == BO_Shr) { | ||||
15307 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | ||||
15308 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | ||||
15309 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | ||||
15310 | } | ||||
15311 | |||||
15312 | // Warn on overloaded shift operators and comparisons, such as: | ||||
15313 | // cout << 5 == 4; | ||||
15314 | if (BinaryOperator::isComparisonOp(Opc)) | ||||
15315 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | ||||
15316 | } | ||||
15317 | |||||
15318 | // Binary Operators. 'Tok' is the token for the operator. | ||||
15319 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | ||||
15320 | tok::TokenKind Kind, | ||||
15321 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15322 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | ||||
15323 | assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression" ) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "clang/lib/Sema/SemaExpr.cpp", 15323, __extension__ __PRETTY_FUNCTION__ )); | ||||
15324 | assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression" ) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "clang/lib/Sema/SemaExpr.cpp", 15324, __extension__ __PRETTY_FUNCTION__ )); | ||||
15325 | |||||
15326 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | ||||
15327 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | ||||
15328 | |||||
15329 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | ||||
15330 | } | ||||
15331 | |||||
15332 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | ||||
15333 | UnresolvedSetImpl &Functions) { | ||||
15334 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | ||||
15335 | if (OverOp != OO_None && OverOp != OO_Equal) | ||||
15336 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
15337 | |||||
15338 | // In C++20 onwards, we may have a second operator to look up. | ||||
15339 | if (getLangOpts().CPlusPlus20) { | ||||
15340 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | ||||
15341 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | ||||
15342 | } | ||||
15343 | } | ||||
15344 | |||||
15345 | /// Build an overloaded binary operator expression in the given scope. | ||||
15346 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | ||||
15347 | BinaryOperatorKind Opc, | ||||
15348 | Expr *LHS, Expr *RHS) { | ||||
15349 | switch (Opc) { | ||||
15350 | case BO_Assign: | ||||
15351 | case BO_DivAssign: | ||||
15352 | case BO_RemAssign: | ||||
15353 | case BO_SubAssign: | ||||
15354 | case BO_AndAssign: | ||||
15355 | case BO_OrAssign: | ||||
15356 | case BO_XorAssign: | ||||
15357 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | ||||
15358 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | ||||
15359 | break; | ||||
15360 | default: | ||||
15361 | break; | ||||
15362 | } | ||||
15363 | |||||
15364 | // Find all of the overloaded operators visible from this point. | ||||
15365 | UnresolvedSet<16> Functions; | ||||
15366 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | ||||
15367 | |||||
15368 | // Build the (potentially-overloaded, potentially-dependent) | ||||
15369 | // binary operation. | ||||
15370 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | ||||
15371 | } | ||||
15372 | |||||
15373 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | ||||
15374 | BinaryOperatorKind Opc, | ||||
15375 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
15376 | ExprResult LHS, RHS; | ||||
15377 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
15378 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
15379 | return ExprError(); | ||||
15380 | LHSExpr = LHS.get(); | ||||
15381 | RHSExpr = RHS.get(); | ||||
15382 | |||||
15383 | // We want to end up calling one of checkPseudoObjectAssignment | ||||
15384 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | ||||
15385 | // both expressions are overloadable or either is type-dependent), | ||||
15386 | // or CreateBuiltinBinOp (in any other case). We also want to get | ||||
15387 | // any placeholder types out of the way. | ||||
15388 | |||||
15389 | // Handle pseudo-objects in the LHS. | ||||
15390 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | ||||
15391 | // Assignments with a pseudo-object l-value need special analysis. | ||||
15392 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
15393 | BinaryOperator::isAssignmentOp(Opc)) | ||||
15394 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15395 | |||||
15396 | // Don't resolve overloads if the other type is overloadable. | ||||
15397 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | ||||
15398 | // We can't actually test that if we still have a placeholder, | ||||
15399 | // though. Fortunately, none of the exceptions we see in that | ||||
15400 | // code below are valid when the LHS is an overload set. Note | ||||
15401 | // that an overload set can be dependently-typed, but it never | ||||
15402 | // instantiates to having an overloadable type. | ||||
15403 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
15404 | if (resolvedRHS.isInvalid()) return ExprError(); | ||||
15405 | RHSExpr = resolvedRHS.get(); | ||||
15406 | |||||
15407 | if (RHSExpr->isTypeDependent() || | ||||
15408 | RHSExpr->getType()->isOverloadableType()) | ||||
15409 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15410 | } | ||||
15411 | |||||
15412 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | ||||
15413 | // template, diagnose the missing 'template' keyword instead of diagnosing | ||||
15414 | // an invalid use of a bound member function. | ||||
15415 | // | ||||
15416 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | ||||
15417 | // to C++1z [over.over]/1.4, but we already checked for that case above. | ||||
15418 | if (Opc == BO_LT && inTemplateInstantiation() && | ||||
15419 | (pty->getKind() == BuiltinType::BoundMember || | ||||
15420 | pty->getKind() == BuiltinType::Overload)) { | ||||
15421 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | ||||
15422 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | ||||
15423 | llvm::any_of(OE->decls(), [](NamedDecl *ND) { | ||||
15424 | return isa<FunctionTemplateDecl>(ND); | ||||
15425 | })) { | ||||
15426 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | ||||
15427 | : OE->getNameLoc(), | ||||
15428 | diag::err_template_kw_missing) | ||||
15429 | << OE->getName().getAsString() << ""; | ||||
15430 | return ExprError(); | ||||
15431 | } | ||||
15432 | } | ||||
15433 | |||||
15434 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | ||||
15435 | if (LHS.isInvalid()) return ExprError(); | ||||
15436 | LHSExpr = LHS.get(); | ||||
15437 | } | ||||
15438 | |||||
15439 | // Handle pseudo-objects in the RHS. | ||||
15440 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | ||||
15441 | // An overload in the RHS can potentially be resolved by the type | ||||
15442 | // being assigned to. | ||||
15443 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | ||||
15444 | if (getLangOpts().CPlusPlus && | ||||
15445 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | ||||
15446 | LHSExpr->getType()->isOverloadableType())) | ||||
15447 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15448 | |||||
15449 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15450 | } | ||||
15451 | |||||
15452 | // Don't resolve overloads if the other type is overloadable. | ||||
15453 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | ||||
15454 | LHSExpr->getType()->isOverloadableType()) | ||||
15455 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15456 | |||||
15457 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
15458 | if (!resolvedRHS.isUsable()) return ExprError(); | ||||
15459 | RHSExpr = resolvedRHS.get(); | ||||
15460 | } | ||||
15461 | |||||
15462 | if (getLangOpts().CPlusPlus) { | ||||
15463 | // If either expression is type-dependent, always build an | ||||
15464 | // overloaded op. | ||||
15465 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | ||||
15466 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15467 | |||||
15468 | // Otherwise, build an overloaded op if either expression has an | ||||
15469 | // overloadable type. | ||||
15470 | if (LHSExpr->getType()->isOverloadableType() || | ||||
15471 | RHSExpr->getType()->isOverloadableType()) | ||||
15472 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15473 | } | ||||
15474 | |||||
15475 | if (getLangOpts().RecoveryAST && | ||||
15476 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | ||||
15477 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "clang/lib/Sema/SemaExpr.cpp" , 15477, __extension__ __PRETTY_FUNCTION__)); | ||||
15478 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 15479, __extension__ __PRETTY_FUNCTION__ )) | ||||
15479 | "Should only occur in error-recovery path.")(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaExpr.cpp", 15479, __extension__ __PRETTY_FUNCTION__ )); | ||||
15480 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | ||||
15481 | // C [6.15.16] p3: | ||||
15482 | // An assignment expression has the value of the left operand after the | ||||
15483 | // assignment, but is not an lvalue. | ||||
15484 | return CompoundAssignOperator::Create( | ||||
15485 | Context, LHSExpr, RHSExpr, Opc, | ||||
15486 | LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, | ||||
15487 | OpLoc, CurFPFeatureOverrides()); | ||||
15488 | QualType ResultType; | ||||
15489 | switch (Opc) { | ||||
15490 | case BO_Assign: | ||||
15491 | ResultType = LHSExpr->getType().getUnqualifiedType(); | ||||
15492 | break; | ||||
15493 | case BO_LT: | ||||
15494 | case BO_GT: | ||||
15495 | case BO_LE: | ||||
15496 | case BO_GE: | ||||
15497 | case BO_EQ: | ||||
15498 | case BO_NE: | ||||
15499 | case BO_LAnd: | ||||
15500 | case BO_LOr: | ||||
15501 | // These operators have a fixed result type regardless of operands. | ||||
15502 | ResultType = Context.IntTy; | ||||
15503 | break; | ||||
15504 | case BO_Comma: | ||||
15505 | ResultType = RHSExpr->getType(); | ||||
15506 | break; | ||||
15507 | default: | ||||
15508 | ResultType = Context.DependentTy; | ||||
15509 | break; | ||||
15510 | } | ||||
15511 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | ||||
15512 | VK_PRValue, OK_Ordinary, OpLoc, | ||||
15513 | CurFPFeatureOverrides()); | ||||
15514 | } | ||||
15515 | |||||
15516 | // Build a built-in binary operation. | ||||
15517 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
15518 | } | ||||
15519 | |||||
15520 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | ||||
15521 | if (T.isNull() || T->isDependentType()) | ||||
15522 | return false; | ||||
15523 | |||||
15524 | if (!T->isPromotableIntegerType()) | ||||
15525 | return true; | ||||
15526 | |||||
15527 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | ||||
15528 | } | ||||
15529 | |||||
15530 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | ||||
15531 | UnaryOperatorKind Opc, Expr *InputExpr, | ||||
15532 | bool IsAfterAmp) { | ||||
15533 | ExprResult Input = InputExpr; | ||||
15534 | ExprValueKind VK = VK_PRValue; | ||||
15535 | ExprObjectKind OK = OK_Ordinary; | ||||
15536 | QualType resultType; | ||||
15537 | bool CanOverflow = false; | ||||
15538 | |||||
15539 | bool ConvertHalfVec = false; | ||||
15540 | if (getLangOpts().OpenCL) { | ||||
15541 | QualType Ty = InputExpr->getType(); | ||||
15542 | // The only legal unary operation for atomics is '&'. | ||||
15543 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | ||||
15544 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
15545 | // only with a builtin functions and therefore should be disallowed here. | ||||
15546 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | ||||
15547 | || Ty->isBlockPointerType())) { | ||||
15548 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15549 | << InputExpr->getType() | ||||
15550 | << Input.get()->getSourceRange()); | ||||
15551 | } | ||||
15552 | } | ||||
15553 | |||||
15554 | if (getLangOpts().HLSL) { | ||||
15555 | if (Opc == UO_AddrOf) | ||||
15556 | return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); | ||||
15557 | if (Opc == UO_Deref) | ||||
15558 | return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); | ||||
15559 | } | ||||
15560 | |||||
15561 | switch (Opc) { | ||||
15562 | case UO_PreInc: | ||||
15563 | case UO_PreDec: | ||||
15564 | case UO_PostInc: | ||||
15565 | case UO_PostDec: | ||||
15566 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | ||||
15567 | OpLoc, | ||||
15568 | Opc == UO_PreInc || | ||||
15569 | Opc == UO_PostInc, | ||||
15570 | Opc == UO_PreInc || | ||||
15571 | Opc == UO_PreDec); | ||||
15572 | CanOverflow = isOverflowingIntegerType(Context, resultType); | ||||
15573 | break; | ||||
15574 | case UO_AddrOf: | ||||
15575 | resultType = CheckAddressOfOperand(Input, OpLoc); | ||||
15576 | CheckAddressOfNoDeref(InputExpr); | ||||
15577 | RecordModifiableNonNullParam(*this, InputExpr); | ||||
15578 | break; | ||||
15579 | case UO_Deref: { | ||||
15580 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
15581 | if (Input.isInvalid()) return ExprError(); | ||||
15582 | resultType = | ||||
15583 | CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp); | ||||
15584 | break; | ||||
15585 | } | ||||
15586 | case UO_Plus: | ||||
15587 | case UO_Minus: | ||||
15588 | CanOverflow = Opc == UO_Minus && | ||||
15589 | isOverflowingIntegerType(Context, Input.get()->getType()); | ||||
15590 | Input = UsualUnaryConversions(Input.get()); | ||||
15591 | if (Input.isInvalid()) return ExprError(); | ||||
15592 | // Unary plus and minus require promoting an operand of half vector to a | ||||
15593 | // float vector and truncating the result back to a half vector. For now, we | ||||
15594 | // do this only when HalfArgsAndReturns is set (that is, when the target is | ||||
15595 | // arm or arm64). | ||||
15596 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | ||||
15597 | |||||
15598 | // If the operand is a half vector, promote it to a float vector. | ||||
15599 | if (ConvertHalfVec) | ||||
15600 | Input = convertVector(Input.get(), Context.FloatTy, *this); | ||||
15601 | resultType = Input.get()->getType(); | ||||
15602 | if (resultType->isDependentType()) | ||||
15603 | break; | ||||
15604 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | ||||
15605 | break; | ||||
15606 | else if (resultType->isVectorType() && | ||||
15607 | // The z vector extensions don't allow + or - with bool vectors. | ||||
15608 | (!Context.getLangOpts().ZVector || | ||||
15609 | resultType->castAs<VectorType>()->getVectorKind() != | ||||
15610 | VectorType::AltiVecBool)) | ||||
15611 | break; | ||||
15612 | else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and - | ||||
15613 | break; | ||||
15614 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | ||||
15615 | Opc == UO_Plus && | ||||
15616 | resultType->isPointerType()) | ||||
15617 | break; | ||||
15618 | |||||
15619 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15620 | << resultType << Input.get()->getSourceRange()); | ||||
15621 | |||||
15622 | case UO_Not: // bitwise complement | ||||
15623 | Input = UsualUnaryConversions(Input.get()); | ||||
15624 | if (Input.isInvalid()) | ||||
15625 | return ExprError(); | ||||
15626 | resultType = Input.get()->getType(); | ||||
15627 | if (resultType->isDependentType()) | ||||
15628 | break; | ||||
15629 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | ||||
15630 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | ||||
15631 | // C99 does not support '~' for complex conjugation. | ||||
15632 | Diag(OpLoc, diag::ext_integer_complement_complex) | ||||
15633 | << resultType << Input.get()->getSourceRange(); | ||||
15634 | else if (resultType->hasIntegerRepresentation()) | ||||
15635 | break; | ||||
15636 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | ||||
15637 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | ||||
15638 | // on vector float types. | ||||
15639 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
15640 | if (!T->isIntegerType()) | ||||
15641 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15642 | << resultType << Input.get()->getSourceRange()); | ||||
15643 | } else { | ||||
15644 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15645 | << resultType << Input.get()->getSourceRange()); | ||||
15646 | } | ||||
15647 | break; | ||||
15648 | |||||
15649 | case UO_LNot: // logical negation | ||||
15650 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | ||||
15651 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
15652 | if (Input.isInvalid()) return ExprError(); | ||||
15653 | resultType = Input.get()->getType(); | ||||
15654 | |||||
15655 | // Though we still have to promote half FP to float... | ||||
15656 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | ||||
15657 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | ||||
15658 | resultType = Context.FloatTy; | ||||
15659 | } | ||||
15660 | |||||
15661 | if (resultType->isDependentType()) | ||||
15662 | break; | ||||
15663 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | ||||
15664 | // C99 6.5.3.3p1: ok, fallthrough; | ||||
15665 | if (Context.getLangOpts().CPlusPlus) { | ||||
15666 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | ||||
15667 | // operand contextually converted to bool. | ||||
15668 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | ||||
15669 | ScalarTypeToBooleanCastKind(resultType)); | ||||
15670 | } else if (Context.getLangOpts().OpenCL && | ||||
15671 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
15672 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
15673 | // operate on scalar float types. | ||||
15674 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | ||||
15675 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15676 | << resultType << Input.get()->getSourceRange()); | ||||
15677 | } | ||||
15678 | } else if (resultType->isExtVectorType()) { | ||||
15679 | if (Context.getLangOpts().OpenCL && | ||||
15680 | Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { | ||||
15681 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
15682 | // operate on vector float types. | ||||
15683 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
15684 | if (!T->isIntegerType()) | ||||
15685 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15686 | << resultType << Input.get()->getSourceRange()); | ||||
15687 | } | ||||
15688 | // Vector logical not returns the signed variant of the operand type. | ||||
15689 | resultType = GetSignedVectorType(resultType); | ||||
15690 | break; | ||||
15691 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | ||||
15692 | const VectorType *VTy = resultType->castAs<VectorType>(); | ||||
15693 | if (VTy->getVectorKind() != VectorType::GenericVector) | ||||
15694 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15695 | << resultType << Input.get()->getSourceRange()); | ||||
15696 | |||||
15697 | // Vector logical not returns the signed variant of the operand type. | ||||
15698 | resultType = GetSignedVectorType(resultType); | ||||
15699 | break; | ||||
15700 | } else { | ||||
15701 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15702 | << resultType << Input.get()->getSourceRange()); | ||||
15703 | } | ||||
15704 | |||||
15705 | // LNot always has type int. C99 6.5.3.3p5. | ||||
15706 | // In C++, it's bool. C++ 5.3.1p8 | ||||
15707 | resultType = Context.getLogicalOperationType(); | ||||
15708 | break; | ||||
15709 | case UO_Real: | ||||
15710 | case UO_Imag: | ||||
15711 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | ||||
15712 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | ||||
15713 | // complex l-values to ordinary l-values and all other values to r-values. | ||||
15714 | if (Input.isInvalid()) return ExprError(); | ||||
15715 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | ||||
15716 | if (Input.get()->isGLValue() && | ||||
15717 | Input.get()->getObjectKind() == OK_Ordinary) | ||||
15718 | VK = Input.get()->getValueKind(); | ||||
15719 | } else if (!getLangOpts().CPlusPlus) { | ||||
15720 | // In C, a volatile scalar is read by __imag. In C++, it is not. | ||||
15721 | Input = DefaultLvalueConversion(Input.get()); | ||||
15722 | } | ||||
15723 | break; | ||||
15724 | case UO_Extension: | ||||
15725 | resultType = Input.get()->getType(); | ||||
15726 | VK = Input.get()->getValueKind(); | ||||
15727 | OK = Input.get()->getObjectKind(); | ||||
15728 | break; | ||||
15729 | case UO_Coawait: | ||||
15730 | // It's unnecessary to represent the pass-through operator co_await in the | ||||
15731 | // AST; just return the input expression instead. | ||||
15732 | assert(!Input.get()->getType()->isDependentType() &&(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 15734, __extension__ __PRETTY_FUNCTION__ )) | ||||
15733 | "the co_await expression must be non-dependant before "(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 15734, __extension__ __PRETTY_FUNCTION__ )) | ||||
15734 | "building operator co_await")(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "clang/lib/Sema/SemaExpr.cpp", 15734, __extension__ __PRETTY_FUNCTION__ )); | ||||
15735 | return Input; | ||||
15736 | } | ||||
15737 | if (resultType.isNull() || Input.isInvalid()) | ||||
15738 | return ExprError(); | ||||
15739 | |||||
15740 | // Check for array bounds violations in the operand of the UnaryOperator, | ||||
15741 | // except for the '*' and '&' operators that have to be handled specially | ||||
15742 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | ||||
15743 | // that are explicitly defined as valid by the standard). | ||||
15744 | if (Opc != UO_AddrOf && Opc != UO_Deref) | ||||
15745 | CheckArrayAccess(Input.get()); | ||||
15746 | |||||
15747 | auto *UO = | ||||
15748 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | ||||
15749 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | ||||
15750 | |||||
15751 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | ||||
15752 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | ||||
15753 | !isUnevaluatedContext()) | ||||
15754 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | ||||
15755 | |||||
15756 | // Convert the result back to a half vector. | ||||
15757 | if (ConvertHalfVec) | ||||
15758 | return convertVector(UO, Context.HalfTy, *this); | ||||
15759 | return UO; | ||||
15760 | } | ||||
15761 | |||||
15762 | /// Determine whether the given expression is a qualified member | ||||
15763 | /// access expression, of a form that could be turned into a pointer to member | ||||
15764 | /// with the address-of operator. | ||||
15765 | bool Sema::isQualifiedMemberAccess(Expr *E) { | ||||
15766 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
15767 | if (!DRE->getQualifier()) | ||||
15768 | return false; | ||||
15769 | |||||
15770 | ValueDecl *VD = DRE->getDecl(); | ||||
15771 | if (!VD->isCXXClassMember()) | ||||
15772 | return false; | ||||
15773 | |||||
15774 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | ||||
15775 | return true; | ||||
15776 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | ||||
15777 | return Method->isInstance(); | ||||
15778 | |||||
15779 | return false; | ||||
15780 | } | ||||
15781 | |||||
15782 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | ||||
15783 | if (!ULE->getQualifier()) | ||||
15784 | return false; | ||||
15785 | |||||
15786 | for (NamedDecl *D : ULE->decls()) { | ||||
15787 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | ||||
15788 | if (Method->isInstance()) | ||||
15789 | return true; | ||||
15790 | } else { | ||||
15791 | // Overload set does not contain methods. | ||||
15792 | break; | ||||
15793 | } | ||||
15794 | } | ||||
15795 | |||||
15796 | return false; | ||||
15797 | } | ||||
15798 | |||||
15799 | return false; | ||||
15800 | } | ||||
15801 | |||||
15802 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
15803 | UnaryOperatorKind Opc, Expr *Input, | ||||
15804 | bool IsAfterAmp) { | ||||
15805 | // First things first: handle placeholders so that the | ||||
15806 | // overloaded-operator check considers the right type. | ||||
15807 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | ||||
15808 | // Increment and decrement of pseudo-object references. | ||||
15809 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
15810 | UnaryOperator::isIncrementDecrementOp(Opc)) | ||||
15811 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | ||||
15812 | |||||
15813 | // extension is always a builtin operator. | ||||
15814 | if (Opc == UO_Extension) | ||||
15815 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
15816 | |||||
15817 | // & gets special logic for several kinds of placeholder. | ||||
15818 | // The builtin code knows what to do. | ||||
15819 | if (Opc == UO_AddrOf && | ||||
15820 | (pty->getKind() == BuiltinType::Overload || | ||||
15821 | pty->getKind() == BuiltinType::UnknownAny || | ||||
15822 | pty->getKind() == BuiltinType::BoundMember)) | ||||
15823 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
15824 | |||||
15825 | // Anything else needs to be handled now. | ||||
15826 | ExprResult Result = CheckPlaceholderExpr(Input); | ||||
15827 | if (Result.isInvalid()) return ExprError(); | ||||
15828 | Input = Result.get(); | ||||
15829 | } | ||||
15830 | |||||
15831 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | ||||
15832 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | ||||
15833 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | ||||
15834 | // Find all of the overloaded operators visible from this point. | ||||
15835 | UnresolvedSet<16> Functions; | ||||
15836 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | ||||
15837 | if (S && OverOp != OO_None) | ||||
15838 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
15839 | |||||
15840 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | ||||
15841 | } | ||||
15842 | |||||
15843 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp); | ||||
15844 | } | ||||
15845 | |||||
15846 | // Unary Operators. 'Tok' is the token for the operator. | ||||
15847 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, | ||||
15848 | Expr *Input, bool IsAfterAmp) { | ||||
15849 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input, | ||||
15850 | IsAfterAmp); | ||||
15851 | } | ||||
15852 | |||||
15853 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | ||||
15854 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | ||||
15855 | LabelDecl *TheDecl) { | ||||
15856 | TheDecl->markUsed(Context); | ||||
15857 | // Create the AST node. The address of a label always has type 'void*'. | ||||
15858 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | ||||
15859 | Context.getPointerType(Context.VoidTy)); | ||||
15860 | } | ||||
15861 | |||||
15862 | void Sema::ActOnStartStmtExpr() { | ||||
15863 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
15864 | } | ||||
15865 | |||||
15866 | void Sema::ActOnStmtExprError() { | ||||
15867 | // Note that function is also called by TreeTransform when leaving a | ||||
15868 | // StmtExpr scope without rebuilding anything. | ||||
15869 | |||||
15870 | DiscardCleanupsInEvaluationContext(); | ||||
15871 | PopExpressionEvaluationContext(); | ||||
15872 | } | ||||
15873 | |||||
15874 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | ||||
15875 | SourceLocation RPLoc) { | ||||
15876 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | ||||
15877 | } | ||||
15878 | |||||
15879 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | ||||
15880 | SourceLocation RPLoc, unsigned TemplateDepth) { | ||||
15881 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast <bool> (SubStmt && isa<CompoundStmt >(SubStmt) && "Invalid action invocation!") ? void (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "clang/lib/Sema/SemaExpr.cpp", 15881, __extension__ __PRETTY_FUNCTION__ )); | ||||
15882 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | ||||
15883 | |||||
15884 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
15885 | DiscardCleanupsInEvaluationContext(); | ||||
15886 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 15887, __extension__ __PRETTY_FUNCTION__ )) | ||||
15887 | "cleanups within StmtExpr not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 15887, __extension__ __PRETTY_FUNCTION__ )); | ||||
15888 | PopExpressionEvaluationContext(); | ||||
15889 | |||||
15890 | // FIXME: there are a variety of strange constraints to enforce here, for | ||||
15891 | // example, it is not possible to goto into a stmt expression apparently. | ||||
15892 | // More semantic analysis is needed. | ||||
15893 | |||||
15894 | // If there are sub-stmts in the compound stmt, take the type of the last one | ||||
15895 | // as the type of the stmtexpr. | ||||
15896 | QualType Ty = Context.VoidTy; | ||||
15897 | bool StmtExprMayBindToTemp = false; | ||||
15898 | if (!Compound->body_empty()) { | ||||
15899 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | ||||
15900 | if (const auto *LastStmt = | ||||
15901 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | ||||
15902 | if (const Expr *Value = LastStmt->getExprStmt()) { | ||||
15903 | StmtExprMayBindToTemp = true; | ||||
15904 | Ty = Value->getType(); | ||||
15905 | } | ||||
15906 | } | ||||
15907 | } | ||||
15908 | |||||
15909 | // FIXME: Check that expression type is complete/non-abstract; statement | ||||
15910 | // expressions are not lvalues. | ||||
15911 | Expr *ResStmtExpr = | ||||
15912 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | ||||
15913 | if (StmtExprMayBindToTemp) | ||||
15914 | return MaybeBindToTemporary(ResStmtExpr); | ||||
15915 | return ResStmtExpr; | ||||
15916 | } | ||||
15917 | |||||
15918 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | ||||
15919 | if (ER.isInvalid()) | ||||
15920 | return ExprError(); | ||||
15921 | |||||
15922 | // Do function/array conversion on the last expression, but not | ||||
15923 | // lvalue-to-rvalue. However, initialize an unqualified type. | ||||
15924 | ER = DefaultFunctionArrayConversion(ER.get()); | ||||
15925 | if (ER.isInvalid()) | ||||
15926 | return ExprError(); | ||||
15927 | Expr *E = ER.get(); | ||||
15928 | |||||
15929 | if (E->isTypeDependent()) | ||||
15930 | return E; | ||||
15931 | |||||
15932 | // In ARC, if the final expression ends in a consume, splice | ||||
15933 | // the consume out and bind it later. In the alternate case | ||||
15934 | // (when dealing with a retainable type), the result | ||||
15935 | // initialization will create a produce. In both cases the | ||||
15936 | // result will be +1, and we'll need to balance that out with | ||||
15937 | // a bind. | ||||
15938 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | ||||
15939 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | ||||
15940 | return Cast->getSubExpr(); | ||||
15941 | |||||
15942 | // FIXME: Provide a better location for the initialization. | ||||
15943 | return PerformCopyInitialization( | ||||
15944 | InitializedEntity::InitializeStmtExprResult( | ||||
15945 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | ||||
15946 | SourceLocation(), E); | ||||
15947 | } | ||||
15948 | |||||
15949 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | ||||
15950 | TypeSourceInfo *TInfo, | ||||
15951 | ArrayRef<OffsetOfComponent> Components, | ||||
15952 | SourceLocation RParenLoc) { | ||||
15953 | QualType ArgTy = TInfo->getType(); | ||||
15954 | bool Dependent = ArgTy->isDependentType(); | ||||
15955 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | ||||
15956 | |||||
15957 | // We must have at least one component that refers to the type, and the first | ||||
15958 | // one is known to be a field designator. Verify that the ArgTy represents | ||||
15959 | // a struct/union/class. | ||||
15960 | if (!Dependent && !ArgTy->isRecordType()) | ||||
15961 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | ||||
15962 | << ArgTy << TypeRange); | ||||
15963 | |||||
15964 | // Type must be complete per C99 7.17p3 because a declaring a variable | ||||
15965 | // with an incomplete type would be ill-formed. | ||||
15966 | if (!Dependent | ||||
15967 | && RequireCompleteType(BuiltinLoc, ArgTy, | ||||
15968 | diag::err_offsetof_incomplete_type, TypeRange)) | ||||
15969 | return ExprError(); | ||||
15970 | |||||
15971 | bool DidWarnAboutNonPOD = false; | ||||
15972 | QualType CurrentType = ArgTy; | ||||
15973 | SmallVector<OffsetOfNode, 4> Comps; | ||||
15974 | SmallVector<Expr*, 4> Exprs; | ||||
15975 | for (const OffsetOfComponent &OC : Components) { | ||||
15976 | if (OC.isBrackets) { | ||||
15977 | // Offset of an array sub-field. TODO: Should we allow vector elements? | ||||
15978 | if (!CurrentType->isDependentType()) { | ||||
15979 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | ||||
15980 | if(!AT) | ||||
15981 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | ||||
15982 | << CurrentType); | ||||
15983 | CurrentType = AT->getElementType(); | ||||
15984 | } else | ||||
15985 | CurrentType = Context.DependentTy; | ||||
15986 | |||||
15987 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | ||||
15988 | if (IdxRval.isInvalid()) | ||||
15989 | return ExprError(); | ||||
15990 | Expr *Idx = IdxRval.get(); | ||||
15991 | |||||
15992 | // The expression must be an integral expression. | ||||
15993 | // FIXME: An integral constant expression? | ||||
15994 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | ||||
15995 | !Idx->getType()->isIntegerType()) | ||||
15996 | return ExprError( | ||||
15997 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | ||||
15998 | << Idx->getSourceRange()); | ||||
15999 | |||||
16000 | // Record this array index. | ||||
16001 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | ||||
16002 | Exprs.push_back(Idx); | ||||
16003 | continue; | ||||
16004 | } | ||||
16005 | |||||
16006 | // Offset of a field. | ||||
16007 | if (CurrentType->isDependentType()) { | ||||
16008 | // We have the offset of a field, but we can't look into the dependent | ||||
16009 | // type. Just record the identifier of the field. | ||||
16010 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | ||||
16011 | CurrentType = Context.DependentTy; | ||||
16012 | continue; | ||||
16013 | } | ||||
16014 | |||||
16015 | // We need to have a complete type to look into. | ||||
16016 | if (RequireCompleteType(OC.LocStart, CurrentType, | ||||
16017 | diag::err_offsetof_incomplete_type)) | ||||
16018 | return ExprError(); | ||||
16019 | |||||
16020 | // Look for the designated field. | ||||
16021 | const RecordType *RC = CurrentType->getAs<RecordType>(); | ||||
16022 | if (!RC) | ||||
16023 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | ||||
16024 | << CurrentType); | ||||
16025 | RecordDecl *RD = RC->getDecl(); | ||||
16026 | |||||
16027 | // C++ [lib.support.types]p5: | ||||
16028 | // The macro offsetof accepts a restricted set of type arguments in this | ||||
16029 | // International Standard. type shall be a POD structure or a POD union | ||||
16030 | // (clause 9). | ||||
16031 | // C++11 [support.types]p4: | ||||
16032 | // If type is not a standard-layout class (Clause 9), the results are | ||||
16033 | // undefined. | ||||
16034 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
16035 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | ||||
16036 | unsigned DiagID = | ||||
16037 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | ||||
16038 | : diag::ext_offsetof_non_pod_type; | ||||
16039 | |||||
16040 | if (!IsSafe && !DidWarnAboutNonPOD && | ||||
16041 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | ||||
16042 | PDiag(DiagID) | ||||
16043 | << SourceRange(Components[0].LocStart, OC.LocEnd) | ||||
16044 | << CurrentType)) | ||||
16045 | DidWarnAboutNonPOD = true; | ||||
16046 | } | ||||
16047 | |||||
16048 | // Look for the field. | ||||
16049 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | ||||
16050 | LookupQualifiedName(R, RD); | ||||
16051 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | ||||
16052 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | ||||
16053 | if (!MemberDecl) { | ||||
16054 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | ||||
16055 | MemberDecl = IndirectMemberDecl->getAnonField(); | ||||
16056 | } | ||||
16057 | |||||
16058 | if (!MemberDecl) | ||||
16059 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | ||||
16060 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | ||||
16061 | OC.LocEnd)); | ||||
16062 | |||||
16063 | // C99 7.17p3: | ||||
16064 | // (If the specified member is a bit-field, the behavior is undefined.) | ||||
16065 | // | ||||
16066 | // We diagnose this as an error. | ||||
16067 | if (MemberDecl->isBitField()) { | ||||
16068 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | ||||
16069 | << MemberDecl->getDeclName() | ||||
16070 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
16071 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | ||||
16072 | return ExprError(); | ||||
16073 | } | ||||
16074 | |||||
16075 | RecordDecl *Parent = MemberDecl->getParent(); | ||||
16076 | if (IndirectMemberDecl) | ||||
16077 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | ||||
16078 | |||||
16079 | // If the member was found in a base class, introduce OffsetOfNodes for | ||||
16080 | // the base class indirections. | ||||
16081 | CXXBasePaths Paths; | ||||
16082 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | ||||
16083 | Paths)) { | ||||
16084 | if (Paths.getDetectedVirtual()) { | ||||
16085 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | ||||
16086 | << MemberDecl->getDeclName() | ||||
16087 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
16088 | return ExprError(); | ||||
16089 | } | ||||
16090 | |||||
16091 | CXXBasePath &Path = Paths.front(); | ||||
16092 | for (const CXXBasePathElement &B : Path) | ||||
16093 | Comps.push_back(OffsetOfNode(B.Base)); | ||||
16094 | } | ||||
16095 | |||||
16096 | if (IndirectMemberDecl) { | ||||
16097 | for (auto *FI : IndirectMemberDecl->chain()) { | ||||
16098 | assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(FI)", "clang/lib/Sema/SemaExpr.cpp" , 16098, __extension__ __PRETTY_FUNCTION__)); | ||||
16099 | Comps.push_back(OffsetOfNode(OC.LocStart, | ||||
16100 | cast<FieldDecl>(FI), OC.LocEnd)); | ||||
16101 | } | ||||
16102 | } else | ||||
16103 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | ||||
16104 | |||||
16105 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
16106 | } | ||||
16107 | |||||
16108 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | ||||
16109 | Comps, Exprs, RParenLoc); | ||||
16110 | } | ||||
16111 | |||||
16112 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | ||||
16113 | SourceLocation BuiltinLoc, | ||||
16114 | SourceLocation TypeLoc, | ||||
16115 | ParsedType ParsedArgTy, | ||||
16116 | ArrayRef<OffsetOfComponent> Components, | ||||
16117 | SourceLocation RParenLoc) { | ||||
16118 | |||||
16119 | TypeSourceInfo *ArgTInfo; | ||||
16120 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | ||||
16121 | if (ArgTy.isNull()) | ||||
16122 | return ExprError(); | ||||
16123 | |||||
16124 | if (!ArgTInfo) | ||||
16125 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | ||||
16126 | |||||
16127 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | ||||
16128 | } | ||||
16129 | |||||
16130 | |||||
16131 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | ||||
16132 | Expr *CondExpr, | ||||
16133 | Expr *LHSExpr, Expr *RHSExpr, | ||||
16134 | SourceLocation RPLoc) { | ||||
16135 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast <bool> ((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? void (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "clang/lib/Sema/SemaExpr.cpp", 16135, __extension__ __PRETTY_FUNCTION__ )); | ||||
16136 | |||||
16137 | ExprValueKind VK = VK_PRValue; | ||||
16138 | ExprObjectKind OK = OK_Ordinary; | ||||
16139 | QualType resType; | ||||
16140 | bool CondIsTrue = false; | ||||
16141 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | ||||
16142 | resType = Context.DependentTy; | ||||
16143 | } else { | ||||
16144 | // The conditional expression is required to be a constant expression. | ||||
16145 | llvm::APSInt condEval(32); | ||||
16146 | ExprResult CondICE = VerifyIntegerConstantExpression( | ||||
16147 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | ||||
16148 | if (CondICE.isInvalid()) | ||||
16149 | return ExprError(); | ||||
16150 | CondExpr = CondICE.get(); | ||||
16151 | CondIsTrue = condEval.getZExtValue(); | ||||
16152 | |||||
16153 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | ||||
16154 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | ||||
16155 | |||||
16156 | resType = ActiveExpr->getType(); | ||||
16157 | VK = ActiveExpr->getValueKind(); | ||||
16158 | OK = ActiveExpr->getObjectKind(); | ||||
16159 | } | ||||
16160 | |||||
16161 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | ||||
16162 | resType, VK, OK, RPLoc, CondIsTrue); | ||||
16163 | } | ||||
16164 | |||||
16165 | //===----------------------------------------------------------------------===// | ||||
16166 | // Clang Extensions. | ||||
16167 | //===----------------------------------------------------------------------===// | ||||
16168 | |||||
16169 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | ||||
16170 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | ||||
16171 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | ||||
16172 | |||||
16173 | if (LangOpts.CPlusPlus) { | ||||
16174 | MangleNumberingContext *MCtx; | ||||
16175 | Decl *ManglingContextDecl; | ||||
16176 | std::tie(MCtx, ManglingContextDecl) = | ||||
16177 | getCurrentMangleNumberContext(Block->getDeclContext()); | ||||
16178 | if (MCtx) { | ||||
16179 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | ||||
16180 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | ||||
16181 | } | ||||
16182 | } | ||||
16183 | |||||
16184 | PushBlockScope(CurScope, Block); | ||||
16185 | CurContext->addDecl(Block); | ||||
16186 | if (CurScope) | ||||
16187 | PushDeclContext(CurScope, Block); | ||||
16188 | else | ||||
16189 | CurContext = Block; | ||||
16190 | |||||
16191 | getCurBlock()->HasImplicitReturnType = true; | ||||
16192 | |||||
16193 | // Enter a new evaluation context to insulate the block from any | ||||
16194 | // cleanups from the enclosing full-expression. | ||||
16195 | PushExpressionEvaluationContext( | ||||
16196 | ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
16197 | } | ||||
16198 | |||||
16199 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | ||||
16200 | Scope *CurScope) { | ||||
16201 | assert(ParamInfo.getIdentifier() == nullptr &&(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "clang/lib/Sema/SemaExpr.cpp", 16202, __extension__ __PRETTY_FUNCTION__ )) | ||||
16202 | "block-id should have no identifier!")(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "clang/lib/Sema/SemaExpr.cpp", 16202, __extension__ __PRETTY_FUNCTION__ )); | ||||
16203 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext ::BlockLiteral) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "clang/lib/Sema/SemaExpr.cpp", 16203, __extension__ __PRETTY_FUNCTION__ )); | ||||
16204 | BlockScopeInfo *CurBlock = getCurBlock(); | ||||
16205 | |||||
16206 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | ||||
16207 | QualType T = Sig->getType(); | ||||
16208 | |||||
16209 | // FIXME: We should allow unexpanded parameter packs here, but that would, | ||||
16210 | // in turn, make the block expression contain unexpanded parameter packs. | ||||
16211 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | ||||
16212 | // Drop the parameters. | ||||
16213 | FunctionProtoType::ExtProtoInfo EPI; | ||||
16214 | EPI.HasTrailingReturn = false; | ||||
16215 | EPI.TypeQuals.addConst(); | ||||
16216 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | ||||
16217 | Sig = Context.getTrivialTypeSourceInfo(T); | ||||
16218 | } | ||||
16219 | |||||
16220 | // GetTypeForDeclarator always produces a function type for a block | ||||
16221 | // literal signature. Furthermore, it is always a FunctionProtoType | ||||
16222 | // unless the function was written with a typedef. | ||||
16223 | assert(T->isFunctionType() &&(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "clang/lib/Sema/SemaExpr.cpp", 16224, __extension__ __PRETTY_FUNCTION__ )) | ||||
16224 | "GetTypeForDeclarator made a non-function block signature")(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "clang/lib/Sema/SemaExpr.cpp", 16224, __extension__ __PRETTY_FUNCTION__ )); | ||||
16225 | |||||
16226 | // Look for an explicit signature in that function type. | ||||
16227 | FunctionProtoTypeLoc ExplicitSignature; | ||||
16228 | |||||
16229 | if ((ExplicitSignature = Sig->getTypeLoc() | ||||
16230 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | ||||
16231 | |||||
16232 | // Check whether that explicit signature was synthesized by | ||||
16233 | // GetTypeForDeclarator. If so, don't save that as part of the | ||||
16234 | // written signature. | ||||
16235 | if (ExplicitSignature.getLocalRangeBegin() == | ||||
16236 | ExplicitSignature.getLocalRangeEnd()) { | ||||
16237 | // This would be much cheaper if we stored TypeLocs instead of | ||||
16238 | // TypeSourceInfos. | ||||
16239 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | ||||
16240 | unsigned Size = Result.getFullDataSize(); | ||||
16241 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | ||||
16242 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | ||||
16243 | |||||
16244 | ExplicitSignature = FunctionProtoTypeLoc(); | ||||
16245 | } | ||||
16246 | } | ||||
16247 | |||||
16248 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | ||||
16249 | CurBlock->FunctionType = T; | ||||
16250 | |||||
16251 | const auto *Fn = T->castAs<FunctionType>(); | ||||
16252 | QualType RetTy = Fn->getReturnType(); | ||||
16253 | bool isVariadic = | ||||
16254 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | ||||
16255 | |||||
16256 | CurBlock->TheDecl->setIsVariadic(isVariadic); | ||||
16257 | |||||
16258 | // Context.DependentTy is used as a placeholder for a missing block | ||||
16259 | // return type. TODO: what should we do with declarators like: | ||||
16260 | // ^ * { ... } | ||||
16261 | // If the answer is "apply template argument deduction".... | ||||
16262 | if (RetTy != Context.DependentTy) { | ||||
16263 | CurBlock->ReturnType = RetTy; | ||||
16264 | CurBlock->TheDecl->setBlockMissingReturnType(false); | ||||
16265 | CurBlock->HasImplicitReturnType = false; | ||||
16266 | } | ||||
16267 | |||||
16268 | // Push block parameters from the declarator if we had them. | ||||
16269 | SmallVector<ParmVarDecl*, 8> Params; | ||||
16270 | if (ExplicitSignature) { | ||||
16271 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | ||||
16272 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | ||||
16273 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | ||||
16274 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | ||||
16275 | // Diagnose this as an extension in C17 and earlier. | ||||
16276 | if (!getLangOpts().C2x) | ||||
16277 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | ||||
16278 | } | ||||
16279 | Params.push_back(Param); | ||||
16280 | } | ||||
16281 | |||||
16282 | // Fake up parameter variables if we have a typedef, like | ||||
16283 | // ^ fntype { ... } | ||||
16284 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | ||||
16285 | for (const auto &I : Fn->param_types()) { | ||||
16286 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | ||||
16287 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | ||||
16288 | Params.push_back(Param); | ||||
16289 | } | ||||
16290 | } | ||||
16291 | |||||
16292 | // Set the parameters on the block decl. | ||||
16293 | if (!Params.empty()) { | ||||
16294 | CurBlock->TheDecl->setParams(Params); | ||||
16295 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | ||||
16296 | /*CheckParameterNames=*/false); | ||||
16297 | } | ||||
16298 | |||||
16299 | // Finally we can process decl attributes. | ||||
16300 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | ||||
16301 | |||||
16302 | // Put the parameter variables in scope. | ||||
16303 | for (auto *AI : CurBlock->TheDecl->parameters()) { | ||||
16304 | AI->setOwningFunction(CurBlock->TheDecl); | ||||
16305 | |||||
16306 | // If this has an identifier, add it to the scope stack. | ||||
16307 | if (AI->getIdentifier()) { | ||||
16308 | CheckShadow(CurBlock->TheScope, AI); | ||||
16309 | |||||
16310 | PushOnScopeChains(AI, CurBlock->TheScope); | ||||
16311 | } | ||||
16312 | } | ||||
16313 | } | ||||
16314 | |||||
16315 | /// ActOnBlockError - If there is an error parsing a block, this callback | ||||
16316 | /// is invoked to pop the information about the block from the action impl. | ||||
16317 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | ||||
16318 | // Leave the expression-evaluation context. | ||||
16319 | DiscardCleanupsInEvaluationContext(); | ||||
16320 | PopExpressionEvaluationContext(); | ||||
16321 | |||||
16322 | // Pop off CurBlock, handle nested blocks. | ||||
16323 | PopDeclContext(); | ||||
16324 | PopFunctionScopeInfo(); | ||||
16325 | } | ||||
16326 | |||||
16327 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | ||||
16328 | /// literal was successfully completed. ^(int x){...} | ||||
16329 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | ||||
16330 | Stmt *Body, Scope *CurScope) { | ||||
16331 | // If blocks are disabled, emit an error. | ||||
16332 | if (!LangOpts.Blocks) | ||||
16333 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||
16334 | |||||
16335 | // Leave the expression-evaluation context. | ||||
16336 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
16337 | DiscardCleanupsInEvaluationContext(); | ||||
16338 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 16339, __extension__ __PRETTY_FUNCTION__ )) | ||||
16339 | "cleanups within block not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "clang/lib/Sema/SemaExpr.cpp", 16339, __extension__ __PRETTY_FUNCTION__ )); | ||||
16340 | PopExpressionEvaluationContext(); | ||||
16341 | |||||
16342 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | ||||
16343 | BlockDecl *BD = BSI->TheDecl; | ||||
16344 | |||||
16345 | if (BSI->HasImplicitReturnType) | ||||
16346 | deduceClosureReturnType(*BSI); | ||||
16347 | |||||
16348 | QualType RetTy = Context.VoidTy; | ||||
16349 | if (!BSI->ReturnType.isNull()) | ||||
16350 | RetTy = BSI->ReturnType; | ||||
16351 | |||||
16352 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | ||||
16353 | QualType BlockTy; | ||||
16354 | |||||
16355 | // If the user wrote a function type in some form, try to use that. | ||||
16356 | if (!BSI->FunctionType.isNull()) { | ||||
16357 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | ||||
16358 | |||||
16359 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | ||||
16360 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | ||||
16361 | |||||
16362 | // Turn protoless block types into nullary block types. | ||||
16363 | if (isa<FunctionNoProtoType>(FTy)) { | ||||
16364 | FunctionProtoType::ExtProtoInfo EPI; | ||||
16365 | EPI.ExtInfo = Ext; | ||||
16366 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
16367 | |||||
16368 | // Otherwise, if we don't need to change anything about the function type, | ||||
16369 | // preserve its sugar structure. | ||||
16370 | } else if (FTy->getReturnType() == RetTy && | ||||
16371 | (!NoReturn || FTy->getNoReturnAttr())) { | ||||
16372 | BlockTy = BSI->FunctionType; | ||||
16373 | |||||
16374 | // Otherwise, make the minimal modifications to the function type. | ||||
16375 | } else { | ||||
16376 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | ||||
16377 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
16378 | EPI.TypeQuals = Qualifiers(); | ||||
16379 | EPI.ExtInfo = Ext; | ||||
16380 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | ||||
16381 | } | ||||
16382 | |||||
16383 | // If we don't have a function type, just build one from nothing. | ||||
16384 | } else { | ||||
16385 | FunctionProtoType::ExtProtoInfo EPI; | ||||
16386 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | ||||
16387 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
16388 | } | ||||
16389 | |||||
16390 | DiagnoseUnusedParameters(BD->parameters()); | ||||
16391 | BlockTy = Context.getBlockPointerType(BlockTy); | ||||
16392 | |||||
16393 | // If needed, diagnose invalid gotos and switches in the block. | ||||
16394 | if (getCurFunction()->NeedsScopeChecking() && | ||||
16395 | !PP.isCodeCompletionEnabled()) | ||||
16396 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | ||||
16397 | |||||
16398 | BD->setBody(cast<CompoundStmt>(Body)); | ||||
16399 | |||||
16400 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||
16401 | DiagnoseUnguardedAvailabilityViolations(BD); | ||||
16402 | |||||
16403 | // Try to apply the named return value optimization. We have to check again | ||||
16404 | // if we can do this, though, because blocks keep return statements around | ||||
16405 | // to deduce an implicit return type. | ||||
16406 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | ||||
16407 | !BD->isDependentContext()) | ||||
16408 | computeNRVO(Body, BSI); | ||||
16409 | |||||
16410 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | ||||
16411 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
16412 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | ||||
16413 | NTCUK_Destruct|NTCUK_Copy); | ||||
16414 | |||||
16415 | PopDeclContext(); | ||||
16416 | |||||
16417 | // Set the captured variables on the block. | ||||
16418 | SmallVector<BlockDecl::Capture, 4> Captures; | ||||
16419 | for (Capture &Cap : BSI->Captures) { | ||||
16420 | if (Cap.isInvalid() || Cap.isThisCapture()) | ||||
16421 | continue; | ||||
16422 | // Cap.getVariable() is always a VarDecl because | ||||
16423 | // blocks cannot capture structured bindings or other ValueDecl kinds. | ||||
16424 | auto *Var = cast<VarDecl>(Cap.getVariable()); | ||||
16425 | Expr *CopyExpr = nullptr; | ||||
16426 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | ||||
16427 | if (const RecordType *Record = | ||||
16428 | Cap.getCaptureType()->getAs<RecordType>()) { | ||||
16429 | // The capture logic needs the destructor, so make sure we mark it. | ||||
16430 | // Usually this is unnecessary because most local variables have | ||||
16431 | // their destructors marked at declaration time, but parameters are | ||||
16432 | // an exception because it's technically only the call site that | ||||
16433 | // actually requires the destructor. | ||||
16434 | if (isa<ParmVarDecl>(Var)) | ||||
16435 | FinalizeVarWithDestructor(Var, Record); | ||||
16436 | |||||
16437 | // Enter a separate potentially-evaluated context while building block | ||||
16438 | // initializers to isolate their cleanups from those of the block | ||||
16439 | // itself. | ||||
16440 | // FIXME: Is this appropriate even when the block itself occurs in an | ||||
16441 | // unevaluated operand? | ||||
16442 | EnterExpressionEvaluationContext EvalContext( | ||||
16443 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
16444 | |||||
16445 | SourceLocation Loc = Cap.getLocation(); | ||||
16446 | |||||
16447 | ExprResult Result = BuildDeclarationNameExpr( | ||||
16448 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | ||||
16449 | |||||
16450 | // According to the blocks spec, the capture of a variable from | ||||
16451 | // the stack requires a const copy constructor. This is not true | ||||
16452 | // of the copy/move done to move a __block variable to the heap. | ||||
16453 | if (!Result.isInvalid() && | ||||
16454 | !Result.get()->getType().isConstQualified()) { | ||||
16455 | Result = ImpCastExprToType(Result.get(), | ||||
16456 | Result.get()->getType().withConst(), | ||||
16457 | CK_NoOp, VK_LValue); | ||||
16458 | } | ||||
16459 | |||||
16460 | if (!Result.isInvalid()) { | ||||
16461 | Result = PerformCopyInitialization( | ||||
16462 | InitializedEntity::InitializeBlock(Var->getLocation(), | ||||
16463 | Cap.getCaptureType()), | ||||
16464 | Loc, Result.get()); | ||||
16465 | } | ||||
16466 | |||||
16467 | // Build a full-expression copy expression if initialization | ||||
16468 | // succeeded and used a non-trivial constructor. Recover from | ||||
16469 | // errors by pretending that the copy isn't necessary. | ||||
16470 | if (!Result.isInvalid() && | ||||
16471 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | ||||
16472 | ->isTrivial()) { | ||||
16473 | Result = MaybeCreateExprWithCleanups(Result); | ||||
16474 | CopyExpr = Result.get(); | ||||
16475 | } | ||||
16476 | } | ||||
16477 | } | ||||
16478 | |||||
16479 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | ||||
16480 | CopyExpr); | ||||
16481 | Captures.push_back(NewCap); | ||||
16482 | } | ||||
16483 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | ||||
16484 | |||||
16485 | // Pop the block scope now but keep it alive to the end of this function. | ||||
16486 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||
16487 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | ||||
16488 | |||||
16489 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | ||||
16490 | |||||
16491 | // If the block isn't obviously global, i.e. it captures anything at | ||||
16492 | // all, then we need to do a few things in the surrounding context: | ||||
16493 | if (Result->getBlockDecl()->hasCaptures()) { | ||||
16494 | // First, this expression has a new cleanup object. | ||||
16495 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | ||||
16496 | Cleanup.setExprNeedsCleanups(true); | ||||
16497 | |||||
16498 | // It also gets a branch-protected scope if any of the captured | ||||
16499 | // variables needs destruction. | ||||
16500 | for (const auto &CI : Result->getBlockDecl()->captures()) { | ||||
16501 | const VarDecl *var = CI.getVariable(); | ||||
16502 | if (var->getType().isDestructedType() != QualType::DK_none) { | ||||
16503 | setFunctionHasBranchProtectedScope(); | ||||
16504 | break; | ||||
16505 | } | ||||
16506 | } | ||||
16507 | } | ||||
16508 | |||||
16509 | if (getCurFunction()) | ||||
16510 | getCurFunction()->addBlock(BD); | ||||
16511 | |||||
16512 | return Result; | ||||
16513 | } | ||||
16514 | |||||
16515 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | ||||
16516 | SourceLocation RPLoc) { | ||||
16517 | TypeSourceInfo *TInfo; | ||||
16518 | GetTypeFromParser(Ty, &TInfo); | ||||
16519 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | ||||
16520 | } | ||||
16521 | |||||
16522 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | ||||
16523 | Expr *E, TypeSourceInfo *TInfo, | ||||
16524 | SourceLocation RPLoc) { | ||||
16525 | Expr *OrigExpr = E; | ||||
16526 | bool IsMS = false; | ||||
16527 | |||||
16528 | // CUDA device code does not support varargs. | ||||
16529 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | ||||
16530 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | ||||
16531 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | ||||
16532 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | ||||
16533 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | ||||
16534 | } | ||||
16535 | } | ||||
16536 | |||||
16537 | // NVPTX does not support va_arg expression. | ||||
16538 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | ||||
16539 | Context.getTargetInfo().getTriple().isNVPTX()) | ||||
16540 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | ||||
16541 | |||||
16542 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | ||||
16543 | // as Microsoft ABI on an actual Microsoft platform, where | ||||
16544 | // __builtin_ms_va_list and __builtin_va_list are the same.) | ||||
16545 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | ||||
16546 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | ||||
16547 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | ||||
16548 | if (Context.hasSameType(MSVaListType, E->getType())) { | ||||
16549 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
16550 | return ExprError(); | ||||
16551 | IsMS = true; | ||||
16552 | } | ||||
16553 | } | ||||
16554 | |||||
16555 | // Get the va_list type | ||||
16556 | QualType VaListType = Context.getBuiltinVaListType(); | ||||
16557 | if (!IsMS) { | ||||
16558 | if (VaListType->isArrayType()) { | ||||
16559 | // Deal with implicit array decay; for example, on x86-64, | ||||
16560 | // va_list is an array, but it's supposed to decay to | ||||
16561 | // a pointer for va_arg. | ||||
16562 | VaListType = Context.getArrayDecayedType(VaListType); | ||||
16563 | // Make sure the input expression also decays appropriately. | ||||
16564 | ExprResult Result = UsualUnaryConversions(E); | ||||
16565 | if (Result.isInvalid()) | ||||
16566 | return ExprError(); | ||||
16567 | E = Result.get(); | ||||
16568 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | ||||
16569 | // If va_list is a record type and we are compiling in C++ mode, | ||||
16570 | // check the argument using reference binding. | ||||
16571 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
16572 | Context, Context.getLValueReferenceType(VaListType), false); | ||||
16573 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | ||||
16574 | if (Init.isInvalid()) | ||||
16575 | return ExprError(); | ||||
16576 | E = Init.getAs<Expr>(); | ||||
16577 | } else { | ||||
16578 | // Otherwise, the va_list argument must be an l-value because | ||||
16579 | // it is modified by va_arg. | ||||
16580 | if (!E->isTypeDependent() && | ||||
16581 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
16582 | return ExprError(); | ||||
16583 | } | ||||
16584 | } | ||||
16585 | |||||
16586 | if (!IsMS && !E->isTypeDependent() && | ||||
16587 | !Context.hasSameType(VaListType, E->getType())) | ||||
16588 | return ExprError( | ||||
16589 | Diag(E->getBeginLoc(), | ||||
16590 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | ||||
16591 | << OrigExpr->getType() << E->getSourceRange()); | ||||
16592 | |||||
16593 | if (!TInfo->getType()->isDependentType()) { | ||||
16594 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | ||||
16595 | diag::err_second_parameter_to_va_arg_incomplete, | ||||
16596 | TInfo->getTypeLoc())) | ||||
16597 | return ExprError(); | ||||
16598 | |||||
16599 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | ||||
16600 | TInfo->getType(), | ||||
16601 | diag::err_second_parameter_to_va_arg_abstract, | ||||
16602 | TInfo->getTypeLoc())) | ||||
16603 | return ExprError(); | ||||
16604 | |||||
16605 | if (!TInfo->getType().isPODType(Context)) { | ||||
16606 | Diag(TInfo->getTypeLoc().getBeginLoc(), | ||||
16607 | TInfo->getType()->isObjCLifetimeType() | ||||
16608 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | ||||
16609 | : diag::warn_second_parameter_to_va_arg_not_pod) | ||||
16610 | << TInfo->getType() | ||||
16611 | << TInfo->getTypeLoc().getSourceRange(); | ||||
16612 | } | ||||
16613 | |||||
16614 | // Check for va_arg where arguments of the given type will be promoted | ||||
16615 | // (i.e. this va_arg is guaranteed to have undefined behavior). | ||||
16616 | QualType PromoteType; | ||||
16617 | if (TInfo->getType()->isPromotableIntegerType()) { | ||||
16618 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | ||||
16619 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, | ||||
16620 | // and C2x 7.16.1.1p2 says, in part: | ||||
16621 | // If type is not compatible with the type of the actual next argument | ||||
16622 | // (as promoted according to the default argument promotions), the | ||||
16623 | // behavior is undefined, except for the following cases: | ||||
16624 | // - both types are pointers to qualified or unqualified versions of | ||||
16625 | // compatible types; | ||||
16626 | // - one type is a signed integer type, the other type is the | ||||
16627 | // corresponding unsigned integer type, and the value is | ||||
16628 | // representable in both types; | ||||
16629 | // - one type is pointer to qualified or unqualified void and the | ||||
16630 | // other is a pointer to a qualified or unqualified character type. | ||||
16631 | // Given that type compatibility is the primary requirement (ignoring | ||||
16632 | // qualifications), you would think we could call typesAreCompatible() | ||||
16633 | // directly to test this. However, in C++, that checks for *same type*, | ||||
16634 | // which causes false positives when passing an enumeration type to | ||||
16635 | // va_arg. Instead, get the underlying type of the enumeration and pass | ||||
16636 | // that. | ||||
16637 | QualType UnderlyingType = TInfo->getType(); | ||||
16638 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) | ||||
16639 | UnderlyingType = ET->getDecl()->getIntegerType(); | ||||
16640 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | ||||
16641 | /*CompareUnqualified*/ true)) | ||||
16642 | PromoteType = QualType(); | ||||
16643 | |||||
16644 | // If the types are still not compatible, we need to test whether the | ||||
16645 | // promoted type and the underlying type are the same except for | ||||
16646 | // signedness. Ask the AST for the correctly corresponding type and see | ||||
16647 | // if that's compatible. | ||||
16648 | if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && | ||||
16649 | PromoteType->isUnsignedIntegerType() != | ||||
16650 | UnderlyingType->isUnsignedIntegerType()) { | ||||
16651 | UnderlyingType = | ||||
16652 | UnderlyingType->isUnsignedIntegerType() | ||||
16653 | ? Context.getCorrespondingSignedType(UnderlyingType) | ||||
16654 | : Context.getCorrespondingUnsignedType(UnderlyingType); | ||||
16655 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | ||||
16656 | /*CompareUnqualified*/ true)) | ||||
16657 | PromoteType = QualType(); | ||||
16658 | } | ||||
16659 | } | ||||
16660 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | ||||
16661 | PromoteType = Context.DoubleTy; | ||||
16662 | if (!PromoteType.isNull()) | ||||
16663 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | ||||
16664 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | ||||
16665 | << TInfo->getType() | ||||
16666 | << PromoteType | ||||
16667 | << TInfo->getTypeLoc().getSourceRange()); | ||||
16668 | } | ||||
16669 | |||||
16670 | QualType T = TInfo->getType().getNonLValueExprType(Context); | ||||
16671 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | ||||
16672 | } | ||||
16673 | |||||
16674 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | ||||
16675 | // The type of __null will be int or long, depending on the size of | ||||
16676 | // pointers on the target. | ||||
16677 | QualType Ty; | ||||
16678 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | ||||
16679 | if (pw == Context.getTargetInfo().getIntWidth()) | ||||
16680 | Ty = Context.IntTy; | ||||
16681 | else if (pw == Context.getTargetInfo().getLongWidth()) | ||||
16682 | Ty = Context.LongTy; | ||||
16683 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | ||||
16684 | Ty = Context.LongLongTy; | ||||
16685 | else { | ||||
16686 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "clang/lib/Sema/SemaExpr.cpp", 16686); | ||||
16687 | } | ||||
16688 | |||||
16689 | return new (Context) GNUNullExpr(Ty, TokenLoc); | ||||
16690 | } | ||||
16691 | |||||
16692 | static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { | ||||
16693 | CXXRecordDecl *ImplDecl = nullptr; | ||||
16694 | |||||
16695 | // Fetch the std::source_location::__impl decl. | ||||
16696 | if (NamespaceDecl *Std = S.getStdNamespace()) { | ||||
16697 | LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), | ||||
16698 | Loc, Sema::LookupOrdinaryName); | ||||
16699 | if (S.LookupQualifiedName(ResultSL, Std)) { | ||||
16700 | if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { | ||||
16701 | LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), | ||||
16702 | Loc, Sema::LookupOrdinaryName); | ||||
16703 | if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && | ||||
16704 | S.LookupQualifiedName(ResultImpl, SLDecl)) { | ||||
16705 | ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); | ||||
16706 | } | ||||
16707 | } | ||||
16708 | } | ||||
16709 | } | ||||
16710 | |||||
16711 | if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { | ||||
16712 | S.Diag(Loc, diag::err_std_source_location_impl_not_found); | ||||
16713 | return nullptr; | ||||
16714 | } | ||||
16715 | |||||
16716 | // Verify that __impl is a trivial struct type, with no base classes, and with | ||||
16717 | // only the four expected fields. | ||||
16718 | if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || | ||||
16719 | ImplDecl->getNumBases() != 0) { | ||||
16720 | S.Diag(Loc, diag::err_std_source_location_impl_malformed); | ||||
16721 | return nullptr; | ||||
16722 | } | ||||
16723 | |||||
16724 | unsigned Count = 0; | ||||
16725 | for (FieldDecl *F : ImplDecl->fields()) { | ||||
16726 | StringRef Name = F->getName(); | ||||
16727 | |||||
16728 | if (Name == "_M_file_name") { | ||||
16729 | if (F->getType() != | ||||
16730 | S.Context.getPointerType(S.Context.CharTy.withConst())) | ||||
16731 | break; | ||||
16732 | Count++; | ||||
16733 | } else if (Name == "_M_function_name") { | ||||
16734 | if (F->getType() != | ||||
16735 | S.Context.getPointerType(S.Context.CharTy.withConst())) | ||||
16736 | break; | ||||
16737 | Count++; | ||||
16738 | } else if (Name == "_M_line") { | ||||
16739 | if (!F->getType()->isIntegerType()) | ||||
16740 | break; | ||||
16741 | Count++; | ||||
16742 | } else if (Name == "_M_column") { | ||||
16743 | if (!F->getType()->isIntegerType()) | ||||
16744 | break; | ||||
16745 | Count++; | ||||
16746 | } else { | ||||
16747 | Count = 100; // invalid | ||||
16748 | break; | ||||
16749 | } | ||||
16750 | } | ||||
16751 | if (Count != 4) { | ||||
16752 | S.Diag(Loc, diag::err_std_source_location_impl_malformed); | ||||
16753 | return nullptr; | ||||
16754 | } | ||||
16755 | |||||
16756 | return ImplDecl; | ||||
16757 | } | ||||
16758 | |||||
16759 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
16760 | SourceLocation BuiltinLoc, | ||||
16761 | SourceLocation RPLoc) { | ||||
16762 | QualType ResultTy; | ||||
16763 | switch (Kind) { | ||||
16764 | case SourceLocExpr::File: | ||||
16765 | case SourceLocExpr::Function: { | ||||
16766 | QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); | ||||
16767 | ResultTy = | ||||
16768 | Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); | ||||
16769 | break; | ||||
16770 | } | ||||
16771 | case SourceLocExpr::Line: | ||||
16772 | case SourceLocExpr::Column: | ||||
16773 | ResultTy = Context.UnsignedIntTy; | ||||
16774 | break; | ||||
16775 | case SourceLocExpr::SourceLocStruct: | ||||
16776 | if (!StdSourceLocationImplDecl) { | ||||
16777 | StdSourceLocationImplDecl = | ||||
16778 | LookupStdSourceLocationImpl(*this, BuiltinLoc); | ||||
16779 | if (!StdSourceLocationImplDecl) | ||||
16780 | return ExprError(); | ||||
16781 | } | ||||
16782 | ResultTy = Context.getPointerType( | ||||
16783 | Context.getRecordType(StdSourceLocationImplDecl).withConst()); | ||||
16784 | break; | ||||
16785 | } | ||||
16786 | |||||
16787 | return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); | ||||
16788 | } | ||||
16789 | |||||
16790 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
16791 | QualType ResultTy, | ||||
16792 | SourceLocation BuiltinLoc, | ||||
16793 | SourceLocation RPLoc, | ||||
16794 | DeclContext *ParentContext) { | ||||
16795 | return new (Context) | ||||
16796 | SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); | ||||
16797 | } | ||||
16798 | |||||
16799 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | ||||
16800 | bool Diagnose) { | ||||
16801 | if (!getLangOpts().ObjC) | ||||
16802 | return false; | ||||
16803 | |||||
16804 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | ||||
16805 | if (!PT) | ||||
16806 | return false; | ||||
16807 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | ||||
16808 | |||||
16809 | // Ignore any parens, implicit casts (should only be | ||||
16810 | // array-to-pointer decays), and not-so-opaque values. The last is | ||||
16811 | // important for making this trigger for property assignments. | ||||
16812 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | ||||
16813 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | ||||
16814 | if (OV->getSourceExpr()) | ||||
16815 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | ||||
16816 | |||||
16817 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | ||||
16818 | if (!PT->isObjCIdType() && | ||||
16819 | !(ID && ID->getIdentifier()->isStr("NSString"))) | ||||
16820 | return false; | ||||
16821 | if (!SL->isOrdinary()) | ||||
16822 | return false; | ||||
16823 | |||||
16824 | if (Diagnose) { | ||||
16825 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
16826 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | ||||
16827 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | ||||
16828 | } | ||||
16829 | return true; | ||||
16830 | } | ||||
16831 | |||||
16832 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | ||||
16833 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | ||||
16834 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | ||||
16835 | !SrcExpr->isNullPointerConstant( | ||||
16836 | getASTContext(), Expr::NPC_NeverValueDependent)) { | ||||
16837 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | ||||
16838 | return false; | ||||
16839 | if (Diagnose) { | ||||
16840 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
16841 | << /*number*/1 | ||||
16842 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | ||||
16843 | Expr *NumLit = | ||||
16844 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | ||||
16845 | if (NumLit) | ||||
16846 | Exp = NumLit; | ||||
16847 | } | ||||
16848 | return true; | ||||
16849 | } | ||||
16850 | |||||
16851 | return false; | ||||
16852 | } | ||||
16853 | |||||
16854 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | ||||
16855 | const Expr *SrcExpr) { | ||||
16856 | if (!DstType->isFunctionPointerType() || | ||||
16857 | !SrcExpr->getType()->isFunctionType()) | ||||
16858 | return false; | ||||
16859 | |||||
16860 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | ||||
16861 | if (!DRE) | ||||
16862 | return false; | ||||
16863 | |||||
16864 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||
16865 | if (!FD) | ||||
16866 | return false; | ||||
16867 | |||||
16868 | return !S.checkAddressOfFunctionIsAvailable(FD, | ||||
16869 | /*Complain=*/true, | ||||
16870 | SrcExpr->getBeginLoc()); | ||||
16871 | } | ||||
16872 | |||||
16873 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | ||||
16874 | SourceLocation Loc, | ||||
16875 | QualType DstType, QualType SrcType, | ||||
16876 | Expr *SrcExpr, AssignmentAction Action, | ||||
16877 | bool *Complained) { | ||||
16878 | if (Complained) | ||||
16879 | *Complained = false; | ||||
16880 | |||||
16881 | // Decode the result (notice that AST's are still created for extensions). | ||||
16882 | bool CheckInferredResultType = false; | ||||
16883 | bool isInvalid = false; | ||||
16884 | unsigned DiagKind = 0; | ||||
16885 | ConversionFixItGenerator ConvHints; | ||||
16886 | bool MayHaveConvFixit = false; | ||||
16887 | bool MayHaveFunctionDiff = false; | ||||
16888 | const ObjCInterfaceDecl *IFace = nullptr; | ||||
16889 | const ObjCProtocolDecl *PDecl = nullptr; | ||||
16890 | |||||
16891 | switch (ConvTy) { | ||||
16892 | case Compatible: | ||||
16893 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | ||||
16894 | return false; | ||||
16895 | |||||
16896 | case PointerToInt: | ||||
16897 | if (getLangOpts().CPlusPlus) { | ||||
16898 | DiagKind = diag::err_typecheck_convert_pointer_int; | ||||
16899 | isInvalid = true; | ||||
16900 | } else { | ||||
16901 | DiagKind = diag::ext_typecheck_convert_pointer_int; | ||||
16902 | } | ||||
16903 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16904 | MayHaveConvFixit = true; | ||||
16905 | break; | ||||
16906 | case IntToPointer: | ||||
16907 | if (getLangOpts().CPlusPlus) { | ||||
16908 | DiagKind = diag::err_typecheck_convert_int_pointer; | ||||
16909 | isInvalid = true; | ||||
16910 | } else { | ||||
16911 | DiagKind = diag::ext_typecheck_convert_int_pointer; | ||||
16912 | } | ||||
16913 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16914 | MayHaveConvFixit = true; | ||||
16915 | break; | ||||
16916 | case IncompatibleFunctionPointer: | ||||
16917 | if (getLangOpts().CPlusPlus) { | ||||
16918 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | ||||
16919 | isInvalid = true; | ||||
16920 | } else { | ||||
16921 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | ||||
16922 | } | ||||
16923 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16924 | MayHaveConvFixit = true; | ||||
16925 | break; | ||||
16926 | case IncompatiblePointer: | ||||
16927 | if (Action == AA_Passing_CFAudited) { | ||||
16928 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | ||||
16929 | } else if (getLangOpts().CPlusPlus) { | ||||
16930 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | ||||
16931 | isInvalid = true; | ||||
16932 | } else { | ||||
16933 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | ||||
16934 | } | ||||
16935 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | ||||
16936 | SrcType->isObjCObjectPointerType(); | ||||
16937 | if (!CheckInferredResultType) { | ||||
16938 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16939 | } else if (CheckInferredResultType) { | ||||
16940 | SrcType = SrcType.getUnqualifiedType(); | ||||
16941 | DstType = DstType.getUnqualifiedType(); | ||||
16942 | } | ||||
16943 | MayHaveConvFixit = true; | ||||
16944 | break; | ||||
16945 | case IncompatiblePointerSign: | ||||
16946 | if (getLangOpts().CPlusPlus) { | ||||
16947 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | ||||
16948 | isInvalid = true; | ||||
16949 | } else { | ||||
16950 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | ||||
16951 | } | ||||
16952 | break; | ||||
16953 | case FunctionVoidPointer: | ||||
16954 | if (getLangOpts().CPlusPlus) { | ||||
16955 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | ||||
16956 | isInvalid = true; | ||||
16957 | } else { | ||||
16958 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | ||||
16959 | } | ||||
16960 | break; | ||||
16961 | case IncompatiblePointerDiscardsQualifiers: { | ||||
16962 | // Perform array-to-pointer decay if necessary. | ||||
16963 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | ||||
16964 | |||||
16965 | isInvalid = true; | ||||
16966 | |||||
16967 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | ||||
16968 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | ||||
16969 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | ||||
16970 | DiagKind = diag::err_typecheck_incompatible_address_space; | ||||
16971 | break; | ||||
16972 | |||||
16973 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | ||||
16974 | DiagKind = diag::err_typecheck_incompatible_ownership; | ||||
16975 | break; | ||||
16976 | } | ||||
16977 | |||||
16978 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "clang/lib/Sema/SemaExpr.cpp", 16978); | ||||
16979 | // fallthrough | ||||
16980 | } | ||||
16981 | case CompatiblePointerDiscardsQualifiers: | ||||
16982 | // If the qualifiers lost were because we were applying the | ||||
16983 | // (deprecated) C++ conversion from a string literal to a char* | ||||
16984 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | ||||
16985 | // Ideally, this check would be performed in | ||||
16986 | // checkPointerTypesForAssignment. However, that would require a | ||||
16987 | // bit of refactoring (so that the second argument is an | ||||
16988 | // expression, rather than a type), which should be done as part | ||||
16989 | // of a larger effort to fix checkPointerTypesForAssignment for | ||||
16990 | // C++ semantics. | ||||
16991 | if (getLangOpts().CPlusPlus && | ||||
16992 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | ||||
16993 | return false; | ||||
16994 | if (getLangOpts().CPlusPlus) { | ||||
16995 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | ||||
16996 | isInvalid = true; | ||||
16997 | } else { | ||||
16998 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | ||||
16999 | } | ||||
17000 | |||||
17001 | break; | ||||
17002 | case IncompatibleNestedPointerQualifiers: | ||||
17003 | if (getLangOpts().CPlusPlus) { | ||||
17004 | isInvalid = true; | ||||
17005 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | ||||
17006 | } else { | ||||
17007 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | ||||
17008 | } | ||||
17009 | break; | ||||
17010 | case IncompatibleNestedPointerAddressSpaceMismatch: | ||||
17011 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | ||||
17012 | isInvalid = true; | ||||
17013 | break; | ||||
17014 | case IntToBlockPointer: | ||||
17015 | DiagKind = diag::err_int_to_block_pointer; | ||||
17016 | isInvalid = true; | ||||
17017 | break; | ||||
17018 | case IncompatibleBlockPointer: | ||||
17019 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | ||||
17020 | isInvalid = true; | ||||
17021 | break; | ||||
17022 | case IncompatibleObjCQualifiedId: { | ||||
17023 | if (SrcType->isObjCQualifiedIdType()) { | ||||
17024 | const ObjCObjectPointerType *srcOPT = | ||||
17025 | SrcType->castAs<ObjCObjectPointerType>(); | ||||
17026 | for (auto *srcProto : srcOPT->quals()) { | ||||
17027 | PDecl = srcProto; | ||||
17028 | break; | ||||
17029 | } | ||||
17030 | if (const ObjCInterfaceType *IFaceT = | ||||
17031 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
17032 | IFace = IFaceT->getDecl(); | ||||
17033 | } | ||||
17034 | else if (DstType->isObjCQualifiedIdType()) { | ||||
17035 | const ObjCObjectPointerType *dstOPT = | ||||
17036 | DstType->castAs<ObjCObjectPointerType>(); | ||||
17037 | for (auto *dstProto : dstOPT->quals()) { | ||||
17038 | PDecl = dstProto; | ||||
17039 | break; | ||||
17040 | } | ||||
17041 | if (const ObjCInterfaceType *IFaceT = | ||||
17042 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
17043 | IFace = IFaceT->getDecl(); | ||||
17044 | } | ||||
17045 | if (getLangOpts().CPlusPlus) { | ||||
17046 | DiagKind = diag::err_incompatible_qualified_id; | ||||
17047 | isInvalid = true; | ||||
17048 | } else { | ||||
17049 | DiagKind = diag::warn_incompatible_qualified_id; | ||||
17050 | } | ||||
17051 | break; | ||||
17052 | } | ||||
17053 | case IncompatibleVectors: | ||||
17054 | if (getLangOpts().CPlusPlus) { | ||||
17055 | DiagKind = diag::err_incompatible_vectors; | ||||
17056 | isInvalid = true; | ||||
17057 | } else { | ||||
17058 | DiagKind = diag::warn_incompatible_vectors; | ||||
17059 | } | ||||
17060 | break; | ||||
17061 | case IncompatibleObjCWeakRef: | ||||
17062 | DiagKind = diag::err_arc_weak_unavailable_assign; | ||||
17063 | isInvalid = true; | ||||
17064 | break; | ||||
17065 | case Incompatible: | ||||
17066 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | ||||
17067 | if (Complained) | ||||
17068 | *Complained = true; | ||||
17069 | return true; | ||||
17070 | } | ||||
17071 | |||||
17072 | DiagKind = diag::err_typecheck_convert_incompatible; | ||||
17073 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
17074 | MayHaveConvFixit = true; | ||||
17075 | isInvalid = true; | ||||
17076 | MayHaveFunctionDiff = true; | ||||
17077 | break; | ||||
17078 | } | ||||
17079 | |||||
17080 | QualType FirstType, SecondType; | ||||
17081 | switch (Action) { | ||||
17082 | case AA_Assigning: | ||||
17083 | case AA_Initializing: | ||||
17084 | // The destination type comes first. | ||||
17085 | FirstType = DstType; | ||||
17086 | SecondType = SrcType; | ||||
17087 | break; | ||||
17088 | |||||
17089 | case AA_Returning: | ||||
17090 | case AA_Passing: | ||||
17091 | case AA_Passing_CFAudited: | ||||
17092 | case AA_Converting: | ||||
17093 | case AA_Sending: | ||||
17094 | case AA_Casting: | ||||
17095 | // The source type comes first. | ||||
17096 | FirstType = SrcType; | ||||
17097 | SecondType = DstType; | ||||
17098 | break; | ||||
17099 | } | ||||
17100 | |||||
17101 | PartialDiagnostic FDiag = PDiag(DiagKind); | ||||
17102 | AssignmentAction ActionForDiag = Action; | ||||
17103 | if (Action == AA_Passing_CFAudited) | ||||
17104 | ActionForDiag = AA_Passing; | ||||
17105 | |||||
17106 | FDiag << FirstType << SecondType << ActionForDiag | ||||
17107 | << SrcExpr->getSourceRange(); | ||||
17108 | |||||
17109 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || | ||||
17110 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { | ||||
17111 | auto isPlainChar = [](const clang::Type *Type) { | ||||
17112 | return Type->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
17113 | Type->isSpecificBuiltinType(BuiltinType::Char_U); | ||||
17114 | }; | ||||
17115 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || | ||||
17116 | isPlainChar(SecondType->getPointeeOrArrayElementType())); | ||||
17117 | } | ||||
17118 | |||||
17119 | // If we can fix the conversion, suggest the FixIts. | ||||
17120 | if (!ConvHints.isNull()) { | ||||
17121 | for (FixItHint &H : ConvHints.Hints) | ||||
17122 | FDiag << H; | ||||
17123 | } | ||||
17124 | |||||
17125 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | ||||
17126 | |||||
17127 | if (MayHaveFunctionDiff) | ||||
17128 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | ||||
17129 | |||||
17130 | Diag(Loc, FDiag); | ||||
17131 | if ((DiagKind == diag::warn_incompatible_qualified_id || | ||||
17132 | DiagKind == diag::err_incompatible_qualified_id) && | ||||
17133 | PDecl && IFace && !IFace->hasDefinition()) | ||||
17134 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | ||||
17135 | << IFace << PDecl; | ||||
17136 | |||||
17137 | if (SecondType == Context.OverloadTy) | ||||
17138 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | ||||
17139 | FirstType, /*TakingAddress=*/true); | ||||
17140 | |||||
17141 | if (CheckInferredResultType) | ||||
17142 | EmitRelatedResultTypeNote(SrcExpr); | ||||
17143 | |||||
17144 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | ||||
17145 | EmitRelatedResultTypeNoteForReturn(DstType); | ||||
17146 | |||||
17147 | if (Complained) | ||||
17148 | *Complained = true; | ||||
17149 | return isInvalid; | ||||
17150 | } | ||||
17151 | |||||
17152 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
17153 | llvm::APSInt *Result, | ||||
17154 | AllowFoldKind CanFold) { | ||||
17155 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | ||||
17156 | public: | ||||
17157 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
17158 | QualType T) override { | ||||
17159 | return S.Diag(Loc, diag::err_ice_not_integral) | ||||
17160 | << T << S.LangOpts.CPlusPlus; | ||||
17161 | } | ||||
17162 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
17163 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
17164 | } | ||||
17165 | } Diagnoser; | ||||
17166 | |||||
17167 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
17168 | } | ||||
17169 | |||||
17170 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
17171 | llvm::APSInt *Result, | ||||
17172 | unsigned DiagID, | ||||
17173 | AllowFoldKind CanFold) { | ||||
17174 | class IDDiagnoser : public VerifyICEDiagnoser { | ||||
17175 | unsigned DiagID; | ||||
17176 | |||||
17177 | public: | ||||
17178 | IDDiagnoser(unsigned DiagID) | ||||
17179 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | ||||
17180 | |||||
17181 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
17182 | return S.Diag(Loc, DiagID); | ||||
17183 | } | ||||
17184 | } Diagnoser(DiagID); | ||||
17185 | |||||
17186 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
17187 | } | ||||
17188 | |||||
17189 | Sema::SemaDiagnosticBuilder | ||||
17190 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
17191 | QualType T) { | ||||
17192 | return diagnoseNotICE(S, Loc); | ||||
17193 | } | ||||
17194 | |||||
17195 | Sema::SemaDiagnosticBuilder | ||||
17196 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | ||||
17197 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
17198 | } | ||||
17199 | |||||
17200 | ExprResult | ||||
17201 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | ||||
17202 | VerifyICEDiagnoser &Diagnoser, | ||||
17203 | AllowFoldKind CanFold) { | ||||
17204 | SourceLocation DiagLoc = E->getBeginLoc(); | ||||
17205 | |||||
17206 | if (getLangOpts().CPlusPlus11) { | ||||
17207 | // C++11 [expr.const]p5: | ||||
17208 | // If an expression of literal class type is used in a context where an | ||||
17209 | // integral constant expression is required, then that class type shall | ||||
17210 | // have a single non-explicit conversion function to an integral or | ||||
17211 | // unscoped enumeration type | ||||
17212 | ExprResult Converted; | ||||
17213 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | ||||
17214 | VerifyICEDiagnoser &BaseDiagnoser; | ||||
17215 | public: | ||||
17216 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | ||||
17217 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | ||||
17218 | BaseDiagnoser.Suppress, true), | ||||
17219 | BaseDiagnoser(BaseDiagnoser) {} | ||||
17220 | |||||
17221 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | ||||
17222 | QualType T) override { | ||||
17223 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | ||||
17224 | } | ||||
17225 | |||||
17226 | SemaDiagnosticBuilder diagnoseIncomplete( | ||||
17227 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
17228 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | ||||
17229 | } | ||||
17230 | |||||
17231 | SemaDiagnosticBuilder diagnoseExplicitConv( | ||||
17232 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
17233 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | ||||
17234 | } | ||||
17235 | |||||
17236 | SemaDiagnosticBuilder noteExplicitConv( | ||||
17237 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
17238 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
17239 | << ConvTy->isEnumeralType() << ConvTy; | ||||
17240 | } | ||||
17241 | |||||
17242 | SemaDiagnosticBuilder diagnoseAmbiguous( | ||||
17243 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
17244 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | ||||
17245 | } | ||||
17246 | |||||
17247 | SemaDiagnosticBuilder noteAmbiguous( | ||||
17248 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
17249 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
17250 | << ConvTy->isEnumeralType() << ConvTy; | ||||
17251 | } | ||||
17252 | |||||
17253 | SemaDiagnosticBuilder diagnoseConversion( | ||||
17254 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
17255 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "clang/lib/Sema/SemaExpr.cpp", 17255); | ||||
17256 | } | ||||
17257 | } ConvertDiagnoser(Diagnoser); | ||||
17258 | |||||
17259 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | ||||
17260 | ConvertDiagnoser); | ||||
17261 | if (Converted.isInvalid()) | ||||
17262 | return Converted; | ||||
17263 | E = Converted.get(); | ||||
17264 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | ||||
17265 | return ExprError(); | ||||
17266 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
17267 | // An ICE must be of integral or unscoped enumeration type. | ||||
17268 | if (!Diagnoser.Suppress) | ||||
17269 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | ||||
17270 | << E->getSourceRange(); | ||||
17271 | return ExprError(); | ||||
17272 | } | ||||
17273 | |||||
17274 | ExprResult RValueExpr = DefaultLvalueConversion(E); | ||||
17275 | if (RValueExpr.isInvalid()) | ||||
17276 | return ExprError(); | ||||
17277 | |||||
17278 | E = RValueExpr.get(); | ||||
17279 | |||||
17280 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | ||||
17281 | // in the non-ICE case. | ||||
17282 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | ||||
17283 | if (Result) | ||||
17284 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | ||||
17285 | if (!isa<ConstantExpr>(E)) | ||||
17286 | E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) | ||||
17287 | : ConstantExpr::Create(Context, E); | ||||
17288 | return E; | ||||
17289 | } | ||||
17290 | |||||
17291 | Expr::EvalResult EvalResult; | ||||
17292 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
17293 | EvalResult.Diag = &Notes; | ||||
17294 | |||||
17295 | // Try to evaluate the expression, and produce diagnostics explaining why it's | ||||
17296 | // not a constant expression as a side-effect. | ||||
17297 | bool Folded = | ||||
17298 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | ||||
17299 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | ||||
17300 | |||||
17301 | if (!isa<ConstantExpr>(E)) | ||||
17302 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | ||||
17303 | |||||
17304 | // In C++11, we can rely on diagnostics being produced for any expression | ||||
17305 | // which is not a constant expression. If no diagnostics were produced, then | ||||
17306 | // this is a constant expression. | ||||
17307 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | ||||
17308 | if (Result) | ||||
17309 | *Result = EvalResult.Val.getInt(); | ||||
17310 | return E; | ||||
17311 | } | ||||
17312 | |||||
17313 | // If our only note is the usual "invalid subexpression" note, just point | ||||
17314 | // the caret at its location rather than producing an essentially | ||||
17315 | // redundant note. | ||||
17316 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||
17317 | diag::note_invalid_subexpr_in_const_expr) { | ||||
17318 | DiagLoc = Notes[0].first; | ||||
17319 | Notes.clear(); | ||||
17320 | } | ||||
17321 | |||||
17322 | if (!Folded || !CanFold) { | ||||
17323 | if (!Diagnoser.Suppress) { | ||||
17324 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | ||||
17325 | for (const PartialDiagnosticAt &Note : Notes) | ||||
17326 | Diag(Note.first, Note.second); | ||||
17327 | } | ||||
17328 | |||||
17329 | return ExprError(); | ||||
17330 | } | ||||
17331 | |||||
17332 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | ||||
17333 | for (const PartialDiagnosticAt &Note : Notes) | ||||
17334 | Diag(Note.first, Note.second); | ||||
17335 | |||||
17336 | if (Result) | ||||
17337 | *Result = EvalResult.Val.getInt(); | ||||
17338 | return E; | ||||
17339 | } | ||||
17340 | |||||
17341 | namespace { | ||||
17342 | // Handle the case where we conclude a expression which we speculatively | ||||
17343 | // considered to be unevaluated is actually evaluated. | ||||
17344 | class TransformToPE : public TreeTransform<TransformToPE> { | ||||
17345 | typedef TreeTransform<TransformToPE> BaseTransform; | ||||
17346 | |||||
17347 | public: | ||||
17348 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | ||||
17349 | |||||
17350 | // Make sure we redo semantic analysis | ||||
17351 | bool AlwaysRebuild() { return true; } | ||||
17352 | bool ReplacingOriginal() { return true; } | ||||
17353 | |||||
17354 | // We need to special-case DeclRefExprs referring to FieldDecls which | ||||
17355 | // are not part of a member pointer formation; normal TreeTransforming | ||||
17356 | // doesn't catch this case because of the way we represent them in the AST. | ||||
17357 | // FIXME: This is a bit ugly; is it really the best way to handle this | ||||
17358 | // case? | ||||
17359 | // | ||||
17360 | // Error on DeclRefExprs referring to FieldDecls. | ||||
17361 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
17362 | if (isa<FieldDecl>(E->getDecl()) && | ||||
17363 | !SemaRef.isUnevaluatedContext()) | ||||
17364 | return SemaRef.Diag(E->getLocation(), | ||||
17365 | diag::err_invalid_non_static_member_use) | ||||
17366 | << E->getDecl() << E->getSourceRange(); | ||||
17367 | |||||
17368 | return BaseTransform::TransformDeclRefExpr(E); | ||||
17369 | } | ||||
17370 | |||||
17371 | // Exception: filter out member pointer formation | ||||
17372 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | ||||
17373 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | ||||
17374 | return E; | ||||
17375 | |||||
17376 | return BaseTransform::TransformUnaryOperator(E); | ||||
17377 | } | ||||
17378 | |||||
17379 | // The body of a lambda-expression is in a separate expression evaluation | ||||
17380 | // context so never needs to be transformed. | ||||
17381 | // FIXME: Ideally we wouldn't transform the closure type either, and would | ||||
17382 | // just recreate the capture expressions and lambda expression. | ||||
17383 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | ||||
17384 | return SkipLambdaBody(E, Body); | ||||
17385 | } | ||||
17386 | }; | ||||
17387 | } | ||||
17388 | |||||
17389 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | ||||
17390 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17391, __extension__ __PRETTY_FUNCTION__ )) | ||||
17391 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17391, __extension__ __PRETTY_FUNCTION__ )); | ||||
17392 | ExprEvalContexts.back().Context = | ||||
17393 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | ||||
17394 | if (isUnevaluatedContext()) | ||||
17395 | return E; | ||||
17396 | return TransformToPE(*this).TransformExpr(E); | ||||
17397 | } | ||||
17398 | |||||
17399 | TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { | ||||
17400 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17401, __extension__ __PRETTY_FUNCTION__ )) | ||||
17401 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "clang/lib/Sema/SemaExpr.cpp", 17401, __extension__ __PRETTY_FUNCTION__ )); | ||||
17402 | ExprEvalContexts.back().Context = | ||||
17403 | ExprEvalContexts[ExprEvalContexts.size() - 2].Context; | ||||
17404 | if (isUnevaluatedContext()) | ||||
17405 | return TInfo; | ||||
17406 | return TransformToPE(*this).TransformType(TInfo); | ||||
17407 | } | ||||
17408 | |||||
17409 | void | ||||
17410 | Sema::PushExpressionEvaluationContext( | ||||
17411 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | ||||
17412 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
17413 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | ||||
17414 | LambdaContextDecl, ExprContext); | ||||
17415 | |||||
17416 | // Discarded statements and immediate contexts nested in other | ||||
17417 | // discarded statements or immediate context are themselves | ||||
17418 | // a discarded statement or an immediate context, respectively. | ||||
17419 | ExprEvalContexts.back().InDiscardedStatement = | ||||
17420 | ExprEvalContexts[ExprEvalContexts.size() - 2] | ||||
17421 | .isDiscardedStatementContext(); | ||||
17422 | ExprEvalContexts.back().InImmediateFunctionContext = | ||||
17423 | ExprEvalContexts[ExprEvalContexts.size() - 2] | ||||
17424 | .isImmediateFunctionContext(); | ||||
17425 | |||||
17426 | Cleanup.reset(); | ||||
17427 | if (!MaybeODRUseExprs.empty()) | ||||
17428 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | ||||
17429 | } | ||||
17430 | |||||
17431 | void | ||||
17432 | Sema::PushExpressionEvaluationContext( | ||||
17433 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | ||||
17434 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
17435 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | ||||
17436 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | ||||
17437 | } | ||||
17438 | |||||
17439 | namespace { | ||||
17440 | |||||
17441 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | ||||
17442 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | ||||
17443 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | ||||
17444 | if (E->getOpcode() == UO_Deref) | ||||
17445 | return CheckPossibleDeref(S, E->getSubExpr()); | ||||
17446 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | ||||
17447 | return CheckPossibleDeref(S, E->getBase()); | ||||
17448 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | ||||
17449 | return CheckPossibleDeref(S, E->getBase()); | ||||
17450 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | ||||
17451 | QualType Inner; | ||||
17452 | QualType Ty = E->getType(); | ||||
17453 | if (const auto *Ptr = Ty->getAs<PointerType>()) | ||||
17454 | Inner = Ptr->getPointeeType(); | ||||
17455 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | ||||
17456 | Inner = Arr->getElementType(); | ||||
17457 | else | ||||
17458 | return nullptr; | ||||
17459 | |||||
17460 | if (Inner->hasAttr(attr::NoDeref)) | ||||
17461 | return E; | ||||
17462 | } | ||||
17463 | return nullptr; | ||||
17464 | } | ||||
17465 | |||||
17466 | } // namespace | ||||
17467 | |||||
17468 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | ||||
17469 | for (const Expr *E : Rec.PossibleDerefs) { | ||||
17470 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | ||||
17471 | if (DeclRef) { | ||||
17472 | const ValueDecl *Decl = DeclRef->getDecl(); | ||||
17473 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | ||||
17474 | << Decl->getName() << E->getSourceRange(); | ||||
17475 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | ||||
17476 | } else { | ||||
17477 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | ||||
17478 | << E->getSourceRange(); | ||||
17479 | } | ||||
17480 | } | ||||
17481 | Rec.PossibleDerefs.clear(); | ||||
17482 | } | ||||
17483 | |||||
17484 | /// Check whether E, which is either a discarded-value expression or an | ||||
17485 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | ||||
17486 | /// and if so, remove it from the list of volatile-qualified assignments that | ||||
17487 | /// we are going to warn are deprecated. | ||||
17488 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | ||||
17489 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | ||||
17490 | return; | ||||
17491 | |||||
17492 | // Note: ignoring parens here is not justified by the standard rules, but | ||||
17493 | // ignoring parentheses seems like a more reasonable approach, and this only | ||||
17494 | // drives a deprecation warning so doesn't affect conformance. | ||||
17495 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | ||||
17496 | if (BO->getOpcode() == BO_Assign) { | ||||
17497 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | ||||
17498 | llvm::erase_value(LHSs, BO->getLHS()); | ||||
17499 | } | ||||
17500 | } | ||||
17501 | } | ||||
17502 | |||||
17503 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | ||||
17504 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || | ||||
17505 | !Decl->isConsteval() || isConstantEvaluated() || | ||||
17506 | RebuildingImmediateInvocation || isImmediateFunctionContext()) | ||||
17507 | return E; | ||||
17508 | |||||
17509 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | ||||
17510 | /// It's OK if this fails; we'll also remove this in | ||||
17511 | /// HandleImmediateInvocations, but catching it here allows us to avoid | ||||
17512 | /// walking the AST looking for it in simple cases. | ||||
17513 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | ||||
17514 | if (auto *DeclRef = | ||||
17515 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | ||||
17516 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | ||||
17517 | |||||
17518 | E = MaybeCreateExprWithCleanups(E); | ||||
17519 | |||||
17520 | ConstantExpr *Res = ConstantExpr::Create( | ||||
17521 | getASTContext(), E.get(), | ||||
17522 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | ||||
17523 | getASTContext()), | ||||
17524 | /*IsImmediateInvocation*/ true); | ||||
17525 | /// Value-dependent constant expressions should not be immediately | ||||
17526 | /// evaluated until they are instantiated. | ||||
17527 | if (!Res->isValueDependent()) | ||||
17528 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | ||||
17529 | return Res; | ||||
17530 | } | ||||
17531 | |||||
17532 | static void EvaluateAndDiagnoseImmediateInvocation( | ||||
17533 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | ||||
17534 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
17535 | Expr::EvalResult Eval; | ||||
17536 | Eval.Diag = &Notes; | ||||
17537 | ConstantExpr *CE = Candidate.getPointer(); | ||||
17538 | bool Result = CE->EvaluateAsConstantExpr( | ||||
17539 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | ||||
17540 | if (!Result || !Notes.empty()) { | ||||
17541 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | ||||
17542 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | ||||
17543 | InnerExpr = FunctionalCast->getSubExpr(); | ||||
17544 | FunctionDecl *FD = nullptr; | ||||
17545 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | ||||
17546 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | ||||
17547 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | ||||
17548 | FD = Call->getConstructor(); | ||||
17549 | else | ||||
17550 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "clang/lib/Sema/SemaExpr.cpp" , 17550); | ||||
17551 | assert(FD->isConsteval())(static_cast <bool> (FD->isConsteval()) ? void (0) : __assert_fail ("FD->isConsteval()", "clang/lib/Sema/SemaExpr.cpp" , 17551, __extension__ __PRETTY_FUNCTION__)); | ||||
17552 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | ||||
17553 | for (auto &Note : Notes) | ||||
17554 | SemaRef.Diag(Note.first, Note.second); | ||||
17555 | return; | ||||
17556 | } | ||||
17557 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | ||||
17558 | } | ||||
17559 | |||||
17560 | static void RemoveNestedImmediateInvocation( | ||||
17561 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | ||||
17562 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | ||||
17563 | struct ComplexRemove : TreeTransform<ComplexRemove> { | ||||
17564 | using Base = TreeTransform<ComplexRemove>; | ||||
17565 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
17566 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | ||||
17567 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | ||||
17568 | CurrentII; | ||||
17569 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | ||||
17570 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | ||||
17571 | SmallVector<Sema::ImmediateInvocationCandidate, | ||||
17572 | 4>::reverse_iterator Current) | ||||
17573 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | ||||
17574 | void RemoveImmediateInvocation(ConstantExpr* E) { | ||||
17575 | auto It = std::find_if(CurrentII, IISet.rend(), | ||||
17576 | [E](Sema::ImmediateInvocationCandidate Elem) { | ||||
17577 | return Elem.getPointer() == E; | ||||
17578 | }); | ||||
17579 | assert(It != IISet.rend() &&(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 17581, __extension__ __PRETTY_FUNCTION__ )) | ||||
17580 | "ConstantExpr marked IsImmediateInvocation should "(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 17581, __extension__ __PRETTY_FUNCTION__ )) | ||||
17581 | "be present")(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "clang/lib/Sema/SemaExpr.cpp", 17581, __extension__ __PRETTY_FUNCTION__ )); | ||||
17582 | It->setInt(1); // Mark as deleted | ||||
17583 | } | ||||
17584 | ExprResult TransformConstantExpr(ConstantExpr *E) { | ||||
17585 | if (!E->isImmediateInvocation()) | ||||
17586 | return Base::TransformConstantExpr(E); | ||||
17587 | RemoveImmediateInvocation(E); | ||||
17588 | return Base::TransformExpr(E->getSubExpr()); | ||||
17589 | } | ||||
17590 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | ||||
17591 | /// we need to remove its DeclRefExpr from the DRSet. | ||||
17592 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
17593 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | ||||
17594 | return Base::TransformCXXOperatorCallExpr(E); | ||||
17595 | } | ||||
17596 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | ||||
17597 | /// here. | ||||
17598 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | ||||
17599 | if (!Init) | ||||
17600 | return Init; | ||||
17601 | /// ConstantExpr are the first layer of implicit node to be removed so if | ||||
17602 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | ||||
17603 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||
17604 | if (CE->isImmediateInvocation()) | ||||
17605 | RemoveImmediateInvocation(CE); | ||||
17606 | return Base::TransformInitializer(Init, NotCopyInit); | ||||
17607 | } | ||||
17608 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
17609 | DRSet.erase(E); | ||||
17610 | return E; | ||||
17611 | } | ||||
17612 | ExprResult TransformLambdaExpr(LambdaExpr *E) { | ||||
17613 | // Do not rebuild lambdas to avoid creating a new type. | ||||
17614 | // Lambdas have already been processed inside their eval context. | ||||
17615 | return E; | ||||
17616 | } | ||||
17617 | bool AlwaysRebuild() { return false; } | ||||
17618 | bool ReplacingOriginal() { return true; } | ||||
17619 | bool AllowSkippingCXXConstructExpr() { | ||||
17620 | bool Res = AllowSkippingFirstCXXConstructExpr; | ||||
17621 | AllowSkippingFirstCXXConstructExpr = true; | ||||
17622 | return Res; | ||||
17623 | } | ||||
17624 | bool AllowSkippingFirstCXXConstructExpr = true; | ||||
17625 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | ||||
17626 | Rec.ImmediateInvocationCandidates, It); | ||||
17627 | |||||
17628 | /// CXXConstructExpr with a single argument are getting skipped by | ||||
17629 | /// TreeTransform in some situtation because they could be implicit. This | ||||
17630 | /// can only occur for the top-level CXXConstructExpr because it is used | ||||
17631 | /// nowhere in the expression being transformed therefore will not be rebuilt. | ||||
17632 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | ||||
17633 | /// skipping the first CXXConstructExpr. | ||||
17634 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | ||||
17635 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | ||||
17636 | |||||
17637 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | ||||
17638 | // The result may not be usable in case of previous compilation errors. | ||||
17639 | // In this case evaluation of the expression may result in crash so just | ||||
17640 | // don't do anything further with the result. | ||||
17641 | if (Res.isUsable()) { | ||||
17642 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | ||||
17643 | It->getPointer()->setSubExpr(Res.get()); | ||||
17644 | } | ||||
17645 | } | ||||
17646 | |||||
17647 | static void | ||||
17648 | HandleImmediateInvocations(Sema &SemaRef, | ||||
17649 | Sema::ExpressionEvaluationContextRecord &Rec) { | ||||
17650 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | ||||
17651 | Rec.ReferenceToConsteval.size() == 0) || | ||||
17652 | SemaRef.RebuildingImmediateInvocation) | ||||
17653 | return; | ||||
17654 | |||||
17655 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | ||||
17656 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | ||||
17657 | /// need to remove ReferenceToConsteval in the immediate invocation. | ||||
17658 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | ||||
17659 | |||||
17660 | /// Prevent sema calls during the tree transform from adding pointers that | ||||
17661 | /// are already in the sets. | ||||
17662 | llvm::SaveAndRestore<bool> DisableIITracking( | ||||
17663 | SemaRef.RebuildingImmediateInvocation, true); | ||||
17664 | |||||
17665 | /// Prevent diagnostic during tree transfrom as they are duplicates | ||||
17666 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | ||||
17667 | |||||
17668 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | ||||
17669 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | ||||
17670 | if (!It->getInt()) | ||||
17671 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | ||||
17672 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | ||||
17673 | Rec.ReferenceToConsteval.size()) { | ||||
17674 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | ||||
17675 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
17676 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | ||||
17677 | bool VisitDeclRefExpr(DeclRefExpr *E) { | ||||
17678 | DRSet.erase(E); | ||||
17679 | return DRSet.size(); | ||||
17680 | } | ||||
17681 | } Visitor(Rec.ReferenceToConsteval); | ||||
17682 | Visitor.TraverseStmt( | ||||
17683 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | ||||
17684 | } | ||||
17685 | for (auto CE : Rec.ImmediateInvocationCandidates) | ||||
17686 | if (!CE.getInt()) | ||||
17687 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | ||||
17688 | for (auto *DR : Rec.ReferenceToConsteval) { | ||||
17689 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | ||||
17690 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | ||||
17691 | << FD; | ||||
17692 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | ||||
17693 | } | ||||
17694 | } | ||||
17695 | |||||
17696 | void Sema::PopExpressionEvaluationContext() { | ||||
17697 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | ||||
17698 | unsigned NumTypos = Rec.NumTypos; | ||||
17699 | |||||
17700 | if (!Rec.Lambdas.empty()) { | ||||
17701 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | ||||
17702 | if (!getLangOpts().CPlusPlus20 && | ||||
17703 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || | ||||
17704 | Rec.isUnevaluated() || | ||||
17705 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { | ||||
17706 | unsigned D; | ||||
17707 | if (Rec.isUnevaluated()) { | ||||
17708 | // C++11 [expr.prim.lambda]p2: | ||||
17709 | // A lambda-expression shall not appear in an unevaluated operand | ||||
17710 | // (Clause 5). | ||||
17711 | D = diag::err_lambda_unevaluated_operand; | ||||
17712 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | ||||
17713 | // C++1y [expr.const]p2: | ||||
17714 | // A conditional-expression e is a core constant expression unless the | ||||
17715 | // evaluation of e, following the rules of the abstract machine, would | ||||
17716 | // evaluate [...] a lambda-expression. | ||||
17717 | D = diag::err_lambda_in_constant_expression; | ||||
17718 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | ||||
17719 | // C++17 [expr.prim.lamda]p2: | ||||
17720 | // A lambda-expression shall not appear [...] in a template-argument. | ||||
17721 | D = diag::err_lambda_in_invalid_context; | ||||
17722 | } else | ||||
17723 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "clang/lib/Sema/SemaExpr.cpp", 17723); | ||||
17724 | |||||
17725 | for (const auto *L : Rec.Lambdas) | ||||
17726 | Diag(L->getBeginLoc(), D); | ||||
17727 | } | ||||
17728 | } | ||||
17729 | |||||
17730 | WarnOnPendingNoDerefs(Rec); | ||||
17731 | HandleImmediateInvocations(*this, Rec); | ||||
17732 | |||||
17733 | // Warn on any volatile-qualified simple-assignments that are not discarded- | ||||
17734 | // value expressions nor unevaluated operands (those cases get removed from | ||||
17735 | // this list by CheckUnusedVolatileAssignment). | ||||
17736 | for (auto *BO : Rec.VolatileAssignmentLHSs) | ||||
17737 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | ||||
17738 | << BO->getType(); | ||||
17739 | |||||
17740 | // When are coming out of an unevaluated context, clear out any | ||||
17741 | // temporaries that we may have created as part of the evaluation of | ||||
17742 | // the expression in that context: they aren't relevant because they | ||||
17743 | // will never be constructed. | ||||
17744 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | ||||
17745 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | ||||
17746 | ExprCleanupObjects.end()); | ||||
17747 | Cleanup = Rec.ParentCleanup; | ||||
17748 | CleanupVarDeclMarking(); | ||||
17749 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | ||||
17750 | // Otherwise, merge the contexts together. | ||||
17751 | } else { | ||||
17752 | Cleanup.mergeFrom(Rec.ParentCleanup); | ||||
17753 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | ||||
17754 | Rec.SavedMaybeODRUseExprs.end()); | ||||
17755 | } | ||||
17756 | |||||
17757 | // Pop the current expression evaluation context off the stack. | ||||
17758 | ExprEvalContexts.pop_back(); | ||||
17759 | |||||
17760 | // The global expression evaluation context record is never popped. | ||||
17761 | ExprEvalContexts.back().NumTypos += NumTypos; | ||||
17762 | } | ||||
17763 | |||||
17764 | void Sema::DiscardCleanupsInEvaluationContext() { | ||||
17765 | ExprCleanupObjects.erase( | ||||
17766 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | ||||
17767 | ExprCleanupObjects.end()); | ||||
17768 | Cleanup.reset(); | ||||
17769 | MaybeODRUseExprs.clear(); | ||||
17770 | } | ||||
17771 | |||||
17772 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | ||||
17773 | ExprResult Result = CheckPlaceholderExpr(E); | ||||
17774 | if (Result.isInvalid()) | ||||
17775 | return ExprError(); | ||||
17776 | E = Result.get(); | ||||
17777 | if (!E->getType()->isVariablyModifiedType()) | ||||
17778 | return E; | ||||
17779 | return TransformToPotentiallyEvaluated(E); | ||||
17780 | } | ||||
17781 | |||||
17782 | /// Are we in a context that is potentially constant evaluated per C++20 | ||||
17783 | /// [expr.const]p12? | ||||
17784 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | ||||
17785 | /// C++2a [expr.const]p12: | ||||
17786 | // An expression or conversion is potentially constant evaluated if it is | ||||
17787 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
17788 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
17789 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: | ||||
17790 | |||||
17791 | // -- a manifestly constant-evaluated expression, | ||||
17792 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
17793 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
17794 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
17795 | // -- a potentially-evaluated expression, | ||||
17796 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
17797 | // -- an immediate subexpression of a braced-init-list, | ||||
17798 | |||||
17799 | // -- [FIXME] an expression of the form & cast-expression that occurs | ||||
17800 | // within a templated entity | ||||
17801 | // -- a subexpression of one of the above that is not a subexpression of | ||||
17802 | // a nested unevaluated operand. | ||||
17803 | return true; | ||||
17804 | |||||
17805 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
17806 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
17807 | // Expressions in this context are never evaluated. | ||||
17808 | return false; | ||||
17809 | } | ||||
17810 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "clang/lib/Sema/SemaExpr.cpp" , 17810); | ||||
17811 | } | ||||
17812 | |||||
17813 | /// Return true if this function has a calling convention that requires mangling | ||||
17814 | /// in the size of the parameter pack. | ||||
17815 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | ||||
17816 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | ||||
17817 | // we don't need parameter type sizes. | ||||
17818 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | ||||
17819 | if (!TT.isOSWindows() || !TT.isX86()) | ||||
17820 | return false; | ||||
17821 | |||||
17822 | // If this is C++ and this isn't an extern "C" function, parameters do not | ||||
17823 | // need to be complete. In this case, C++ mangling will apply, which doesn't | ||||
17824 | // use the size of the parameters. | ||||
17825 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | ||||
17826 | return false; | ||||
17827 | |||||
17828 | // Stdcall, fastcall, and vectorcall need this special treatment. | ||||
17829 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
17830 | switch (CC) { | ||||
17831 | case CC_X86StdCall: | ||||
17832 | case CC_X86FastCall: | ||||
17833 | case CC_X86VectorCall: | ||||
17834 | return true; | ||||
17835 | default: | ||||
17836 | break; | ||||
17837 | } | ||||
17838 | return false; | ||||
17839 | } | ||||
17840 | |||||
17841 | /// Require that all of the parameter types of function be complete. Normally, | ||||
17842 | /// parameter types are only required to be complete when a function is called | ||||
17843 | /// or defined, but to mangle functions with certain calling conventions, the | ||||
17844 | /// mangler needs to know the size of the parameter list. In this situation, | ||||
17845 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | ||||
17846 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | ||||
17847 | /// result in a linker error. Clang doesn't implement this behavior, and instead | ||||
17848 | /// attempts to error at compile time. | ||||
17849 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | ||||
17850 | SourceLocation Loc) { | ||||
17851 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | ||||
17852 | FunctionDecl *FD; | ||||
17853 | ParmVarDecl *Param; | ||||
17854 | |||||
17855 | public: | ||||
17856 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | ||||
17857 | : FD(FD), Param(Param) {} | ||||
17858 | |||||
17859 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
17860 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
17861 | StringRef CCName; | ||||
17862 | switch (CC) { | ||||
17863 | case CC_X86StdCall: | ||||
17864 | CCName = "stdcall"; | ||||
17865 | break; | ||||
17866 | case CC_X86FastCall: | ||||
17867 | CCName = "fastcall"; | ||||
17868 | break; | ||||
17869 | case CC_X86VectorCall: | ||||
17870 | CCName = "vectorcall"; | ||||
17871 | break; | ||||
17872 | default: | ||||
17873 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "clang/lib/Sema/SemaExpr.cpp", 17873); | ||||
17874 | } | ||||
17875 | |||||
17876 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | ||||
17877 | << Param->getDeclName() << FD->getDeclName() << CCName; | ||||
17878 | } | ||||
17879 | }; | ||||
17880 | |||||
17881 | for (ParmVarDecl *Param : FD->parameters()) { | ||||
17882 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | ||||
17883 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | ||||
17884 | } | ||||
17885 | } | ||||
17886 | |||||
17887 | namespace { | ||||
17888 | enum class OdrUseContext { | ||||
17889 | /// Declarations in this context are not odr-used. | ||||
17890 | None, | ||||
17891 | /// Declarations in this context are formally odr-used, but this is a | ||||
17892 | /// dependent context. | ||||
17893 | Dependent, | ||||
17894 | /// Declarations in this context are odr-used but not actually used (yet). | ||||
17895 | FormallyOdrUsed, | ||||
17896 | /// Declarations in this context are used. | ||||
17897 | Used | ||||
17898 | }; | ||||
17899 | } | ||||
17900 | |||||
17901 | /// Are we within a context in which references to resolved functions or to | ||||
17902 | /// variables result in odr-use? | ||||
17903 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | ||||
17904 | OdrUseContext Result; | ||||
17905 | |||||
17906 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
17907 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
17908 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
17909 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
17910 | return OdrUseContext::None; | ||||
17911 | |||||
17912 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
17913 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: | ||||
17914 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
17915 | Result = OdrUseContext::Used; | ||||
17916 | break; | ||||
17917 | |||||
17918 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
17919 | Result = OdrUseContext::FormallyOdrUsed; | ||||
17920 | break; | ||||
17921 | |||||
17922 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
17923 | // A default argument formally results in odr-use, but doesn't actually | ||||
17924 | // result in a use in any real sense until it itself is used. | ||||
17925 | Result = OdrUseContext::FormallyOdrUsed; | ||||
17926 | break; | ||||
17927 | } | ||||
17928 | |||||
17929 | if (SemaRef.CurContext->isDependentContext()) | ||||
17930 | return OdrUseContext::Dependent; | ||||
17931 | |||||
17932 | return Result; | ||||
17933 | } | ||||
17934 | |||||
17935 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | ||||
17936 | if (!Func->isConstexpr()) | ||||
17937 | return false; | ||||
17938 | |||||
17939 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | ||||
17940 | return true; | ||||
17941 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | ||||
17942 | return CCD && CCD->getInheritedConstructor(); | ||||
17943 | } | ||||
17944 | |||||
17945 | /// Mark a function referenced, and check whether it is odr-used | ||||
17946 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | ||||
17947 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | ||||
17948 | bool MightBeOdrUse) { | ||||
17949 | assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void (0) : __assert_fail ("Func && \"No function?\"", "clang/lib/Sema/SemaExpr.cpp" , 17949, __extension__ __PRETTY_FUNCTION__)); | ||||
17950 | |||||
17951 | Func->setReferenced(); | ||||
17952 | |||||
17953 | // Recursive functions aren't really used until they're used from some other | ||||
17954 | // context. | ||||
17955 | bool IsRecursiveCall = CurContext == Func; | ||||
17956 | |||||
17957 | // C++11 [basic.def.odr]p3: | ||||
17958 | // A function whose name appears as a potentially-evaluated expression is | ||||
17959 | // odr-used if it is the unique lookup result or the selected member of a | ||||
17960 | // set of overloaded functions [...]. | ||||
17961 | // | ||||
17962 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | ||||
17963 | // can just check that here. | ||||
17964 | OdrUseContext OdrUse = | ||||
17965 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | ||||
17966 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | ||||
17967 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
17968 | |||||
17969 | // Trivial default constructors and destructors are never actually used. | ||||
17970 | // FIXME: What about other special members? | ||||
17971 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | ||||
17972 | OdrUse == OdrUseContext::Used) { | ||||
17973 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | ||||
17974 | if (Constructor->isDefaultConstructor()) | ||||
17975 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
17976 | if (isa<CXXDestructorDecl>(Func)) | ||||
17977 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
17978 | } | ||||
17979 | |||||
17980 | // C++20 [expr.const]p12: | ||||
17981 | // A function [...] is needed for constant evaluation if it is [...] a | ||||
17982 | // constexpr function that is named by an expression that is potentially | ||||
17983 | // constant evaluated | ||||
17984 | bool NeededForConstantEvaluation = | ||||
17985 | isPotentiallyConstantEvaluatedContext(*this) && | ||||
17986 | isImplicitlyDefinableConstexprFunction(Func); | ||||
17987 | |||||
17988 | // Determine whether we require a function definition to exist, per | ||||
17989 | // C++11 [temp.inst]p3: | ||||
17990 | // Unless a function template specialization has been explicitly | ||||
17991 | // instantiated or explicitly specialized, the function template | ||||
17992 | // specialization is implicitly instantiated when the specialization is | ||||
17993 | // referenced in a context that requires a function definition to exist. | ||||
17994 | // C++20 [temp.inst]p7: | ||||
17995 | // The existence of a definition of a [...] function is considered to | ||||
17996 | // affect the semantics of the program if the [...] function is needed for | ||||
17997 | // constant evaluation by an expression | ||||
17998 | // C++20 [basic.def.odr]p10: | ||||
17999 | // Every program shall contain exactly one definition of every non-inline | ||||
18000 | // function or variable that is odr-used in that program outside of a | ||||
18001 | // discarded statement | ||||
18002 | // C++20 [special]p1: | ||||
18003 | // The implementation will implicitly define [defaulted special members] | ||||
18004 | // if they are odr-used or needed for constant evaluation. | ||||
18005 | // | ||||
18006 | // Note that we skip the implicit instantiation of templates that are only | ||||
18007 | // used in unused default arguments or by recursive calls to themselves. | ||||
18008 | // This is formally non-conforming, but seems reasonable in practice. | ||||
18009 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | ||||
18010 | NeededForConstantEvaluation); | ||||
18011 | |||||
18012 | // C++14 [temp.expl.spec]p6: | ||||
18013 | // If a template [...] is explicitly specialized then that specialization | ||||
18014 | // shall be declared before the first use of that specialization that would | ||||
18015 | // cause an implicit instantiation to take place, in every translation unit | ||||
18016 | // in which such a use occurs | ||||
18017 | if (NeedDefinition && | ||||
18018 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | ||||
18019 | Func->getMemberSpecializationInfo())) | ||||
18020 | checkSpecializationReachability(Loc, Func); | ||||
18021 | |||||
18022 | if (getLangOpts().CUDA) | ||||
18023 | CheckCUDACall(Loc, Func); | ||||
18024 | |||||
18025 | if (getLangOpts().SYCLIsDevice) | ||||
18026 | checkSYCLDeviceFunction(Loc, Func); | ||||
18027 | |||||
18028 | // If we need a definition, try to create one. | ||||
18029 | if (NeedDefinition && !Func->getBody()) { | ||||
18030 | runWithSufficientStackSpace(Loc, [&] { | ||||
18031 | if (CXXConstructorDecl *Constructor = | ||||
18032 | dyn_cast<CXXConstructorDecl>(Func)) { | ||||
18033 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | ||||
18034 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | ||||
18035 | if (Constructor->isDefaultConstructor()) { | ||||
18036 | if (Constructor->isTrivial() && | ||||
18037 | !Constructor->hasAttr<DLLExportAttr>()) | ||||
18038 | return; | ||||
18039 | DefineImplicitDefaultConstructor(Loc, Constructor); | ||||
18040 | } else if (Constructor->isCopyConstructor()) { | ||||
18041 | DefineImplicitCopyConstructor(Loc, Constructor); | ||||
18042 | } else if (Constructor->isMoveConstructor()) { | ||||
18043 | DefineImplicitMoveConstructor(Loc, Constructor); | ||||
18044 | } | ||||
18045 | } else if (Constructor->getInheritedConstructor()) { | ||||
18046 | DefineInheritingConstructor(Loc, Constructor); | ||||
18047 | } | ||||
18048 | } else if (CXXDestructorDecl *Destructor = | ||||
18049 | dyn_cast<CXXDestructorDecl>(Func)) { | ||||
18050 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | ||||
18051 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | ||||
18052 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | ||||
18053 | return; | ||||
18054 | DefineImplicitDestructor(Loc, Destructor); | ||||
18055 | } | ||||
18056 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | ||||
18057 | MarkVTableUsed(Loc, Destructor->getParent()); | ||||
18058 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | ||||
18059 | if (MethodDecl->isOverloadedOperator() && | ||||
18060 | MethodDecl->getOverloadedOperator() == OO_Equal) { | ||||
18061 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | ||||
18062 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | ||||
18063 | if (MethodDecl->isCopyAssignmentOperator()) | ||||
18064 | DefineImplicitCopyAssignment(Loc, MethodDecl); | ||||
18065 | else if (MethodDecl->isMoveAssignmentOperator()) | ||||
18066 | DefineImplicitMoveAssignment(Loc, MethodDecl); | ||||
18067 | } | ||||
18068 | } else if (isa<CXXConversionDecl>(MethodDecl) && | ||||
18069 | MethodDecl->getParent()->isLambda()) { | ||||
18070 | CXXConversionDecl *Conversion = | ||||
18071 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | ||||
18072 | if (Conversion->isLambdaToBlockPointerConversion()) | ||||
18073 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | ||||
18074 | else | ||||
18075 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | ||||
18076 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | ||||
18077 | MarkVTableUsed(Loc, MethodDecl->getParent()); | ||||
18078 | } | ||||
18079 | |||||
18080 | if (Func->isDefaulted() && !Func->isDeleted()) { | ||||
18081 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | ||||
18082 | if (DCK != DefaultedComparisonKind::None) | ||||
18083 | DefineDefaultedComparison(Loc, Func, DCK); | ||||
18084 | } | ||||
18085 | |||||
18086 | // Implicit instantiation of function templates and member functions of | ||||
18087 | // class templates. | ||||
18088 | if (Func->isImplicitlyInstantiable()) { | ||||
18089 | TemplateSpecializationKind TSK = | ||||
18090 | Func->getTemplateSpecializationKindForInstantiation(); | ||||
18091 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | ||||
18092 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
18093 | if (FirstInstantiation) { | ||||
18094 | PointOfInstantiation = Loc; | ||||
18095 | if (auto *MSI = Func->getMemberSpecializationInfo()) | ||||
18096 | MSI->setPointOfInstantiation(Loc); | ||||
18097 | // FIXME: Notify listener. | ||||
18098 | else | ||||
18099 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
18100 | } else if (TSK != TSK_ImplicitInstantiation) { | ||||
18101 | // Use the point of use as the point of instantiation, instead of the | ||||
18102 | // point of explicit instantiation (which we track as the actual point | ||||
18103 | // of instantiation). This gives better backtraces in diagnostics. | ||||
18104 | PointOfInstantiation = Loc; | ||||
18105 | } | ||||
18106 | |||||
18107 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | ||||
18108 | Func->isConstexpr()) { | ||||
18109 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | ||||
18110 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | ||||
18111 | CodeSynthesisContexts.size()) | ||||
18112 | PendingLocalImplicitInstantiations.push_back( | ||||
18113 | std::make_pair(Func, PointOfInstantiation)); | ||||
18114 | else if (Func->isConstexpr()) | ||||
18115 | // Do not defer instantiations of constexpr functions, to avoid the | ||||
18116 | // expression evaluator needing to call back into Sema if it sees a | ||||
18117 | // call to such a function. | ||||
18118 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | ||||
18119 | else { | ||||
18120 | Func->setInstantiationIsPending(true); | ||||
18121 | PendingInstantiations.push_back( | ||||
18122 | std::make_pair(Func, PointOfInstantiation)); | ||||
18123 | // Notify the consumer that a function was implicitly instantiated. | ||||
18124 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | ||||
18125 | } | ||||
18126 | } | ||||
18127 | } else { | ||||
18128 | // Walk redefinitions, as some of them may be instantiable. | ||||
18129 | for (auto *i : Func->redecls()) { | ||||
18130 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | ||||
18131 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | ||||
18132 | } | ||||
18133 | } | ||||
18134 | }); | ||||
18135 | } | ||||
18136 | |||||
18137 | // C++14 [except.spec]p17: | ||||
18138 | // An exception-specification is considered to be needed when: | ||||
18139 | // - the function is odr-used or, if it appears in an unevaluated operand, | ||||
18140 | // would be odr-used if the expression were potentially-evaluated; | ||||
18141 | // | ||||
18142 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | ||||
18143 | // function is a pure virtual function we're calling, and in that case the | ||||
18144 | // function was selected by overload resolution and we need to resolve its | ||||
18145 | // exception specification for a different reason. | ||||
18146 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | ||||
18147 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | ||||
18148 | ResolveExceptionSpec(Loc, FPT); | ||||
18149 | |||||
18150 | // If this is the first "real" use, act on that. | ||||
18151 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | ||||
18152 | // Keep track of used but undefined functions. | ||||
18153 | if (!Func->isDefined()) { | ||||
18154 | if (mightHaveNonExternalLinkage(Func)) | ||||
18155 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
18156 | else if (Func->getMostRecentDecl()->isInlined() && | ||||
18157 | !LangOpts.GNUInline && | ||||
18158 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | ||||
18159 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
18160 | else if (isExternalWithNoLinkageType(Func)) | ||||
18161 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
18162 | } | ||||
18163 | |||||
18164 | // Some x86 Windows calling conventions mangle the size of the parameter | ||||
18165 | // pack into the name. Computing the size of the parameters requires the | ||||
18166 | // parameter types to be complete. Check that now. | ||||
18167 | if (funcHasParameterSizeMangling(*this, Func)) | ||||
18168 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | ||||
18169 | |||||
18170 | // In the MS C++ ABI, the compiler emits destructor variants where they are | ||||
18171 | // used. If the destructor is used here but defined elsewhere, mark the | ||||
18172 | // virtual base destructors referenced. If those virtual base destructors | ||||
18173 | // are inline, this will ensure they are defined when emitting the complete | ||||
18174 | // destructor variant. This checking may be redundant if the destructor is | ||||
18175 | // provided later in this TU. | ||||
18176 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
18177 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | ||||
18178 | CXXRecordDecl *Parent = Dtor->getParent(); | ||||
18179 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | ||||
18180 | CheckCompleteDestructorVariant(Loc, Dtor); | ||||
18181 | } | ||||
18182 | } | ||||
18183 | |||||
18184 | Func->markUsed(Context); | ||||
18185 | } | ||||
18186 | } | ||||
18187 | |||||
18188 | /// Directly mark a variable odr-used. Given a choice, prefer to use | ||||
18189 | /// MarkVariableReferenced since it does additional checks and then | ||||
18190 | /// calls MarkVarDeclODRUsed. | ||||
18191 | /// If the variable must be captured: | ||||
18192 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | ||||
18193 | /// - else capture it in the DeclContext that maps to the | ||||
18194 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | ||||
18195 | static void | ||||
18196 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | ||||
18197 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | ||||
18198 | // Keep track of used but undefined variables. | ||||
18199 | // FIXME: We shouldn't suppress this warning for static data members. | ||||
18200 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | ||||
18201 | (!Var->isExternallyVisible() || Var->isInline() || | ||||
18202 | SemaRef.isExternalWithNoLinkageType(Var)) && | ||||
18203 | !(Var->isStaticDataMember() && Var->hasInit())) { | ||||
18204 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | ||||
18205 | if (old.isInvalid()) | ||||
18206 | old = Loc; | ||||
18207 | } | ||||
18208 | QualType CaptureType, DeclRefType; | ||||
18209 | if (SemaRef.LangOpts.OpenMP) | ||||
18210 | SemaRef.tryCaptureOpenMPLambdas(Var); | ||||
18211 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | ||||
18212 | /*EllipsisLoc*/ SourceLocation(), | ||||
18213 | /*BuildAndDiagnose*/ true, | ||||
18214 | CaptureType, DeclRefType, | ||||
18215 | FunctionScopeIndexToStopAt); | ||||
18216 | |||||
18217 | if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { | ||||
18218 | auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); | ||||
18219 | auto VarTarget = SemaRef.IdentifyCUDATarget(Var); | ||||
18220 | auto UserTarget = SemaRef.IdentifyCUDATarget(FD); | ||||
18221 | if (VarTarget == Sema::CVT_Host && | ||||
18222 | (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || | ||||
18223 | UserTarget == Sema::CFT_Global)) { | ||||
18224 | // Diagnose ODR-use of host global variables in device functions. | ||||
18225 | // Reference of device global variables in host functions is allowed | ||||
18226 | // through shadow variables therefore it is not diagnosed. | ||||
18227 | if (SemaRef.LangOpts.CUDAIsDevice) { | ||||
18228 | SemaRef.targetDiag(Loc, diag::err_ref_bad_target) | ||||
18229 | << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; | ||||
18230 | SemaRef.targetDiag(Var->getLocation(), | ||||
18231 | Var->getType().isConstQualified() | ||||
18232 | ? diag::note_cuda_const_var_unpromoted | ||||
18233 | : diag::note_cuda_host_var); | ||||
18234 | } | ||||
18235 | } else if (VarTarget == Sema::CVT_Device && | ||||
18236 | (UserTarget == Sema::CFT_Host || | ||||
18237 | UserTarget == Sema::CFT_HostDevice)) { | ||||
18238 | // Record a CUDA/HIP device side variable if it is ODR-used | ||||
18239 | // by host code. This is done conservatively, when the variable is | ||||
18240 | // referenced in any of the following contexts: | ||||
18241 | // - a non-function context | ||||
18242 | // - a host function | ||||
18243 | // - a host device function | ||||
18244 | // This makes the ODR-use of the device side variable by host code to | ||||
18245 | // be visible in the device compilation for the compiler to be able to | ||||
18246 | // emit template variables instantiated by host code only and to | ||||
18247 | // externalize the static device side variable ODR-used by host code. | ||||
18248 | if (!Var->hasExternalStorage()) | ||||
18249 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); | ||||
18250 | else if (SemaRef.LangOpts.GPURelocatableDeviceCode) | ||||
18251 | SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); | ||||
18252 | } | ||||
18253 | } | ||||
18254 | |||||
18255 | Var->markUsed(SemaRef.Context); | ||||
18256 | } | ||||
18257 | |||||
18258 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | ||||
18259 | SourceLocation Loc, | ||||
18260 | unsigned CapturingScopeIndex) { | ||||
18261 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | ||||
18262 | } | ||||
18263 | |||||
18264 | void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, | ||||
18265 | ValueDecl *var) { | ||||
18266 | DeclContext *VarDC = var->getDeclContext(); | ||||
18267 | |||||
18268 | // If the parameter still belongs to the translation unit, then | ||||
18269 | // we're actually just using one parameter in the declaration of | ||||
18270 | // the next. | ||||
18271 | if (isa<ParmVarDecl>(var) && | ||||
18272 | isa<TranslationUnitDecl>(VarDC)) | ||||
18273 | return; | ||||
18274 | |||||
18275 | // For C code, don't diagnose about capture if we're not actually in code | ||||
18276 | // right now; it's impossible to write a non-constant expression outside of | ||||
18277 | // function context, so we'll get other (more useful) diagnostics later. | ||||
18278 | // | ||||
18279 | // For C++, things get a bit more nasty... it would be nice to suppress this | ||||
18280 | // diagnostic for certain cases like using a local variable in an array bound | ||||
18281 | // for a member of a local class, but the correct predicate is not obvious. | ||||
18282 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | ||||
18283 | return; | ||||
18284 | |||||
18285 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | ||||
18286 | unsigned ContextKind = 3; // unknown | ||||
18287 | if (isa<CXXMethodDecl>(VarDC) && | ||||
18288 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | ||||
18289 | ContextKind = 2; | ||||
18290 | } else if (isa<FunctionDecl>(VarDC)) { | ||||
18291 | ContextKind = 0; | ||||
18292 | } else if (isa<BlockDecl>(VarDC)) { | ||||
18293 | ContextKind = 1; | ||||
18294 | } | ||||
18295 | |||||
18296 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | ||||
18297 | << var << ValueKind << ContextKind << VarDC; | ||||
18298 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | ||||
18299 | << var; | ||||
18300 | |||||
18301 | // FIXME: Add additional diagnostic info about class etc. which prevents | ||||
18302 | // capture. | ||||
18303 | } | ||||
18304 | |||||
18305 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, | ||||
18306 | ValueDecl *Var, | ||||
18307 | bool &SubCapturesAreNested, | ||||
18308 | QualType &CaptureType, | ||||
18309 | QualType &DeclRefType) { | ||||
18310 | // Check whether we've already captured it. | ||||
18311 | if (CSI->CaptureMap.count(Var)) { | ||||
18312 | // If we found a capture, any subcaptures are nested. | ||||
18313 | SubCapturesAreNested = true; | ||||
18314 | |||||
18315 | // Retrieve the capture type for this variable. | ||||
18316 | CaptureType = CSI->getCapture(Var).getCaptureType(); | ||||
18317 | |||||
18318 | // Compute the type of an expression that refers to this variable. | ||||
18319 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18320 | |||||
18321 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | ||||
18322 | // are mutable in the sense that user can change their value - they are | ||||
18323 | // private instances of the captured declarations. | ||||
18324 | const Capture &Cap = CSI->getCapture(Var); | ||||
18325 | if (Cap.isCopyCapture() && | ||||
18326 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | ||||
18327 | !(isa<CapturedRegionScopeInfo>(CSI) && | ||||
18328 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | ||||
18329 | DeclRefType.addConst(); | ||||
18330 | return true; | ||||
18331 | } | ||||
18332 | return false; | ||||
18333 | } | ||||
18334 | |||||
18335 | // Only block literals, captured statements, and lambda expressions can | ||||
18336 | // capture; other scopes don't work. | ||||
18337 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, | ||||
18338 | ValueDecl *Var, | ||||
18339 | SourceLocation Loc, | ||||
18340 | const bool Diagnose, | ||||
18341 | Sema &S) { | ||||
18342 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | ||||
18343 | return getLambdaAwareParentOfDeclContext(DC); | ||||
18344 | |||||
18345 | ValueDecl *Underlying = Var; | ||||
18346 | auto *BD = dyn_cast_or_null<BindingDecl>(Var); | ||||
18347 | if (BD) | ||||
18348 | Underlying = BD->getDecomposedDecl(); | ||||
18349 | |||||
18350 | if (auto *VD = dyn_cast<VarDecl>(Underlying)) { | ||||
18351 | if (VD->hasLocalStorage() && Diagnose) | ||||
18352 | diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); | ||||
18353 | } | ||||
18354 | return nullptr; | ||||
18355 | } | ||||
18356 | |||||
18357 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
18358 | // certain types of variables (unnamed, variably modified types etc.) | ||||
18359 | // so check for eligibility. | ||||
18360 | static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, | ||||
18361 | SourceLocation Loc, const bool Diagnose, | ||||
18362 | Sema &S) { | ||||
18363 | |||||
18364 | assert((isa<VarDecl, BindingDecl>(Var)) &&(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var )) && "Only variables and structured bindings can be captured" ) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\"" , "clang/lib/Sema/SemaExpr.cpp", 18365, __extension__ __PRETTY_FUNCTION__ )) | ||||
18365 | "Only variables and structured bindings can be captured")(static_cast <bool> ((isa<VarDecl, BindingDecl>(Var )) && "Only variables and structured bindings can be captured" ) ? void (0) : __assert_fail ("(isa<VarDecl, BindingDecl>(Var)) && \"Only variables and structured bindings can be captured\"" , "clang/lib/Sema/SemaExpr.cpp", 18365, __extension__ __PRETTY_FUNCTION__ )); | ||||
18366 | |||||
18367 | bool IsBlock = isa<BlockScopeInfo>(CSI); | ||||
18368 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | ||||
18369 | |||||
18370 | // Lambdas are not allowed to capture unnamed variables | ||||
18371 | // (e.g. anonymous unions). | ||||
18372 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | ||||
18373 | // assuming that's the intent. | ||||
18374 | if (IsLambda && !Var->getDeclName()) { | ||||
18375 | if (Diagnose) { | ||||
18376 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | ||||
18377 | S.Diag(Var->getLocation(), diag::note_declared_at); | ||||
18378 | } | ||||
18379 | return false; | ||||
18380 | } | ||||
18381 | |||||
18382 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | ||||
18383 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | ||||
18384 | if (Diagnose) { | ||||
18385 | S.Diag(Loc, diag::err_ref_vm_type); | ||||
18386 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18387 | } | ||||
18388 | return false; | ||||
18389 | } | ||||
18390 | // Prohibit structs with flexible array members too. | ||||
18391 | // We cannot capture what is in the tail end of the struct. | ||||
18392 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | ||||
18393 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | ||||
18394 | if (Diagnose) { | ||||
18395 | if (IsBlock) | ||||
18396 | S.Diag(Loc, diag::err_ref_flexarray_type); | ||||
18397 | else | ||||
18398 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | ||||
18399 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18400 | } | ||||
18401 | return false; | ||||
18402 | } | ||||
18403 | } | ||||
18404 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
18405 | // Lambdas and captured statements are not allowed to capture __block | ||||
18406 | // variables; they don't support the expected semantics. | ||||
18407 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | ||||
18408 | if (Diagnose) { | ||||
18409 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | ||||
18410 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18411 | } | ||||
18412 | return false; | ||||
18413 | } | ||||
18414 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | ||||
18415 | if (S.getLangOpts().OpenCL && IsBlock && | ||||
18416 | Var->getType()->isBlockPointerType()) { | ||||
18417 | if (Diagnose) | ||||
18418 | S.Diag(Loc, diag::err_opencl_block_ref_block); | ||||
18419 | return false; | ||||
18420 | } | ||||
18421 | |||||
18422 | if (isa<BindingDecl>(Var)) { | ||||
18423 | if (!IsLambda || !S.getLangOpts().CPlusPlus) { | ||||
18424 | if (Diagnose) | ||||
18425 | diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); | ||||
18426 | return false; | ||||
18427 | } else if (Diagnose && S.getLangOpts().CPlusPlus) { | ||||
18428 | S.Diag(Loc, S.LangOpts.CPlusPlus20 | ||||
18429 | ? diag::warn_cxx17_compat_capture_binding | ||||
18430 | : diag::ext_capture_binding) | ||||
18431 | << Var; | ||||
18432 | S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; | ||||
18433 | } | ||||
18434 | } | ||||
18435 | |||||
18436 | return true; | ||||
18437 | } | ||||
18438 | |||||
18439 | // Returns true if the capture by block was successful. | ||||
18440 | static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, | ||||
18441 | SourceLocation Loc, const bool BuildAndDiagnose, | ||||
18442 | QualType &CaptureType, QualType &DeclRefType, | ||||
18443 | const bool Nested, Sema &S, bool Invalid) { | ||||
18444 | bool ByRef = false; | ||||
18445 | |||||
18446 | // Blocks are not allowed to capture arrays, excepting OpenCL. | ||||
18447 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | ||||
18448 | // (decayed to pointers). | ||||
18449 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | ||||
18450 | if (BuildAndDiagnose) { | ||||
18451 | S.Diag(Loc, diag::err_ref_array_type); | ||||
18452 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18453 | Invalid = true; | ||||
18454 | } else { | ||||
18455 | return false; | ||||
18456 | } | ||||
18457 | } | ||||
18458 | |||||
18459 | // Forbid the block-capture of autoreleasing variables. | ||||
18460 | if (!Invalid && | ||||
18461 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
18462 | if (BuildAndDiagnose) { | ||||
18463 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | ||||
18464 | << /*block*/ 0; | ||||
18465 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18466 | Invalid = true; | ||||
18467 | } else { | ||||
18468 | return false; | ||||
18469 | } | ||||
18470 | } | ||||
18471 | |||||
18472 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | ||||
18473 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | ||||
18474 | QualType PointeeTy = PT->getPointeeType(); | ||||
18475 | |||||
18476 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | ||||
18477 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | ||||
18478 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | ||||
18479 | if (BuildAndDiagnose) { | ||||
18480 | SourceLocation VarLoc = Var->getLocation(); | ||||
18481 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | ||||
18482 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | ||||
18483 | } | ||||
18484 | } | ||||
18485 | } | ||||
18486 | |||||
18487 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
18488 | if (HasBlocksAttr || CaptureType->isReferenceType() || | ||||
18489 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | ||||
18490 | // Block capture by reference does not change the capture or | ||||
18491 | // declaration reference types. | ||||
18492 | ByRef = true; | ||||
18493 | } else { | ||||
18494 | // Block capture by copy introduces 'const'. | ||||
18495 | CaptureType = CaptureType.getNonReferenceType().withConst(); | ||||
18496 | DeclRefType = CaptureType; | ||||
18497 | } | ||||
18498 | |||||
18499 | // Actually capture the variable. | ||||
18500 | if (BuildAndDiagnose) | ||||
18501 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | ||||
18502 | CaptureType, Invalid); | ||||
18503 | |||||
18504 | return !Invalid; | ||||
18505 | } | ||||
18506 | |||||
18507 | /// Capture the given variable in the captured region. | ||||
18508 | static bool captureInCapturedRegion( | ||||
18509 | CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, | ||||
18510 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, | ||||
18511 | const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, | ||||
18512 | bool IsTopScope, Sema &S, bool Invalid) { | ||||
18513 | // By default, capture variables by reference. | ||||
18514 | bool ByRef = true; | ||||
18515 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
18516 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
18517 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | ||||
18518 | // Using an LValue reference type is consistent with Lambdas (see below). | ||||
18519 | if (S.isOpenMPCapturedDecl(Var)) { | ||||
18520 | bool HasConst = DeclRefType.isConstQualified(); | ||||
18521 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
18522 | // Don't lose diagnostics about assignments to const. | ||||
18523 | if (HasConst) | ||||
18524 | DeclRefType.addConst(); | ||||
18525 | } | ||||
18526 | // Do not capture firstprivates in tasks. | ||||
18527 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | ||||
18528 | OMPC_unknown) | ||||
18529 | return true; | ||||
18530 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | ||||
18531 | RSI->OpenMPCaptureLevel); | ||||
18532 | } | ||||
18533 | |||||
18534 | if (ByRef) | ||||
18535 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
18536 | else | ||||
18537 | CaptureType = DeclRefType; | ||||
18538 | |||||
18539 | // Actually capture the variable. | ||||
18540 | if (BuildAndDiagnose) | ||||
18541 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | ||||
18542 | Loc, SourceLocation(), CaptureType, Invalid); | ||||
18543 | |||||
18544 | return !Invalid; | ||||
18545 | } | ||||
18546 | |||||
18547 | /// Capture the given variable in the lambda. | ||||
18548 | static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, | ||||
18549 | SourceLocation Loc, const bool BuildAndDiagnose, | ||||
18550 | QualType &CaptureType, QualType &DeclRefType, | ||||
18551 | const bool RefersToCapturedVariable, | ||||
18552 | const Sema::TryCaptureKind Kind, | ||||
18553 | SourceLocation EllipsisLoc, const bool IsTopScope, | ||||
18554 | Sema &S, bool Invalid) { | ||||
18555 | // Determine whether we are capturing by reference or by value. | ||||
18556 | bool ByRef = false; | ||||
18557 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
18558 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
18559 | } else { | ||||
18560 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | ||||
18561 | } | ||||
18562 | |||||
18563 | BindingDecl *BD = dyn_cast<BindingDecl>(Var); | ||||
18564 | // FIXME: We should support capturing structured bindings in OpenMP. | ||||
18565 | if (!Invalid && BD && S.LangOpts.OpenMP) { | ||||
18566 | if (BuildAndDiagnose) { | ||||
18567 | S.Diag(Loc, diag::err_capture_binding_openmp) << Var; | ||||
18568 | S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; | ||||
18569 | } | ||||
18570 | Invalid = true; | ||||
18571 | } | ||||
18572 | |||||
18573 | // Compute the type of the field that will capture this variable. | ||||
18574 | if (ByRef) { | ||||
18575 | // C++11 [expr.prim.lambda]p15: | ||||
18576 | // An entity is captured by reference if it is implicitly or | ||||
18577 | // explicitly captured but not captured by copy. It is | ||||
18578 | // unspecified whether additional unnamed non-static data | ||||
18579 | // members are declared in the closure type for entities | ||||
18580 | // captured by reference. | ||||
18581 | // | ||||
18582 | // FIXME: It is not clear whether we want to build an lvalue reference | ||||
18583 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | ||||
18584 | // to do the former, while EDG does the latter. Core issue 1249 will | ||||
18585 | // clarify, but for now we follow GCC because it's a more permissive and | ||||
18586 | // easily defensible position. | ||||
18587 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
18588 | } else { | ||||
18589 | // C++11 [expr.prim.lambda]p14: | ||||
18590 | // For each entity captured by copy, an unnamed non-static | ||||
18591 | // data member is declared in the closure type. The | ||||
18592 | // declaration order of these members is unspecified. The type | ||||
18593 | // of such a data member is the type of the corresponding | ||||
18594 | // captured entity if the entity is not a reference to an | ||||
18595 | // object, or the referenced type otherwise. [Note: If the | ||||
18596 | // captured entity is a reference to a function, the | ||||
18597 | // corresponding data member is also a reference to a | ||||
18598 | // function. - end note ] | ||||
18599 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | ||||
18600 | if (!RefType->getPointeeType()->isFunctionType()) | ||||
18601 | CaptureType = RefType->getPointeeType(); | ||||
18602 | } | ||||
18603 | |||||
18604 | // Forbid the lambda copy-capture of autoreleasing variables. | ||||
18605 | if (!Invalid && | ||||
18606 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
18607 | if (BuildAndDiagnose) { | ||||
18608 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | ||||
18609 | S.Diag(Var->getLocation(), diag::note_previous_decl) | ||||
18610 | << Var->getDeclName(); | ||||
18611 | Invalid = true; | ||||
18612 | } else { | ||||
18613 | return false; | ||||
18614 | } | ||||
18615 | } | ||||
18616 | |||||
18617 | // Make sure that by-copy captures are of a complete and non-abstract type. | ||||
18618 | if (!Invalid && BuildAndDiagnose) { | ||||
18619 | if (!CaptureType->isDependentType() && | ||||
18620 | S.RequireCompleteSizedType( | ||||
18621 | Loc, CaptureType, | ||||
18622 | diag::err_capture_of_incomplete_or_sizeless_type, | ||||
18623 | Var->getDeclName())) | ||||
18624 | Invalid = true; | ||||
18625 | else if (S.RequireNonAbstractType(Loc, CaptureType, | ||||
18626 | diag::err_capture_of_abstract_type)) | ||||
18627 | Invalid = true; | ||||
18628 | } | ||||
18629 | } | ||||
18630 | |||||
18631 | // Compute the type of a reference to this captured variable. | ||||
18632 | if (ByRef) | ||||
18633 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18634 | else { | ||||
18635 | // C++ [expr.prim.lambda]p5: | ||||
18636 | // The closure type for a lambda-expression has a public inline | ||||
18637 | // function call operator [...]. This function call operator is | ||||
18638 | // declared const (9.3.1) if and only if the lambda-expression's | ||||
18639 | // parameter-declaration-clause is not followed by mutable. | ||||
18640 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18641 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | ||||
18642 | DeclRefType.addConst(); | ||||
18643 | } | ||||
18644 | |||||
18645 | // Add the capture. | ||||
18646 | if (BuildAndDiagnose) | ||||
18647 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | ||||
18648 | Loc, EllipsisLoc, CaptureType, Invalid); | ||||
18649 | |||||
18650 | return !Invalid; | ||||
18651 | } | ||||
18652 | |||||
18653 | static bool canCaptureVariableByCopy(ValueDecl *Var, | ||||
18654 | const ASTContext &Context) { | ||||
18655 | // Offer a Copy fix even if the type is dependent. | ||||
18656 | if (Var->getType()->isDependentType()) | ||||
18657 | return true; | ||||
18658 | QualType T = Var->getType().getNonReferenceType(); | ||||
18659 | if (T.isTriviallyCopyableType(Context)) | ||||
18660 | return true; | ||||
18661 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | ||||
18662 | |||||
18663 | if (!(RD = RD->getDefinition())) | ||||
18664 | return false; | ||||
18665 | if (RD->hasSimpleCopyConstructor()) | ||||
18666 | return true; | ||||
18667 | if (RD->hasUserDeclaredCopyConstructor()) | ||||
18668 | for (CXXConstructorDecl *Ctor : RD->ctors()) | ||||
18669 | if (Ctor->isCopyConstructor()) | ||||
18670 | return !Ctor->isDeleted(); | ||||
18671 | } | ||||
18672 | return false; | ||||
18673 | } | ||||
18674 | |||||
18675 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or | ||||
18676 | /// default capture. Fixes may be omitted if they aren't allowed by the | ||||
18677 | /// standard, for example we can't emit a default copy capture fix-it if we | ||||
18678 | /// already explicitly copy capture capture another variable. | ||||
18679 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, | ||||
18680 | ValueDecl *Var) { | ||||
18681 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast <bool> (LSI->ImpCaptureStyle == CapturingScopeInfo ::ImpCap_None) ? void (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None" , "clang/lib/Sema/SemaExpr.cpp", 18681, __extension__ __PRETTY_FUNCTION__ )); | ||||
18682 | // Don't offer Capture by copy of default capture by copy fixes if Var is | ||||
18683 | // known not to be copy constructible. | ||||
18684 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); | ||||
18685 | |||||
18686 | SmallString<32> FixBuffer; | ||||
18687 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; | ||||
18688 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { | ||||
18689 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); | ||||
18690 | if (ShouldOfferCopyFix) { | ||||
18691 | // Offer fixes to insert an explicit capture for the variable. | ||||
18692 | // [] -> [VarName] | ||||
18693 | // [OtherCapture] -> [OtherCapture, VarName] | ||||
18694 | FixBuffer.assign({Separator, Var->getName()}); | ||||
18695 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
18696 | << Var << /*value*/ 0 | ||||
18697 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
18698 | } | ||||
18699 | // As above but capture by reference. | ||||
18700 | FixBuffer.assign({Separator, "&", Var->getName()}); | ||||
18701 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
18702 | << Var << /*reference*/ 1 | ||||
18703 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
18704 | } | ||||
18705 | |||||
18706 | // Only try to offer default capture if there are no captures excluding this | ||||
18707 | // and init captures. | ||||
18708 | // [this]: OK. | ||||
18709 | // [X = Y]: OK. | ||||
18710 | // [&A, &B]: Don't offer. | ||||
18711 | // [A, B]: Don't offer. | ||||
18712 | if (llvm::any_of(LSI->Captures, [](Capture &C) { | ||||
18713 | return !C.isThisCapture() && !C.isInitCapture(); | ||||
18714 | })) | ||||
18715 | return; | ||||
18716 | |||||
18717 | // The default capture specifiers, '=' or '&', must appear first in the | ||||
18718 | // capture body. | ||||
18719 | SourceLocation DefaultInsertLoc = | ||||
18720 | LSI->IntroducerRange.getBegin().getLocWithOffset(1); | ||||
18721 | |||||
18722 | if (ShouldOfferCopyFix) { | ||||
18723 | bool CanDefaultCopyCapture = true; | ||||
18724 | // [=, *this] OK since c++17 | ||||
18725 | // [=, this] OK since c++20 | ||||
18726 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) | ||||
18727 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 | ||||
18728 | ? LSI->getCXXThisCapture().isCopyCapture() | ||||
18729 | : false; | ||||
18730 | // We can't use default capture by copy if any captures already specified | ||||
18731 | // capture by copy. | ||||
18732 | if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
18733 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); | ||||
18734 | })) { | ||||
18735 | FixBuffer.assign({"=", Separator}); | ||||
18736 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
18737 | << /*value*/ 0 | ||||
18738 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
18739 | } | ||||
18740 | } | ||||
18741 | |||||
18742 | // We can't use default capture by reference if any captures already specified | ||||
18743 | // capture by reference. | ||||
18744 | if (llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
18745 | return !C.isInitCapture() && C.isReferenceCapture() && | ||||
18746 | !C.isThisCapture(); | ||||
18747 | })) { | ||||
18748 | FixBuffer.assign({"&", Separator}); | ||||
18749 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
18750 | << /*reference*/ 1 | ||||
18751 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
18752 | } | ||||
18753 | } | ||||
18754 | |||||
18755 | bool Sema::tryCaptureVariable( | ||||
18756 | ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | ||||
18757 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | ||||
18758 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | ||||
18759 | // An init-capture is notionally from the context surrounding its | ||||
18760 | // declaration, but its parent DC is the lambda class. | ||||
18761 | DeclContext *VarDC = Var->getDeclContext(); | ||||
18762 | const auto *VD = dyn_cast<VarDecl>(Var); | ||||
18763 | if (VD) { | ||||
18764 | if (VD->isInitCapture()) | ||||
18765 | VarDC = VarDC->getParent(); | ||||
18766 | } else { | ||||
18767 | VD = dyn_cast<DecompositionDecl>( | ||||
18768 | cast<BindingDecl>(Var)->getDecomposedDecl()); | ||||
18769 | } | ||||
18770 | assert(VD && "Cannot capture a null variable")(static_cast <bool> (VD && "Cannot capture a null variable" ) ? void (0) : __assert_fail ("VD && \"Cannot capture a null variable\"" , "clang/lib/Sema/SemaExpr.cpp", 18770, __extension__ __PRETTY_FUNCTION__ )); | ||||
18771 | |||||
18772 | DeclContext *DC = CurContext; | ||||
18773 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | ||||
18774 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | ||||
18775 | // We need to sync up the Declaration Context with the | ||||
18776 | // FunctionScopeIndexToStopAt | ||||
18777 | if (FunctionScopeIndexToStopAt) { | ||||
18778 | unsigned FSIndex = FunctionScopes.size() - 1; | ||||
18779 | while (FSIndex != MaxFunctionScopesIndex) { | ||||
18780 | DC = getLambdaAwareParentOfDeclContext(DC); | ||||
18781 | --FSIndex; | ||||
18782 | } | ||||
18783 | } | ||||
18784 | |||||
18785 | |||||
18786 | // If the variable is declared in the current context, there is no need to | ||||
18787 | // capture it. | ||||
18788 | if (VarDC == DC) return true; | ||||
18789 | |||||
18790 | // Capture global variables if it is required to use private copy of this | ||||
18791 | // variable. | ||||
18792 | bool IsGlobal = !VD->hasLocalStorage(); | ||||
18793 | if (IsGlobal && | ||||
18794 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | ||||
18795 | MaxFunctionScopesIndex))) | ||||
18796 | return true; | ||||
18797 | |||||
18798 | if (isa<VarDecl>(Var)) | ||||
18799 | Var = cast<VarDecl>(Var->getCanonicalDecl()); | ||||
18800 | |||||
18801 | // Walk up the stack to determine whether we can capture the variable, | ||||
18802 | // performing the "simple" checks that don't depend on type. We stop when | ||||
18803 | // we've either hit the declared scope of the variable or find an existing | ||||
18804 | // capture of that variable. We start from the innermost capturing-entity | ||||
18805 | // (the DC) and ensure that all intervening capturing-entities | ||||
18806 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | ||||
18807 | // declcontext can either capture the variable or have already captured | ||||
18808 | // the variable. | ||||
18809 | CaptureType = Var->getType(); | ||||
18810 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
18811 | bool Nested = false; | ||||
18812 | bool Explicit = (Kind != TryCapture_Implicit); | ||||
18813 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | ||||
18814 | do { | ||||
18815 | // Only block literals, captured statements, and lambda expressions can | ||||
18816 | // capture; other scopes don't work. | ||||
18817 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | ||||
18818 | ExprLoc, | ||||
18819 | BuildAndDiagnose, | ||||
18820 | *this); | ||||
18821 | // We need to check for the parent *first* because, if we *have* | ||||
18822 | // private-captured a global variable, we need to recursively capture it in | ||||
18823 | // intermediate blocks, lambdas, etc. | ||||
18824 | if (!ParentDC) { | ||||
18825 | if (IsGlobal) { | ||||
18826 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | ||||
18827 | break; | ||||
18828 | } | ||||
18829 | return true; | ||||
18830 | } | ||||
18831 | |||||
18832 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | ||||
18833 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | ||||
18834 | |||||
18835 | |||||
18836 | // Check whether we've already captured it. | ||||
18837 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | ||||
18838 | DeclRefType)) { | ||||
18839 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | ||||
18840 | break; | ||||
18841 | } | ||||
18842 | // If we are instantiating a generic lambda call operator body, | ||||
18843 | // we do not want to capture new variables. What was captured | ||||
18844 | // during either a lambdas transformation or initial parsing | ||||
18845 | // should be used. | ||||
18846 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | ||||
18847 | if (BuildAndDiagnose) { | ||||
18848 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
18849 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | ||||
18850 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
18851 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18852 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
18853 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
18854 | } else | ||||
18855 | diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var); | ||||
18856 | } | ||||
18857 | return true; | ||||
18858 | } | ||||
18859 | |||||
18860 | // Try to capture variable-length arrays types. | ||||
18861 | if (Var->getType()->isVariablyModifiedType()) { | ||||
18862 | // We're going to walk down into the type and look for VLA | ||||
18863 | // expressions. | ||||
18864 | QualType QTy = Var->getType(); | ||||
18865 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
18866 | QTy = PVD->getOriginalType(); | ||||
18867 | captureVariablyModifiedType(Context, QTy, CSI); | ||||
18868 | } | ||||
18869 | |||||
18870 | if (getLangOpts().OpenMP) { | ||||
18871 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
18872 | // OpenMP private variables should not be captured in outer scope, so | ||||
18873 | // just break here. Similarly, global variables that are captured in a | ||||
18874 | // target region should not be captured outside the scope of the region. | ||||
18875 | if (RSI->CapRegionKind == CR_OpenMP) { | ||||
18876 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | ||||
18877 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | ||||
18878 | // If the variable is private (i.e. not captured) and has variably | ||||
18879 | // modified type, we still need to capture the type for correct | ||||
18880 | // codegen in all regions, associated with the construct. Currently, | ||||
18881 | // it is captured in the innermost captured region only. | ||||
18882 | if (IsOpenMPPrivateDecl != OMPC_unknown && | ||||
18883 | Var->getType()->isVariablyModifiedType()) { | ||||
18884 | QualType QTy = Var->getType(); | ||||
18885 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
18886 | QTy = PVD->getOriginalType(); | ||||
18887 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | ||||
18888 | I < E; ++I) { | ||||
18889 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | ||||
18890 | FunctionScopes[FunctionScopesIndex - I]); | ||||
18891 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 18893, __extension__ __PRETTY_FUNCTION__ )) | ||||
18892 | "Wrong number of captured regions associated with the "(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 18893, __extension__ __PRETTY_FUNCTION__ )) | ||||
18893 | "OpenMP construct.")(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "clang/lib/Sema/SemaExpr.cpp", 18893, __extension__ __PRETTY_FUNCTION__ )); | ||||
18894 | captureVariablyModifiedType(Context, QTy, OuterRSI); | ||||
18895 | } | ||||
18896 | } | ||||
18897 | bool IsTargetCap = | ||||
18898 | IsOpenMPPrivateDecl != OMPC_private && | ||||
18899 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | ||||
18900 | RSI->OpenMPCaptureLevel); | ||||
18901 | // Do not capture global if it is not privatized in outer regions. | ||||
18902 | bool IsGlobalCap = | ||||
18903 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | ||||
18904 | RSI->OpenMPCaptureLevel); | ||||
18905 | |||||
18906 | // When we detect target captures we are looking from inside the | ||||
18907 | // target region, therefore we need to propagate the capture from the | ||||
18908 | // enclosing region. Therefore, the capture is not initially nested. | ||||
18909 | if (IsTargetCap) | ||||
18910 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | ||||
18911 | |||||
18912 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | ||||
18913 | (IsGlobal && !IsGlobalCap)) { | ||||
18914 | Nested = !IsTargetCap; | ||||
18915 | bool HasConst = DeclRefType.isConstQualified(); | ||||
18916 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
18917 | // Don't lose diagnostics about assignments to const. | ||||
18918 | if (HasConst) | ||||
18919 | DeclRefType.addConst(); | ||||
18920 | CaptureType = Context.getLValueReferenceType(DeclRefType); | ||||
18921 | break; | ||||
18922 | } | ||||
18923 | } | ||||
18924 | } | ||||
18925 | } | ||||
18926 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | ||||
18927 | // No capture-default, and this is not an explicit capture | ||||
18928 | // so cannot capture this variable. | ||||
18929 | if (BuildAndDiagnose) { | ||||
18930 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
18931 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18932 | auto *LSI = cast<LambdaScopeInfo>(CSI); | ||||
18933 | if (LSI->Lambda) { | ||||
18934 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
18935 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
18936 | } | ||||
18937 | // FIXME: If we error out because an outer lambda can not implicitly | ||||
18938 | // capture a variable that an inner lambda explicitly captures, we | ||||
18939 | // should have the inner lambda do the explicit capture - because | ||||
18940 | // it makes for cleaner diagnostics later. This would purely be done | ||||
18941 | // so that the diagnostic does not misleadingly claim that a variable | ||||
18942 | // can not be captured by a lambda implicitly even though it is captured | ||||
18943 | // explicitly. Suggestion: | ||||
18944 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | ||||
18945 | // at the function head | ||||
18946 | // - cache the StartingDeclContext - this must be a lambda | ||||
18947 | // - captureInLambda in the innermost lambda the variable. | ||||
18948 | } | ||||
18949 | return true; | ||||
18950 | } | ||||
18951 | |||||
18952 | FunctionScopesIndex--; | ||||
18953 | DC = ParentDC; | ||||
18954 | Explicit = false; | ||||
18955 | } while (!VarDC->Equals(DC)); | ||||
18956 | |||||
18957 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | ||||
18958 | // computing the type of the capture at each step, checking type-specific | ||||
18959 | // requirements, and adding captures if requested. | ||||
18960 | // If the variable had already been captured previously, we start capturing | ||||
18961 | // at the lambda nested within that one. | ||||
18962 | bool Invalid = false; | ||||
18963 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | ||||
18964 | ++I) { | ||||
18965 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | ||||
18966 | |||||
18967 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
18968 | // certain types of variables (unnamed, variably modified types etc.) | ||||
18969 | // so check for eligibility. | ||||
18970 | if (!Invalid) | ||||
18971 | Invalid = | ||||
18972 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | ||||
18973 | |||||
18974 | // After encountering an error, if we're actually supposed to capture, keep | ||||
18975 | // capturing in nested contexts to suppress any follow-on diagnostics. | ||||
18976 | if (Invalid && !BuildAndDiagnose) | ||||
18977 | return true; | ||||
18978 | |||||
18979 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | ||||
18980 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
18981 | DeclRefType, Nested, *this, Invalid); | ||||
18982 | Nested = true; | ||||
18983 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
18984 | Invalid = !captureInCapturedRegion( | ||||
18985 | RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, | ||||
18986 | Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
18987 | Nested = true; | ||||
18988 | } else { | ||||
18989 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
18990 | Invalid = | ||||
18991 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
18992 | DeclRefType, Nested, Kind, EllipsisLoc, | ||||
18993 | /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
18994 | Nested = true; | ||||
18995 | } | ||||
18996 | |||||
18997 | if (Invalid && !BuildAndDiagnose) | ||||
18998 | return true; | ||||
18999 | } | ||||
19000 | return Invalid; | ||||
19001 | } | ||||
19002 | |||||
19003 | bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, | ||||
19004 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | ||||
19005 | QualType CaptureType; | ||||
19006 | QualType DeclRefType; | ||||
19007 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | ||||
19008 | /*BuildAndDiagnose=*/true, CaptureType, | ||||
19009 | DeclRefType, nullptr); | ||||
19010 | } | ||||
19011 | |||||
19012 | bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { | ||||
19013 | QualType CaptureType; | ||||
19014 | QualType DeclRefType; | ||||
19015 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
19016 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
19017 | DeclRefType, nullptr); | ||||
19018 | } | ||||
19019 | |||||
19020 | QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { | ||||
19021 | QualType CaptureType; | ||||
19022 | QualType DeclRefType; | ||||
19023 | |||||
19024 | // Determine whether we can capture this variable. | ||||
19025 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
19026 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
19027 | DeclRefType, nullptr)) | ||||
19028 | return QualType(); | ||||
19029 | |||||
19030 | return DeclRefType; | ||||
19031 | } | ||||
19032 | |||||
19033 | namespace { | ||||
19034 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | ||||
19035 | // The produced TemplateArgumentListInfo* points to data stored within this | ||||
19036 | // object, so should only be used in contexts where the pointer will not be | ||||
19037 | // used after the CopiedTemplateArgs object is destroyed. | ||||
19038 | class CopiedTemplateArgs { | ||||
19039 | bool HasArgs; | ||||
19040 | TemplateArgumentListInfo TemplateArgStorage; | ||||
19041 | public: | ||||
19042 | template<typename RefExpr> | ||||
19043 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | ||||
19044 | if (HasArgs) | ||||
19045 | E->copyTemplateArgumentsInto(TemplateArgStorage); | ||||
19046 | } | ||||
19047 | operator TemplateArgumentListInfo*() | ||||
19048 | #ifdef __has_cpp_attribute | ||||
19049 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | ||||
19050 | [[clang::lifetimebound]] | ||||
19051 | #endif | ||||
19052 | #endif | ||||
19053 | { | ||||
19054 | return HasArgs ? &TemplateArgStorage : nullptr; | ||||
19055 | } | ||||
19056 | }; | ||||
19057 | } | ||||
19058 | |||||
19059 | /// Walk the set of potential results of an expression and mark them all as | ||||
19060 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | ||||
19061 | /// | ||||
19062 | /// \return A new expression if we found any potential results, ExprEmpty() if | ||||
19063 | /// not, and ExprError() if we diagnosed an error. | ||||
19064 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | ||||
19065 | NonOdrUseReason NOUR) { | ||||
19066 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | ||||
19067 | // an object that satisfies the requirements for appearing in a | ||||
19068 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | ||||
19069 | // is immediately applied." This function handles the lvalue-to-rvalue | ||||
19070 | // conversion part. | ||||
19071 | // | ||||
19072 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | ||||
19073 | // transform it into the relevant kind of non-odr-use node and rebuild the | ||||
19074 | // tree of nodes leading to it. | ||||
19075 | // | ||||
19076 | // This is a mini-TreeTransform that only transforms a restricted subset of | ||||
19077 | // nodes (and only certain operands of them). | ||||
19078 | |||||
19079 | // Rebuild a subexpression. | ||||
19080 | auto Rebuild = [&](Expr *Sub) { | ||||
19081 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | ||||
19082 | }; | ||||
19083 | |||||
19084 | // Check whether a potential result satisfies the requirements of NOUR. | ||||
19085 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | ||||
19086 | // Any entity other than a VarDecl is always odr-used whenever it's named | ||||
19087 | // in a potentially-evaluated expression. | ||||
19088 | auto *VD = dyn_cast<VarDecl>(D); | ||||
19089 | if (!VD) | ||||
19090 | return true; | ||||
19091 | |||||
19092 | // C++2a [basic.def.odr]p4: | ||||
19093 | // A variable x whose name appears as a potentially-evalauted expression | ||||
19094 | // e is odr-used by e unless | ||||
19095 | // -- x is a reference that is usable in constant expressions, or | ||||
19096 | // -- x is a variable of non-reference type that is usable in constant | ||||
19097 | // expressions and has no mutable subobjects, and e is an element of | ||||
19098 | // the set of potential results of an expression of | ||||
19099 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
19100 | // conversion is applied, or | ||||
19101 | // -- x is a variable of non-reference type, and e is an element of the | ||||
19102 | // set of potential results of a discarded-value expression to which | ||||
19103 | // the lvalue-to-rvalue conversion is not applied | ||||
19104 | // | ||||
19105 | // We check the first bullet and the "potentially-evaluated" condition in | ||||
19106 | // BuildDeclRefExpr. We check the type requirements in the second bullet | ||||
19107 | // in CheckLValueToRValueConversionOperand below. | ||||
19108 | switch (NOUR) { | ||||
19109 | case NOUR_None: | ||||
19110 | case NOUR_Unevaluated: | ||||
19111 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "clang/lib/Sema/SemaExpr.cpp", 19111); | ||||
19112 | |||||
19113 | case NOUR_Constant: | ||||
19114 | // Constant references were handled when they were built. | ||||
19115 | if (VD->getType()->isReferenceType()) | ||||
19116 | return true; | ||||
19117 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | ||||
19118 | if (RD->hasMutableFields()) | ||||
19119 | return true; | ||||
19120 | if (!VD->isUsableInConstantExpressions(S.Context)) | ||||
19121 | return true; | ||||
19122 | break; | ||||
19123 | |||||
19124 | case NOUR_Discarded: | ||||
19125 | if (VD->getType()->isReferenceType()) | ||||
19126 | return true; | ||||
19127 | break; | ||||
19128 | } | ||||
19129 | return false; | ||||
19130 | }; | ||||
19131 | |||||
19132 | // Mark that this expression does not constitute an odr-use. | ||||
19133 | auto MarkNotOdrUsed = [&] { | ||||
19134 | S.MaybeODRUseExprs.remove(E); | ||||
19135 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | ||||
19136 | LSI->markVariableExprAsNonODRUsed(E); | ||||
19137 | }; | ||||
19138 | |||||
19139 | // C++2a [basic.def.odr]p2: | ||||
19140 | // The set of potential results of an expression e is defined as follows: | ||||
19141 | switch (E->getStmtClass()) { | ||||
19142 | // -- If e is an id-expression, ... | ||||
19143 | case Expr::DeclRefExprClass: { | ||||
19144 | auto *DRE = cast<DeclRefExpr>(E); | ||||
19145 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | ||||
19146 | break; | ||||
19147 | |||||
19148 | // Rebuild as a non-odr-use DeclRefExpr. | ||||
19149 | MarkNotOdrUsed(); | ||||
19150 | return DeclRefExpr::Create( | ||||
19151 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | ||||
19152 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | ||||
19153 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | ||||
19154 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | ||||
19155 | } | ||||
19156 | |||||
19157 | case Expr::FunctionParmPackExprClass: { | ||||
19158 | auto *FPPE = cast<FunctionParmPackExpr>(E); | ||||
19159 | // If any of the declarations in the pack is odr-used, then the expression | ||||
19160 | // as a whole constitutes an odr-use. | ||||
19161 | for (VarDecl *D : *FPPE) | ||||
19162 | if (IsPotentialResultOdrUsed(D)) | ||||
19163 | return ExprEmpty(); | ||||
19164 | |||||
19165 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | ||||
19166 | // nothing cares about whether we marked this as an odr-use, but it might | ||||
19167 | // be useful for non-compiler tools. | ||||
19168 | MarkNotOdrUsed(); | ||||
19169 | break; | ||||
19170 | } | ||||
19171 | |||||
19172 | // -- If e is a subscripting operation with an array operand... | ||||
19173 | case Expr::ArraySubscriptExprClass: { | ||||
19174 | auto *ASE = cast<ArraySubscriptExpr>(E); | ||||
19175 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | ||||
19176 | if (!OldBase->getType()->isArrayType()) | ||||
19177 | break; | ||||
19178 | ExprResult Base = Rebuild(OldBase); | ||||
19179 | if (!Base.isUsable()) | ||||
19180 | return Base; | ||||
19181 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | ||||
19182 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | ||||
19183 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | ||||
19184 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | ||||
19185 | ASE->getRBracketLoc()); | ||||
19186 | } | ||||
19187 | |||||
19188 | case Expr::MemberExprClass: { | ||||
19189 | auto *ME = cast<MemberExpr>(E); | ||||
19190 | // -- If e is a class member access expression [...] naming a non-static | ||||
19191 | // data member... | ||||
19192 | if (isa<FieldDecl>(ME->getMemberDecl())) { | ||||
19193 | ExprResult Base = Rebuild(ME->getBase()); | ||||
19194 | if (!Base.isUsable()) | ||||
19195 | return Base; | ||||
19196 | return MemberExpr::Create( | ||||
19197 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | ||||
19198 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | ||||
19199 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | ||||
19200 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | ||||
19201 | ME->getObjectKind(), ME->isNonOdrUse()); | ||||
19202 | } | ||||
19203 | |||||
19204 | if (ME->getMemberDecl()->isCXXInstanceMember()) | ||||
19205 | break; | ||||
19206 | |||||
19207 | // -- If e is a class member access expression naming a static data member, | ||||
19208 | // ... | ||||
19209 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | ||||
19210 | break; | ||||
19211 | |||||
19212 | // Rebuild as a non-odr-use MemberExpr. | ||||
19213 | MarkNotOdrUsed(); | ||||
19214 | return MemberExpr::Create( | ||||
19215 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | ||||
19216 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | ||||
19217 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | ||||
19218 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | ||||
19219 | } | ||||
19220 | |||||
19221 | case Expr::BinaryOperatorClass: { | ||||
19222 | auto *BO = cast<BinaryOperator>(E); | ||||
19223 | Expr *LHS = BO->getLHS(); | ||||
19224 | Expr *RHS = BO->getRHS(); | ||||
19225 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | ||||
19226 | if (BO->getOpcode() == BO_PtrMemD) { | ||||
19227 | ExprResult Sub = Rebuild(LHS); | ||||
19228 | if (!Sub.isUsable()) | ||||
19229 | return Sub; | ||||
19230 | LHS = Sub.get(); | ||||
19231 | // -- If e is a comma expression, ... | ||||
19232 | } else if (BO->getOpcode() == BO_Comma) { | ||||
19233 | ExprResult Sub = Rebuild(RHS); | ||||
19234 | if (!Sub.isUsable()) | ||||
19235 | return Sub; | ||||
19236 | RHS = Sub.get(); | ||||
19237 | } else { | ||||
19238 | break; | ||||
19239 | } | ||||
19240 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | ||||
19241 | LHS, RHS); | ||||
19242 | } | ||||
19243 | |||||
19244 | // -- If e has the form (e1)... | ||||
19245 | case Expr::ParenExprClass: { | ||||
19246 | auto *PE = cast<ParenExpr>(E); | ||||
19247 | ExprResult Sub = Rebuild(PE->getSubExpr()); | ||||
19248 | if (!Sub.isUsable()) | ||||
19249 | return Sub; | ||||
19250 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | ||||
19251 | } | ||||
19252 | |||||
19253 | // -- If e is a glvalue conditional expression, ... | ||||
19254 | // We don't apply this to a binary conditional operator. FIXME: Should we? | ||||
19255 | case Expr::ConditionalOperatorClass: { | ||||
19256 | auto *CO = cast<ConditionalOperator>(E); | ||||
19257 | ExprResult LHS = Rebuild(CO->getLHS()); | ||||
19258 | if (LHS.isInvalid()) | ||||
19259 | return ExprError(); | ||||
19260 | ExprResult RHS = Rebuild(CO->getRHS()); | ||||
19261 | if (RHS.isInvalid()) | ||||
19262 | return ExprError(); | ||||
19263 | if (!LHS.isUsable() && !RHS.isUsable()) | ||||
19264 | return ExprEmpty(); | ||||
19265 | if (!LHS.isUsable()) | ||||
19266 | LHS = CO->getLHS(); | ||||
19267 | if (!RHS.isUsable()) | ||||
19268 | RHS = CO->getRHS(); | ||||
19269 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | ||||
19270 | CO->getCond(), LHS.get(), RHS.get()); | ||||
19271 | } | ||||
19272 | |||||
19273 | // [Clang extension] | ||||
19274 | // -- If e has the form __extension__ e1... | ||||
19275 | case Expr::UnaryOperatorClass: { | ||||
19276 | auto *UO = cast<UnaryOperator>(E); | ||||
19277 | if (UO->getOpcode() != UO_Extension) | ||||
19278 | break; | ||||
19279 | ExprResult Sub = Rebuild(UO->getSubExpr()); | ||||
19280 | if (!Sub.isUsable()) | ||||
19281 | return Sub; | ||||
19282 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | ||||
19283 | Sub.get()); | ||||
19284 | } | ||||
19285 | |||||
19286 | // [Clang extension] | ||||
19287 | // -- If e has the form _Generic(...), the set of potential results is the | ||||
19288 | // union of the sets of potential results of the associated expressions. | ||||
19289 | case Expr::GenericSelectionExprClass: { | ||||
19290 | auto *GSE = cast<GenericSelectionExpr>(E); | ||||
19291 | |||||
19292 | SmallVector<Expr *, 4> AssocExprs; | ||||
19293 | bool AnyChanged = false; | ||||
19294 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | ||||
19295 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | ||||
19296 | if (AssocExpr.isInvalid()) | ||||
19297 | return ExprError(); | ||||
19298 | if (AssocExpr.isUsable()) { | ||||
19299 | AssocExprs.push_back(AssocExpr.get()); | ||||
19300 | AnyChanged = true; | ||||
19301 | } else { | ||||
19302 | AssocExprs.push_back(OrigAssocExpr); | ||||
19303 | } | ||||
19304 | } | ||||
19305 | |||||
19306 | return AnyChanged ? S.CreateGenericSelectionExpr( | ||||
19307 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | ||||
19308 | GSE->getRParenLoc(), GSE->getControllingExpr(), | ||||
19309 | GSE->getAssocTypeSourceInfos(), AssocExprs) | ||||
19310 | : ExprEmpty(); | ||||
19311 | } | ||||
19312 | |||||
19313 | // [Clang extension] | ||||
19314 | // -- If e has the form __builtin_choose_expr(...), the set of potential | ||||
19315 | // results is the union of the sets of potential results of the | ||||
19316 | // second and third subexpressions. | ||||
19317 | case Expr::ChooseExprClass: { | ||||
19318 | auto *CE = cast<ChooseExpr>(E); | ||||
19319 | |||||
19320 | ExprResult LHS = Rebuild(CE->getLHS()); | ||||
19321 | if (LHS.isInvalid()) | ||||
19322 | return ExprError(); | ||||
19323 | |||||
19324 | ExprResult RHS = Rebuild(CE->getLHS()); | ||||
19325 | if (RHS.isInvalid()) | ||||
19326 | return ExprError(); | ||||
19327 | |||||
19328 | if (!LHS.get() && !RHS.get()) | ||||
19329 | return ExprEmpty(); | ||||
19330 | if (!LHS.isUsable()) | ||||
19331 | LHS = CE->getLHS(); | ||||
19332 | if (!RHS.isUsable()) | ||||
19333 | RHS = CE->getRHS(); | ||||
19334 | |||||
19335 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | ||||
19336 | RHS.get(), CE->getRParenLoc()); | ||||
19337 | } | ||||
19338 | |||||
19339 | // Step through non-syntactic nodes. | ||||
19340 | case Expr::ConstantExprClass: { | ||||
19341 | auto *CE = cast<ConstantExpr>(E); | ||||
19342 | ExprResult Sub = Rebuild(CE->getSubExpr()); | ||||
19343 | if (!Sub.isUsable()) | ||||
19344 | return Sub; | ||||
19345 | return ConstantExpr::Create(S.Context, Sub.get()); | ||||
19346 | } | ||||
19347 | |||||
19348 | // We could mostly rely on the recursive rebuilding to rebuild implicit | ||||
19349 | // casts, but not at the top level, so rebuild them here. | ||||
19350 | case Expr::ImplicitCastExprClass: { | ||||
19351 | auto *ICE = cast<ImplicitCastExpr>(E); | ||||
19352 | // Only step through the narrow set of cast kinds we expect to encounter. | ||||
19353 | // Anything else suggests we've left the region in which potential results | ||||
19354 | // can be found. | ||||
19355 | switch (ICE->getCastKind()) { | ||||
19356 | case CK_NoOp: | ||||
19357 | case CK_DerivedToBase: | ||||
19358 | case CK_UncheckedDerivedToBase: { | ||||
19359 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | ||||
19360 | if (!Sub.isUsable()) | ||||
19361 | return Sub; | ||||
19362 | CXXCastPath Path(ICE->path()); | ||||
19363 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | ||||
19364 | ICE->getValueKind(), &Path); | ||||
19365 | } | ||||
19366 | |||||
19367 | default: | ||||
19368 | break; | ||||
19369 | } | ||||
19370 | break; | ||||
19371 | } | ||||
19372 | |||||
19373 | default: | ||||
19374 | break; | ||||
19375 | } | ||||
19376 | |||||
19377 | // Can't traverse through this node. Nothing to do. | ||||
19378 | return ExprEmpty(); | ||||
19379 | } | ||||
19380 | |||||
19381 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | ||||
19382 | // Check whether the operand is or contains an object of non-trivial C union | ||||
19383 | // type. | ||||
19384 | if (E->getType().isVolatileQualified() && | ||||
19385 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
19386 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | ||||
19387 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
19388 | Sema::NTCUC_LValueToRValueVolatile, | ||||
19389 | NTCUK_Destruct|NTCUK_Copy); | ||||
19390 | |||||
19391 | // C++2a [basic.def.odr]p4: | ||||
19392 | // [...] an expression of non-volatile-qualified non-class type to which | ||||
19393 | // the lvalue-to-rvalue conversion is applied [...] | ||||
19394 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | ||||
19395 | return E; | ||||
19396 | |||||
19397 | ExprResult Result = | ||||
19398 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | ||||
19399 | if (Result.isInvalid()) | ||||
19400 | return ExprError(); | ||||
19401 | return Result.get() ? Result : E; | ||||
19402 | } | ||||
19403 | |||||
19404 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | ||||
19405 | Res = CorrectDelayedTyposInExpr(Res); | ||||
19406 | |||||
19407 | if (!Res.isUsable()) | ||||
19408 | return Res; | ||||
19409 | |||||
19410 | // If a constant-expression is a reference to a variable where we delay | ||||
19411 | // deciding whether it is an odr-use, just assume we will apply the | ||||
19412 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | ||||
19413 | // (a non-type template argument), we have special handling anyway. | ||||
19414 | return CheckLValueToRValueConversionOperand(Res.get()); | ||||
19415 | } | ||||
19416 | |||||
19417 | void Sema::CleanupVarDeclMarking() { | ||||
19418 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | ||||
19419 | // call. | ||||
19420 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | ||||
19421 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | ||||
19422 | |||||
19423 | for (Expr *E : LocalMaybeODRUseExprs) { | ||||
19424 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
19425 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | ||||
19426 | DRE->getLocation(), *this); | ||||
19427 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
19428 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | ||||
19429 | *this); | ||||
19430 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | ||||
19431 | for (VarDecl *VD : *FP) | ||||
19432 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | ||||
19433 | } else { | ||||
19434 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "clang/lib/Sema/SemaExpr.cpp" , 19434); | ||||
19435 | } | ||||
19436 | } | ||||
19437 | |||||
19438 | assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "clang/lib/Sema/SemaExpr.cpp", 19439, __extension__ __PRETTY_FUNCTION__ )) | ||||
19439 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "clang/lib/Sema/SemaExpr.cpp", 19439, __extension__ __PRETTY_FUNCTION__ )); | ||||
19440 | } | ||||
19441 | |||||
19442 | static void DoMarkVarDeclReferenced( | ||||
19443 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, | ||||
19444 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | ||||
19445 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 19447, __extension__ __PRETTY_FUNCTION__ )) | ||||
19446 | isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 19447, __extension__ __PRETTY_FUNCTION__ )) | ||||
19447 | "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "clang/lib/Sema/SemaExpr.cpp", 19447, __extension__ __PRETTY_FUNCTION__ )); | ||||
19448 | Var->setReferenced(); | ||||
19449 | |||||
19450 | if (Var->isInvalidDecl()) | ||||
19451 | return; | ||||
19452 | |||||
19453 | auto *MSI = Var->getMemberSpecializationInfo(); | ||||
19454 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | ||||
19455 | : Var->getTemplateSpecializationKind(); | ||||
19456 | |||||
19457 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
19458 | bool UsableInConstantExpr = | ||||
19459 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | ||||
19460 | |||||
19461 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { | ||||
19462 | RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; | ||||
19463 | } | ||||
19464 | |||||
19465 | // C++20 [expr.const]p12: | ||||
19466 | // A variable [...] is needed for constant evaluation if it is [...] a | ||||
19467 | // variable whose name appears as a potentially constant evaluated | ||||
19468 | // expression that is either a contexpr variable or is of non-volatile | ||||
19469 | // const-qualified integral type or of reference type | ||||
19470 | bool NeededForConstantEvaluation = | ||||
19471 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | ||||
19472 | |||||
19473 | bool NeedDefinition = | ||||
19474 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | ||||
19475 | |||||
19476 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "clang/lib/Sema/SemaExpr.cpp", 19477, __extension__ __PRETTY_FUNCTION__ )) | ||||
19477 | "Can't instantiate a partial template specialization.")(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "clang/lib/Sema/SemaExpr.cpp", 19477, __extension__ __PRETTY_FUNCTION__ )); | ||||
19478 | |||||
19479 | // If this might be a member specialization of a static data member, check | ||||
19480 | // the specialization is visible. We already did the checks for variable | ||||
19481 | // template specializations when we created them. | ||||
19482 | if (NeedDefinition && TSK != TSK_Undeclared && | ||||
19483 | !isa<VarTemplateSpecializationDecl>(Var)) | ||||
19484 | SemaRef.checkSpecializationVisibility(Loc, Var); | ||||
19485 | |||||
19486 | // Perform implicit instantiation of static data members, static data member | ||||
19487 | // templates of class templates, and variable template specializations. Delay | ||||
19488 | // instantiations of variable templates, except for those that could be used | ||||
19489 | // in a constant expression. | ||||
19490 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | ||||
19491 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | ||||
19492 | // instantiation declaration if a variable is usable in a constant | ||||
19493 | // expression (among other cases). | ||||
19494 | bool TryInstantiating = | ||||
19495 | TSK == TSK_ImplicitInstantiation || | ||||
19496 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | ||||
19497 | |||||
19498 | if (TryInstantiating) { | ||||
19499 | SourceLocation PointOfInstantiation = | ||||
19500 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | ||||
19501 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
19502 | if (FirstInstantiation) { | ||||
19503 | PointOfInstantiation = Loc; | ||||
19504 | if (MSI) | ||||
19505 | MSI->setPointOfInstantiation(PointOfInstantiation); | ||||
19506 | // FIXME: Notify listener. | ||||
19507 | else | ||||
19508 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
19509 | } | ||||
19510 | |||||
19511 | if (UsableInConstantExpr) { | ||||
19512 | // Do not defer instantiations of variables that could be used in a | ||||
19513 | // constant expression. | ||||
19514 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||
19515 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||
19516 | }); | ||||
19517 | |||||
19518 | // Re-set the member to trigger a recomputation of the dependence bits | ||||
19519 | // for the expression. | ||||
19520 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
19521 | DRE->setDecl(DRE->getDecl()); | ||||
19522 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
19523 | ME->setMemberDecl(ME->getMemberDecl()); | ||||
19524 | } else if (FirstInstantiation || | ||||
19525 | isa<VarTemplateSpecializationDecl>(Var)) { | ||||
19526 | // FIXME: For a specialization of a variable template, we don't | ||||
19527 | // distinguish between "declaration and type implicitly instantiated" | ||||
19528 | // and "implicit instantiation of definition requested", so we have | ||||
19529 | // no direct way to avoid enqueueing the pending instantiation | ||||
19530 | // multiple times. | ||||
19531 | SemaRef.PendingInstantiations | ||||
19532 | .push_back(std::make_pair(Var, PointOfInstantiation)); | ||||
19533 | } | ||||
19534 | } | ||||
19535 | } | ||||
19536 | |||||
19537 | // C++2a [basic.def.odr]p4: | ||||
19538 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
19539 | // is odr-used by e unless | ||||
19540 | // -- x is a reference that is usable in constant expressions | ||||
19541 | // -- x is a variable of non-reference type that is usable in constant | ||||
19542 | // expressions and has no mutable subobjects [FIXME], and e is an | ||||
19543 | // element of the set of potential results of an expression of | ||||
19544 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
19545 | // conversion is applied | ||||
19546 | // -- x is a variable of non-reference type, and e is an element of the set | ||||
19547 | // of potential results of a discarded-value expression to which the | ||||
19548 | // lvalue-to-rvalue conversion is not applied [FIXME] | ||||
19549 | // | ||||
19550 | // We check the first part of the second bullet here, and | ||||
19551 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | ||||
19552 | // FIXME: To get the third bullet right, we need to delay this even for | ||||
19553 | // variables that are not usable in constant expressions. | ||||
19554 | |||||
19555 | // If we already know this isn't an odr-use, there's nothing more to do. | ||||
19556 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
19557 | if (DRE->isNonOdrUse()) | ||||
19558 | return; | ||||
19559 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
19560 | if (ME->isNonOdrUse()) | ||||
19561 | return; | ||||
19562 | |||||
19563 | switch (OdrUse) { | ||||
19564 | case OdrUseContext::None: | ||||
19565 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 19566, __extension__ __PRETTY_FUNCTION__ )) | ||||
19566 | "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "clang/lib/Sema/SemaExpr.cpp", 19566, __extension__ __PRETTY_FUNCTION__ )); | ||||
19567 | break; | ||||
19568 | |||||
19569 | case OdrUseContext::FormallyOdrUsed: | ||||
19570 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | ||||
19571 | // behavior. | ||||
19572 | break; | ||||
19573 | |||||
19574 | case OdrUseContext::Used: | ||||
19575 | // If we might later find that this expression isn't actually an odr-use, | ||||
19576 | // delay the marking. | ||||
19577 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
19578 | SemaRef.MaybeODRUseExprs.insert(E); | ||||
19579 | else | ||||
19580 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | ||||
19581 | break; | ||||
19582 | |||||
19583 | case OdrUseContext::Dependent: | ||||
19584 | // If this is a dependent context, we don't need to mark variables as | ||||
19585 | // odr-used, but we may still need to track them for lambda capture. | ||||
19586 | // FIXME: Do we also need to do this inside dependent typeid expressions | ||||
19587 | // (which are modeled as unevaluated at this point)? | ||||
19588 | const bool RefersToEnclosingScope = | ||||
19589 | (SemaRef.CurContext != Var->getDeclContext() && | ||||
19590 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | ||||
19591 | if (RefersToEnclosingScope) { | ||||
19592 | LambdaScopeInfo *const LSI = | ||||
19593 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | ||||
19594 | if (LSI && (!LSI->CallOperator || | ||||
19595 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | ||||
19596 | // If a variable could potentially be odr-used, defer marking it so | ||||
19597 | // until we finish analyzing the full expression for any | ||||
19598 | // lvalue-to-rvalue | ||||
19599 | // or discarded value conversions that would obviate odr-use. | ||||
19600 | // Add it to the list of potential captures that will be analyzed | ||||
19601 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | ||||
19602 | // unless the variable is a reference that was initialized by a constant | ||||
19603 | // expression (this will never need to be captured or odr-used). | ||||
19604 | // | ||||
19605 | // FIXME: We can simplify this a lot after implementing P0588R1. | ||||
19606 | assert(E && "Capture variable should be used in an expression.")(static_cast <bool> (E && "Capture variable should be used in an expression." ) ? void (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "clang/lib/Sema/SemaExpr.cpp", 19606, __extension__ __PRETTY_FUNCTION__ )); | ||||
19607 | if (!Var->getType()->isReferenceType() || | ||||
19608 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
19609 | LSI->addPotentialCapture(E->IgnoreParens()); | ||||
19610 | } | ||||
19611 | } | ||||
19612 | break; | ||||
19613 | } | ||||
19614 | } | ||||
19615 | |||||
19616 | static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, | ||||
19617 | BindingDecl *BD) { | ||||
19618 | BD->setReferenced(); | ||||
19619 | |||||
19620 | if (BD->isInvalidDecl()) | ||||
19621 | return; | ||||
19622 | |||||
19623 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
19624 | if (OdrUse == OdrUseContext::Used) { | ||||
19625 | QualType CaptureType, DeclRefType; | ||||
19626 | SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit, | ||||
19627 | /*EllipsisLoc*/ SourceLocation(), | ||||
19628 | /*BuildAndDiagnose*/ true, CaptureType, | ||||
19629 | DeclRefType, | ||||
19630 | /*FunctionScopeIndexToStopAt*/ nullptr); | ||||
19631 | } | ||||
19632 | } | ||||
19633 | |||||
19634 | /// Mark a variable referenced, and check whether it is odr-used | ||||
19635 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | ||||
19636 | /// used directly for normal expressions referring to VarDecl. | ||||
19637 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | ||||
19638 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); | ||||
19639 | } | ||||
19640 | |||||
19641 | static void | ||||
19642 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, | ||||
19643 | bool MightBeOdrUse, | ||||
19644 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | ||||
19645 | if (SemaRef.isInOpenMPDeclareTargetContext()) | ||||
19646 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | ||||
19647 | |||||
19648 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | ||||
19649 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); | ||||
19650 | return; | ||||
19651 | } | ||||
19652 | |||||
19653 | if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) { | ||||
19654 | DoMarkBindingDeclReferenced(SemaRef, Loc, Decl); | ||||
19655 | return; | ||||
19656 | } | ||||
19657 | |||||
19658 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | ||||
19659 | |||||
19660 | // If this is a call to a method via a cast, also mark the method in the | ||||
19661 | // derived class used in case codegen can devirtualize the call. | ||||
19662 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
19663 | if (!ME) | ||||
19664 | return; | ||||
19665 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
19666 | if (!MD) | ||||
19667 | return; | ||||
19668 | // Only attempt to devirtualize if this is truly a virtual call. | ||||
19669 | bool IsVirtualCall = MD->isVirtual() && | ||||
19670 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | ||||
19671 | if (!IsVirtualCall) | ||||
19672 | return; | ||||
19673 | |||||
19674 | // If it's possible to devirtualize the call, mark the called function | ||||
19675 | // referenced. | ||||
19676 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | ||||
19677 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | ||||
19678 | if (DM) | ||||
19679 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | ||||
19680 | } | ||||
19681 | |||||
19682 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | ||||
19683 | /// | ||||
19684 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to be | ||||
19685 | /// handled with care if the DeclRefExpr is not newly-created. | ||||
19686 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | ||||
19687 | // TODO: update this with DR# once a defect report is filed. | ||||
19688 | // C++11 defect. The address of a pure member should not be an ODR use, even | ||||
19689 | // if it's a qualified reference. | ||||
19690 | bool OdrUse = true; | ||||
19691 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | ||||
19692 | if (Method->isVirtual() && | ||||
19693 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | ||||
19694 | OdrUse = false; | ||||
19695 | |||||
19696 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||
19697 | if (!isUnevaluatedContext() && !isConstantEvaluated() && | ||||
19698 | !isImmediateFunctionContext() && FD->isConsteval() && | ||||
19699 | !RebuildingImmediateInvocation && !FD->isDependentContext()) | ||||
19700 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | ||||
19701 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, | ||||
19702 | RefsMinusAssignments); | ||||
19703 | } | ||||
19704 | |||||
19705 | /// Perform reference-marking and odr-use handling for a MemberExpr. | ||||
19706 | void Sema::MarkMemberReferenced(MemberExpr *E) { | ||||
19707 | // C++11 [basic.def.odr]p2: | ||||
19708 | // A non-overloaded function whose name appears as a potentially-evaluated | ||||
19709 | // expression or a member of a set of candidate functions, if selected by | ||||
19710 | // overload resolution when referred to from a potentially-evaluated | ||||
19711 | // expression, is odr-used, unless it is a pure virtual function and its | ||||
19712 | // name is not explicitly qualified. | ||||
19713 | bool MightBeOdrUse = true; | ||||
19714 | if (E->performsVirtualDispatch(getLangOpts())) { | ||||
19715 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | ||||
19716 | if (Method->isPure()) | ||||
19717 | MightBeOdrUse = false; | ||||
19718 | } | ||||
19719 | SourceLocation Loc = | ||||
19720 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | ||||
19721 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, | ||||
19722 | RefsMinusAssignments); | ||||
19723 | } | ||||
19724 | |||||
19725 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | ||||
19726 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | ||||
19727 | for (VarDecl *VD : *E) | ||||
19728 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, | ||||
19729 | RefsMinusAssignments); | ||||
19730 | } | ||||
19731 | |||||
19732 | /// Perform marking for a reference to an arbitrary declaration. It | ||||
19733 | /// marks the declaration referenced, and performs odr-use checking for | ||||
19734 | /// functions and variables. This method should not be used when building a | ||||
19735 | /// normal expression which refers to a variable. | ||||
19736 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | ||||
19737 | bool MightBeOdrUse) { | ||||
19738 | if (MightBeOdrUse) { | ||||
19739 | if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||
19740 | MarkVariableReferenced(Loc, VD); | ||||
19741 | return; | ||||
19742 | } | ||||
19743 | } | ||||
19744 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||
19745 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | ||||
19746 | return; | ||||
19747 | } | ||||
19748 | D->setReferenced(); | ||||
19749 | } | ||||
19750 | |||||
19751 | namespace { | ||||
19752 | // Mark all of the declarations used by a type as referenced. | ||||
19753 | // FIXME: Not fully implemented yet! We need to have a better understanding | ||||
19754 | // of when we're entering a context we should not recurse into. | ||||
19755 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | ||||
19756 | // TreeTransforms rebuilding the type in a new context. Rather than | ||||
19757 | // duplicating the TreeTransform logic, we should consider reusing it here. | ||||
19758 | // Currently that causes problems when rebuilding LambdaExprs. | ||||
19759 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | ||||
19760 | Sema &S; | ||||
19761 | SourceLocation Loc; | ||||
19762 | |||||
19763 | public: | ||||
19764 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | ||||
19765 | |||||
19766 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | ||||
19767 | |||||
19768 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | ||||
19769 | }; | ||||
19770 | } | ||||
19771 | |||||
19772 | bool MarkReferencedDecls::TraverseTemplateArgument( | ||||
19773 | const TemplateArgument &Arg) { | ||||
19774 | { | ||||
19775 | // A non-type template argument is a constant-evaluated context. | ||||
19776 | EnterExpressionEvaluationContext Evaluated( | ||||
19777 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
19778 | if (Arg.getKind() == TemplateArgument::Declaration) { | ||||
19779 | if (Decl *D = Arg.getAsDecl()) | ||||
19780 | S.MarkAnyDeclReferenced(Loc, D, true); | ||||
19781 | } else if (Arg.getKind() == TemplateArgument::Expression) { | ||||
19782 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | ||||
19783 | } | ||||
19784 | } | ||||
19785 | |||||
19786 | return Inherited::TraverseTemplateArgument(Arg); | ||||
19787 | } | ||||
19788 | |||||
19789 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | ||||
19790 | MarkReferencedDecls Marker(*this, Loc); | ||||
19791 | Marker.TraverseType(T); | ||||
19792 | } | ||||
19793 | |||||
19794 | namespace { | ||||
19795 | /// Helper class that marks all of the declarations referenced by | ||||
19796 | /// potentially-evaluated subexpressions as "referenced". | ||||
19797 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | ||||
19798 | public: | ||||
19799 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | ||||
19800 | bool SkipLocalVariables; | ||||
19801 | ArrayRef<const Expr *> StopAt; | ||||
19802 | |||||
19803 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, | ||||
19804 | ArrayRef<const Expr *> StopAt) | ||||
19805 | : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} | ||||
19806 | |||||
19807 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | ||||
19808 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | ||||
19809 | } | ||||
19810 | |||||
19811 | void Visit(Expr *E) { | ||||
19812 | if (llvm::is_contained(StopAt, E)) | ||||
19813 | return; | ||||
19814 | Inherited::Visit(E); | ||||
19815 | } | ||||
19816 | |||||
19817 | void VisitConstantExpr(ConstantExpr *E) { | ||||
19818 | // Don't mark declarations within a ConstantExpression, as this expression | ||||
19819 | // will be evaluated and folded to a value. | ||||
19820 | } | ||||
19821 | |||||
19822 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||
19823 | // If we were asked not to visit local variables, don't. | ||||
19824 | if (SkipLocalVariables) { | ||||
19825 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||
19826 | if (VD->hasLocalStorage()) | ||||
19827 | return; | ||||
19828 | } | ||||
19829 | |||||
19830 | // FIXME: This can trigger the instantiation of the initializer of a | ||||
19831 | // variable, which can cause the expression to become value-dependent | ||||
19832 | // or error-dependent. Do we need to propagate the new dependence bits? | ||||
19833 | S.MarkDeclRefReferenced(E); | ||||
19834 | } | ||||
19835 | |||||
19836 | void VisitMemberExpr(MemberExpr *E) { | ||||
19837 | S.MarkMemberReferenced(E); | ||||
19838 | Visit(E->getBase()); | ||||
19839 | } | ||||
19840 | }; | ||||
19841 | } // namespace | ||||
19842 | |||||
19843 | /// Mark any declarations that appear within this expression or any | ||||
19844 | /// potentially-evaluated subexpressions as "referenced". | ||||
19845 | /// | ||||
19846 | /// \param SkipLocalVariables If true, don't mark local variables as | ||||
19847 | /// 'referenced'. | ||||
19848 | /// \param StopAt Subexpressions that we shouldn't recurse into. | ||||
19849 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | ||||
19850 | bool SkipLocalVariables, | ||||
19851 | ArrayRef<const Expr*> StopAt) { | ||||
19852 | EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); | ||||
19853 | } | ||||
19854 | |||||
19855 | /// Emit a diagnostic when statements are reachable. | ||||
19856 | /// FIXME: check for reachability even in expressions for which we don't build a | ||||
19857 | /// CFG (eg, in the initializer of a global or in a constant expression). | ||||
19858 | /// For example, | ||||
19859 | /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } | ||||
19860 | bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, | ||||
19861 | const PartialDiagnostic &PD) { | ||||
19862 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | ||||
19863 | if (!FunctionScopes.empty()) | ||||
19864 | FunctionScopes.back()->PossiblyUnreachableDiags.push_back( | ||||
19865 | sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | ||||
19866 | return true; | ||||
19867 | } | ||||
19868 | |||||
19869 | // The initializer of a constexpr variable or of the first declaration of a | ||||
19870 | // static data member is not syntactically a constant evaluated constant, | ||||
19871 | // but nonetheless is always required to be a constant expression, so we | ||||
19872 | // can skip diagnosing. | ||||
19873 | // FIXME: Using the mangling context here is a hack. | ||||
19874 | if (auto *VD = dyn_cast_or_null<VarDecl>( | ||||
19875 | ExprEvalContexts.back().ManglingContextDecl)) { | ||||
19876 | if (VD->isConstexpr() || | ||||
19877 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | ||||
19878 | return false; | ||||
19879 | // FIXME: For any other kind of variable, we should build a CFG for its | ||||
19880 | // initializer and check whether the context in question is reachable. | ||||
19881 | } | ||||
19882 | |||||
19883 | Diag(Loc, PD); | ||||
19884 | return true; | ||||
19885 | } | ||||
19886 | |||||
19887 | /// Emit a diagnostic that describes an effect on the run-time behavior | ||||
19888 | /// of the program being compiled. | ||||
19889 | /// | ||||
19890 | /// This routine emits the given diagnostic when the code currently being | ||||
19891 | /// type-checked is "potentially evaluated", meaning that there is a | ||||
19892 | /// possibility that the code will actually be executable. Code in sizeof() | ||||
19893 | /// expressions, code used only during overload resolution, etc., are not | ||||
19894 | /// potentially evaluated. This routine will suppress such diagnostics or, | ||||
19895 | /// in the absolutely nutty case of potentially potentially evaluated | ||||
19896 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | ||||
19897 | /// later. | ||||
19898 | /// | ||||
19899 | /// This routine should be used for all diagnostics that describe the run-time | ||||
19900 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | ||||
19901 | /// Failure to do so will likely result in spurious diagnostics or failures | ||||
19902 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | ||||
19903 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | ||||
19904 | const PartialDiagnostic &PD) { | ||||
19905 | |||||
19906 | if (ExprEvalContexts.back().isDiscardedStatementContext()) | ||||
19907 | return false; | ||||
19908 | |||||
19909 | switch (ExprEvalContexts.back().Context) { | ||||
19910 | case ExpressionEvaluationContext::Unevaluated: | ||||
19911 | case ExpressionEvaluationContext::UnevaluatedList: | ||||
19912 | case ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
19913 | case ExpressionEvaluationContext::DiscardedStatement: | ||||
19914 | // The argument will never be evaluated, so don't complain. | ||||
19915 | break; | ||||
19916 | |||||
19917 | case ExpressionEvaluationContext::ConstantEvaluated: | ||||
19918 | case ExpressionEvaluationContext::ImmediateFunctionContext: | ||||
19919 | // Relevant diagnostics should be produced by constant evaluation. | ||||
19920 | break; | ||||
19921 | |||||
19922 | case ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
19923 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
19924 | return DiagIfReachable(Loc, Stmts, PD); | ||||
19925 | } | ||||
19926 | |||||
19927 | return false; | ||||
19928 | } | ||||
19929 | |||||
19930 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | ||||
19931 | const PartialDiagnostic &PD) { | ||||
19932 | return DiagRuntimeBehavior( | ||||
19933 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | ||||
19934 | } | ||||
19935 | |||||
19936 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | ||||
19937 | CallExpr *CE, FunctionDecl *FD) { | ||||
19938 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | ||||
19939 | return false; | ||||
19940 | |||||
19941 | // If we're inside a decltype's expression, don't check for a valid return | ||||
19942 | // type or construct temporaries until we know whether this is the last call. | ||||
19943 | if (ExprEvalContexts.back().ExprContext == | ||||
19944 | ExpressionEvaluationContextRecord::EK_Decltype) { | ||||
19945 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | ||||
19946 | return false; | ||||
19947 | } | ||||
19948 | |||||
19949 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | ||||
19950 | FunctionDecl *FD; | ||||
19951 | CallExpr *CE; | ||||
19952 | |||||
19953 | public: | ||||
19954 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | ||||
19955 | : FD(FD), CE(CE) { } | ||||
19956 | |||||
19957 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
19958 | if (!FD) { | ||||
19959 | S.Diag(Loc, diag::err_call_incomplete_return) | ||||
19960 | << T << CE->getSourceRange(); | ||||
19961 | return; | ||||
19962 | } | ||||
19963 | |||||
19964 | S.Diag(Loc, diag::err_call_function_incomplete_return) | ||||
19965 | << CE->getSourceRange() << FD << T; | ||||
19966 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | ||||
19967 | << FD->getDeclName(); | ||||
19968 | } | ||||
19969 | } Diagnoser(FD, CE); | ||||
19970 | |||||
19971 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | ||||
19972 | return true; | ||||
19973 | |||||
19974 | return false; | ||||
19975 | } | ||||
19976 | |||||
19977 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | ||||
19978 | // will prevent this condition from triggering, which is what we want. | ||||
19979 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | ||||
19980 | SourceLocation Loc; | ||||
19981 | |||||
19982 | unsigned diagnostic = diag::warn_condition_is_assignment; | ||||
19983 | bool IsOrAssign = false; | ||||
19984 | |||||
19985 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | ||||
19986 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | ||||
19987 | return; | ||||
19988 | |||||
19989 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | ||||
19990 | |||||
19991 | // Greylist some idioms by putting them into a warning subcategory. | ||||
19992 | if (ObjCMessageExpr *ME | ||||
19993 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | ||||
19994 | Selector Sel = ME->getSelector(); | ||||
19995 | |||||
19996 | // self = [<foo> init...] | ||||
19997 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | ||||
19998 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
19999 | |||||
20000 | // <foo> = [<bar> nextObject] | ||||
20001 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | ||||
20002 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
20003 | } | ||||
20004 | |||||
20005 | Loc = Op->getOperatorLoc(); | ||||
20006 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
20007 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | ||||
20008 | return; | ||||
20009 | |||||
20010 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | ||||
20011 | Loc = Op->getOperatorLoc(); | ||||
20012 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | ||||
20013 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | ||||
20014 | else { | ||||
20015 | // Not an assignment. | ||||
20016 | return; | ||||
20017 | } | ||||
20018 | |||||
20019 | Diag(Loc, diagnostic) << E->getSourceRange(); | ||||
20020 | |||||
20021 | SourceLocation Open = E->getBeginLoc(); | ||||
20022 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | ||||
20023 | Diag(Loc, diag::note_condition_assign_silence) | ||||
20024 | << FixItHint::CreateInsertion(Open, "(") | ||||
20025 | << FixItHint::CreateInsertion(Close, ")"); | ||||
20026 | |||||
20027 | if (IsOrAssign) | ||||
20028 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | ||||
20029 | << FixItHint::CreateReplacement(Loc, "!="); | ||||
20030 | else | ||||
20031 | Diag(Loc, diag::note_condition_assign_to_comparison) | ||||
20032 | << FixItHint::CreateReplacement(Loc, "=="); | ||||
20033 | } | ||||
20034 | |||||
20035 | /// Redundant parentheses over an equality comparison can indicate | ||||
20036 | /// that the user intended an assignment used as condition. | ||||
20037 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | ||||
20038 | // Don't warn if the parens came from a macro. | ||||
20039 | SourceLocation parenLoc = ParenE->getBeginLoc(); | ||||
20040 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | ||||
20041 | return; | ||||
20042 | // Don't warn for dependent expressions. | ||||
20043 | if (ParenE->isTypeDependent()) | ||||
20044 | return; | ||||
20045 | |||||
20046 | Expr *E = ParenE->IgnoreParens(); | ||||
20047 | |||||
20048 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | ||||
20049 | if (opE->getOpcode() == BO_EQ && | ||||
20050 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | ||||
20051 | == Expr::MLV_Valid) { | ||||
20052 | SourceLocation Loc = opE->getOperatorLoc(); | ||||
20053 | |||||
20054 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | ||||
20055 | SourceRange ParenERange = ParenE->getSourceRange(); | ||||
20056 | Diag(Loc, diag::note_equality_comparison_silence) | ||||
20057 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | ||||
20058 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | ||||
20059 | Diag(Loc, diag::note_equality_comparison_to_assign) | ||||
20060 | << FixItHint::CreateReplacement(Loc, "="); | ||||
20061 | } | ||||
20062 | } | ||||
20063 | |||||
20064 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | ||||
20065 | bool IsConstexpr) { | ||||
20066 | DiagnoseAssignmentAsCondition(E); | ||||
20067 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | ||||
20068 | DiagnoseEqualityWithExtraParens(parenE); | ||||
20069 | |||||
20070 | ExprResult result = CheckPlaceholderExpr(E); | ||||
20071 | if (result.isInvalid()) return ExprError(); | ||||
20072 | E = result.get(); | ||||
20073 | |||||
20074 | if (!E->isTypeDependent()) { | ||||
20075 | if (getLangOpts().CPlusPlus) | ||||
20076 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | ||||
20077 | |||||
20078 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | ||||
20079 | if (ERes.isInvalid()) | ||||
20080 | return ExprError(); | ||||
20081 | E = ERes.get(); | ||||
20082 | |||||
20083 | QualType T = E->getType(); | ||||
20084 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | ||||
20085 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | ||||
20086 | << T << E->getSourceRange(); | ||||
20087 | return ExprError(); | ||||
20088 | } | ||||
20089 | CheckBoolLikeConversion(E, Loc); | ||||
20090 | } | ||||
20091 | |||||
20092 | return E; | ||||
20093 | } | ||||
20094 | |||||
20095 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | ||||
20096 | Expr *SubExpr, ConditionKind CK, | ||||
20097 | bool MissingOK) { | ||||
20098 | // MissingOK indicates whether having no condition expression is valid | ||||
20099 | // (for loop) or invalid (e.g. while loop). | ||||
20100 | if (!SubExpr) | ||||
20101 | return MissingOK ? ConditionResult() : ConditionError(); | ||||
20102 | |||||
20103 | ExprResult Cond; | ||||
20104 | switch (CK) { | ||||
20105 | case ConditionKind::Boolean: | ||||
20106 | Cond = CheckBooleanCondition(Loc, SubExpr); | ||||
20107 | break; | ||||
20108 | |||||
20109 | case ConditionKind::ConstexprIf: | ||||
20110 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | ||||
20111 | break; | ||||
20112 | |||||
20113 | case ConditionKind::Switch: | ||||
20114 | Cond = CheckSwitchCondition(Loc, SubExpr); | ||||
20115 | break; | ||||
20116 | } | ||||
20117 | if (Cond.isInvalid()) { | ||||
20118 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | ||||
20119 | {SubExpr}, PreferredConditionType(CK)); | ||||
20120 | if (!Cond.get()) | ||||
20121 | return ConditionError(); | ||||
20122 | } | ||||
20123 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | ||||
20124 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | ||||
20125 | if (!FullExpr.get()) | ||||
20126 | return ConditionError(); | ||||
20127 | |||||
20128 | return ConditionResult(*this, nullptr, FullExpr, | ||||
20129 | CK == ConditionKind::ConstexprIf); | ||||
20130 | } | ||||
20131 | |||||
20132 | namespace { | ||||
20133 | /// A visitor for rebuilding a call to an __unknown_any expression | ||||
20134 | /// to have an appropriate type. | ||||
20135 | struct RebuildUnknownAnyFunction | ||||
20136 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | ||||
20137 | |||||
20138 | Sema &S; | ||||
20139 | |||||
20140 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | ||||
20141 | |||||
20142 | ExprResult VisitStmt(Stmt *S) { | ||||
20143 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp" , 20143); | ||||
20144 | } | ||||
20145 | |||||
20146 | ExprResult VisitExpr(Expr *E) { | ||||
20147 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | ||||
20148 | << E->getSourceRange(); | ||||
20149 | return ExprError(); | ||||
20150 | } | ||||
20151 | |||||
20152 | /// Rebuild an expression which simply semantically wraps another | ||||
20153 | /// expression which it shares the type and value kind of. | ||||
20154 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
20155 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20156 | if (SubResult.isInvalid()) return ExprError(); | ||||
20157 | |||||
20158 | Expr *SubExpr = SubResult.get(); | ||||
20159 | E->setSubExpr(SubExpr); | ||||
20160 | E->setType(SubExpr->getType()); | ||||
20161 | E->setValueKind(SubExpr->getValueKind()); | ||||
20162 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20162, __extension__ __PRETTY_FUNCTION__ )); | ||||
20163 | return E; | ||||
20164 | } | ||||
20165 | |||||
20166 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
20167 | return rebuildSugarExpr(E); | ||||
20168 | } | ||||
20169 | |||||
20170 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
20171 | return rebuildSugarExpr(E); | ||||
20172 | } | ||||
20173 | |||||
20174 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
20175 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20176 | if (SubResult.isInvalid()) return ExprError(); | ||||
20177 | |||||
20178 | Expr *SubExpr = SubResult.get(); | ||||
20179 | E->setSubExpr(SubExpr); | ||||
20180 | E->setType(S.Context.getPointerType(SubExpr->getType())); | ||||
20181 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20181, __extension__ __PRETTY_FUNCTION__)); | ||||
20182 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20182, __extension__ __PRETTY_FUNCTION__ )); | ||||
20183 | return E; | ||||
20184 | } | ||||
20185 | |||||
20186 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | ||||
20187 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | ||||
20188 | |||||
20189 | E->setType(VD->getType()); | ||||
20190 | |||||
20191 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20191, __extension__ __PRETTY_FUNCTION__)); | ||||
20192 | if (S.getLangOpts().CPlusPlus && | ||||
20193 | !(isa<CXXMethodDecl>(VD) && | ||||
20194 | cast<CXXMethodDecl>(VD)->isInstance())) | ||||
20195 | E->setValueKind(VK_LValue); | ||||
20196 | |||||
20197 | return E; | ||||
20198 | } | ||||
20199 | |||||
20200 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
20201 | return resolveDecl(E, E->getMemberDecl()); | ||||
20202 | } | ||||
20203 | |||||
20204 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
20205 | return resolveDecl(E, E->getDecl()); | ||||
20206 | } | ||||
20207 | }; | ||||
20208 | } | ||||
20209 | |||||
20210 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
20211 | /// to have a function type. | ||||
20212 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | ||||
20213 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | ||||
20214 | if (Result.isInvalid()) return ExprError(); | ||||
20215 | return S.DefaultFunctionArrayConversion(Result.get()); | ||||
20216 | } | ||||
20217 | |||||
20218 | namespace { | ||||
20219 | /// A visitor for rebuilding an expression of type __unknown_anytype | ||||
20220 | /// into one which resolves the type directly on the referring | ||||
20221 | /// expression. Strict preservation of the original source | ||||
20222 | /// structure is not a goal. | ||||
20223 | struct RebuildUnknownAnyExpr | ||||
20224 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | ||||
20225 | |||||
20226 | Sema &S; | ||||
20227 | |||||
20228 | /// The current destination type. | ||||
20229 | QualType DestType; | ||||
20230 | |||||
20231 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | ||||
20232 | : S(S), DestType(CastType) {} | ||||
20233 | |||||
20234 | ExprResult VisitStmt(Stmt *S) { | ||||
20235 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "clang/lib/Sema/SemaExpr.cpp" , 20235); | ||||
20236 | } | ||||
20237 | |||||
20238 | ExprResult VisitExpr(Expr *E) { | ||||
20239 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
20240 | << E->getSourceRange(); | ||||
20241 | return ExprError(); | ||||
20242 | } | ||||
20243 | |||||
20244 | ExprResult VisitCallExpr(CallExpr *E); | ||||
20245 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | ||||
20246 | |||||
20247 | /// Rebuild an expression which simply semantically wraps another | ||||
20248 | /// expression which it shares the type and value kind of. | ||||
20249 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
20250 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20251 | if (SubResult.isInvalid()) return ExprError(); | ||||
20252 | Expr *SubExpr = SubResult.get(); | ||||
20253 | E->setSubExpr(SubExpr); | ||||
20254 | E->setType(SubExpr->getType()); | ||||
20255 | E->setValueKind(SubExpr->getValueKind()); | ||||
20256 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20256, __extension__ __PRETTY_FUNCTION__ )); | ||||
20257 | return E; | ||||
20258 | } | ||||
20259 | |||||
20260 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
20261 | return rebuildSugarExpr(E); | ||||
20262 | } | ||||
20263 | |||||
20264 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
20265 | return rebuildSugarExpr(E); | ||||
20266 | } | ||||
20267 | |||||
20268 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
20269 | const PointerType *Ptr = DestType->getAs<PointerType>(); | ||||
20270 | if (!Ptr) { | ||||
20271 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | ||||
20272 | << E->getSourceRange(); | ||||
20273 | return ExprError(); | ||||
20274 | } | ||||
20275 | |||||
20276 | if (isa<CallExpr>(E->getSubExpr())) { | ||||
20277 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | ||||
20278 | << E->getSourceRange(); | ||||
20279 | return ExprError(); | ||||
20280 | } | ||||
20281 | |||||
20282 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20282, __extension__ __PRETTY_FUNCTION__)); | ||||
20283 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20283, __extension__ __PRETTY_FUNCTION__ )); | ||||
20284 | E->setType(DestType); | ||||
20285 | |||||
20286 | // Build the sub-expression as if it were an object of the pointee type. | ||||
20287 | DestType = Ptr->getPointeeType(); | ||||
20288 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
20289 | if (SubResult.isInvalid()) return ExprError(); | ||||
20290 | E->setSubExpr(SubResult.get()); | ||||
20291 | return E; | ||||
20292 | } | ||||
20293 | |||||
20294 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | ||||
20295 | |||||
20296 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | ||||
20297 | |||||
20298 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
20299 | return resolveDecl(E, E->getMemberDecl()); | ||||
20300 | } | ||||
20301 | |||||
20302 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
20303 | return resolveDecl(E, E->getDecl()); | ||||
20304 | } | ||||
20305 | }; | ||||
20306 | } | ||||
20307 | |||||
20308 | /// Rebuilds a call expression which yielded __unknown_anytype. | ||||
20309 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | ||||
20310 | Expr *CalleeExpr = E->getCallee(); | ||||
20311 | |||||
20312 | enum FnKind { | ||||
20313 | FK_MemberFunction, | ||||
20314 | FK_FunctionPointer, | ||||
20315 | FK_BlockPointer | ||||
20316 | }; | ||||
20317 | |||||
20318 | FnKind Kind; | ||||
20319 | QualType CalleeType = CalleeExpr->getType(); | ||||
20320 | if (CalleeType == S.Context.BoundMemberTy) { | ||||
20321 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast <bool> (isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)) ? void (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "clang/lib/Sema/SemaExpr.cpp", 20321, __extension__ __PRETTY_FUNCTION__ )); | ||||
20322 | Kind = FK_MemberFunction; | ||||
20323 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | ||||
20324 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | ||||
20325 | CalleeType = Ptr->getPointeeType(); | ||||
20326 | Kind = FK_FunctionPointer; | ||||
20327 | } else { | ||||
20328 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | ||||
20329 | Kind = FK_BlockPointer; | ||||
20330 | } | ||||
20331 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | ||||
20332 | |||||
20333 | // Verify that this is a legal result type of a function. | ||||
20334 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
20335 | unsigned diagID = diag::err_func_returning_array_function; | ||||
20336 | if (Kind == FK_BlockPointer) | ||||
20337 | diagID = diag::err_block_returning_array_function; | ||||
20338 | |||||
20339 | S.Diag(E->getExprLoc(), diagID) | ||||
20340 | << DestType->isFunctionType() << DestType; | ||||
20341 | return ExprError(); | ||||
20342 | } | ||||
20343 | |||||
20344 | // Otherwise, go ahead and set DestType as the call's result. | ||||
20345 | E->setType(DestType.getNonLValueExprType(S.Context)); | ||||
20346 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
20347 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20347, __extension__ __PRETTY_FUNCTION__ )); | ||||
20348 | |||||
20349 | // Rebuild the function type, replacing the result type with DestType. | ||||
20350 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | ||||
20351 | if (Proto) { | ||||
20352 | // __unknown_anytype(...) is a special case used by the debugger when | ||||
20353 | // it has no idea what a function's signature is. | ||||
20354 | // | ||||
20355 | // We want to build this call essentially under the K&R | ||||
20356 | // unprototyped rules, but making a FunctionNoProtoType in C++ | ||||
20357 | // would foul up all sorts of assumptions. However, we cannot | ||||
20358 | // simply pass all arguments as variadic arguments, nor can we | ||||
20359 | // portably just call the function under a non-variadic type; see | ||||
20360 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | ||||
20361 | // However, it turns out that in practice it is generally safe to | ||||
20362 | // call a function declared as "A foo(B,C,D);" under the prototype | ||||
20363 | // "A foo(B,C,D,...);". The only known exception is with the | ||||
20364 | // Windows ABI, where any variadic function is implicitly cdecl | ||||
20365 | // regardless of its normal CC. Therefore we change the parameter | ||||
20366 | // types to match the types of the arguments. | ||||
20367 | // | ||||
20368 | // This is a hack, but it is far superior to moving the | ||||
20369 | // corresponding target-specific code from IR-gen to Sema/AST. | ||||
20370 | |||||
20371 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | ||||
20372 | SmallVector<QualType, 8> ArgTypes; | ||||
20373 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | ||||
20374 | ArgTypes.reserve(E->getNumArgs()); | ||||
20375 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | ||||
20376 | ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); | ||||
20377 | } | ||||
20378 | ParamTypes = ArgTypes; | ||||
20379 | } | ||||
20380 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | ||||
20381 | Proto->getExtProtoInfo()); | ||||
20382 | } else { | ||||
20383 | DestType = S.Context.getFunctionNoProtoType(DestType, | ||||
20384 | FnType->getExtInfo()); | ||||
20385 | } | ||||
20386 | |||||
20387 | // Rebuild the appropriate pointer-to-function type. | ||||
20388 | switch (Kind) { | ||||
20389 | case FK_MemberFunction: | ||||
20390 | // Nothing to do. | ||||
20391 | break; | ||||
20392 | |||||
20393 | case FK_FunctionPointer: | ||||
20394 | DestType = S.Context.getPointerType(DestType); | ||||
20395 | break; | ||||
20396 | |||||
20397 | case FK_BlockPointer: | ||||
20398 | DestType = S.Context.getBlockPointerType(DestType); | ||||
20399 | break; | ||||
20400 | } | ||||
20401 | |||||
20402 | // Finally, we can recurse. | ||||
20403 | ExprResult CalleeResult = Visit(CalleeExpr); | ||||
20404 | if (!CalleeResult.isUsable()) return ExprError(); | ||||
20405 | E->setCallee(CalleeResult.get()); | ||||
20406 | |||||
20407 | // Bind a temporary if necessary. | ||||
20408 | return S.MaybeBindToTemporary(E); | ||||
20409 | } | ||||
20410 | |||||
20411 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | ||||
20412 | // Verify that this is a legal result type of a call. | ||||
20413 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
20414 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | ||||
20415 | << DestType->isFunctionType() << DestType; | ||||
20416 | return ExprError(); | ||||
20417 | } | ||||
20418 | |||||
20419 | // Rewrite the method result type if available. | ||||
20420 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | ||||
20421 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context .UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "clang/lib/Sema/SemaExpr.cpp", 20421, __extension__ __PRETTY_FUNCTION__ )); | ||||
20422 | Method->setReturnType(DestType); | ||||
20423 | } | ||||
20424 | |||||
20425 | // Change the type of the message. | ||||
20426 | E->setType(DestType.getNonReferenceType()); | ||||
20427 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
20428 | |||||
20429 | return S.MaybeBindToTemporary(E); | ||||
20430 | } | ||||
20431 | |||||
20432 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
20433 | // The only case we should ever see here is a function-to-pointer decay. | ||||
20434 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | ||||
20435 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20435, __extension__ __PRETTY_FUNCTION__)); | ||||
20436 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20436, __extension__ __PRETTY_FUNCTION__ )); | ||||
20437 | |||||
20438 | E->setType(DestType); | ||||
20439 | |||||
20440 | // Rebuild the sub-expression as the pointee (function) type. | ||||
20441 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | ||||
20442 | |||||
20443 | ExprResult Result = Visit(E->getSubExpr()); | ||||
20444 | if (!Result.isUsable()) return ExprError(); | ||||
20445 | |||||
20446 | E->setSubExpr(Result.get()); | ||||
20447 | return E; | ||||
20448 | } else if (E->getCastKind() == CK_LValueToRValue) { | ||||
20449 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "clang/lib/Sema/SemaExpr.cpp", 20449, __extension__ __PRETTY_FUNCTION__)); | ||||
20450 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "clang/lib/Sema/SemaExpr.cpp", 20450, __extension__ __PRETTY_FUNCTION__ )); | ||||
20451 | |||||
20452 | assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E-> getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "clang/lib/Sema/SemaExpr.cpp", 20452, __extension__ __PRETTY_FUNCTION__ )); | ||||
20453 | |||||
20454 | E->setType(DestType); | ||||
20455 | |||||
20456 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | ||||
20457 | DestType = S.Context.getLValueReferenceType(DestType); | ||||
20458 | |||||
20459 | ExprResult Result = Visit(E->getSubExpr()); | ||||
20460 | if (!Result.isUsable()) return ExprError(); | ||||
20461 | |||||
20462 | E->setSubExpr(Result.get()); | ||||
20463 | return E; | ||||
20464 | } else { | ||||
20465 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "clang/lib/Sema/SemaExpr.cpp" , 20465); | ||||
20466 | } | ||||
20467 | } | ||||
20468 | |||||
20469 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | ||||
20470 | ExprValueKind ValueKind = VK_LValue; | ||||
20471 | QualType Type = DestType; | ||||
20472 | |||||
20473 | // We know how to make this work for certain kinds of decls: | ||||
20474 | |||||
20475 | // - functions | ||||
20476 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | ||||
20477 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | ||||
20478 | DestType = Ptr->getPointeeType(); | ||||
20479 | ExprResult Result = resolveDecl(E, VD); | ||||
20480 | if (Result.isInvalid()) return ExprError(); | ||||
20481 | return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, | ||||
20482 | VK_PRValue); | ||||
20483 | } | ||||
20484 | |||||
20485 | if (!Type->isFunctionType()) { | ||||
20486 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | ||||
20487 | << VD << E->getSourceRange(); | ||||
20488 | return ExprError(); | ||||
20489 | } | ||||
20490 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | ||||
20491 | // We must match the FunctionDecl's type to the hack introduced in | ||||
20492 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | ||||
20493 | // type. See the lengthy commentary in that routine. | ||||
20494 | QualType FDT = FD->getType(); | ||||
20495 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | ||||
20496 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | ||||
20497 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
20498 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | ||||
20499 | SourceLocation Loc = FD->getLocation(); | ||||
20500 | FunctionDecl *NewFD = FunctionDecl::Create( | ||||
20501 | S.Context, FD->getDeclContext(), Loc, Loc, | ||||
20502 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | ||||
20503 | SC_None, S.getCurFPFeatures().isFPConstrained(), | ||||
20504 | false /*isInlineSpecified*/, FD->hasPrototype(), | ||||
20505 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | ||||
20506 | |||||
20507 | if (FD->getQualifier()) | ||||
20508 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | ||||
20509 | |||||
20510 | SmallVector<ParmVarDecl*, 16> Params; | ||||
20511 | for (const auto &AI : FT->param_types()) { | ||||
20512 | ParmVarDecl *Param = | ||||
20513 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | ||||
20514 | Param->setScopeInfo(0, Params.size()); | ||||
20515 | Params.push_back(Param); | ||||
20516 | } | ||||
20517 | NewFD->setParams(Params); | ||||
20518 | DRE->setDecl(NewFD); | ||||
20519 | VD = DRE->getDecl(); | ||||
20520 | } | ||||
20521 | } | ||||
20522 | |||||
20523 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | ||||
20524 | if (MD->isInstance()) { | ||||
20525 | ValueKind = VK_PRValue; | ||||
20526 | Type = S.Context.BoundMemberTy; | ||||
20527 | } | ||||
20528 | |||||
20529 | // Function references aren't l-values in C. | ||||
20530 | if (!S.getLangOpts().CPlusPlus) | ||||
20531 | ValueKind = VK_PRValue; | ||||
20532 | |||||
20533 | // - variables | ||||
20534 | } else if (isa<VarDecl>(VD)) { | ||||
20535 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | ||||
20536 | Type = RefTy->getPointeeType(); | ||||
20537 | } else if (Type->isFunctionType()) { | ||||
20538 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | ||||
20539 | << VD << E->getSourceRange(); | ||||
20540 | return ExprError(); | ||||
20541 | } | ||||
20542 | |||||
20543 | // - nothing else | ||||
20544 | } else { | ||||
20545 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | ||||
20546 | << VD << E->getSourceRange(); | ||||
20547 | return ExprError(); | ||||
20548 | } | ||||
20549 | |||||
20550 | // Modifying the declaration like this is friendly to IR-gen but | ||||
20551 | // also really dangerous. | ||||
20552 | VD->setType(DestType); | ||||
20553 | E->setType(Type); | ||||
20554 | E->setValueKind(ValueKind); | ||||
20555 | return E; | ||||
20556 | } | ||||
20557 | |||||
20558 | /// Check a cast of an unknown-any type. We intentionally only | ||||
20559 | /// trigger this for C-style casts. | ||||
20560 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | ||||
20561 | Expr *CastExpr, CastKind &CastKind, | ||||
20562 | ExprValueKind &VK, CXXCastPath &Path) { | ||||
20563 | // The type we're casting to must be either void or complete. | ||||
20564 | if (!CastType->isVoidType() && | ||||
20565 | RequireCompleteType(TypeRange.getBegin(), CastType, | ||||
20566 | diag::err_typecheck_cast_to_incomplete)) | ||||
20567 | return ExprError(); | ||||
20568 | |||||
20569 | // Rewrite the casted expression from scratch. | ||||
20570 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | ||||
20571 | if (!result.isUsable()) return ExprError(); | ||||
20572 | |||||
20573 | CastExpr = result.get(); | ||||
20574 | VK = CastExpr->getValueKind(); | ||||
20575 | CastKind = CK_NoOp; | ||||
20576 | |||||
20577 | return CastExpr; | ||||
20578 | } | ||||
20579 | |||||
20580 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | ||||
20581 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | ||||
20582 | } | ||||
20583 | |||||
20584 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | ||||
20585 | Expr *arg, QualType ¶mType) { | ||||
20586 | // If the syntactic form of the argument is not an explicit cast of | ||||
20587 | // any sort, just do default argument promotion. | ||||
20588 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | ||||
20589 | if (!castArg) { | ||||
20590 | ExprResult result = DefaultArgumentPromotion(arg); | ||||
20591 | if (result.isInvalid()) return ExprError(); | ||||
20592 | paramType = result.get()->getType(); | ||||
20593 | return result; | ||||
20594 | } | ||||
20595 | |||||
20596 | // Otherwise, use the type that was written in the explicit cast. | ||||
20597 | assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void (0) : __assert_fail ("!arg->hasPlaceholderType()", "clang/lib/Sema/SemaExpr.cpp" , 20597, __extension__ __PRETTY_FUNCTION__)); | ||||
20598 | paramType = castArg->getTypeAsWritten(); | ||||
20599 | |||||
20600 | // Copy-initialize a parameter of that type. | ||||
20601 | InitializedEntity entity = | ||||
20602 | InitializedEntity::InitializeParameter(Context, paramType, | ||||
20603 | /*consumed*/ false); | ||||
20604 | return PerformCopyInitialization(entity, callLoc, arg); | ||||
20605 | } | ||||
20606 | |||||
20607 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | ||||
20608 | Expr *orig = E; | ||||
20609 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | ||||
20610 | while (true) { | ||||
20611 | E = E->IgnoreParenImpCasts(); | ||||
20612 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | ||||
20613 | E = call->getCallee(); | ||||
20614 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
20615 | } else { | ||||
20616 | break; | ||||
20617 | } | ||||
20618 | } | ||||
20619 | |||||
20620 | SourceLocation loc; | ||||
20621 | NamedDecl *d; | ||||
20622 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | ||||
20623 | loc = ref->getLocation(); | ||||
20624 | d = ref->getDecl(); | ||||
20625 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | ||||
20626 | loc = mem->getMemberLoc(); | ||||
20627 | d = mem->getMemberDecl(); | ||||
20628 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | ||||
20629 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
20630 | loc = msg->getSelectorStartLoc(); | ||||
20631 | d = msg->getMethodDecl(); | ||||
20632 | if (!d) { | ||||
20633 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | ||||
20634 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | ||||
20635 | << orig->getSourceRange(); | ||||
20636 | return ExprError(); | ||||
20637 | } | ||||
20638 | } else { | ||||
20639 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
20640 | << E->getSourceRange(); | ||||
20641 | return ExprError(); | ||||
20642 | } | ||||
20643 | |||||
20644 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | ||||
20645 | |||||
20646 | // Never recoverable. | ||||
20647 | return ExprError(); | ||||
20648 | } | ||||
20649 | |||||
20650 | /// Check for operands with placeholder types and complain if found. | ||||
20651 | /// Returns ExprError() if there was an error and no recovery was possible. | ||||
20652 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | ||||
20653 | if (!Context.isDependenceAllowed()) { | ||||
20654 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
20655 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
20656 | // been dealt with before checking the operands. | ||||
20657 | ExprResult Result = CorrectDelayedTyposInExpr(E); | ||||
20658 | if (!Result.isUsable()) return ExprError(); | ||||
20659 | E = Result.get(); | ||||
20660 | } | ||||
20661 | |||||
20662 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | ||||
20663 | if (!placeholderType) return E; | ||||
20664 | |||||
20665 | switch (placeholderType->getKind()) { | ||||
20666 | |||||
20667 | // Overloaded expressions. | ||||
20668 | case BuiltinType::Overload: { | ||||
20669 | // Try to resolve a single function template specialization. | ||||
20670 | // This is obligatory. | ||||
20671 | ExprResult Result = E; | ||||
20672 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | ||||
20673 | return Result; | ||||
20674 | |||||
20675 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||
20676 | // leaves Result unchanged on failure. | ||||
20677 | Result = E; | ||||
20678 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | ||||
20679 | return Result; | ||||
20680 | |||||
20681 | // If that failed, try to recover with a call. | ||||
20682 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | ||||
20683 | /*complain*/ true); | ||||
20684 | return Result; | ||||
20685 | } | ||||
20686 | |||||
20687 | // Bound member functions. | ||||
20688 | case BuiltinType::BoundMember: { | ||||
20689 | ExprResult result = E; | ||||
20690 | const Expr *BME = E->IgnoreParens(); | ||||
20691 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | ||||
20692 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | ||||
20693 | if (isa<CXXPseudoDestructorExpr>(BME)) { | ||||
20694 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | ||||
20695 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | ||||
20696 | if (ME->getMemberNameInfo().getName().getNameKind() == | ||||
20697 | DeclarationName::CXXDestructorName) | ||||
20698 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | ||||
20699 | } | ||||
20700 | tryToRecoverWithCall(result, PD, | ||||
20701 | /*complain*/ true); | ||||
20702 | return result; | ||||
20703 | } | ||||
20704 | |||||
20705 | // ARC unbridged casts. | ||||
20706 | case BuiltinType::ARCUnbridgedCast: { | ||||
20707 | Expr *realCast = stripARCUnbridgedCast(E); | ||||
20708 | diagnoseARCUnbridgedCast(realCast); | ||||
20709 | return realCast; | ||||
20710 | } | ||||
20711 | |||||
20712 | // Expressions of unknown type. | ||||
20713 | case BuiltinType::UnknownAny: | ||||
20714 | return diagnoseUnknownAnyExpr(*this, E); | ||||
20715 | |||||
20716 | // Pseudo-objects. | ||||
20717 | case BuiltinType::PseudoObject: | ||||
20718 | return checkPseudoObjectRValue(E); | ||||
20719 | |||||
20720 | case BuiltinType::BuiltinFn: { | ||||
20721 | // Accept __noop without parens by implicitly converting it to a call expr. | ||||
20722 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | ||||
20723 | if (DRE) { | ||||
20724 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | ||||
20725 | unsigned BuiltinID = FD->getBuiltinID(); | ||||
20726 | if (BuiltinID == Builtin::BI__noop) { | ||||
20727 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | ||||
20728 | CK_BuiltinFnToFnPtr) | ||||
20729 | .get(); | ||||
20730 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | ||||
20731 | VK_PRValue, SourceLocation(), | ||||
20732 | FPOptionsOverride()); | ||||
20733 | } | ||||
20734 | |||||
20735 | if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { | ||||
20736 | // Any use of these other than a direct call is ill-formed as of C++20, | ||||
20737 | // because they are not addressable functions. In earlier language | ||||
20738 | // modes, warn and force an instantiation of the real body. | ||||
20739 | Diag(E->getBeginLoc(), | ||||
20740 | getLangOpts().CPlusPlus20 | ||||
20741 | ? diag::err_use_of_unaddressable_function | ||||
20742 | : diag::warn_cxx20_compat_use_of_unaddressable_function); | ||||
20743 | if (FD->isImplicitlyInstantiable()) { | ||||
20744 | // Require a definition here because a normal attempt at | ||||
20745 | // instantiation for a builtin will be ignored, and we won't try | ||||
20746 | // again later. We assume that the definition of the template | ||||
20747 | // precedes this use. | ||||
20748 | InstantiateFunctionDefinition(E->getBeginLoc(), FD, | ||||
20749 | /*Recursive=*/false, | ||||
20750 | /*DefinitionRequired=*/true, | ||||
20751 | /*AtEndOfTU=*/false); | ||||
20752 | } | ||||
20753 | // Produce a properly-typed reference to the function. | ||||
20754 | CXXScopeSpec SS; | ||||
20755 | SS.Adopt(DRE->getQualifierLoc()); | ||||
20756 | TemplateArgumentListInfo TemplateArgs; | ||||
20757 | DRE->copyTemplateArgumentsInto(TemplateArgs); | ||||
20758 | return BuildDeclRefExpr( | ||||
20759 | FD, FD->getType(), VK_LValue, DRE->getNameInfo(), | ||||
20760 | DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), | ||||
20761 | DRE->getTemplateKeywordLoc(), | ||||
20762 | DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); | ||||
20763 | } | ||||
20764 | } | ||||
20765 | |||||
20766 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | ||||
20767 | return ExprError(); | ||||
20768 | } | ||||
20769 | |||||
20770 | case BuiltinType::IncompleteMatrixIdx: | ||||
20771 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | ||||
20772 | ->getRowIdx() | ||||
20773 | ->getBeginLoc(), | ||||
20774 | diag::err_matrix_incomplete_index); | ||||
20775 | return ExprError(); | ||||
20776 | |||||
20777 | // Expressions of unknown type. | ||||
20778 | case BuiltinType::OMPArraySection: | ||||
20779 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | ||||
20780 | return ExprError(); | ||||
20781 | |||||
20782 | // Expressions of unknown type. | ||||
20783 | case BuiltinType::OMPArrayShaping: | ||||
20784 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | ||||
20785 | |||||
20786 | case BuiltinType::OMPIterator: | ||||
20787 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | ||||
20788 | |||||
20789 | // Everything else should be impossible. | ||||
20790 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
20791 | case BuiltinType::Id: | ||||
20792 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
20793 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
20794 | case BuiltinType::Id: | ||||
20795 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
20796 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
20797 | case BuiltinType::Id: | ||||
20798 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
20799 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
20800 | case BuiltinType::Id: | ||||
20801 | #include "clang/Basic/PPCTypes.def" | ||||
20802 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
20803 | #include "clang/Basic/RISCVVTypes.def" | ||||
20804 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | ||||
20805 | #define PLACEHOLDER_TYPE(Id, SingletonId) | ||||
20806 | #include "clang/AST/BuiltinTypes.def" | ||||
20807 | break; | ||||
20808 | } | ||||
20809 | |||||
20810 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "clang/lib/Sema/SemaExpr.cpp", 20810); | ||||
20811 | } | ||||
20812 | |||||
20813 | bool Sema::CheckCaseExpression(Expr *E) { | ||||
20814 | if (E->isTypeDependent()) | ||||
20815 | return true; | ||||
20816 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | ||||
20817 | return E->getType()->isIntegralOrEnumerationType(); | ||||
20818 | return false; | ||||
20819 | } | ||||
20820 | |||||
20821 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | ||||
20822 | ExprResult | ||||
20823 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | ||||
20824 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "clang/lib/Sema/SemaExpr.cpp", 20825, __extension__ __PRETTY_FUNCTION__ )) | ||||
20825 | "Unknown Objective-C Boolean value!")(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "clang/lib/Sema/SemaExpr.cpp", 20825, __extension__ __PRETTY_FUNCTION__ )); | ||||
20826 | QualType BoolT = Context.ObjCBuiltinBoolTy; | ||||
20827 | if (!Context.getBOOLDecl()) { | ||||
20828 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | ||||
20829 | Sema::LookupOrdinaryName); | ||||
20830 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | ||||
20831 | NamedDecl *ND = Result.getFoundDecl(); | ||||
20832 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | ||||
20833 | Context.setBOOLDecl(TD); | ||||
20834 | } | ||||
20835 | } | ||||
20836 | if (Context.getBOOLDecl()) | ||||
20837 | BoolT = Context.getBOOLType(); | ||||
20838 | return new (Context) | ||||
20839 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | ||||
20840 | } | ||||
20841 | |||||
20842 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | ||||
20843 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | ||||
20844 | SourceLocation RParen) { | ||||
20845 | auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { | ||||
20846 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
20847 | return Spec.getPlatform() == Platform; | ||||
20848 | }); | ||||
20849 | // Transcribe the "ios" availability check to "maccatalyst" when compiling | ||||
20850 | // for "maccatalyst" if "maccatalyst" is not specified. | ||||
20851 | if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { | ||||
20852 | Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
20853 | return Spec.getPlatform() == "ios"; | ||||
20854 | }); | ||||
20855 | } | ||||
20856 | if (Spec == AvailSpecs.end()) | ||||
20857 | return None; | ||||
20858 | return Spec->getVersion(); | ||||
20859 | }; | ||||
20860 | |||||
20861 | VersionTuple Version; | ||||
20862 | if (auto MaybeVersion = | ||||
20863 | FindSpecVersion(Context.getTargetInfo().getPlatformName())) | ||||
20864 | Version = *MaybeVersion; | ||||
20865 | |||||
20866 | // The use of `@available` in the enclosing context should be analyzed to | ||||
20867 | // warn when it's used inappropriately (i.e. not if(@available)). | ||||
20868 | if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) | ||||
20869 | Context->HasPotentialAvailabilityViolations = true; | ||||
20870 | |||||
20871 | return new (Context) | ||||
20872 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | ||||
20873 | } | ||||
20874 | |||||
20875 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | ||||
20876 | ArrayRef<Expr *> SubExprs, QualType T) { | ||||
20877 | if (!Context.getLangOpts().RecoveryAST) | ||||
20878 | return ExprError(); | ||||
20879 | |||||
20880 | if (isSFINAEContext()) | ||||
20881 | return ExprError(); | ||||
20882 | |||||
20883 | if (T.isNull() || T->isUndeducedType() || | ||||
20884 | !Context.getLangOpts().RecoveryASTType) | ||||
20885 | // We don't know the concrete type, fallback to dependent type. | ||||
20886 | T = Context.DependentTy; | ||||
20887 | |||||
20888 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | ||||
20889 | } |
1 | //===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===// |
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 defines the isa<X>(), cast<X>(), dyn_cast<X>(), |
10 | // cast_if_present<X>(), and dyn_cast_if_present<X>() templates. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_SUPPORT_CASTING_H |
15 | #define LLVM_SUPPORT_CASTING_H |
16 | |
17 | #include "llvm/ADT/Optional.h" |
18 | #include "llvm/Support/Compiler.h" |
19 | #include "llvm/Support/type_traits.h" |
20 | #include <cassert> |
21 | #include <memory> |
22 | #include <type_traits> |
23 | |
24 | namespace llvm { |
25 | |
26 | //===----------------------------------------------------------------------===// |
27 | // simplify_type |
28 | //===----------------------------------------------------------------------===// |
29 | |
30 | /// Define a template that can be specialized by smart pointers to reflect the |
31 | /// fact that they are automatically dereferenced, and are not involved with the |
32 | /// template selection process... the default implementation is a noop. |
33 | // TODO: rename this and/or replace it with other cast traits. |
34 | template <typename From> struct simplify_type { |
35 | using SimpleType = From; // The real type this represents... |
36 | |
37 | // An accessor to get the real value... |
38 | static SimpleType &getSimplifiedValue(From &Val) { return Val; } |
39 | }; |
40 | |
41 | template <typename From> struct simplify_type<const From> { |
42 | using NonConstSimpleType = typename simplify_type<From>::SimpleType; |
43 | using SimpleType = typename add_const_past_pointer<NonConstSimpleType>::type; |
44 | using RetType = |
45 | typename add_lvalue_reference_if_not_pointer<SimpleType>::type; |
46 | |
47 | static RetType getSimplifiedValue(const From &Val) { |
48 | return simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val)); |
49 | } |
50 | }; |
51 | |
52 | // TODO: add this namespace once everyone is switched to using the new |
53 | // interface. |
54 | // namespace detail { |
55 | |
56 | //===----------------------------------------------------------------------===// |
57 | // isa_impl |
58 | //===----------------------------------------------------------------------===// |
59 | |
60 | // The core of the implementation of isa<X> is here; To and From should be |
61 | // the names of classes. This template can be specialized to customize the |
62 | // implementation of isa<> without rewriting it from scratch. |
63 | template <typename To, typename From, typename Enabler = void> struct isa_impl { |
64 | static inline bool doit(const From &Val) { return To::classof(&Val); } |
65 | }; |
66 | |
67 | // Always allow upcasts, and perform no dynamic check for them. |
68 | template <typename To, typename From> |
69 | struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> { |
70 | static inline bool doit(const From &) { return true; } |
71 | }; |
72 | |
73 | template <typename To, typename From> struct isa_impl_cl { |
74 | static inline bool doit(const From &Val) { |
75 | return isa_impl<To, From>::doit(Val); |
76 | } |
77 | }; |
78 | |
79 | template <typename To, typename From> struct isa_impl_cl<To, const From> { |
80 | static inline bool doit(const From &Val) { |
81 | return isa_impl<To, From>::doit(Val); |
82 | } |
83 | }; |
84 | |
85 | template <typename To, typename From> |
86 | struct isa_impl_cl<To, const std::unique_ptr<From>> { |
87 | static inline bool doit(const std::unique_ptr<From> &Val) { |
88 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 88, __extension__ __PRETTY_FUNCTION__ )); |
89 | return isa_impl_cl<To, From>::doit(*Val); |
90 | } |
91 | }; |
92 | |
93 | template <typename To, typename From> struct isa_impl_cl<To, From *> { |
94 | static inline bool doit(const From *Val) { |
95 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 95, __extension__ __PRETTY_FUNCTION__ )); |
96 | return isa_impl<To, From>::doit(*Val); |
97 | } |
98 | }; |
99 | |
100 | template <typename To, typename From> struct isa_impl_cl<To, From *const> { |
101 | static inline bool doit(const From *Val) { |
102 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 102, __extension__ __PRETTY_FUNCTION__ )); |
103 | return isa_impl<To, From>::doit(*Val); |
104 | } |
105 | }; |
106 | |
107 | template <typename To, typename From> struct isa_impl_cl<To, const From *> { |
108 | static inline bool doit(const From *Val) { |
109 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 109, __extension__ __PRETTY_FUNCTION__ )); |
110 | return isa_impl<To, From>::doit(*Val); |
111 | } |
112 | }; |
113 | |
114 | template <typename To, typename From> |
115 | struct isa_impl_cl<To, const From *const> { |
116 | static inline bool doit(const From *Val) { |
117 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "llvm/include/llvm/Support/Casting.h", 117, __extension__ __PRETTY_FUNCTION__ )); |
118 | return isa_impl<To, From>::doit(*Val); |
119 | } |
120 | }; |
121 | |
122 | template <typename To, typename From, typename SimpleFrom> |
123 | struct isa_impl_wrap { |
124 | // When From != SimplifiedType, we can simplify the type some more by using |
125 | // the simplify_type template. |
126 | static bool doit(const From &Val) { |
127 | return isa_impl_wrap<To, SimpleFrom, |
128 | typename simplify_type<SimpleFrom>::SimpleType>:: |
129 | doit(simplify_type<const From>::getSimplifiedValue(Val)); |
130 | } |
131 | }; |
132 | |
133 | template <typename To, typename FromTy> |
134 | struct isa_impl_wrap<To, FromTy, FromTy> { |
135 | // When From == SimpleType, we are as simple as we are going to get. |
136 | static bool doit(const FromTy &Val) { |
137 | return isa_impl_cl<To, FromTy>::doit(Val); |
138 | } |
139 | }; |
140 | |
141 | //===----------------------------------------------------------------------===// |
142 | // cast_retty + cast_retty_impl |
143 | //===----------------------------------------------------------------------===// |
144 | |
145 | template <class To, class From> struct cast_retty; |
146 | |
147 | // Calculate what type the 'cast' function should return, based on a requested |
148 | // type of To and a source type of From. |
149 | template <class To, class From> struct cast_retty_impl { |
150 | using ret_type = To &; // Normal case, return Ty& |
151 | }; |
152 | template <class To, class From> struct cast_retty_impl<To, const From> { |
153 | using ret_type = const To &; // Normal case, return Ty& |
154 | }; |
155 | |
156 | template <class To, class From> struct cast_retty_impl<To, From *> { |
157 | using ret_type = To *; // Pointer arg case, return Ty* |
158 | }; |
159 | |
160 | template <class To, class From> struct cast_retty_impl<To, const From *> { |
161 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
162 | }; |
163 | |
164 | template <class To, class From> struct cast_retty_impl<To, const From *const> { |
165 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
166 | }; |
167 | |
168 | template <class To, class From> |
169 | struct cast_retty_impl<To, std::unique_ptr<From>> { |
170 | private: |
171 | using PointerType = typename cast_retty_impl<To, From *>::ret_type; |
172 | using ResultType = std::remove_pointer_t<PointerType>; |
173 | |
174 | public: |
175 | using ret_type = std::unique_ptr<ResultType>; |
176 | }; |
177 | |
178 | template <class To, class From, class SimpleFrom> struct cast_retty_wrap { |
179 | // When the simplified type and the from type are not the same, use the type |
180 | // simplifier to reduce the type, then reuse cast_retty_impl to get the |
181 | // resultant type. |
182 | using ret_type = typename cast_retty<To, SimpleFrom>::ret_type; |
183 | }; |
184 | |
185 | template <class To, class FromTy> struct cast_retty_wrap<To, FromTy, FromTy> { |
186 | // When the simplified type is equal to the from type, use it directly. |
187 | using ret_type = typename cast_retty_impl<To, FromTy>::ret_type; |
188 | }; |
189 | |
190 | template <class To, class From> struct cast_retty { |
191 | using ret_type = typename cast_retty_wrap< |
192 | To, From, typename simplify_type<From>::SimpleType>::ret_type; |
193 | }; |
194 | |
195 | //===----------------------------------------------------------------------===// |
196 | // cast_convert_val |
197 | //===----------------------------------------------------------------------===// |
198 | |
199 | // Ensure the non-simple values are converted using the simplify_type template |
200 | // that may be specialized by smart pointers... |
201 | // |
202 | template <class To, class From, class SimpleFrom> struct cast_convert_val { |
203 | // This is not a simple type, use the template to simplify it... |
204 | static typename cast_retty<To, From>::ret_type doit(const From &Val) { |
205 | return cast_convert_val<To, SimpleFrom, |
206 | typename simplify_type<SimpleFrom>::SimpleType>:: |
207 | doit(simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val))); |
208 | } |
209 | }; |
210 | |
211 | template <class To, class FromTy> struct cast_convert_val<To, FromTy, FromTy> { |
212 | // If it's a reference, switch to a pointer to do the cast and then deref it. |
213 | static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) { |
214 | return *(std::remove_reference_t<typename cast_retty<To, FromTy>::ret_type> |
215 | *)&const_cast<FromTy &>(Val); |
216 | } |
217 | }; |
218 | |
219 | template <class To, class FromTy> |
220 | struct cast_convert_val<To, FromTy *, FromTy *> { |
221 | // If it's a pointer, we can use c-style casting directly. |
222 | static typename cast_retty<To, FromTy *>::ret_type doit(const FromTy *Val) { |
223 | return (typename cast_retty<To, FromTy *>::ret_type) const_cast<FromTy *>( |
224 | Val); |
225 | } |
226 | }; |
227 | |
228 | //===----------------------------------------------------------------------===// |
229 | // is_simple_type |
230 | //===----------------------------------------------------------------------===// |
231 | |
232 | template <class X> struct is_simple_type { |
233 | static const bool value = |
234 | std::is_same<X, typename simplify_type<X>::SimpleType>::value; |
235 | }; |
236 | |
237 | // } // namespace detail |
238 | |
239 | //===----------------------------------------------------------------------===// |
240 | // CastIsPossible |
241 | //===----------------------------------------------------------------------===// |
242 | |
243 | /// This struct provides a way to check if a given cast is possible. It provides |
244 | /// a static function called isPossible that is used to check if a cast can be |
245 | /// performed. It should be overridden like this: |
246 | /// |
247 | /// template<> struct CastIsPossible<foo, bar> { |
248 | /// static inline bool isPossible(const bar &b) { |
249 | /// return bar.isFoo(); |
250 | /// } |
251 | /// }; |
252 | template <typename To, typename From, typename Enable = void> |
253 | struct CastIsPossible { |
254 | static inline bool isPossible(const From &f) { |
255 | return isa_impl_wrap< |
256 | To, const From, |
257 | typename simplify_type<const From>::SimpleType>::doit(f); |
258 | } |
259 | }; |
260 | |
261 | // Needed for optional unwrapping. This could be implemented with isa_impl, but |
262 | // we want to implement things in the new method and move old implementations |
263 | // over. In fact, some of the isa_impl templates should be moved over to |
264 | // CastIsPossible. |
265 | template <typename To, typename From> |
266 | struct CastIsPossible<To, Optional<From>> { |
267 | static inline bool isPossible(const Optional<From> &f) { |
268 | assert(f && "CastIsPossible::isPossible called on a nullopt!")(static_cast <bool> (f && "CastIsPossible::isPossible called on a nullopt!" ) ? void (0) : __assert_fail ("f && \"CastIsPossible::isPossible called on a nullopt!\"" , "llvm/include/llvm/Support/Casting.h", 268, __extension__ __PRETTY_FUNCTION__ )); |
269 | return isa_impl_wrap< |
270 | To, const From, |
271 | typename simplify_type<const From>::SimpleType>::doit(*f); |
272 | } |
273 | }; |
274 | |
275 | /// Upcasting (from derived to base) and casting from a type to itself should |
276 | /// always be possible. |
277 | template <typename To, typename From> |
278 | struct CastIsPossible<To, From, |
279 | std::enable_if_t<std::is_base_of<To, From>::value>> { |
280 | static inline bool isPossible(const From &f) { return true; } |
281 | }; |
282 | |
283 | //===----------------------------------------------------------------------===// |
284 | // Cast traits |
285 | //===----------------------------------------------------------------------===// |
286 | |
287 | /// All of these cast traits are meant to be implementations for useful casts |
288 | /// that users may want to use that are outside the standard behavior. An |
289 | /// example of how to use a special cast called `CastTrait` is: |
290 | /// |
291 | /// template<> struct CastInfo<foo, bar> : public CastTrait<foo, bar> {}; |
292 | /// |
293 | /// Essentially, if your use case falls directly into one of the use cases |
294 | /// supported by a given cast trait, simply inherit your special CastInfo |
295 | /// directly from one of these to avoid having to reimplement the boilerplate |
296 | /// `isPossible/castFailed/doCast/doCastIfPossible`. A cast trait can also |
297 | /// provide a subset of those functions. |
298 | |
299 | /// This cast trait just provides castFailed for the specified `To` type to make |
300 | /// CastInfo specializations more declarative. In order to use this, the target |
301 | /// result type must be `To` and `To` must be constructible from `nullptr`. |
302 | template <typename To> struct NullableValueCastFailed { |
303 | static To castFailed() { return To(nullptr); } |
304 | }; |
305 | |
306 | /// This cast trait just provides the default implementation of doCastIfPossible |
307 | /// to make CastInfo specializations more declarative. The `Derived` template |
308 | /// parameter *must* be provided for forwarding castFailed and doCast. |
309 | template <typename To, typename From, typename Derived> |
310 | struct DefaultDoCastIfPossible { |
311 | static To doCastIfPossible(From f) { |
312 | if (!Derived::isPossible(f)) |
313 | return Derived::castFailed(); |
314 | return Derived::doCast(f); |
315 | } |
316 | }; |
317 | |
318 | namespace detail { |
319 | /// A helper to derive the type to use with `Self` for cast traits, when the |
320 | /// provided CRTP derived type is allowed to be void. |
321 | template <typename OptionalDerived, typename Default> |
322 | using SelfType = std::conditional_t<std::is_same<OptionalDerived, void>::value, |
323 | Default, OptionalDerived>; |
324 | } // namespace detail |
325 | |
326 | /// This cast trait provides casting for the specific case of casting to a |
327 | /// value-typed object from a pointer-typed object. Note that `To` must be |
328 | /// nullable/constructible from a pointer to `From` to use this cast. |
329 | template <typename To, typename From, typename Derived = void> |
330 | struct ValueFromPointerCast |
331 | : public CastIsPossible<To, From *>, |
332 | public NullableValueCastFailed<To>, |
333 | public DefaultDoCastIfPossible< |
334 | To, From *, |
335 | detail::SelfType<Derived, ValueFromPointerCast<To, From>>> { |
336 | static inline To doCast(From *f) { return To(f); } |
337 | }; |
338 | |
339 | /// This cast trait provides std::unique_ptr casting. It has the semantics of |
340 | /// moving the contents of the input unique_ptr into the output unique_ptr |
341 | /// during the cast. It's also a good example of how to implement a move-only |
342 | /// cast. |
343 | template <typename To, typename From, typename Derived = void> |
344 | struct UniquePtrCast : public CastIsPossible<To, From *> { |
345 | using Self = detail::SelfType<Derived, UniquePtrCast<To, From>>; |
346 | using CastResultType = std::unique_ptr< |
347 | std::remove_reference_t<typename cast_retty<To, From>::ret_type>>; |
348 | |
349 | static inline CastResultType doCast(std::unique_ptr<From> &&f) { |
350 | return CastResultType((typename CastResultType::element_type *)f.release()); |
351 | } |
352 | |
353 | static inline CastResultType castFailed() { return CastResultType(nullptr); } |
354 | |
355 | static inline CastResultType doCastIfPossible(std::unique_ptr<From> &&f) { |
356 | if (!Self::isPossible(f)) |
357 | return castFailed(); |
358 | return doCast(f); |
359 | } |
360 | }; |
361 | |
362 | /// This cast trait provides Optional<T> casting. This means that if you have a |
363 | /// value type, you can cast it to another value type and have dyn_cast return |
364 | /// an Optional<T>. |
365 | template <typename To, typename From, typename Derived = void> |
366 | struct OptionalValueCast |
367 | : public CastIsPossible<To, From>, |
368 | public DefaultDoCastIfPossible< |
369 | Optional<To>, From, |
370 | detail::SelfType<Derived, OptionalValueCast<To, From>>> { |
371 | static inline Optional<To> castFailed() { return Optional<To>{}; } |
372 | |
373 | static inline Optional<To> doCast(const From &f) { return To(f); } |
374 | }; |
375 | |
376 | /// Provides a cast trait that strips `const` from types to make it easier to |
377 | /// implement a const-version of a non-const cast. It just removes boilerplate |
378 | /// and reduces the amount of code you as the user need to implement. You can |
379 | /// use it like this: |
380 | /// |
381 | /// template<> struct CastInfo<foo, bar> { |
382 | /// ...verbose implementation... |
383 | /// }; |
384 | /// |
385 | /// template<> struct CastInfo<foo, const bar> : public |
386 | /// ConstStrippingForwardingCast<foo, const bar, CastInfo<foo, bar>> {}; |
387 | /// |
388 | template <typename To, typename From, typename ForwardTo> |
389 | struct ConstStrippingForwardingCast { |
390 | // Remove the pointer if it exists, then we can get rid of consts/volatiles. |
391 | using DecayedFrom = std::remove_cv_t<std::remove_pointer_t<From>>; |
392 | // Now if it's a pointer, add it back. Otherwise, we want a ref. |
393 | using NonConstFrom = std::conditional_t<std::is_pointer<From>::value, |
394 | DecayedFrom *, DecayedFrom &>; |
395 | |
396 | static inline bool isPossible(const From &f) { |
397 | return ForwardTo::isPossible(const_cast<NonConstFrom>(f)); |
398 | } |
399 | |
400 | static inline decltype(auto) castFailed() { return ForwardTo::castFailed(); } |
401 | |
402 | static inline decltype(auto) doCast(const From &f) { |
403 | return ForwardTo::doCast(const_cast<NonConstFrom>(f)); |
404 | } |
405 | |
406 | static inline decltype(auto) doCastIfPossible(const From &f) { |
407 | return ForwardTo::doCastIfPossible(const_cast<NonConstFrom>(f)); |
408 | } |
409 | }; |
410 | |
411 | /// Provides a cast trait that uses a defined pointer to pointer cast as a base |
412 | /// for reference-to-reference casts. Note that it does not provide castFailed |
413 | /// and doCastIfPossible because a pointer-to-pointer cast would likely just |
414 | /// return `nullptr` which could cause nullptr dereference. You can use it like |
415 | /// this: |
416 | /// |
417 | /// template <> struct CastInfo<foo, bar *> { ... verbose implementation... }; |
418 | /// |
419 | /// template <> |
420 | /// struct CastInfo<foo, bar> |
421 | /// : public ForwardToPointerCast<foo, bar, CastInfo<foo, bar *>> {}; |
422 | /// |
423 | template <typename To, typename From, typename ForwardTo> |
424 | struct ForwardToPointerCast { |
425 | static inline bool isPossible(const From &f) { |
426 | return ForwardTo::isPossible(&f); |
427 | } |
428 | |
429 | static inline decltype(auto) doCast(const From &f) { |
430 | return *ForwardTo::doCast(&f); |
431 | } |
432 | }; |
433 | |
434 | //===----------------------------------------------------------------------===// |
435 | // CastInfo |
436 | //===----------------------------------------------------------------------===// |
437 | |
438 | /// This struct provides a method for customizing the way a cast is performed. |
439 | /// It inherits from CastIsPossible, to support the case of declaring many |
440 | /// CastIsPossible specializations without having to specialize the full |
441 | /// CastInfo. |
442 | /// |
443 | /// In order to specialize different behaviors, specify different functions in |
444 | /// your CastInfo specialization. |
445 | /// For isa<> customization, provide: |
446 | /// |
447 | /// `static bool isPossible(const From &f)` |
448 | /// |
449 | /// For cast<> customization, provide: |
450 | /// |
451 | /// `static To doCast(const From &f)` |
452 | /// |
453 | /// For dyn_cast<> and the *_if_present<> variants' customization, provide: |
454 | /// |
455 | /// `static To castFailed()` and `static To doCastIfPossible(const From &f)` |
456 | /// |
457 | /// Your specialization might look something like this: |
458 | /// |
459 | /// template<> struct CastInfo<foo, bar> : public CastIsPossible<foo, bar> { |
460 | /// static inline foo doCast(const bar &b) { |
461 | /// return foo(const_cast<bar &>(b)); |
462 | /// } |
463 | /// static inline foo castFailed() { return foo(); } |
464 | /// static inline foo doCastIfPossible(const bar &b) { |
465 | /// if (!CastInfo<foo, bar>::isPossible(b)) |
466 | /// return castFailed(); |
467 | /// return doCast(b); |
468 | /// } |
469 | /// }; |
470 | |
471 | // The default implementations of CastInfo don't use cast traits for now because |
472 | // we need to specify types all over the place due to the current expected |
473 | // casting behavior and the way cast_retty works. New use cases can and should |
474 | // take advantage of the cast traits whenever possible! |
475 | |
476 | template <typename To, typename From, typename Enable = void> |
477 | struct CastInfo : public CastIsPossible<To, From> { |
478 | using Self = CastInfo<To, From, Enable>; |
479 | |
480 | using CastReturnType = typename cast_retty<To, From>::ret_type; |
481 | |
482 | static inline CastReturnType doCast(const From &f) { |
483 | return cast_convert_val< |
484 | To, From, |
485 | typename simplify_type<From>::SimpleType>::doit(const_cast<From &>(f)); |
486 | } |
487 | |
488 | // This assumes that you can construct the cast return type from `nullptr`. |
489 | // This is largely to support legacy use cases - if you don't want this |
490 | // behavior you should specialize CastInfo for your use case. |
491 | static inline CastReturnType castFailed() { return CastReturnType(nullptr); } |
492 | |
493 | static inline CastReturnType doCastIfPossible(const From &f) { |
494 | if (!Self::isPossible(f)) |
495 | return castFailed(); |
496 | return doCast(f); |
497 | } |
498 | }; |
499 | |
500 | /// This struct provides an overload for CastInfo where From has simplify_type |
501 | /// defined. This simply forwards to the appropriate CastInfo with the |
502 | /// simplified type/value, so you don't have to implement both. |
503 | template <typename To, typename From> |
504 | struct CastInfo<To, From, std::enable_if_t<!is_simple_type<From>::value>> { |
505 | using Self = CastInfo<To, From>; |
506 | using SimpleFrom = typename simplify_type<From>::SimpleType; |
507 | using SimplifiedSelf = CastInfo<To, SimpleFrom>; |
508 | |
509 | static inline bool isPossible(From &f) { |
510 | return SimplifiedSelf::isPossible( |
511 | simplify_type<From>::getSimplifiedValue(f)); |
512 | } |
513 | |
514 | static inline decltype(auto) doCast(From &f) { |
515 | return SimplifiedSelf::doCast(simplify_type<From>::getSimplifiedValue(f)); |
516 | } |
517 | |
518 | static inline decltype(auto) castFailed() { |
519 | return SimplifiedSelf::castFailed(); |
520 | } |
521 | |
522 | static inline decltype(auto) doCastIfPossible(From &f) { |
523 | return SimplifiedSelf::doCastIfPossible( |
524 | simplify_type<From>::getSimplifiedValue(f)); |
525 | } |
526 | }; |
527 | |
528 | //===----------------------------------------------------------------------===// |
529 | // Pre-specialized CastInfo |
530 | //===----------------------------------------------------------------------===// |
531 | |
532 | /// Provide a CastInfo specialized for std::unique_ptr. |
533 | template <typename To, typename From> |
534 | struct CastInfo<To, std::unique_ptr<From>> : public UniquePtrCast<To, From> {}; |
535 | |
536 | /// Provide a CastInfo specialized for Optional<From>. It's assumed that if the |
537 | /// input is Optional<From> that the output can be Optional<To>. If that's not |
538 | /// the case, specialize CastInfo for your use case. |
539 | template <typename To, typename From> |
540 | struct CastInfo<To, Optional<From>> : public OptionalValueCast<To, From> {}; |
541 | |
542 | /// isa<X> - Return true if the parameter to the template is an instance of one |
543 | /// of the template type arguments. Used like this: |
544 | /// |
545 | /// if (isa<Type>(myVal)) { ... } |
546 | /// if (isa<Type0, Type1, Type2>(myVal)) { ... } |
547 | template <typename To, typename From> |
548 | [[nodiscard]] inline bool isa(const From &Val) { |
549 | return CastInfo<To, const From>::isPossible(Val); |
550 | } |
551 | |
552 | template <typename First, typename Second, typename... Rest, typename From> |
553 | [[nodiscard]] inline bool isa(const From &Val) { |
554 | return isa<First>(Val) || isa<Second, Rest...>(Val); |
555 | } |
556 | |
557 | /// cast<X> - Return the argument parameter cast to the specified type. This |
558 | /// casting operator asserts that the type is correct, so it does not return |
559 | /// null on failure. It does not allow a null argument (use cast_if_present for |
560 | /// that). It is typically used like this: |
561 | /// |
562 | /// cast<Instruction>(myVal)->getParent() |
563 | |
564 | template <typename To, typename From> |
565 | [[nodiscard]] inline decltype(auto) cast(const From &Val) { |
566 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 566, __extension__ __PRETTY_FUNCTION__ )); |
567 | return CastInfo<To, const From>::doCast(Val); |
568 | } |
569 | |
570 | template <typename To, typename From> |
571 | [[nodiscard]] inline decltype(auto) cast(From &Val) { |
572 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 572, __extension__ __PRETTY_FUNCTION__ )); |
573 | return CastInfo<To, From>::doCast(Val); |
574 | } |
575 | |
576 | template <typename To, typename From> |
577 | [[nodiscard]] inline decltype(auto) cast(From *Val) { |
578 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 578, __extension__ __PRETTY_FUNCTION__ )); |
579 | return CastInfo<To, From *>::doCast(Val); |
580 | } |
581 | |
582 | template <typename To, typename From> |
583 | [[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) { |
584 | assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 584, __extension__ __PRETTY_FUNCTION__ )); |
585 | return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val)); |
586 | } |
587 | |
588 | //===----------------------------------------------------------------------===// |
589 | // ValueIsPresent |
590 | //===----------------------------------------------------------------------===// |
591 | |
592 | template <typename T> |
593 | constexpr bool IsNullable = |
594 | std::is_pointer_v<T> || std::is_constructible_v<T, std::nullptr_t>; |
595 | |
596 | /// ValueIsPresent provides a way to check if a value is, well, present. For |
597 | /// pointers, this is the equivalent of checking against nullptr, for Optionals |
598 | /// this is the equivalent of checking hasValue(). It also provides a method for |
599 | /// unwrapping a value (think calling .value() on an optional). |
600 | |
601 | // Generic values can't *not* be present. |
602 | template <typename T, typename Enable = void> struct ValueIsPresent { |
603 | using UnwrappedType = T; |
604 | static inline bool isPresent(const T &t) { return true; } |
605 | static inline decltype(auto) unwrapValue(T &t) { return t; } |
606 | }; |
607 | |
608 | // Optional provides its own way to check if something is present. |
609 | template <typename T> struct ValueIsPresent<Optional<T>> { |
610 | using UnwrappedType = T; |
611 | static inline bool isPresent(const Optional<T> &t) { return t.has_value(); } |
612 | static inline decltype(auto) unwrapValue(Optional<T> &t) { return t.value(); } |
613 | }; |
614 | |
615 | // If something is "nullable" then we just compare it to nullptr to see if it |
616 | // exists. |
617 | template <typename T> |
618 | struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> { |
619 | using UnwrappedType = T; |
620 | static inline bool isPresent(const T &t) { return t != T(nullptr); } |
621 | static inline decltype(auto) unwrapValue(T &t) { return t; } |
622 | }; |
623 | |
624 | namespace detail { |
625 | // Convenience function we can use to check if a value is present. Because of |
626 | // simplify_type, we have to call it on the simplified type for now. |
627 | template <typename T> inline bool isPresent(const T &t) { |
628 | return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent( |
629 | simplify_type<T>::getSimplifiedValue(const_cast<T &>(t))); |
630 | } |
631 | |
632 | // Convenience function we can use to unwrap a value. |
633 | template <typename T> inline decltype(auto) unwrapValue(T &t) { |
634 | return ValueIsPresent<T>::unwrapValue(t); |
635 | } |
636 | } // namespace detail |
637 | |
638 | /// dyn_cast<X> - Return the argument parameter cast to the specified type. This |
639 | /// casting operator returns null if the argument is of the wrong type, so it |
640 | /// can be used to test for a type as well as cast if successful. The value |
641 | /// passed in must be present, if not, use dyn_cast_if_present. This should be |
642 | /// used in the context of an if statement like this: |
643 | /// |
644 | /// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... } |
645 | |
646 | template <typename To, typename From> |
647 | [[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) { |
648 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 648, __extension__ __PRETTY_FUNCTION__ )); |
649 | return CastInfo<To, const From>::doCastIfPossible(Val); |
650 | } |
651 | |
652 | template <typename To, typename From> |
653 | [[nodiscard]] inline decltype(auto) dyn_cast(From &Val) { |
654 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 654, __extension__ __PRETTY_FUNCTION__ )); |
655 | return CastInfo<To, From>::doCastIfPossible(Val); |
656 | } |
657 | |
658 | template <typename To, typename From> |
659 | [[nodiscard]] inline decltype(auto) dyn_cast(From *Val) { |
660 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 660, __extension__ __PRETTY_FUNCTION__ )); |
661 | return CastInfo<To, From *>::doCastIfPossible(Val); |
662 | } |
663 | |
664 | template <typename To, typename From> |
665 | [[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &&Val) { |
666 | assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value" ) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\"" , "llvm/include/llvm/Support/Casting.h", 666, __extension__ __PRETTY_FUNCTION__ )); |
667 | return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible( |
668 | std::forward<std::unique_ptr<From> &&>(Val)); |
669 | } |
670 | |
671 | /// isa_and_present<X> - Functionally identical to isa, except that a null value |
672 | /// is accepted. |
673 | template <typename... X, class Y> |
674 | [[nodiscard]] inline bool isa_and_present(const Y &Val) { |
675 | if (!detail::isPresent(Val)) |
676 | return false; |
677 | return isa<X...>(Val); |
678 | } |
679 | |
680 | template <typename... X, class Y> |
681 | [[nodiscard]] inline bool isa_and_nonnull(const Y &Val) { |
682 | return isa_and_present<X...>(Val); |
683 | } |
684 | |
685 | /// cast_if_present<X> - Functionally identical to cast, except that a null |
686 | /// value is accepted. |
687 | template <class X, class Y> |
688 | [[nodiscard]] inline auto cast_if_present(const Y &Val) { |
689 | if (!detail::isPresent(Val)) |
690 | return CastInfo<X, const Y>::castFailed(); |
691 | assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 691, __extension__ __PRETTY_FUNCTION__ )); |
692 | return cast<X>(detail::unwrapValue(Val)); |
693 | } |
694 | |
695 | template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) { |
696 | if (!detail::isPresent(Val)) |
697 | return CastInfo<X, Y>::castFailed(); |
698 | assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 698, __extension__ __PRETTY_FUNCTION__ )); |
699 | return cast<X>(detail::unwrapValue(Val)); |
700 | } |
701 | |
702 | template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) { |
703 | if (!detail::isPresent(Val)) |
704 | return CastInfo<X, Y *>::castFailed(); |
705 | assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\"" , "llvm/include/llvm/Support/Casting.h", 705, __extension__ __PRETTY_FUNCTION__ )); |
706 | return cast<X>(detail::unwrapValue(Val)); |
707 | } |
708 | |
709 | template <class X, class Y> |
710 | [[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) { |
711 | if (!detail::isPresent(Val)) |
712 | return UniquePtrCast<X, Y>::castFailed(); |
713 | return UniquePtrCast<X, Y>::doCast(std::move(Val)); |
714 | } |
715 | |
716 | // Provide a forwarding from cast_or_null to cast_if_present for current |
717 | // users. This is deprecated and will be removed in a future patch, use |
718 | // cast_if_present instead. |
719 | template <class X, class Y> auto cast_or_null(const Y &Val) { |
720 | return cast_if_present<X>(Val); |
721 | } |
722 | |
723 | template <class X, class Y> auto cast_or_null(Y &Val) { |
724 | return cast_if_present<X>(Val); |
725 | } |
726 | |
727 | template <class X, class Y> auto cast_or_null(Y *Val) { |
728 | return cast_if_present<X>(Val); |
729 | } |
730 | |
731 | template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) { |
732 | return cast_if_present<X>(std::move(Val)); |
733 | } |
734 | |
735 | /// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a |
736 | /// null (or none in the case of optionals) value is accepted. |
737 | template <class X, class Y> auto dyn_cast_if_present(const Y &Val) { |
738 | if (!detail::isPresent(Val)) |
739 | return CastInfo<X, const Y>::castFailed(); |
740 | return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val)); |
741 | } |
742 | |
743 | template <class X, class Y> auto dyn_cast_if_present(Y &Val) { |
744 | if (!detail::isPresent(Val)) |
745 | return CastInfo<X, Y>::castFailed(); |
746 | return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val)); |
747 | } |
748 | |
749 | template <class X, class Y> auto dyn_cast_if_present(Y *Val) { |
750 | if (!detail::isPresent(Val)) |
751 | return CastInfo<X, Y *>::castFailed(); |
752 | return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val)); |
753 | } |
754 | |
755 | // Forwards to dyn_cast_if_present to avoid breaking current users. This is |
756 | // deprecated and will be removed in a future patch, use |
757 | // cast_if_present instead. |
758 | template <class X, class Y> auto dyn_cast_or_null(const Y &Val) { |
759 | return dyn_cast_if_present<X>(Val); |
760 | } |
761 | |
762 | template <class X, class Y> auto dyn_cast_or_null(Y &Val) { |
763 | return dyn_cast_if_present<X>(Val); |
764 | } |
765 | |
766 | template <class X, class Y> auto dyn_cast_or_null(Y *Val) { |
767 | return dyn_cast_if_present<X>(Val); |
768 | } |
769 | |
770 | /// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>, |
771 | /// taking ownership of the input pointer iff isa<X>(Val) is true. If the |
772 | /// cast is successful, From refers to nullptr on exit and the casted value |
773 | /// is returned. If the cast is unsuccessful, the function returns nullptr |
774 | /// and From is unchanged. |
775 | template <class X, class Y> |
776 | [[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType |
777 | unique_dyn_cast(std::unique_ptr<Y> &Val) { |
778 | if (!isa<X>(Val)) |
779 | return nullptr; |
780 | return cast<X>(std::move(Val)); |
781 | } |
782 | |
783 | template <class X, class Y> |
784 | [[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) { |
785 | return unique_dyn_cast<X, Y>(Val); |
786 | } |
787 | |
788 | // unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, |
789 | // except that a null value is accepted. |
790 | template <class X, class Y> |
791 | [[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType |
792 | unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) { |
793 | if (!Val) |
794 | return nullptr; |
795 | return unique_dyn_cast<X, Y>(Val); |
796 | } |
797 | |
798 | template <class X, class Y> |
799 | [[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) { |
800 | return unique_dyn_cast_or_null<X, Y>(Val); |
801 | } |
802 | |
803 | } // end namespace llvm |
804 | |
805 | #endif // LLVM_SUPPORT_CASTING_H |