File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 5547, column 18 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements semantic analysis for expressions. | ||||
10 | // | ||||
11 | //===----------------------------------------------------------------------===// | ||||
12 | |||||
13 | #include "TreeTransform.h" | ||||
14 | #include "UsedDeclVisitor.h" | ||||
15 | #include "clang/AST/ASTConsumer.h" | ||||
16 | #include "clang/AST/ASTContext.h" | ||||
17 | #include "clang/AST/ASTLambda.h" | ||||
18 | #include "clang/AST/ASTMutationListener.h" | ||||
19 | #include "clang/AST/CXXInheritance.h" | ||||
20 | #include "clang/AST/DeclObjC.h" | ||||
21 | #include "clang/AST/DeclTemplate.h" | ||||
22 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||
23 | #include "clang/AST/Expr.h" | ||||
24 | #include "clang/AST/ExprCXX.h" | ||||
25 | #include "clang/AST/ExprObjC.h" | ||||
26 | #include "clang/AST/ExprOpenMP.h" | ||||
27 | #include "clang/AST/OperationKinds.h" | ||||
28 | #include "clang/AST/RecursiveASTVisitor.h" | ||||
29 | #include "clang/AST/TypeLoc.h" | ||||
30 | #include "clang/Basic/Builtins.h" | ||||
31 | #include "clang/Basic/PartialDiagnostic.h" | ||||
32 | #include "clang/Basic/SourceManager.h" | ||||
33 | #include "clang/Basic/TargetInfo.h" | ||||
34 | #include "clang/Lex/LiteralSupport.h" | ||||
35 | #include "clang/Lex/Preprocessor.h" | ||||
36 | #include "clang/Sema/AnalysisBasedWarnings.h" | ||||
37 | #include "clang/Sema/DeclSpec.h" | ||||
38 | #include "clang/Sema/DelayedDiagnostic.h" | ||||
39 | #include "clang/Sema/Designator.h" | ||||
40 | #include "clang/Sema/Initialization.h" | ||||
41 | #include "clang/Sema/Lookup.h" | ||||
42 | #include "clang/Sema/Overload.h" | ||||
43 | #include "clang/Sema/ParsedTemplate.h" | ||||
44 | #include "clang/Sema/Scope.h" | ||||
45 | #include "clang/Sema/ScopeInfo.h" | ||||
46 | #include "clang/Sema/SemaFixItUtils.h" | ||||
47 | #include "clang/Sema/SemaInternal.h" | ||||
48 | #include "clang/Sema/Template.h" | ||||
49 | #include "llvm/ADT/STLExtras.h" | ||||
50 | #include "llvm/Support/ConvertUTF.h" | ||||
51 | #include "llvm/Support/SaveAndRestore.h" | ||||
52 | using namespace clang; | ||||
53 | using namespace sema; | ||||
54 | using llvm::RoundingMode; | ||||
55 | |||||
56 | /// Determine whether the use of this declaration is valid, without | ||||
57 | /// emitting diagnostics. | ||||
58 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||
59 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
60 | if (ParsingInitForAutoVars.count(D)) | ||||
61 | return false; | ||||
62 | |||||
63 | // See if this is a deleted function. | ||||
64 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
65 | if (FD->isDeleted()) | ||||
66 | return false; | ||||
67 | |||||
68 | // If the function has a deduced return type, and we can't deduce it, | ||||
69 | // then we can't use it either. | ||||
70 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
71 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||
72 | return false; | ||||
73 | |||||
74 | // See if this is an aligned allocation/deallocation function that is | ||||
75 | // unavailable. | ||||
76 | if (TreatUnavailableAsInvalid && | ||||
77 | isUnavailableAlignedAllocationFunction(*FD)) | ||||
78 | return false; | ||||
79 | } | ||||
80 | |||||
81 | // See if this function is unavailable. | ||||
82 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||
83 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||
84 | return false; | ||||
85 | |||||
86 | return true; | ||||
87 | } | ||||
88 | |||||
89 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||
90 | // Warn if this is used but marked unused. | ||||
91 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||
92 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||
93 | // should diagnose them. | ||||
94 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||
95 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||
96 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||
97 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||
98 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||
99 | } | ||||
100 | } | ||||
101 | } | ||||
102 | |||||
103 | /// Emit a note explaining that this function is deleted. | ||||
104 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||
105 | assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void > (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 105, __PRETTY_FUNCTION__)); | ||||
106 | |||||
107 | if (Decl->isDefaulted()) { | ||||
108 | // If the method was explicitly defaulted, point at that declaration. | ||||
109 | if (!Decl->isImplicit()) | ||||
110 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||
111 | |||||
112 | // Try to diagnose why this special member function was implicitly | ||||
113 | // deleted. This might fail, if that reason no longer applies. | ||||
114 | DiagnoseDeletedDefaultedFunction(Decl); | ||||
115 | return; | ||||
116 | } | ||||
117 | |||||
118 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||
119 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
120 | return NoteDeletedInheritingConstructor(Ctor); | ||||
121 | |||||
122 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||
123 | << Decl << 1; | ||||
124 | } | ||||
125 | |||||
126 | /// Determine whether a FunctionDecl was ever declared with an | ||||
127 | /// explicit storage class. | ||||
128 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||
129 | for (auto I : D->redecls()) { | ||||
130 | if (I->getStorageClass() != SC_None) | ||||
131 | return true; | ||||
132 | } | ||||
133 | return false; | ||||
134 | } | ||||
135 | |||||
136 | /// Check whether we're in an extern inline function and referring to a | ||||
137 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||
138 | /// | ||||
139 | /// This is only a warning because we used to silently accept this code, but | ||||
140 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||
141 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||
142 | /// and so while there may still be user mistakes, most of the time we can't | ||||
143 | /// prove that there are errors. | ||||
144 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||
145 | const NamedDecl *D, | ||||
146 | SourceLocation Loc) { | ||||
147 | // This is disabled under C++; there are too many ways for this to fire in | ||||
148 | // contexts where the warning is a false positive, or where it is technically | ||||
149 | // correct but benign. | ||||
150 | if (S.getLangOpts().CPlusPlus) | ||||
151 | return; | ||||
152 | |||||
153 | // Check if this is an inlined function or method. | ||||
154 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||
155 | if (!Current) | ||||
156 | return; | ||||
157 | if (!Current->isInlined()) | ||||
158 | return; | ||||
159 | if (!Current->isExternallyVisible()) | ||||
160 | return; | ||||
161 | |||||
162 | // Check if the decl has internal linkage. | ||||
163 | if (D->getFormalLinkage() != InternalLinkage) | ||||
164 | return; | ||||
165 | |||||
166 | // Downgrade from ExtWarn to Extension if | ||||
167 | // (1) the supposedly external inline function is in the main file, | ||||
168 | // and probably won't be included anywhere else. | ||||
169 | // (2) the thing we're referencing is a pure function. | ||||
170 | // (3) the thing we're referencing is another inline function. | ||||
171 | // This last can give us false negatives, but it's better than warning on | ||||
172 | // wrappers for simple C library functions. | ||||
173 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||
174 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||
175 | if (!DowngradeWarning && UsedFn) | ||||
176 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||
177 | |||||
178 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||
179 | : diag::ext_internal_in_extern_inline) | ||||
180 | << /*IsVar=*/!UsedFn << D; | ||||
181 | |||||
182 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||
183 | |||||
184 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||
185 | << D; | ||||
186 | } | ||||
187 | |||||
188 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||
189 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||
190 | |||||
191 | // Suggest "static" on the function, if possible. | ||||
192 | if (!hasAnyExplicitStorageClass(First)) { | ||||
193 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||
194 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||
195 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||
196 | } | ||||
197 | } | ||||
198 | |||||
199 | /// Determine whether the use of this declaration is valid, and | ||||
200 | /// emit any corresponding diagnostics. | ||||
201 | /// | ||||
202 | /// This routine diagnoses various problems with referencing | ||||
203 | /// declarations that can occur when using a declaration. For example, | ||||
204 | /// it might warn if a deprecated or unavailable declaration is being | ||||
205 | /// used, or produce an error (and return true) if a C++0x deleted | ||||
206 | /// function is being used. | ||||
207 | /// | ||||
208 | /// \returns true if there was an error (this declaration cannot be | ||||
209 | /// referenced), false otherwise. | ||||
210 | /// | ||||
211 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||
212 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||
213 | bool ObjCPropertyAccess, | ||||
214 | bool AvoidPartialAvailabilityChecks, | ||||
215 | ObjCInterfaceDecl *ClassReceiver) { | ||||
216 | SourceLocation Loc = Locs.front(); | ||||
217 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||
218 | // If there were any diagnostics suppressed by template argument deduction, | ||||
219 | // emit them now. | ||||
220 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||
221 | if (Pos != SuppressedDiagnostics.end()) { | ||||
222 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||
223 | Diag(Suppressed.first, Suppressed.second); | ||||
224 | |||||
225 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||
226 | // them again for this specialization. However, we don't obsolete this | ||||
227 | // entry from the table, because we want to avoid ever emitting these | ||||
228 | // diagnostics again. | ||||
229 | Pos->second.clear(); | ||||
230 | } | ||||
231 | |||||
232 | // C++ [basic.start.main]p3: | ||||
233 | // The function 'main' shall not be used within a program. | ||||
234 | if (cast<FunctionDecl>(D)->isMain()) | ||||
235 | Diag(Loc, diag::ext_main_used); | ||||
236 | |||||
237 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||
238 | } | ||||
239 | |||||
240 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
241 | if (ParsingInitForAutoVars.count(D)) { | ||||
242 | if (isa<BindingDecl>(D)) { | ||||
243 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||
244 | << D->getDeclName(); | ||||
245 | } else { | ||||
246 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||
247 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||
248 | } | ||||
249 | return true; | ||||
250 | } | ||||
251 | |||||
252 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
253 | // See if this is a deleted function. | ||||
254 | if (FD->isDeleted()) { | ||||
255 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||
256 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
257 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||
258 | << Ctor->getParent() | ||||
259 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||
260 | else | ||||
261 | Diag(Loc, diag::err_deleted_function_use); | ||||
262 | NoteDeletedFunction(FD); | ||||
263 | return true; | ||||
264 | } | ||||
265 | |||||
266 | // [expr.prim.id]p4 | ||||
267 | // A program that refers explicitly or implicitly to a function with a | ||||
268 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||
269 | // other than to declare it, is ill-formed. [...] | ||||
270 | // | ||||
271 | // See if this is a function with constraints that need to be satisfied. | ||||
272 | // Check this before deducing the return type, as it might instantiate the | ||||
273 | // definition. | ||||
274 | if (FD->getTrailingRequiresClause()) { | ||||
275 | ConstraintSatisfaction Satisfaction; | ||||
276 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | ||||
277 | // A diagnostic will have already been generated (non-constant | ||||
278 | // constraint expression, for example) | ||||
279 | return true; | ||||
280 | if (!Satisfaction.IsSatisfied) { | ||||
281 | Diag(Loc, | ||||
282 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||
283 | << D; | ||||
284 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||
285 | return true; | ||||
286 | } | ||||
287 | } | ||||
288 | |||||
289 | // If the function has a deduced return type, and we can't deduce it, | ||||
290 | // then we can't use it either. | ||||
291 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
292 | DeduceReturnType(FD, Loc)) | ||||
293 | return true; | ||||
294 | |||||
295 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||
296 | return true; | ||||
297 | |||||
298 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||
299 | return true; | ||||
300 | } | ||||
301 | |||||
302 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
303 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||
304 | if (MD->getParent()->isLambda() && | ||||
305 | ((isa<CXXConstructorDecl>(MD) && | ||||
306 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||
307 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||
308 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||
309 | << !isa<CXXConstructorDecl>(MD); | ||||
310 | } | ||||
311 | } | ||||
312 | |||||
313 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||
314 | const ObjCPropertyDecl * { | ||||
315 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||
316 | return MD->findPropertyDecl(); | ||||
317 | return nullptr; | ||||
318 | }; | ||||
319 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||
320 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||
321 | return true; | ||||
322 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||
323 | return true; | ||||
324 | } | ||||
325 | |||||
326 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||
327 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||
328 | // Only the variables omp_priv and omp_orig are allowed in the | ||||
329 | // initializer-clause. | ||||
330 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||
331 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||
332 | isa<VarDecl>(D)) { | ||||
333 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||
334 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||
335 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
336 | return true; | ||||
337 | } | ||||
338 | |||||
339 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||
340 | // List-items in map clauses on this construct may only refer to the declared | ||||
341 | // variable var and entities that could be referenced by a procedure defined | ||||
342 | // at the same location | ||||
343 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||
344 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||
345 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||
346 | << getOpenMPDeclareMapperVarName(); | ||||
347 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
348 | return true; | ||||
349 | } | ||||
350 | |||||
351 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||
352 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||
353 | |||||
354 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||
355 | |||||
356 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||
357 | |||||
358 | // CUDA/HIP: Diagnose invalid references of host global variables in device | ||||
359 | // functions. Reference of device global variables in host functions is | ||||
360 | // allowed through shadow variables therefore it is not diagnosed. | ||||
361 | if (LangOpts.CUDAIsDevice) { | ||||
362 | auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); | ||||
363 | auto Target = IdentifyCUDATarget(FD); | ||||
364 | if (FD && Target != CFT_Host) { | ||||
365 | const auto *VD = dyn_cast<VarDecl>(D); | ||||
366 | if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && | ||||
367 | !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && | ||||
368 | !VD->getType()->isCUDADeviceBuiltinSurfaceType() && | ||||
369 | !VD->getType()->isCUDADeviceBuiltinTextureType() && | ||||
370 | !VD->isConstexpr() && !VD->getType().isConstQualified()) | ||||
371 | targetDiag(*Locs.begin(), diag::err_ref_bad_target) | ||||
372 | << /*host*/ 2 << /*variable*/ 1 << VD << Target; | ||||
373 | } | ||||
374 | } | ||||
375 | |||||
376 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||
377 | if (auto *VD = dyn_cast<ValueDecl>(D)) | ||||
378 | checkDeviceDecl(VD, Loc); | ||||
379 | |||||
380 | if (!Context.getTargetInfo().isTLSSupported()) | ||||
381 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
382 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||
383 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||
384 | } | ||||
385 | |||||
386 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||
387 | !isUnevaluatedContext()) { | ||||
388 | // C++ [expr.prim.req.nested] p3 | ||||
389 | // A local parameter shall only appear as an unevaluated operand | ||||
390 | // (Clause 8) within the constraint-expression. | ||||
391 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||
392 | << D; | ||||
393 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
394 | return true; | ||||
395 | } | ||||
396 | |||||
397 | return false; | ||||
398 | } | ||||
399 | |||||
400 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||
401 | /// message-send is to a declaration with the sentinel attribute, and | ||||
402 | /// if so, it checks that the requirements of the sentinel are | ||||
403 | /// satisfied. | ||||
404 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||
405 | ArrayRef<Expr *> Args) { | ||||
406 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||
407 | if (!attr) | ||||
408 | return; | ||||
409 | |||||
410 | // The number of formal parameters of the declaration. | ||||
411 | unsigned numFormalParams; | ||||
412 | |||||
413 | // The kind of declaration. This is also an index into a %select in | ||||
414 | // the diagnostic. | ||||
415 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||
416 | |||||
417 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||
418 | numFormalParams = MD->param_size(); | ||||
419 | calleeType = CT_Method; | ||||
420 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
421 | numFormalParams = FD->param_size(); | ||||
422 | calleeType = CT_Function; | ||||
423 | } else if (isa<VarDecl>(D)) { | ||||
424 | QualType type = cast<ValueDecl>(D)->getType(); | ||||
425 | const FunctionType *fn = nullptr; | ||||
426 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||
427 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||
428 | if (!fn) return; | ||||
429 | calleeType = CT_Function; | ||||
430 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||
431 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||
432 | calleeType = CT_Block; | ||||
433 | } else { | ||||
434 | return; | ||||
435 | } | ||||
436 | |||||
437 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||
438 | numFormalParams = proto->getNumParams(); | ||||
439 | } else { | ||||
440 | numFormalParams = 0; | ||||
441 | } | ||||
442 | } else { | ||||
443 | return; | ||||
444 | } | ||||
445 | |||||
446 | // "nullPos" is the number of formal parameters at the end which | ||||
447 | // effectively count as part of the variadic arguments. This is | ||||
448 | // useful if you would prefer to not have *any* formal parameters, | ||||
449 | // but the language forces you to have at least one. | ||||
450 | unsigned nullPos = attr->getNullPos(); | ||||
451 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel" ) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 451, __PRETTY_FUNCTION__)); | ||||
452 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||
453 | |||||
454 | // The number of arguments which should follow the sentinel. | ||||
455 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||
456 | |||||
457 | // If there aren't enough arguments for all the formal parameters, | ||||
458 | // the sentinel, and the args after the sentinel, complain. | ||||
459 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||
460 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||
461 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
462 | return; | ||||
463 | } | ||||
464 | |||||
465 | // Otherwise, find the sentinel expression. | ||||
466 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||
467 | if (!sentinelExpr) return; | ||||
468 | if (sentinelExpr->isValueDependent()) return; | ||||
469 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||
470 | |||||
471 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||
472 | // or 'NULL' if those are actually defined in the context. Only use | ||||
473 | // 'nil' for ObjC methods, where it's much more likely that the | ||||
474 | // variadic arguments form a list of object pointers. | ||||
475 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||
476 | std::string NullValue; | ||||
477 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||
478 | NullValue = "nil"; | ||||
479 | else if (getLangOpts().CPlusPlus11) | ||||
480 | NullValue = "nullptr"; | ||||
481 | else if (PP.isMacroDefined("NULL")) | ||||
482 | NullValue = "NULL"; | ||||
483 | else | ||||
484 | NullValue = "(void*) 0"; | ||||
485 | |||||
486 | if (MissingNilLoc.isInvalid()) | ||||
487 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||
488 | else | ||||
489 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||
490 | << int(calleeType) | ||||
491 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||
492 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
493 | } | ||||
494 | |||||
495 | SourceRange Sema::getExprRange(Expr *E) const { | ||||
496 | return E ? E->getSourceRange() : SourceRange(); | ||||
497 | } | ||||
498 | |||||
499 | //===----------------------------------------------------------------------===// | ||||
500 | // Standard Promotions and Conversions | ||||
501 | //===----------------------------------------------------------------------===// | ||||
502 | |||||
503 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||
504 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||
505 | // Handle any placeholder expressions which made it here. | ||||
506 | if (E->getType()->isPlaceholderType()) { | ||||
507 | ExprResult result = CheckPlaceholderExpr(E); | ||||
508 | if (result.isInvalid()) return ExprError(); | ||||
509 | E = result.get(); | ||||
510 | } | ||||
511 | |||||
512 | QualType Ty = E->getType(); | ||||
513 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 513, __PRETTY_FUNCTION__)); | ||||
514 | |||||
515 | if (Ty->isFunctionType()) { | ||||
516 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||
517 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||
518 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||
519 | return ExprError(); | ||||
520 | |||||
521 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
522 | CK_FunctionToPointerDecay).get(); | ||||
523 | } else if (Ty->isArrayType()) { | ||||
524 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||
525 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||
526 | // type 'array of type' is converted to an expression that has type 'pointer | ||||
527 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||
528 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||
529 | // (C90) to "an expression" (C99). | ||||
530 | // | ||||
531 | // C++ 4.2p1: | ||||
532 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||
533 | // T" can be converted to an rvalue of type "pointer to T". | ||||
534 | // | ||||
535 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | ||||
536 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||
537 | CK_ArrayToPointerDecay).get(); | ||||
538 | } | ||||
539 | return E; | ||||
540 | } | ||||
541 | |||||
542 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||
543 | // Check to see if we are dereferencing a null pointer. If so, | ||||
544 | // and if not volatile-qualified, this is undefined behavior that the | ||||
545 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||
546 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||
547 | // only handles the pattern "*null", which is a very syntactic check. | ||||
548 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||
549 | if (UO && UO->getOpcode() == UO_Deref && | ||||
550 | UO->getSubExpr()->getType()->isPointerType()) { | ||||
551 | const LangAS AS = | ||||
552 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||
553 | if ((!isTargetAddressSpace(AS) || | ||||
554 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||
555 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||
556 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||
557 | !UO->getType().isVolatileQualified()) { | ||||
558 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
559 | S.PDiag(diag::warn_indirection_through_null) | ||||
560 | << UO->getSubExpr()->getSourceRange()); | ||||
561 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
562 | S.PDiag(diag::note_indirection_through_null)); | ||||
563 | } | ||||
564 | } | ||||
565 | } | ||||
566 | |||||
567 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||
568 | SourceLocation AssignLoc, | ||||
569 | const Expr* RHS) { | ||||
570 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||
571 | if (!IV) | ||||
572 | return; | ||||
573 | |||||
574 | DeclarationName MemberName = IV->getDeclName(); | ||||
575 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||
576 | if (!Member || !Member->isStr("isa")) | ||||
577 | return; | ||||
578 | |||||
579 | const Expr *Base = OIRE->getBase(); | ||||
580 | QualType BaseType = Base->getType(); | ||||
581 | if (OIRE->isArrow()) | ||||
582 | BaseType = BaseType->getPointeeType(); | ||||
583 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||
584 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||
585 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||
586 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||
587 | if (!ClassDeclared->getSuperClass() | ||||
588 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||
589 | if (RHS) { | ||||
590 | NamedDecl *ObjectSetClass = | ||||
591 | S.LookupSingleName(S.TUScope, | ||||
592 | &S.Context.Idents.get("object_setClass"), | ||||
593 | SourceLocation(), S.LookupOrdinaryName); | ||||
594 | if (ObjectSetClass) { | ||||
595 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||
596 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||
597 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
598 | "object_setClass(") | ||||
599 | << FixItHint::CreateReplacement( | ||||
600 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||
601 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
602 | } | ||||
603 | else | ||||
604 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||
605 | } else { | ||||
606 | NamedDecl *ObjectGetClass = | ||||
607 | S.LookupSingleName(S.TUScope, | ||||
608 | &S.Context.Idents.get("object_getClass"), | ||||
609 | SourceLocation(), S.LookupOrdinaryName); | ||||
610 | if (ObjectGetClass) | ||||
611 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||
612 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
613 | "object_getClass(") | ||||
614 | << FixItHint::CreateReplacement( | ||||
615 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||
616 | else | ||||
617 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||
618 | } | ||||
619 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||
620 | } | ||||
621 | } | ||||
622 | } | ||||
623 | |||||
624 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||
625 | // Handle any placeholder expressions which made it here. | ||||
626 | if (E->getType()->isPlaceholderType()) { | ||||
627 | ExprResult result = CheckPlaceholderExpr(E); | ||||
628 | if (result.isInvalid()) return ExprError(); | ||||
629 | E = result.get(); | ||||
630 | } | ||||
631 | |||||
632 | // C++ [conv.lval]p1: | ||||
633 | // A glvalue of a non-function, non-array type T can be | ||||
634 | // converted to a prvalue. | ||||
635 | if (!E->isGLValue()) return E; | ||||
636 | |||||
637 | QualType T = E->getType(); | ||||
638 | assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 638, __PRETTY_FUNCTION__)); | ||||
639 | |||||
640 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||
641 | if (T->isFunctionType() || T->isArrayType()) | ||||
642 | return E; | ||||
643 | |||||
644 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||
645 | // expressions of certain types in C++. | ||||
646 | if (getLangOpts().CPlusPlus && | ||||
647 | (E->getType() == Context.OverloadTy || | ||||
648 | T->isDependentType() || | ||||
649 | T->isRecordType())) | ||||
650 | return E; | ||||
651 | |||||
652 | // The C standard is actually really unclear on this point, and | ||||
653 | // DR106 tells us what the result should be but not why. It's | ||||
654 | // generally best to say that void types just doesn't undergo | ||||
655 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||
656 | // 'void' type are never l-values, but qualified void can be. | ||||
657 | if (T->isVoidType()) | ||||
658 | return E; | ||||
659 | |||||
660 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||
661 | if (getLangOpts().OpenCL && | ||||
662 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
663 | T->isHalfType()) { | ||||
664 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||
665 | << 0 << T; | ||||
666 | return ExprError(); | ||||
667 | } | ||||
668 | |||||
669 | CheckForNullPointerDereference(*this, E); | ||||
670 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||
671 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||
672 | &Context.Idents.get("object_getClass"), | ||||
673 | SourceLocation(), LookupOrdinaryName); | ||||
674 | if (ObjectGetClass) | ||||
675 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||
676 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||
677 | << FixItHint::CreateReplacement( | ||||
678 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||
679 | else | ||||
680 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||
681 | } | ||||
682 | else if (const ObjCIvarRefExpr *OIRE = | ||||
683 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||
684 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||
685 | |||||
686 | // C++ [conv.lval]p1: | ||||
687 | // [...] If T is a non-class type, the type of the prvalue is the | ||||
688 | // cv-unqualified version of T. Otherwise, the type of the | ||||
689 | // rvalue is T. | ||||
690 | // | ||||
691 | // C99 6.3.2.1p2: | ||||
692 | // If the lvalue has qualified type, the value has the unqualified | ||||
693 | // version of the type of the lvalue; otherwise, the value has the | ||||
694 | // type of the lvalue. | ||||
695 | if (T.hasQualifiers()) | ||||
696 | T = T.getUnqualifiedType(); | ||||
697 | |||||
698 | // Under the MS ABI, lock down the inheritance model now. | ||||
699 | if (T->isMemberPointerType() && | ||||
700 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
701 | (void)isCompleteType(E->getExprLoc(), T); | ||||
702 | |||||
703 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||
704 | if (Res.isInvalid()) | ||||
705 | return Res; | ||||
706 | E = Res.get(); | ||||
707 | |||||
708 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||
709 | // balance that. | ||||
710 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
711 | Cleanup.setExprNeedsCleanups(true); | ||||
712 | |||||
713 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
714 | Cleanup.setExprNeedsCleanups(true); | ||||
715 | |||||
716 | // C++ [conv.lval]p3: | ||||
717 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||
718 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||
719 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, | ||||
720 | CurFPFeatureOverrides()); | ||||
721 | |||||
722 | // C11 6.3.2.1p2: | ||||
723 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||
724 | // of the type of the lvalue ... | ||||
725 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||
726 | T = Atomic->getValueType().getUnqualifiedType(); | ||||
727 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||
728 | nullptr, VK_RValue, FPOptionsOverride()); | ||||
729 | } | ||||
730 | |||||
731 | return Res; | ||||
732 | } | ||||
733 | |||||
734 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||
735 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||
736 | if (Res.isInvalid()) | ||||
737 | return ExprError(); | ||||
738 | Res = DefaultLvalueConversion(Res.get()); | ||||
739 | if (Res.isInvalid()) | ||||
740 | return ExprError(); | ||||
741 | return Res; | ||||
742 | } | ||||
743 | |||||
744 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||
745 | /// performed on a function designator of a call expression. | ||||
746 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||
747 | QualType Ty = E->getType(); | ||||
748 | ExprResult Res = E; | ||||
749 | // Only do implicit cast for a function type, but not for a pointer | ||||
750 | // to function type. | ||||
751 | if (Ty->isFunctionType()) { | ||||
752 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
753 | CK_FunctionToPointerDecay); | ||||
754 | if (Res.isInvalid()) | ||||
755 | return ExprError(); | ||||
756 | } | ||||
757 | Res = DefaultLvalueConversion(Res.get()); | ||||
758 | if (Res.isInvalid()) | ||||
759 | return ExprError(); | ||||
760 | return Res.get(); | ||||
761 | } | ||||
762 | |||||
763 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||
764 | /// operators (C99 6.3). The conversions of array and function types are | ||||
765 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||
766 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||
767 | /// In these instances, this routine should *not* be called. | ||||
768 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||
769 | // First, convert to an r-value. | ||||
770 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||
771 | if (Res.isInvalid()) | ||||
772 | return ExprError(); | ||||
773 | E = Res.get(); | ||||
774 | |||||
775 | QualType Ty = E->getType(); | ||||
776 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 776, __PRETTY_FUNCTION__)); | ||||
777 | |||||
778 | // Half FP have to be promoted to float unless it is natively supported | ||||
779 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||
780 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||
781 | |||||
782 | // Try to perform integral promotions if the object has a theoretically | ||||
783 | // promotable type. | ||||
784 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||
785 | // C99 6.3.1.1p2: | ||||
786 | // | ||||
787 | // The following may be used in an expression wherever an int or | ||||
788 | // unsigned int may be used: | ||||
789 | // - an object or expression with an integer type whose integer | ||||
790 | // conversion rank is less than or equal to the rank of int | ||||
791 | // and unsigned int. | ||||
792 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||
793 | // | ||||
794 | // If an int can represent all values of the original type, the | ||||
795 | // value is converted to an int; otherwise, it is converted to an | ||||
796 | // unsigned int. These are called the integer promotions. All | ||||
797 | // other types are unchanged by the integer promotions. | ||||
798 | |||||
799 | QualType PTy = Context.isPromotableBitField(E); | ||||
800 | if (!PTy.isNull()) { | ||||
801 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||
802 | return E; | ||||
803 | } | ||||
804 | if (Ty->isPromotableIntegerType()) { | ||||
805 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||
806 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||
807 | return E; | ||||
808 | } | ||||
809 | } | ||||
810 | return E; | ||||
811 | } | ||||
812 | |||||
813 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||
814 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||
815 | /// are promoted to double. All other argument types are converted by | ||||
816 | /// UsualUnaryConversions(). | ||||
817 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||
818 | QualType Ty = E->getType(); | ||||
819 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 819, __PRETTY_FUNCTION__)); | ||||
820 | |||||
821 | ExprResult Res = UsualUnaryConversions(E); | ||||
822 | if (Res.isInvalid()) | ||||
823 | return ExprError(); | ||||
824 | E = Res.get(); | ||||
825 | |||||
826 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||
827 | // promote to double. | ||||
828 | // Note that default argument promotion applies only to float (and | ||||
829 | // half/fp16); it does not apply to _Float16. | ||||
830 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||
831 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||
832 | BTy->getKind() == BuiltinType::Float)) { | ||||
833 | if (getLangOpts().OpenCL && | ||||
834 | !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { | ||||
835 | if (BTy->getKind() == BuiltinType::Half) { | ||||
836 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||
837 | } | ||||
838 | } else { | ||||
839 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||
840 | } | ||||
841 | } | ||||
842 | |||||
843 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||
844 | // promotion, even on class types, but note: | ||||
845 | // C++11 [conv.lval]p2: | ||||
846 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||
847 | // operand or a subexpression thereof the value contained in the | ||||
848 | // referenced object is not accessed. Otherwise, if the glvalue | ||||
849 | // has a class type, the conversion copy-initializes a temporary | ||||
850 | // of type T from the glvalue and the result of the conversion | ||||
851 | // is a prvalue for the temporary. | ||||
852 | // FIXME: add some way to gate this entire thing for correctness in | ||||
853 | // potentially potentially evaluated contexts. | ||||
854 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||
855 | ExprResult Temp = PerformCopyInitialization( | ||||
856 | InitializedEntity::InitializeTemporary(E->getType()), | ||||
857 | E->getExprLoc(), E); | ||||
858 | if (Temp.isInvalid()) | ||||
859 | return ExprError(); | ||||
860 | E = Temp.get(); | ||||
861 | } | ||||
862 | |||||
863 | return E; | ||||
864 | } | ||||
865 | |||||
866 | /// Determine the degree of POD-ness for an expression. | ||||
867 | /// Incomplete types are considered POD, since this check can be performed | ||||
868 | /// when we're in an unevaluated context. | ||||
869 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||
870 | if (Ty->isIncompleteType()) { | ||||
871 | // C++11 [expr.call]p7: | ||||
872 | // After these conversions, if the argument does not have arithmetic, | ||||
873 | // enumeration, pointer, pointer to member, or class type, the program | ||||
874 | // is ill-formed. | ||||
875 | // | ||||
876 | // Since we've already performed array-to-pointer and function-to-pointer | ||||
877 | // decay, the only such type in C++ is cv void. This also handles | ||||
878 | // initializer lists as variadic arguments. | ||||
879 | if (Ty->isVoidType()) | ||||
880 | return VAK_Invalid; | ||||
881 | |||||
882 | if (Ty->isObjCObjectType()) | ||||
883 | return VAK_Invalid; | ||||
884 | return VAK_Valid; | ||||
885 | } | ||||
886 | |||||
887 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
888 | return VAK_Invalid; | ||||
889 | |||||
890 | if (Ty.isCXX98PODType(Context)) | ||||
891 | return VAK_Valid; | ||||
892 | |||||
893 | // C++11 [expr.call]p7: | ||||
894 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||
895 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||
896 | // or a non-trivial destructor, with no corresponding parameter, | ||||
897 | // is conditionally-supported with implementation-defined semantics. | ||||
898 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||
899 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||
900 | if (!Record->hasNonTrivialCopyConstructor() && | ||||
901 | !Record->hasNonTrivialMoveConstructor() && | ||||
902 | !Record->hasNonTrivialDestructor()) | ||||
903 | return VAK_ValidInCXX11; | ||||
904 | |||||
905 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||
906 | return VAK_Valid; | ||||
907 | |||||
908 | if (Ty->isObjCObjectType()) | ||||
909 | return VAK_Invalid; | ||||
910 | |||||
911 | if (getLangOpts().MSVCCompat) | ||||
912 | return VAK_MSVCUndefined; | ||||
913 | |||||
914 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||
915 | // permitted to reject them. We should consider doing so. | ||||
916 | return VAK_Undefined; | ||||
917 | } | ||||
918 | |||||
919 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||
920 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||
921 | const QualType &Ty = E->getType(); | ||||
922 | VarArgKind VAK = isValidVarArgType(Ty); | ||||
923 | |||||
924 | // Complain about passing non-POD types through varargs. | ||||
925 | switch (VAK) { | ||||
926 | case VAK_ValidInCXX11: | ||||
927 | DiagRuntimeBehavior( | ||||
928 | E->getBeginLoc(), nullptr, | ||||
929 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||
930 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
931 | case VAK_Valid: | ||||
932 | if (Ty->isRecordType()) { | ||||
933 | // This is unlikely to be what the user intended. If the class has a | ||||
934 | // 'c_str' member function, the user probably meant to call that. | ||||
935 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
936 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||
937 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||
938 | } | ||||
939 | break; | ||||
940 | |||||
941 | case VAK_Undefined: | ||||
942 | case VAK_MSVCUndefined: | ||||
943 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
944 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||
945 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||
946 | break; | ||||
947 | |||||
948 | case VAK_Invalid: | ||||
949 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
950 | Diag(E->getBeginLoc(), | ||||
951 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||
952 | << Ty << CT; | ||||
953 | else if (Ty->isObjCObjectType()) | ||||
954 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
955 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||
956 | << Ty << CT); | ||||
957 | else | ||||
958 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||
959 | << isa<InitListExpr>(E) << Ty << CT; | ||||
960 | break; | ||||
961 | } | ||||
962 | } | ||||
963 | |||||
964 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||
965 | /// will create a trap if the resulting type is not a POD type. | ||||
966 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||
967 | FunctionDecl *FDecl) { | ||||
968 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||
969 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
970 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||
971 | (CT == VariadicMethod || | ||||
972 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||
973 | E = stripARCUnbridgedCast(E); | ||||
974 | |||||
975 | // Otherwise, do normal placeholder checking. | ||||
976 | } else { | ||||
977 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||
978 | if (ExprRes.isInvalid()) | ||||
979 | return ExprError(); | ||||
980 | E = ExprRes.get(); | ||||
981 | } | ||||
982 | } | ||||
983 | |||||
984 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||
985 | if (ExprRes.isInvalid()) | ||||
986 | return ExprError(); | ||||
987 | |||||
988 | // Copy blocks to the heap. | ||||
989 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||
990 | maybeExtendBlockObject(ExprRes); | ||||
991 | |||||
992 | E = ExprRes.get(); | ||||
993 | |||||
994 | // Diagnostics regarding non-POD argument types are | ||||
995 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||
996 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||
997 | // Turn this into a trap. | ||||
998 | CXXScopeSpec SS; | ||||
999 | SourceLocation TemplateKWLoc; | ||||
1000 | UnqualifiedId Name; | ||||
1001 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||
1002 | E->getBeginLoc()); | ||||
1003 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||
1004 | /*HasTrailingLParen=*/true, | ||||
1005 | /*IsAddressOfOperand=*/false); | ||||
1006 | if (TrapFn.isInvalid()) | ||||
1007 | return ExprError(); | ||||
1008 | |||||
1009 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||
1010 | None, E->getEndLoc()); | ||||
1011 | if (Call.isInvalid()) | ||||
1012 | return ExprError(); | ||||
1013 | |||||
1014 | ExprResult Comma = | ||||
1015 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||
1016 | if (Comma.isInvalid()) | ||||
1017 | return ExprError(); | ||||
1018 | return Comma.get(); | ||||
1019 | } | ||||
1020 | |||||
1021 | if (!getLangOpts().CPlusPlus && | ||||
1022 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||
1023 | diag::err_call_incomplete_argument)) | ||||
1024 | return ExprError(); | ||||
1025 | |||||
1026 | return E; | ||||
1027 | } | ||||
1028 | |||||
1029 | /// Converts an integer to complex float type. Helper function of | ||||
1030 | /// UsualArithmeticConversions() | ||||
1031 | /// | ||||
1032 | /// \return false if the integer expression is an integer type and is | ||||
1033 | /// successfully converted to the complex type. | ||||
1034 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||
1035 | ExprResult &ComplexExpr, | ||||
1036 | QualType IntTy, | ||||
1037 | QualType ComplexTy, | ||||
1038 | bool SkipCast) { | ||||
1039 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||
1040 | if (SkipCast) return false; | ||||
1041 | if (IntTy->isIntegerType()) { | ||||
1042 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | ||||
1043 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||
1044 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1045 | CK_FloatingRealToComplex); | ||||
1046 | } else { | ||||
1047 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1047, __PRETTY_FUNCTION__)); | ||||
1048 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1049 | CK_IntegralComplexToFloatingComplex); | ||||
1050 | } | ||||
1051 | return false; | ||||
1052 | } | ||||
1053 | |||||
1054 | /// Handle arithmetic conversion with complex types. Helper function of | ||||
1055 | /// UsualArithmeticConversions() | ||||
1056 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | ||||
1057 | ExprResult &RHS, QualType LHSType, | ||||
1058 | QualType RHSType, | ||||
1059 | bool IsCompAssign) { | ||||
1060 | // if we have an integer operand, the result is the complex type. | ||||
1061 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1062 | /*skipCast*/false)) | ||||
1063 | return LHSType; | ||||
1064 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1065 | /*skipCast*/IsCompAssign)) | ||||
1066 | return RHSType; | ||||
1067 | |||||
1068 | // This handles complex/complex, complex/float, or float/complex. | ||||
1069 | // When both operands are complex, the shorter operand is converted to the | ||||
1070 | // type of the longer, and that is the type of the result. This corresponds | ||||
1071 | // to what is done when combining two real floating-point operands. | ||||
1072 | // The fun begins when size promotion occur across type domains. | ||||
1073 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||
1074 | // floating-point type, the less precise type is converted, within it's | ||||
1075 | // real or complex domain, to the precision of the other type. For example, | ||||
1076 | // when combining a "long double" with a "double _Complex", the | ||||
1077 | // "double _Complex" is promoted to "long double _Complex". | ||||
1078 | |||||
1079 | // Compute the rank of the two types, regardless of whether they are complex. | ||||
1080 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1081 | |||||
1082 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | ||||
1083 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | ||||
1084 | QualType LHSElementType = | ||||
1085 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | ||||
1086 | QualType RHSElementType = | ||||
1087 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | ||||
1088 | |||||
1089 | QualType ResultType = S.Context.getComplexType(LHSElementType); | ||||
1090 | if (Order < 0) { | ||||
1091 | // Promote the precision of the LHS if not an assignment. | ||||
1092 | ResultType = S.Context.getComplexType(RHSElementType); | ||||
1093 | if (!IsCompAssign) { | ||||
1094 | if (LHSComplexType) | ||||
1095 | LHS = | ||||
1096 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | ||||
1097 | else | ||||
1098 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | ||||
1099 | } | ||||
1100 | } else if (Order > 0) { | ||||
1101 | // Promote the precision of the RHS. | ||||
1102 | if (RHSComplexType) | ||||
1103 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | ||||
1104 | else | ||||
1105 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | ||||
1106 | } | ||||
1107 | return ResultType; | ||||
1108 | } | ||||
1109 | |||||
1110 | /// Handle arithmetic conversion from integer to float. Helper function | ||||
1111 | /// of UsualArithmeticConversions() | ||||
1112 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||
1113 | ExprResult &IntExpr, | ||||
1114 | QualType FloatTy, QualType IntTy, | ||||
1115 | bool ConvertFloat, bool ConvertInt) { | ||||
1116 | if (IntTy->isIntegerType()) { | ||||
1117 | if (ConvertInt) | ||||
1118 | // Convert intExpr to the lhs floating point type. | ||||
1119 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||
1120 | CK_IntegralToFloating); | ||||
1121 | return FloatTy; | ||||
1122 | } | ||||
1123 | |||||
1124 | // Convert both sides to the appropriate complex float. | ||||
1125 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1125, __PRETTY_FUNCTION__)); | ||||
1126 | QualType result = S.Context.getComplexType(FloatTy); | ||||
1127 | |||||
1128 | // _Complex int -> _Complex float | ||||
1129 | if (ConvertInt) | ||||
1130 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||
1131 | CK_IntegralComplexToFloatingComplex); | ||||
1132 | |||||
1133 | // float -> _Complex float | ||||
1134 | if (ConvertFloat) | ||||
1135 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||
1136 | CK_FloatingRealToComplex); | ||||
1137 | |||||
1138 | return result; | ||||
1139 | } | ||||
1140 | |||||
1141 | /// Handle arithmethic conversion with floating point types. Helper | ||||
1142 | /// function of UsualArithmeticConversions() | ||||
1143 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||
1144 | ExprResult &RHS, QualType LHSType, | ||||
1145 | QualType RHSType, bool IsCompAssign) { | ||||
1146 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||
1147 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||
1148 | |||||
1149 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||
1150 | // operand has a fixed-point type, the fixed-point operand | ||||
1151 | // is converted to the floating type [...] | ||||
1152 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||
1153 | if (LHSFloat) | ||||
1154 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||
1155 | else if (!IsCompAssign) | ||||
1156 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||
1157 | return LHSFloat ? LHSType : RHSType; | ||||
1158 | } | ||||
1159 | |||||
1160 | // If we have two real floating types, convert the smaller operand | ||||
1161 | // to the bigger result. | ||||
1162 | if (LHSFloat && RHSFloat) { | ||||
1163 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1164 | if (order > 0) { | ||||
1165 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||
1166 | return LHSType; | ||||
1167 | } | ||||
1168 | |||||
1169 | assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast <void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1169, __PRETTY_FUNCTION__)); | ||||
1170 | if (!IsCompAssign) | ||||
1171 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||
1172 | return RHSType; | ||||
1173 | } | ||||
1174 | |||||
1175 | if (LHSFloat) { | ||||
1176 | // Half FP has to be promoted to float unless it is natively supported | ||||
1177 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||
1178 | LHSType = S.Context.FloatTy; | ||||
1179 | |||||
1180 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1181 | /*ConvertFloat=*/!IsCompAssign, | ||||
1182 | /*ConvertInt=*/ true); | ||||
1183 | } | ||||
1184 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1184, __PRETTY_FUNCTION__)); | ||||
1185 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1186 | /*ConvertFloat=*/ true, | ||||
1187 | /*ConvertInt=*/!IsCompAssign); | ||||
1188 | } | ||||
1189 | |||||
1190 | /// Diagnose attempts to convert between __float128 and long double if | ||||
1191 | /// there is no support for such conversion. Helper function of | ||||
1192 | /// UsualArithmeticConversions(). | ||||
1193 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||
1194 | QualType RHSType) { | ||||
1195 | /* No issue converting if at least one of the types is not a floating point | ||||
1196 | type or the two types have the same rank. | ||||
1197 | */ | ||||
1198 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | ||||
1199 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | ||||
1200 | return false; | ||||
1201 | |||||
1202 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1203, __PRETTY_FUNCTION__)) | ||||
1203 | "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1203, __PRETTY_FUNCTION__)); | ||||
1204 | |||||
1205 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||
1206 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||
1207 | |||||
1208 | QualType LHSElemType = LHSComplex ? | ||||
1209 | LHSComplex->getElementType() : LHSType; | ||||
1210 | QualType RHSElemType = RHSComplex ? | ||||
1211 | RHSComplex->getElementType() : RHSType; | ||||
1212 | |||||
1213 | // No issue if the two types have the same representation | ||||
1214 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | ||||
1215 | &S.Context.getFloatTypeSemantics(RHSElemType)) | ||||
1216 | return false; | ||||
1217 | |||||
1218 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | ||||
1219 | RHSElemType == S.Context.LongDoubleTy); | ||||
1220 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | ||||
1221 | RHSElemType == S.Context.Float128Ty); | ||||
1222 | |||||
1223 | // We've handled the situation where __float128 and long double have the same | ||||
1224 | // representation. We allow all conversions for all possible long double types | ||||
1225 | // except PPC's double double. | ||||
1226 | return Float128AndLongDouble && | ||||
1227 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | ||||
1228 | &llvm::APFloat::PPCDoubleDouble()); | ||||
1229 | } | ||||
1230 | |||||
1231 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||
1232 | |||||
1233 | namespace { | ||||
1234 | /// These helper callbacks are placed in an anonymous namespace to | ||||
1235 | /// permit their use as function template parameters. | ||||
1236 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1237 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||
1238 | } | ||||
1239 | |||||
1240 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1241 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||
1242 | CK_IntegralComplexCast); | ||||
1243 | } | ||||
1244 | } | ||||
1245 | |||||
1246 | /// Handle integer arithmetic conversions. Helper function of | ||||
1247 | /// UsualArithmeticConversions() | ||||
1248 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||
1249 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||
1250 | ExprResult &RHS, QualType LHSType, | ||||
1251 | QualType RHSType, bool IsCompAssign) { | ||||
1252 | // The rules for this case are in C99 6.3.1.8 | ||||
1253 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||
1254 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||
1255 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||
1256 | if (LHSSigned == RHSSigned) { | ||||
1257 | // Same signedness; use the higher-ranked type | ||||
1258 | if (order >= 0) { | ||||
1259 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1260 | return LHSType; | ||||
1261 | } else if (!IsCompAssign) | ||||
1262 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1263 | return RHSType; | ||||
1264 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||
1265 | // The unsigned type has greater than or equal rank to the | ||||
1266 | // signed type, so use the unsigned type | ||||
1267 | if (RHSSigned) { | ||||
1268 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1269 | return LHSType; | ||||
1270 | } else if (!IsCompAssign) | ||||
1271 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1272 | return RHSType; | ||||
1273 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||
1274 | // The two types are different widths; if we are here, that | ||||
1275 | // means the signed type is larger than the unsigned type, so | ||||
1276 | // use the signed type. | ||||
1277 | if (LHSSigned) { | ||||
1278 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1279 | return LHSType; | ||||
1280 | } else if (!IsCompAssign) | ||||
1281 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1282 | return RHSType; | ||||
1283 | } else { | ||||
1284 | // The signed type is higher-ranked than the unsigned type, | ||||
1285 | // but isn't actually any bigger (like unsigned int and long | ||||
1286 | // on most 32-bit systems). Use the unsigned type corresponding | ||||
1287 | // to the signed type. | ||||
1288 | QualType result = | ||||
1289 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||
1290 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||
1291 | if (!IsCompAssign) | ||||
1292 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||
1293 | return result; | ||||
1294 | } | ||||
1295 | } | ||||
1296 | |||||
1297 | /// Handle conversions with GCC complex int extension. Helper function | ||||
1298 | /// of UsualArithmeticConversions() | ||||
1299 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||
1300 | ExprResult &RHS, QualType LHSType, | ||||
1301 | QualType RHSType, | ||||
1302 | bool IsCompAssign) { | ||||
1303 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||
1304 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||
1305 | |||||
1306 | if (LHSComplexInt && RHSComplexInt) { | ||||
1307 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1308 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1309 | QualType ScalarType = | ||||
1310 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||
1311 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||
1312 | |||||
1313 | return S.Context.getComplexType(ScalarType); | ||||
1314 | } | ||||
1315 | |||||
1316 | if (LHSComplexInt) { | ||||
1317 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1318 | QualType ScalarType = | ||||
1319 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||
1320 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||
1321 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1322 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||
1323 | CK_IntegralRealToComplex); | ||||
1324 | |||||
1325 | return ComplexType; | ||||
1326 | } | ||||
1327 | |||||
1328 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1328, __PRETTY_FUNCTION__)); | ||||
1329 | |||||
1330 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1331 | QualType ScalarType = | ||||
1332 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||
1333 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||
1334 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1335 | |||||
1336 | if (!IsCompAssign) | ||||
1337 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||
1338 | CK_IntegralRealToComplex); | ||||
1339 | return ComplexType; | ||||
1340 | } | ||||
1341 | |||||
1342 | /// Return the rank of a given fixed point or integer type. The value itself | ||||
1343 | /// doesn't matter, but the values must be increasing with proper increasing | ||||
1344 | /// rank as described in N1169 4.1.1. | ||||
1345 | static unsigned GetFixedPointRank(QualType Ty) { | ||||
1346 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||
1347 | assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast< void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1347, __PRETTY_FUNCTION__)); | ||||
1348 | |||||
1349 | switch (BTy->getKind()) { | ||||
1350 | case BuiltinType::ShortFract: | ||||
1351 | case BuiltinType::UShortFract: | ||||
1352 | case BuiltinType::SatShortFract: | ||||
1353 | case BuiltinType::SatUShortFract: | ||||
1354 | return 1; | ||||
1355 | case BuiltinType::Fract: | ||||
1356 | case BuiltinType::UFract: | ||||
1357 | case BuiltinType::SatFract: | ||||
1358 | case BuiltinType::SatUFract: | ||||
1359 | return 2; | ||||
1360 | case BuiltinType::LongFract: | ||||
1361 | case BuiltinType::ULongFract: | ||||
1362 | case BuiltinType::SatLongFract: | ||||
1363 | case BuiltinType::SatULongFract: | ||||
1364 | return 3; | ||||
1365 | case BuiltinType::ShortAccum: | ||||
1366 | case BuiltinType::UShortAccum: | ||||
1367 | case BuiltinType::SatShortAccum: | ||||
1368 | case BuiltinType::SatUShortAccum: | ||||
1369 | return 4; | ||||
1370 | case BuiltinType::Accum: | ||||
1371 | case BuiltinType::UAccum: | ||||
1372 | case BuiltinType::SatAccum: | ||||
1373 | case BuiltinType::SatUAccum: | ||||
1374 | return 5; | ||||
1375 | case BuiltinType::LongAccum: | ||||
1376 | case BuiltinType::ULongAccum: | ||||
1377 | case BuiltinType::SatLongAccum: | ||||
1378 | case BuiltinType::SatULongAccum: | ||||
1379 | return 6; | ||||
1380 | default: | ||||
1381 | if (BTy->isInteger()) | ||||
1382 | return 0; | ||||
1383 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1383); | ||||
1384 | } | ||||
1385 | } | ||||
1386 | |||||
1387 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||
1388 | /// point types and integers or other fixed point types do not fall under | ||||
1389 | /// usual arithmetic conversion since these conversions could result in loss | ||||
1390 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||
1391 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||
1392 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||
1393 | QualType RHSTy) { | ||||
1394 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1395, __PRETTY_FUNCTION__)) | ||||
1395 | "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1395, __PRETTY_FUNCTION__)); | ||||
1396 | assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)) | ||||
1397 | RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)) | ||||
1398 | "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)) | ||||
1399 | "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1399, __PRETTY_FUNCTION__)); | ||||
1400 | |||||
1401 | // If one operand has signed fixed-point type and the other operand has | ||||
1402 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||
1403 | // converted to its corresponding signed fixed-point type and the resulting | ||||
1404 | // type is the type of the converted operand. | ||||
1405 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||
1406 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||
1407 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||
1408 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||
1409 | |||||
1410 | // The result type is the type with the highest rank, whereby a fixed-point | ||||
1411 | // conversion rank is always greater than an integer conversion rank; if the | ||||
1412 | // type of either of the operands is a saturating fixedpoint type, the result | ||||
1413 | // type shall be the saturating fixed-point type corresponding to the type | ||||
1414 | // with the highest rank; the resulting value is converted (taking into | ||||
1415 | // account rounding and overflow) to the precision of the resulting type. | ||||
1416 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||
1417 | // types are either signed or both unsigned at this point. | ||||
1418 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||
1419 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||
1420 | |||||
1421 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||
1422 | |||||
1423 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||
1424 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||
1425 | |||||
1426 | return ResultTy; | ||||
1427 | } | ||||
1428 | |||||
1429 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||
1430 | /// expressions that might be of enumeration type. | ||||
1431 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||
1432 | SourceLocation Loc, | ||||
1433 | Sema::ArithConvKind ACK) { | ||||
1434 | // C++2a [expr.arith.conv]p1: | ||||
1435 | // If one operand is of enumeration type and the other operand is of a | ||||
1436 | // different enumeration type or a floating-point type, this behavior is | ||||
1437 | // deprecated ([depr.arith.conv.enum]). | ||||
1438 | // | ||||
1439 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||
1440 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||
1441 | QualType L = LHS->getType(), R = RHS->getType(); | ||||
1442 | bool LEnum = L->isUnscopedEnumerationType(), | ||||
1443 | REnum = R->isUnscopedEnumerationType(); | ||||
1444 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||
1445 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||
1446 | (REnum && L->isFloatingType())) { | ||||
1447 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||
1448 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||
1449 | : diag::warn_arith_conv_enum_float) | ||||
1450 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1451 | << (int)ACK << LEnum << L << R; | ||||
1452 | } else if (!IsCompAssign && LEnum && REnum && | ||||
1453 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||
1454 | unsigned DiagID; | ||||
1455 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||
1456 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||
1457 | // If either enumeration type is unnamed, it's less likely that the | ||||
1458 | // user cares about this, but this situation is still deprecated in | ||||
1459 | // C++2a. Use a different warning group. | ||||
1460 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1461 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||
1462 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||
1463 | } else if (ACK == Sema::ACK_Conditional) { | ||||
1464 | // Conditional expressions are separated out because they have | ||||
1465 | // historically had a different warning flag. | ||||
1466 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1467 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||
1468 | : diag::warn_conditional_mixed_enum_types; | ||||
1469 | } else if (ACK == Sema::ACK_Comparison) { | ||||
1470 | // Comparison expressions are separated out because they have | ||||
1471 | // historically had a different warning flag. | ||||
1472 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1473 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||
1474 | : diag::warn_comparison_mixed_enum_types; | ||||
1475 | } else { | ||||
1476 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1477 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||
1478 | : diag::warn_arith_conv_mixed_enum_types; | ||||
1479 | } | ||||
1480 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1481 | << (int)ACK << L << R; | ||||
1482 | } | ||||
1483 | } | ||||
1484 | |||||
1485 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||
1486 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||
1487 | /// routine returns the first non-arithmetic type found. The client is | ||||
1488 | /// responsible for emitting appropriate error diagnostics. | ||||
1489 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||
1490 | SourceLocation Loc, | ||||
1491 | ArithConvKind ACK) { | ||||
1492 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||
1493 | |||||
1494 | if (ACK != ACK_CompAssign) { | ||||
1495 | LHS = UsualUnaryConversions(LHS.get()); | ||||
1496 | if (LHS.isInvalid()) | ||||
1497 | return QualType(); | ||||
1498 | } | ||||
1499 | |||||
1500 | RHS = UsualUnaryConversions(RHS.get()); | ||||
1501 | if (RHS.isInvalid()) | ||||
1502 | return QualType(); | ||||
1503 | |||||
1504 | // For conversion purposes, we ignore any qualifiers. | ||||
1505 | // For example, "const float" and "float" are equivalent. | ||||
1506 | QualType LHSType = | ||||
1507 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
1508 | QualType RHSType = | ||||
1509 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
1510 | |||||
1511 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||
1512 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||
1513 | LHSType = AtomicLHS->getValueType(); | ||||
1514 | |||||
1515 | // If both types are identical, no conversion is needed. | ||||
1516 | if (LHSType == RHSType) | ||||
1517 | return LHSType; | ||||
1518 | |||||
1519 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||
1520 | // The caller can deal with this (e.g. pointer + int). | ||||
1521 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||
1522 | return QualType(); | ||||
1523 | |||||
1524 | // Apply unary and bitfield promotions to the LHS's type. | ||||
1525 | QualType LHSUnpromotedType = LHSType; | ||||
1526 | if (LHSType->isPromotableIntegerType()) | ||||
1527 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||
1528 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||
1529 | if (!LHSBitfieldPromoteTy.isNull()) | ||||
1530 | LHSType = LHSBitfieldPromoteTy; | ||||
1531 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||
1532 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||
1533 | |||||
1534 | // If both types are identical, no conversion is needed. | ||||
1535 | if (LHSType == RHSType) | ||||
1536 | return LHSType; | ||||
1537 | |||||
1538 | // ExtInt types aren't subject to conversions between them or normal integers, | ||||
1539 | // so this fails. | ||||
1540 | if(LHSType->isExtIntType() || RHSType->isExtIntType()) | ||||
1541 | return QualType(); | ||||
1542 | |||||
1543 | // At this point, we have two different arithmetic types. | ||||
1544 | |||||
1545 | // Diagnose attempts to convert between __float128 and long double where | ||||
1546 | // such conversions currently can't be handled. | ||||
1547 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
1548 | return QualType(); | ||||
1549 | |||||
1550 | // Handle complex types first (C99 6.3.1.8p1). | ||||
1551 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||
1552 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1553 | ACK == ACK_CompAssign); | ||||
1554 | |||||
1555 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
1556 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
1557 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1558 | ACK == ACK_CompAssign); | ||||
1559 | |||||
1560 | // Handle GCC complex int extension. | ||||
1561 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||
1562 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1563 | ACK == ACK_CompAssign); | ||||
1564 | |||||
1565 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||
1566 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||
1567 | |||||
1568 | // Finally, we have two differing integer types. | ||||
1569 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
1570 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||
1571 | } | ||||
1572 | |||||
1573 | //===----------------------------------------------------------------------===// | ||||
1574 | // Semantic Analysis for various Expression Types | ||||
1575 | //===----------------------------------------------------------------------===// | ||||
1576 | |||||
1577 | |||||
1578 | ExprResult | ||||
1579 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1580 | SourceLocation DefaultLoc, | ||||
1581 | SourceLocation RParenLoc, | ||||
1582 | Expr *ControllingExpr, | ||||
1583 | ArrayRef<ParsedType> ArgTypes, | ||||
1584 | ArrayRef<Expr *> ArgExprs) { | ||||
1585 | unsigned NumAssocs = ArgTypes.size(); | ||||
1586 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1586, __PRETTY_FUNCTION__)); | ||||
1587 | |||||
1588 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||
1589 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1590 | if (ArgTypes[i]) | ||||
1591 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||
1592 | else | ||||
1593 | Types[i] = nullptr; | ||||
1594 | } | ||||
1595 | |||||
1596 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||
1597 | ControllingExpr, | ||||
1598 | llvm::makeArrayRef(Types, NumAssocs), | ||||
1599 | ArgExprs); | ||||
1600 | delete [] Types; | ||||
1601 | return ER; | ||||
1602 | } | ||||
1603 | |||||
1604 | ExprResult | ||||
1605 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1606 | SourceLocation DefaultLoc, | ||||
1607 | SourceLocation RParenLoc, | ||||
1608 | Expr *ControllingExpr, | ||||
1609 | ArrayRef<TypeSourceInfo *> Types, | ||||
1610 | ArrayRef<Expr *> Exprs) { | ||||
1611 | unsigned NumAssocs = Types.size(); | ||||
1612 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1612, __PRETTY_FUNCTION__)); | ||||
1613 | |||||
1614 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||
1615 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||
1616 | { | ||||
1617 | EnterExpressionEvaluationContext Unevaluated( | ||||
1618 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||
1619 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||
1620 | if (R.isInvalid()) | ||||
1621 | return ExprError(); | ||||
1622 | ControllingExpr = R.get(); | ||||
1623 | } | ||||
1624 | |||||
1625 | // The controlling expression is an unevaluated operand, so side effects are | ||||
1626 | // likely unintended. | ||||
1627 | if (!inTemplateInstantiation() && | ||||
1628 | ControllingExpr->HasSideEffects(Context, false)) | ||||
1629 | Diag(ControllingExpr->getExprLoc(), | ||||
1630 | diag::warn_side_effects_unevaluated_context); | ||||
1631 | |||||
1632 | bool TypeErrorFound = false, | ||||
1633 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||
1634 | ContainsUnexpandedParameterPack | ||||
1635 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||
1636 | |||||
1637 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1638 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||
1639 | ContainsUnexpandedParameterPack = true; | ||||
1640 | |||||
1641 | if (Types[i]) { | ||||
1642 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||
1643 | ContainsUnexpandedParameterPack = true; | ||||
1644 | |||||
1645 | if (Types[i]->getType()->isDependentType()) { | ||||
1646 | IsResultDependent = true; | ||||
1647 | } else { | ||||
1648 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||
1649 | // complete object type other than a variably modified type." | ||||
1650 | unsigned D = 0; | ||||
1651 | if (Types[i]->getType()->isIncompleteType()) | ||||
1652 | D = diag::err_assoc_type_incomplete; | ||||
1653 | else if (!Types[i]->getType()->isObjectType()) | ||||
1654 | D = diag::err_assoc_type_nonobject; | ||||
1655 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||
1656 | D = diag::err_assoc_type_variably_modified; | ||||
1657 | |||||
1658 | if (D != 0) { | ||||
1659 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||
1660 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1661 | << Types[i]->getType(); | ||||
1662 | TypeErrorFound = true; | ||||
1663 | } | ||||
1664 | |||||
1665 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||
1666 | // selection shall specify compatible types." | ||||
1667 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||
1668 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||
1669 | Context.typesAreCompatible(Types[i]->getType(), | ||||
1670 | Types[j]->getType())) { | ||||
1671 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||
1672 | diag::err_assoc_compatible_types) | ||||
1673 | << Types[j]->getTypeLoc().getSourceRange() | ||||
1674 | << Types[j]->getType() | ||||
1675 | << Types[i]->getType(); | ||||
1676 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1677 | diag::note_compat_assoc) | ||||
1678 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1679 | << Types[i]->getType(); | ||||
1680 | TypeErrorFound = true; | ||||
1681 | } | ||||
1682 | } | ||||
1683 | } | ||||
1684 | } | ||||
1685 | if (TypeErrorFound) | ||||
1686 | return ExprError(); | ||||
1687 | |||||
1688 | // If we determined that the generic selection is result-dependent, don't | ||||
1689 | // try to compute the result expression. | ||||
1690 | if (IsResultDependent) | ||||
1691 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||
1692 | Exprs, DefaultLoc, RParenLoc, | ||||
1693 | ContainsUnexpandedParameterPack); | ||||
1694 | |||||
1695 | SmallVector<unsigned, 1> CompatIndices; | ||||
1696 | unsigned DefaultIndex = -1U; | ||||
1697 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1698 | if (!Types[i]) | ||||
1699 | DefaultIndex = i; | ||||
1700 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | ||||
1701 | Types[i]->getType())) | ||||
1702 | CompatIndices.push_back(i); | ||||
1703 | } | ||||
1704 | |||||
1705 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||
1706 | // type compatible with at most one of the types named in its generic | ||||
1707 | // association list." | ||||
1708 | if (CompatIndices.size() > 1) { | ||||
1709 | // We strip parens here because the controlling expression is typically | ||||
1710 | // parenthesized in macro definitions. | ||||
1711 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1712 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||
1713 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||
1714 | << (unsigned)CompatIndices.size(); | ||||
1715 | for (unsigned I : CompatIndices) { | ||||
1716 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||
1717 | diag::note_compat_assoc) | ||||
1718 | << Types[I]->getTypeLoc().getSourceRange() | ||||
1719 | << Types[I]->getType(); | ||||
1720 | } | ||||
1721 | return ExprError(); | ||||
1722 | } | ||||
1723 | |||||
1724 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||
1725 | // its controlling expression shall have type compatible with exactly one of | ||||
1726 | // the types named in its generic association list." | ||||
1727 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||
1728 | // We strip parens here because the controlling expression is typically | ||||
1729 | // parenthesized in macro definitions. | ||||
1730 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1731 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||
1732 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||
1733 | return ExprError(); | ||||
1734 | } | ||||
1735 | |||||
1736 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||
1737 | // type name that is compatible with the type of the controlling expression, | ||||
1738 | // then the result expression of the generic selection is the expression | ||||
1739 | // in that generic association. Otherwise, the result expression of the | ||||
1740 | // generic selection is the expression in the default generic association." | ||||
1741 | unsigned ResultIndex = | ||||
1742 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||
1743 | |||||
1744 | return GenericSelectionExpr::Create( | ||||
1745 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||
1746 | ContainsUnexpandedParameterPack, ResultIndex); | ||||
1747 | } | ||||
1748 | |||||
1749 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||
1750 | /// location of the token and the offset of the ud-suffix within it. | ||||
1751 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||
1752 | unsigned Offset) { | ||||
1753 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||
1754 | S.getLangOpts()); | ||||
1755 | } | ||||
1756 | |||||
1757 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||
1758 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||
1759 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||
1760 | IdentifierInfo *UDSuffix, | ||||
1761 | SourceLocation UDSuffixLoc, | ||||
1762 | ArrayRef<Expr*> Args, | ||||
1763 | SourceLocation LitEndLoc) { | ||||
1764 | assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator" ) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1764, __PRETTY_FUNCTION__)); | ||||
1765 | |||||
1766 | QualType ArgTy[2]; | ||||
1767 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||
1768 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||
1769 | if (ArgTy[ArgIdx]->isArrayType()) | ||||
1770 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||
1771 | } | ||||
1772 | |||||
1773 | DeclarationName OpName = | ||||
1774 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1775 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1776 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1777 | |||||
1778 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||
1779 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||
1780 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||
1781 | /*AllowStringTemplatePack*/ false, | ||||
1782 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||
1783 | return ExprError(); | ||||
1784 | |||||
1785 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||
1786 | } | ||||
1787 | |||||
1788 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||
1789 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||
1790 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||
1791 | /// multiple tokens. However, the common case is that StringToks points to one | ||||
1792 | /// string. | ||||
1793 | /// | ||||
1794 | ExprResult | ||||
1795 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||
1796 | assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!" ) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1796, __PRETTY_FUNCTION__)); | ||||
1797 | |||||
1798 | StringLiteralParser Literal(StringToks, PP); | ||||
1799 | if (Literal.hadError) | ||||
1800 | return ExprError(); | ||||
1801 | |||||
1802 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||
1803 | for (const Token &Tok : StringToks) | ||||
1804 | StringTokLocs.push_back(Tok.getLocation()); | ||||
1805 | |||||
1806 | QualType CharTy = Context.CharTy; | ||||
1807 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | ||||
1808 | if (Literal.isWide()) { | ||||
1809 | CharTy = Context.getWideCharType(); | ||||
1810 | Kind = StringLiteral::Wide; | ||||
1811 | } else if (Literal.isUTF8()) { | ||||
1812 | if (getLangOpts().Char8) | ||||
1813 | CharTy = Context.Char8Ty; | ||||
1814 | Kind = StringLiteral::UTF8; | ||||
1815 | } else if (Literal.isUTF16()) { | ||||
1816 | CharTy = Context.Char16Ty; | ||||
1817 | Kind = StringLiteral::UTF16; | ||||
1818 | } else if (Literal.isUTF32()) { | ||||
1819 | CharTy = Context.Char32Ty; | ||||
1820 | Kind = StringLiteral::UTF32; | ||||
1821 | } else if (Literal.isPascal()) { | ||||
1822 | CharTy = Context.UnsignedCharTy; | ||||
1823 | } | ||||
1824 | |||||
1825 | // Warn on initializing an array of char from a u8 string literal; this | ||||
1826 | // becomes ill-formed in C++2a. | ||||
1827 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||
1828 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||
1829 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||
1830 | |||||
1831 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||
1832 | // ensures C++2a compatibility (but may change the program behavior when | ||||
1833 | // built by non-Clang compilers for which the execution character set is | ||||
1834 | // not always UTF-8). | ||||
1835 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||
1836 | SourceLocation RemovalDiagLoc; | ||||
1837 | for (const Token &Tok : StringToks) { | ||||
1838 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||
1839 | if (RemovalDiagLoc.isInvalid()) | ||||
1840 | RemovalDiagLoc = Tok.getLocation(); | ||||
1841 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||
1842 | Tok.getLocation(), | ||||
1843 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||
1844 | getSourceManager(), getLangOpts()))); | ||||
1845 | } | ||||
1846 | } | ||||
1847 | Diag(RemovalDiagLoc, RemovalDiag); | ||||
1848 | } | ||||
1849 | |||||
1850 | QualType StrTy = | ||||
1851 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||
1852 | |||||
1853 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||
1854 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||
1855 | Kind, Literal.Pascal, StrTy, | ||||
1856 | &StringTokLocs[0], | ||||
1857 | StringTokLocs.size()); | ||||
1858 | if (Literal.getUDSuffix().empty()) | ||||
1859 | return Lit; | ||||
1860 | |||||
1861 | // We're building a user-defined literal. | ||||
1862 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
1863 | SourceLocation UDSuffixLoc = | ||||
1864 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||
1865 | Literal.getUDSuffixOffset()); | ||||
1866 | |||||
1867 | // Make sure we're allowed user-defined literals here. | ||||
1868 | if (!UDLScope) | ||||
1869 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||
1870 | |||||
1871 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||
1872 | // operator "" X (str, len) | ||||
1873 | QualType SizeType = Context.getSizeType(); | ||||
1874 | |||||
1875 | DeclarationName OpName = | ||||
1876 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1877 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1878 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1879 | |||||
1880 | QualType ArgTy[] = { | ||||
1881 | Context.getArrayDecayedType(StrTy), SizeType | ||||
1882 | }; | ||||
1883 | |||||
1884 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
1885 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||
1886 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||
1887 | /*AllowStringTemplatePack*/ true, | ||||
1888 | /*DiagnoseMissing*/ true, Lit)) { | ||||
1889 | |||||
1890 | case LOLR_Cooked: { | ||||
1891 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||
1892 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||
1893 | StringTokLocs[0]); | ||||
1894 | Expr *Args[] = { Lit, LenArg }; | ||||
1895 | |||||
1896 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||
1897 | } | ||||
1898 | |||||
1899 | case LOLR_Template: { | ||||
1900 | TemplateArgumentListInfo ExplicitArgs; | ||||
1901 | TemplateArgument Arg(Lit); | ||||
1902 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||
1903 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1904 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1905 | &ExplicitArgs); | ||||
1906 | } | ||||
1907 | |||||
1908 | case LOLR_StringTemplatePack: { | ||||
1909 | TemplateArgumentListInfo ExplicitArgs; | ||||
1910 | |||||
1911 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||
1912 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||
1913 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
1914 | |||||
1915 | TemplateArgument TypeArg(CharTy); | ||||
1916 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||
1917 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||
1918 | |||||
1919 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||
1920 | Value = Lit->getCodeUnit(I); | ||||
1921 | TemplateArgument Arg(Context, Value, CharTy); | ||||
1922 | TemplateArgumentLocInfo ArgInfo; | ||||
1923 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1924 | } | ||||
1925 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1926 | &ExplicitArgs); | ||||
1927 | } | ||||
1928 | case LOLR_Raw: | ||||
1929 | case LOLR_ErrorNoDiagnostic: | ||||
1930 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1930); | ||||
1931 | case LOLR_Error: | ||||
1932 | return ExprError(); | ||||
1933 | } | ||||
1934 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1934); | ||||
1935 | } | ||||
1936 | |||||
1937 | DeclRefExpr * | ||||
1938 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
1939 | SourceLocation Loc, | ||||
1940 | const CXXScopeSpec *SS) { | ||||
1941 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||
1942 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||
1943 | } | ||||
1944 | |||||
1945 | DeclRefExpr * | ||||
1946 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
1947 | const DeclarationNameInfo &NameInfo, | ||||
1948 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||
1949 | SourceLocation TemplateKWLoc, | ||||
1950 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
1951 | NestedNameSpecifierLoc NNS = | ||||
1952 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||
1953 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||
1954 | TemplateArgs); | ||||
1955 | } | ||||
1956 | |||||
1957 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||
1958 | // host variable in a device or host device lambda. | ||||
1959 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||
1960 | VarDecl *VD) { | ||||
1961 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||
1962 | return false; | ||||
1963 | assert(VD->getType()->isReferenceType())((VD->getType()->isReferenceType()) ? static_cast<void > (0) : __assert_fail ("VD->getType()->isReferenceType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 1963, __PRETTY_FUNCTION__)); | ||||
1964 | |||||
1965 | // Check whether the reference variable is referencing a host variable. | ||||
1966 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||
1967 | if (!DRE) | ||||
1968 | return false; | ||||
1969 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
1970 | if (!Referee || !Referee->hasGlobalStorage() || | ||||
1971 | Referee->hasAttr<CUDADeviceAttr>()) | ||||
1972 | return false; | ||||
1973 | |||||
1974 | // Check whether the current function is a device or host device lambda. | ||||
1975 | // Check whether the reference variable is a capture by getDeclContext() | ||||
1976 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||
1977 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||
1978 | if (MD && MD->getParent()->isLambda() && | ||||
1979 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||
1980 | VD->getDeclContext() != MD) | ||||
1981 | return true; | ||||
1982 | |||||
1983 | return false; | ||||
1984 | } | ||||
1985 | |||||
1986 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||
1987 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||
1988 | if (isUnevaluatedContext()) | ||||
1989 | return NOUR_Unevaluated; | ||||
1990 | |||||
1991 | // C++2a [basic.def.odr]p4: | ||||
1992 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
1993 | // is odr-used by e unless [...] x is a reference that is usable in | ||||
1994 | // constant expressions. | ||||
1995 | // CUDA/HIP: | ||||
1996 | // If a reference variable referencing a host variable is captured in a | ||||
1997 | // device or host device lambda, the value of the referee must be copied | ||||
1998 | // to the capture and the reference variable must be treated as odr-use | ||||
1999 | // since the value of the referee is not known at compile time and must | ||||
2000 | // be loaded from the captured. | ||||
2001 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2002 | if (VD->getType()->isReferenceType() && | ||||
2003 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||
2004 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||
2005 | VD->isUsableInConstantExpressions(Context)) | ||||
2006 | return NOUR_Constant; | ||||
2007 | } | ||||
2008 | |||||
2009 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||
2010 | // need to wait and see how the expression is used. | ||||
2011 | return NOUR_None; | ||||
2012 | } | ||||
2013 | |||||
2014 | /// BuildDeclRefExpr - Build an expression that references a | ||||
2015 | /// declaration that does not require a closure capture. | ||||
2016 | DeclRefExpr * | ||||
2017 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2018 | const DeclarationNameInfo &NameInfo, | ||||
2019 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||
2020 | SourceLocation TemplateKWLoc, | ||||
2021 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2022 | bool RefersToCapturedVariable = | ||||
2023 | isa<VarDecl>(D) && | ||||
2024 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | ||||
2025 | |||||
2026 | DeclRefExpr *E = DeclRefExpr::Create( | ||||
2027 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||
2028 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||
2029 | MarkDeclRefReferenced(E); | ||||
2030 | |||||
2031 | // C++ [except.spec]p17: | ||||
2032 | // An exception-specification is considered to be needed when: | ||||
2033 | // - in an expression, the function is the unique lookup result or | ||||
2034 | // the selected member of a set of overloaded functions. | ||||
2035 | // | ||||
2036 | // We delay doing this until after we've built the function reference and | ||||
2037 | // marked it as used so that: | ||||
2038 | // a) if the function is defaulted, we get errors from defining it before / | ||||
2039 | // instead of errors from computing its exception specification, and | ||||
2040 | // b) if the function is a defaulted comparison, we can use the body we | ||||
2041 | // build when defining it as input to the exception specification | ||||
2042 | // computation rather than computing a new body. | ||||
2043 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||
2044 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||
2045 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||
2046 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||
2047 | } | ||||
2048 | } | ||||
2049 | |||||
2050 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||
2051 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||
2052 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||
2053 | getCurFunction()->recordUseOfWeak(E); | ||||
2054 | |||||
2055 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||
2056 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||
2057 | FD = IFD->getAnonField(); | ||||
2058 | if (FD) { | ||||
2059 | UnusedPrivateFields.remove(FD); | ||||
2060 | // Just in case we're building an illegal pointer-to-member. | ||||
2061 | if (FD->isBitField()) | ||||
2062 | E->setObjectKind(OK_BitField); | ||||
2063 | } | ||||
2064 | |||||
2065 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||
2066 | // designates a bit-field. | ||||
2067 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||
2068 | if (auto *BE = BD->getBinding()) | ||||
2069 | E->setObjectKind(BE->getObjectKind()); | ||||
2070 | |||||
2071 | return E; | ||||
2072 | } | ||||
2073 | |||||
2074 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||
2075 | /// possibly a list of template arguments. | ||||
2076 | /// | ||||
2077 | /// If this produces template arguments, it is permitted to call | ||||
2078 | /// DecomposeTemplateName. | ||||
2079 | /// | ||||
2080 | /// This actually loses a lot of source location information for | ||||
2081 | /// non-standard name kinds; we should consider preserving that in | ||||
2082 | /// some way. | ||||
2083 | void | ||||
2084 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||
2085 | TemplateArgumentListInfo &Buffer, | ||||
2086 | DeclarationNameInfo &NameInfo, | ||||
2087 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||
2088 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
2089 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||
2090 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||
2091 | |||||
2092 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||
2093 | Id.TemplateId->NumArgs); | ||||
2094 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||
2095 | |||||
2096 | TemplateName TName = Id.TemplateId->Template.get(); | ||||
2097 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||
2098 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||
2099 | TemplateArgs = &Buffer; | ||||
2100 | } else { | ||||
2101 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||
2102 | TemplateArgs = nullptr; | ||||
2103 | } | ||||
2104 | } | ||||
2105 | |||||
2106 | static void emitEmptyLookupTypoDiagnostic( | ||||
2107 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||
2108 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||
2109 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||
2110 | DeclContext *Ctx = | ||||
2111 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||
2112 | if (!TC) { | ||||
2113 | // Emit a special diagnostic for failed member lookups. | ||||
2114 | // FIXME: computing the declaration context might fail here (?) | ||||
2115 | if (Ctx) | ||||
2116 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||
2117 | << SS.getRange(); | ||||
2118 | else | ||||
2119 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||
2120 | return; | ||||
2121 | } | ||||
2122 | |||||
2123 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||
2124 | bool DroppedSpecifier = | ||||
2125 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||
2126 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2127 | ? diag::note_implicit_param_decl | ||||
2128 | : diag::note_previous_decl; | ||||
2129 | if (!Ctx) | ||||
2130 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||
2131 | SemaRef.PDiag(NoteID)); | ||||
2132 | else | ||||
2133 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||
2134 | << Typo << Ctx << DroppedSpecifier | ||||
2135 | << SS.getRange(), | ||||
2136 | SemaRef.PDiag(NoteID)); | ||||
2137 | } | ||||
2138 | |||||
2139 | /// Diagnose a lookup that found results in an enclosing class during error | ||||
2140 | /// recovery. This usually indicates that the results were found in a dependent | ||||
2141 | /// base class that could not be searched as part of a template definition. | ||||
2142 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||
2143 | /// compatibility mode). | ||||
2144 | /// | ||||
2145 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||
2146 | /// should attempt to recover using these lookup results. | ||||
2147 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||
2148 | // During a default argument instantiation the CurContext points | ||||
2149 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||
2150 | // function parameter list, hence add an explicit check. | ||||
2151 | bool isDefaultArgument = | ||||
2152 | !CodeSynthesisContexts.empty() && | ||||
2153 | CodeSynthesisContexts.back().Kind == | ||||
2154 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||
2155 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||
2156 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||
2157 | R.getNamingClass() == CurMethod->getParent() && | ||||
2158 | !isDefaultArgument; | ||||
2159 | |||||
2160 | // There are two ways we can find a class-scope declaration during template | ||||
2161 | // instantiation that we did not find in the template definition: if it is a | ||||
2162 | // member of a dependent base class, or if it is declared after the point of | ||||
2163 | // use in the same class. Distinguish these by comparing the class in which | ||||
2164 | // the member was found to the naming class of the lookup. | ||||
2165 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||
2166 | unsigned NoteID = diag::note_member_declared_at; | ||||
2167 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||
2168 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||
2169 | : diag::err_found_later_in_class; | ||||
2170 | } else if (getLangOpts().MSVCCompat) { | ||||
2171 | DiagID = diag::ext_found_in_dependent_base; | ||||
2172 | NoteID = diag::note_dependent_member_use; | ||||
2173 | } | ||||
2174 | |||||
2175 | if (isInstance) { | ||||
2176 | // Give a code modification hint to insert 'this->'. | ||||
2177 | Diag(R.getNameLoc(), DiagID) | ||||
2178 | << R.getLookupName() | ||||
2179 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||
2180 | CheckCXXThisCapture(R.getNameLoc()); | ||||
2181 | } else { | ||||
2182 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||
2183 | // they're not shadowed). | ||||
2184 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||
2185 | } | ||||
2186 | |||||
2187 | for (NamedDecl *D : R) | ||||
2188 | Diag(D->getLocation(), NoteID); | ||||
2189 | |||||
2190 | // Return true if we are inside a default argument instantiation | ||||
2191 | // and the found name refers to an instance member function, otherwise | ||||
2192 | // the caller will try to create an implicit member call and this is wrong | ||||
2193 | // for default arguments. | ||||
2194 | // | ||||
2195 | // FIXME: Is this special case necessary? We could allow the caller to | ||||
2196 | // diagnose this. | ||||
2197 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||
2198 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||
2199 | return true; | ||||
2200 | } | ||||
2201 | |||||
2202 | // Tell the callee to try to recover. | ||||
2203 | return false; | ||||
2204 | } | ||||
2205 | |||||
2206 | /// Diagnose an empty lookup. | ||||
2207 | /// | ||||
2208 | /// \return false if new lookup candidates were found | ||||
2209 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||
2210 | CorrectionCandidateCallback &CCC, | ||||
2211 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||
2212 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||
2213 | DeclarationName Name = R.getLookupName(); | ||||
2214 | |||||
2215 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||
2216 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||
2217 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||
2218 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||
2219 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
2220 | diagnostic = diag::err_undeclared_use; | ||||
2221 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||
2222 | } | ||||
2223 | |||||
2224 | // If the original lookup was an unqualified lookup, fake an | ||||
2225 | // unqualified lookup. This is useful when (for example) the | ||||
2226 | // original lookup would not have found something because it was a | ||||
2227 | // dependent name. | ||||
2228 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||
2229 | while (DC) { | ||||
2230 | if (isa<CXXRecordDecl>(DC)) { | ||||
2231 | LookupQualifiedName(R, DC); | ||||
2232 | |||||
2233 | if (!R.empty()) { | ||||
2234 | // Don't give errors about ambiguities in this lookup. | ||||
2235 | R.suppressDiagnostics(); | ||||
2236 | |||||
2237 | // If there's a best viable function among the results, only mention | ||||
2238 | // that one in the notes. | ||||
2239 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||
2240 | OverloadCandidateSet::CSK_Normal); | ||||
2241 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||
2242 | OverloadCandidateSet::iterator Best; | ||||
2243 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||
2244 | OR_Success) { | ||||
2245 | R.clear(); | ||||
2246 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||
2247 | R.resolveKind(); | ||||
2248 | } | ||||
2249 | |||||
2250 | return DiagnoseDependentMemberLookup(R); | ||||
2251 | } | ||||
2252 | |||||
2253 | R.clear(); | ||||
2254 | } | ||||
2255 | |||||
2256 | DC = DC->getLookupParent(); | ||||
2257 | } | ||||
2258 | |||||
2259 | // We didn't find anything, so try to correct for a typo. | ||||
2260 | TypoCorrection Corrected; | ||||
2261 | if (S && Out) { | ||||
2262 | SourceLocation TypoLoc = R.getNameLoc(); | ||||
2263 | assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2264, __PRETTY_FUNCTION__)) | ||||
2264 | "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2264, __PRETTY_FUNCTION__)); | ||||
2265 | *Out = CorrectTypoDelayed( | ||||
2266 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||
2267 | [=](const TypoCorrection &TC) { | ||||
2268 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||
2269 | diagnostic, diagnostic_suggest); | ||||
2270 | }, | ||||
2271 | nullptr, CTK_ErrorRecovery); | ||||
2272 | if (*Out) | ||||
2273 | return true; | ||||
2274 | } else if (S && | ||||
2275 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||
2276 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||
2277 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
2278 | bool DroppedSpecifier = | ||||
2279 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||
2280 | R.setLookupName(Corrected.getCorrection()); | ||||
2281 | |||||
2282 | bool AcceptableWithRecovery = false; | ||||
2283 | bool AcceptableWithoutRecovery = false; | ||||
2284 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||
2285 | if (ND) { | ||||
2286 | if (Corrected.isOverloaded()) { | ||||
2287 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||
2288 | OverloadCandidateSet::CSK_Normal); | ||||
2289 | OverloadCandidateSet::iterator Best; | ||||
2290 | for (NamedDecl *CD : Corrected) { | ||||
2291 | if (FunctionTemplateDecl *FTD = | ||||
2292 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||
2293 | AddTemplateOverloadCandidate( | ||||
2294 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||
2295 | Args, OCS); | ||||
2296 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
2297 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||
2298 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||
2299 | Args, OCS); | ||||
2300 | } | ||||
2301 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||
2302 | case OR_Success: | ||||
2303 | ND = Best->FoundDecl; | ||||
2304 | Corrected.setCorrectionDecl(ND); | ||||
2305 | break; | ||||
2306 | default: | ||||
2307 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||
2308 | Corrected.setCorrectionDecl(ND); | ||||
2309 | break; | ||||
2310 | } | ||||
2311 | } | ||||
2312 | R.addDecl(ND); | ||||
2313 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||
2314 | CXXRecordDecl *Record = nullptr; | ||||
2315 | if (Corrected.getCorrectionSpecifier()) { | ||||
2316 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||
2317 | Record = Ty->getAsCXXRecordDecl(); | ||||
2318 | } | ||||
2319 | if (!Record) | ||||
2320 | Record = cast<CXXRecordDecl>( | ||||
2321 | ND->getDeclContext()->getRedeclContext()); | ||||
2322 | R.setNamingClass(Record); | ||||
2323 | } | ||||
2324 | |||||
2325 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||
2326 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||
2327 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||
2328 | // FIXME: If we ended up with a typo for a type name or | ||||
2329 | // Objective-C class name, we're in trouble because the parser | ||||
2330 | // is in the wrong place to recover. Suggest the typo | ||||
2331 | // correction, but don't make it a fix-it since we're not going | ||||
2332 | // to recover well anyway. | ||||
2333 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||
2334 | getAsTypeTemplateDecl(UnderlyingND) || | ||||
2335 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||
2336 | } else { | ||||
2337 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||
2338 | // because we aren't able to recover. | ||||
2339 | AcceptableWithoutRecovery = true; | ||||
2340 | } | ||||
2341 | |||||
2342 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||
2343 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2344 | ? diag::note_implicit_param_decl | ||||
2345 | : diag::note_previous_decl; | ||||
2346 | if (SS.isEmpty()) | ||||
2347 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||
2348 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2349 | else | ||||
2350 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||
2351 | << Name << computeDeclContext(SS, false) | ||||
2352 | << DroppedSpecifier << SS.getRange(), | ||||
2353 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2354 | |||||
2355 | // Tell the callee whether to try to recover. | ||||
2356 | return !AcceptableWithRecovery; | ||||
2357 | } | ||||
2358 | } | ||||
2359 | R.clear(); | ||||
2360 | |||||
2361 | // Emit a special diagnostic for failed member lookups. | ||||
2362 | // FIXME: computing the declaration context might fail here (?) | ||||
2363 | if (!SS.isEmpty()) { | ||||
2364 | Diag(R.getNameLoc(), diag::err_no_member) | ||||
2365 | << Name << computeDeclContext(SS, false) | ||||
2366 | << SS.getRange(); | ||||
2367 | return true; | ||||
2368 | } | ||||
2369 | |||||
2370 | // Give up, we can't recover. | ||||
2371 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||
2372 | return true; | ||||
2373 | } | ||||
2374 | |||||
2375 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||
2376 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||
2377 | /// assume the identifier is a member of a dependent base class. We can only | ||||
2378 | /// recover successfully in static methods, instance methods, and other contexts | ||||
2379 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||
2380 | /// instantiation model, but it's close enough. | ||||
2381 | static Expr * | ||||
2382 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||
2383 | DeclarationNameInfo &NameInfo, | ||||
2384 | SourceLocation TemplateKWLoc, | ||||
2385 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2386 | // Only try to recover from lookup into dependent bases in static methods or | ||||
2387 | // contexts where 'this' is available. | ||||
2388 | QualType ThisType = S.getCurrentThisType(); | ||||
2389 | const CXXRecordDecl *RD = nullptr; | ||||
2390 | if (!ThisType.isNull()) | ||||
2391 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||
2392 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||
2393 | RD = MD->getParent(); | ||||
2394 | if (!RD || !RD->hasAnyDependentBases()) | ||||
2395 | return nullptr; | ||||
2396 | |||||
2397 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||
2398 | // is available, suggest inserting 'this->' as a fixit. | ||||
2399 | SourceLocation Loc = NameInfo.getLoc(); | ||||
2400 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||
2401 | DB << NameInfo.getName() << RD; | ||||
2402 | |||||
2403 | if (!ThisType.isNull()) { | ||||
2404 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||
2405 | return CXXDependentScopeMemberExpr::Create( | ||||
2406 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||
2407 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||
2408 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||
2409 | } | ||||
2410 | |||||
2411 | // Synthesize a fake NNS that points to the derived class. This will | ||||
2412 | // perform name lookup during template instantiation. | ||||
2413 | CXXScopeSpec SS; | ||||
2414 | auto *NNS = | ||||
2415 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||
2416 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||
2417 | return DependentScopeDeclRefExpr::Create( | ||||
2418 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||
2419 | TemplateArgs); | ||||
2420 | } | ||||
2421 | |||||
2422 | ExprResult | ||||
2423 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||
2424 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||
2425 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||
2426 | CorrectionCandidateCallback *CCC, | ||||
2427 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||
2428 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2429, __PRETTY_FUNCTION__)) | ||||
2429 | "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2429, __PRETTY_FUNCTION__)); | ||||
2430 | if (SS.isInvalid()) | ||||
2431 | return ExprError(); | ||||
2432 | |||||
2433 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||
2434 | |||||
2435 | // Decompose the UnqualifiedId into the following data. | ||||
2436 | DeclarationNameInfo NameInfo; | ||||
2437 | const TemplateArgumentListInfo *TemplateArgs; | ||||
2438 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||
2439 | |||||
2440 | DeclarationName Name = NameInfo.getName(); | ||||
2441 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
2442 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||
2443 | |||||
2444 | if (II && II->isEditorPlaceholder()) { | ||||
2445 | // FIXME: When typed placeholders are supported we can create a typed | ||||
2446 | // placeholder expression node. | ||||
2447 | return ExprError(); | ||||
2448 | } | ||||
2449 | |||||
2450 | // C++ [temp.dep.expr]p3: | ||||
2451 | // An id-expression is type-dependent if it contains: | ||||
2452 | // -- an identifier that was declared with a dependent type, | ||||
2453 | // (note: handled after lookup) | ||||
2454 | // -- a template-id that is dependent, | ||||
2455 | // (note: handled in BuildTemplateIdExpr) | ||||
2456 | // -- a conversion-function-id that specifies a dependent type, | ||||
2457 | // -- a nested-name-specifier that contains a class-name that | ||||
2458 | // names a dependent type. | ||||
2459 | // Determine whether this is a member of an unknown specialization; | ||||
2460 | // we need to handle these differently. | ||||
2461 | bool DependentID = false; | ||||
2462 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||
2463 | Name.getCXXNameType()->isDependentType()) { | ||||
2464 | DependentID = true; | ||||
2465 | } else if (SS.isSet()) { | ||||
2466 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||
2467 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2468 | return ExprError(); | ||||
2469 | } else { | ||||
2470 | DependentID = true; | ||||
2471 | } | ||||
2472 | } | ||||
2473 | |||||
2474 | if (DependentID) | ||||
2475 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2476 | IsAddressOfOperand, TemplateArgs); | ||||
2477 | |||||
2478 | // Perform the required lookup. | ||||
2479 | LookupResult R(*this, NameInfo, | ||||
2480 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||
2481 | ? LookupObjCImplicitSelfParam | ||||
2482 | : LookupOrdinaryName); | ||||
2483 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||
2484 | // Lookup the template name again to correctly establish the context in | ||||
2485 | // which it was found. This is really unfortunate as we already did the | ||||
2486 | // lookup to determine that it was a template name in the first place. If | ||||
2487 | // this becomes a performance hit, we can work harder to preserve those | ||||
2488 | // results until we get here but it's likely not worth it. | ||||
2489 | bool MemberOfUnknownSpecialization; | ||||
2490 | AssumedTemplateKind AssumedTemplate; | ||||
2491 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||
2492 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||
2493 | &AssumedTemplate)) | ||||
2494 | return ExprError(); | ||||
2495 | |||||
2496 | if (MemberOfUnknownSpecialization || | ||||
2497 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||
2498 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2499 | IsAddressOfOperand, TemplateArgs); | ||||
2500 | } else { | ||||
2501 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||
2502 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||
2503 | |||||
2504 | // If the result might be in a dependent base class, this is a dependent | ||||
2505 | // id-expression. | ||||
2506 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2507 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2508 | IsAddressOfOperand, TemplateArgs); | ||||
2509 | |||||
2510 | // If this reference is in an Objective-C method, then we need to do | ||||
2511 | // some special Objective-C lookup, too. | ||||
2512 | if (IvarLookupFollowUp) { | ||||
2513 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||
2514 | if (E.isInvalid()) | ||||
2515 | return ExprError(); | ||||
2516 | |||||
2517 | if (Expr *Ex = E.getAs<Expr>()) | ||||
2518 | return Ex; | ||||
2519 | } | ||||
2520 | } | ||||
2521 | |||||
2522 | if (R.isAmbiguous()) | ||||
2523 | return ExprError(); | ||||
2524 | |||||
2525 | // This could be an implicitly declared function reference (legal in C90, | ||||
2526 | // extension in C99, forbidden in C++). | ||||
2527 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | ||||
2528 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||
2529 | if (D) R.addDecl(D); | ||||
2530 | } | ||||
2531 | |||||
2532 | // Determine whether this name might be a candidate for | ||||
2533 | // argument-dependent lookup. | ||||
2534 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||
2535 | |||||
2536 | if (R.empty() && !ADL) { | ||||
2537 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
2538 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||
2539 | TemplateKWLoc, TemplateArgs)) | ||||
2540 | return E; | ||||
2541 | } | ||||
2542 | |||||
2543 | // Don't diagnose an empty lookup for inline assembly. | ||||
2544 | if (IsInlineAsmIdentifier) | ||||
2545 | return ExprError(); | ||||
2546 | |||||
2547 | // If this name wasn't predeclared and if this is not a function | ||||
2548 | // call, diagnose the problem. | ||||
2549 | TypoExpr *TE = nullptr; | ||||
2550 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||
2551 | : nullptr); | ||||
2552 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||
2553 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2554, __PRETTY_FUNCTION__)) | ||||
2554 | "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2554, __PRETTY_FUNCTION__)); | ||||
2555 | if (CCC) { | ||||
2556 | // Make sure the callback knows what the typo being diagnosed is. | ||||
2557 | CCC->setTypoName(II); | ||||
2558 | if (SS.isValid()) | ||||
2559 | CCC->setTypoNNS(SS.getScopeRep()); | ||||
2560 | } | ||||
2561 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||
2562 | // a template name, but we happen to have always already looked up the name | ||||
2563 | // before we get here if it must be a template name. | ||||
2564 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||
2565 | None, &TE)) { | ||||
2566 | if (TE && KeywordReplacement) { | ||||
2567 | auto &State = getTypoExprState(TE); | ||||
2568 | auto BestTC = State.Consumer->getNextCorrection(); | ||||
2569 | if (BestTC.isKeyword()) { | ||||
2570 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||
2571 | if (State.DiagHandler) | ||||
2572 | State.DiagHandler(BestTC); | ||||
2573 | KeywordReplacement->startToken(); | ||||
2574 | KeywordReplacement->setKind(II->getTokenID()); | ||||
2575 | KeywordReplacement->setIdentifierInfo(II); | ||||
2576 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||
2577 | // Clean up the state associated with the TypoExpr, since it has | ||||
2578 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||
2579 | clearDelayedTypo(TE); | ||||
2580 | // Signal that a correction to a keyword was performed by returning a | ||||
2581 | // valid-but-null ExprResult. | ||||
2582 | return (Expr*)nullptr; | ||||
2583 | } | ||||
2584 | State.Consumer->resetCorrectionStream(); | ||||
2585 | } | ||||
2586 | return TE ? TE : ExprError(); | ||||
2587 | } | ||||
2588 | |||||
2589 | assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2590, __PRETTY_FUNCTION__)) | ||||
2590 | "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2590, __PRETTY_FUNCTION__)); | ||||
2591 | |||||
2592 | // If we found an Objective-C instance variable, let | ||||
2593 | // LookupInObjCMethod build the appropriate expression to | ||||
2594 | // reference the ivar. | ||||
2595 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||
2596 | R.clear(); | ||||
2597 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||
2598 | // In a hopelessly buggy code, Objective-C instance variable | ||||
2599 | // lookup fails and no expression will be built to reference it. | ||||
2600 | if (!E.isInvalid() && !E.get()) | ||||
2601 | return ExprError(); | ||||
2602 | return E; | ||||
2603 | } | ||||
2604 | } | ||||
2605 | |||||
2606 | // This is guaranteed from this point on. | ||||
2607 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2607, __PRETTY_FUNCTION__)); | ||||
2608 | |||||
2609 | // Check whether this might be a C++ implicit instance member access. | ||||
2610 | // C++ [class.mfct.non-static]p3: | ||||
2611 | // When an id-expression that is not part of a class member access | ||||
2612 | // syntax and not used to form a pointer to member is used in the | ||||
2613 | // body of a non-static member function of class X, if name lookup | ||||
2614 | // resolves the name in the id-expression to a non-static non-type | ||||
2615 | // member of some class C, the id-expression is transformed into a | ||||
2616 | // class member access expression using (*this) as the | ||||
2617 | // postfix-expression to the left of the . operator. | ||||
2618 | // | ||||
2619 | // But we don't actually need to do this for '&' operands if R | ||||
2620 | // resolved to a function or overloaded function set, because the | ||||
2621 | // expression is ill-formed if it actually works out to be a | ||||
2622 | // non-static member function: | ||||
2623 | // | ||||
2624 | // C++ [expr.ref]p4: | ||||
2625 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||
2626 | // [t]he expression can be used only as the left-hand operand of a | ||||
2627 | // member function call. | ||||
2628 | // | ||||
2629 | // There are other safeguards against such uses, but it's important | ||||
2630 | // to get this right here so that we don't end up making a | ||||
2631 | // spuriously dependent expression if we're inside a dependent | ||||
2632 | // instance method. | ||||
2633 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||
2634 | bool MightBeImplicitMember; | ||||
2635 | if (!IsAddressOfOperand) | ||||
2636 | MightBeImplicitMember = true; | ||||
2637 | else if (!SS.isEmpty()) | ||||
2638 | MightBeImplicitMember = false; | ||||
2639 | else if (R.isOverloadedResult()) | ||||
2640 | MightBeImplicitMember = false; | ||||
2641 | else if (R.isUnresolvableResult()) | ||||
2642 | MightBeImplicitMember = true; | ||||
2643 | else | ||||
2644 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||
2645 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||
2646 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||
2647 | |||||
2648 | if (MightBeImplicitMember) | ||||
2649 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||
2650 | R, TemplateArgs, S); | ||||
2651 | } | ||||
2652 | |||||
2653 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||
2654 | |||||
2655 | // In C++1y, if this is a variable template id, then check it | ||||
2656 | // in BuildTemplateIdExpr(). | ||||
2657 | // The single lookup result must be a variable template declaration. | ||||
2658 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||
2659 | Id.TemplateId->Kind == TNK_Var_template) { | ||||
2660 | assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2661, __PRETTY_FUNCTION__)) | ||||
2661 | "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2661, __PRETTY_FUNCTION__)); | ||||
2662 | } | ||||
2663 | |||||
2664 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||
2665 | } | ||||
2666 | |||||
2667 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||
2668 | } | ||||
2669 | |||||
2670 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||
2671 | /// declaration name, generally during template instantiation. | ||||
2672 | /// There's a large number of things which don't need to be done along | ||||
2673 | /// this path. | ||||
2674 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||
2675 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||
2676 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||
2677 | DeclContext *DC = computeDeclContext(SS, false); | ||||
2678 | if (!DC) | ||||
2679 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2680 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2681 | |||||
2682 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2683 | return ExprError(); | ||||
2684 | |||||
2685 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
2686 | LookupQualifiedName(R, DC); | ||||
2687 | |||||
2688 | if (R.isAmbiguous()) | ||||
2689 | return ExprError(); | ||||
2690 | |||||
2691 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2692 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2693 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2694 | |||||
2695 | if (R.empty()) { | ||||
2696 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||
2697 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||
2698 | // is invalid because it's derived from an invalid base class, then missing | ||||
2699 | // members were likely supposed to be inherited. | ||||
2700 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||
2701 | if (CD->isInvalidDecl()) | ||||
2702 | return ExprError(); | ||||
2703 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||
2704 | << NameInfo.getName() << DC << SS.getRange(); | ||||
2705 | return ExprError(); | ||||
2706 | } | ||||
2707 | |||||
2708 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||
2709 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||
2710 | // a dependent context. If we can recover with a type, downgrade this to | ||||
2711 | // a warning in Microsoft compatibility mode. | ||||
2712 | unsigned DiagID = diag::err_typename_missing; | ||||
2713 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||
2714 | DiagID = diag::ext_typename_missing; | ||||
2715 | SourceLocation Loc = SS.getBeginLoc(); | ||||
2716 | auto D = Diag(Loc, DiagID); | ||||
2717 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||
2718 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||
2719 | |||||
2720 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||
2721 | // context. | ||||
2722 | if (!RecoveryTSI) | ||||
2723 | return ExprError(); | ||||
2724 | |||||
2725 | // Only issue the fixit if we're prepared to recover. | ||||
2726 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||
2727 | |||||
2728 | // Recover by pretending this was an elaborated type. | ||||
2729 | QualType Ty = Context.getTypeDeclType(TD); | ||||
2730 | TypeLocBuilder TLB; | ||||
2731 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||
2732 | |||||
2733 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||
2734 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||
2735 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
2736 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
2737 | |||||
2738 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||
2739 | |||||
2740 | return ExprEmpty(); | ||||
2741 | } | ||||
2742 | |||||
2743 | // Defend against this resolving to an implicit member access. We usually | ||||
2744 | // won't get here if this might be a legitimate a class member (we end up in | ||||
2745 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||
2746 | // a pointer-to-member or in an unevaluated context in C++11. | ||||
2747 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||
2748 | return BuildPossibleImplicitMemberExpr(SS, | ||||
2749 | /*TemplateKWLoc=*/SourceLocation(), | ||||
2750 | R, /*TemplateArgs=*/nullptr, S); | ||||
2751 | |||||
2752 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||
2753 | } | ||||
2754 | |||||
2755 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2756 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2757 | /// should form a reference to an ivar. | ||||
2758 | /// | ||||
2759 | /// Ideally, most of this would be done by lookup, but there's | ||||
2760 | /// actually quite a lot of extra work involved. | ||||
2761 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2762 | IdentifierInfo *II) { | ||||
2763 | SourceLocation Loc = Lookup.getNameLoc(); | ||||
2764 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2765 | |||||
2766 | // Check for error condition which is already reported. | ||||
2767 | if (!CurMethod) | ||||
2768 | return DeclResult(true); | ||||
2769 | |||||
2770 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||
2771 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||
2772 | // found a decl, but that decl is outside the current instance method (i.e. | ||||
2773 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||
2774 | // this name, if the lookup sucedes, we replace it our current decl. | ||||
2775 | |||||
2776 | // If we're in a class method, we don't normally want to look for | ||||
2777 | // ivars. But if we don't find anything else, and there's an | ||||
2778 | // ivar, that's an error. | ||||
2779 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||
2780 | |||||
2781 | bool LookForIvars; | ||||
2782 | if (Lookup.empty()) | ||||
2783 | LookForIvars = true; | ||||
2784 | else if (IsClassMethod) | ||||
2785 | LookForIvars = false; | ||||
2786 | else | ||||
2787 | LookForIvars = (Lookup.isSingleResult() && | ||||
2788 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||
2789 | ObjCInterfaceDecl *IFace = nullptr; | ||||
2790 | if (LookForIvars) { | ||||
2791 | IFace = CurMethod->getClassInterface(); | ||||
2792 | ObjCInterfaceDecl *ClassDeclared; | ||||
2793 | ObjCIvarDecl *IV = nullptr; | ||||
2794 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||
2795 | // Diagnose using an ivar in a class method. | ||||
2796 | if (IsClassMethod) { | ||||
2797 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2798 | return DeclResult(true); | ||||
2799 | } | ||||
2800 | |||||
2801 | // Diagnose the use of an ivar outside of the declaring class. | ||||
2802 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||
2803 | !declaresSameEntity(ClassDeclared, IFace) && | ||||
2804 | !getLangOpts().DebuggerSupport) | ||||
2805 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||
2806 | |||||
2807 | // Success. | ||||
2808 | return IV; | ||||
2809 | } | ||||
2810 | } else if (CurMethod->isInstanceMethod()) { | ||||
2811 | // We should warn if a local variable hides an ivar. | ||||
2812 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||
2813 | ObjCInterfaceDecl *ClassDeclared; | ||||
2814 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||
2815 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||
2816 | declaresSameEntity(IFace, ClassDeclared)) | ||||
2817 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||
2818 | } | ||||
2819 | } | ||||
2820 | } else if (Lookup.isSingleResult() && | ||||
2821 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||
2822 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||
2823 | if (const ObjCIvarDecl *IV = | ||||
2824 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||
2825 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2826 | return DeclResult(true); | ||||
2827 | } | ||||
2828 | } | ||||
2829 | |||||
2830 | // Didn't encounter an error, didn't find an ivar. | ||||
2831 | return DeclResult(false); | ||||
2832 | } | ||||
2833 | |||||
2834 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||
2835 | ObjCIvarDecl *IV) { | ||||
2836 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2837 | assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2838, __PRETTY_FUNCTION__)) | ||||
2838 | "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2838, __PRETTY_FUNCTION__)); | ||||
2839 | |||||
2840 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||
2841 | assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context" ) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 2841, __PRETTY_FUNCTION__)); | ||||
2842 | |||||
2843 | // If we're referencing an invalid decl, just return this as a silent | ||||
2844 | // error node. The error diagnostic was already emitted on the decl. | ||||
2845 | if (IV->isInvalidDecl()) | ||||
2846 | return ExprError(); | ||||
2847 | |||||
2848 | // Check if referencing a field with __attribute__((deprecated)). | ||||
2849 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||
2850 | return ExprError(); | ||||
2851 | |||||
2852 | // FIXME: This should use a new expr for a direct reference, don't | ||||
2853 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||
2854 | IdentifierInfo &II = Context.Idents.get("self"); | ||||
2855 | UnqualifiedId SelfName; | ||||
2856 | SelfName.setImplicitSelfParam(&II); | ||||
2857 | CXXScopeSpec SelfScopeSpec; | ||||
2858 | SourceLocation TemplateKWLoc; | ||||
2859 | ExprResult SelfExpr = | ||||
2860 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||
2861 | /*HasTrailingLParen=*/false, | ||||
2862 | /*IsAddressOfOperand=*/false); | ||||
2863 | if (SelfExpr.isInvalid()) | ||||
2864 | return ExprError(); | ||||
2865 | |||||
2866 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||
2867 | if (SelfExpr.isInvalid()) | ||||
2868 | return ExprError(); | ||||
2869 | |||||
2870 | MarkAnyDeclReferenced(Loc, IV, true); | ||||
2871 | |||||
2872 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||
2873 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||
2874 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||
2875 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||
2876 | |||||
2877 | ObjCIvarRefExpr *Result = new (Context) | ||||
2878 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||
2879 | IV->getLocation(), SelfExpr.get(), true, true); | ||||
2880 | |||||
2881 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||
2882 | if (!isUnevaluatedContext() && | ||||
2883 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||
2884 | getCurFunction()->recordUseOfWeak(Result); | ||||
2885 | } | ||||
2886 | if (getLangOpts().ObjCAutoRefCount) | ||||
2887 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||
2888 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||
2889 | |||||
2890 | return Result; | ||||
2891 | } | ||||
2892 | |||||
2893 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2894 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2895 | /// should form a reference to an ivar. If so, build an expression referencing | ||||
2896 | /// that ivar. | ||||
2897 | ExprResult | ||||
2898 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2899 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||
2900 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||
2901 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||
2902 | if (Ivar.isInvalid()) | ||||
2903 | return ExprError(); | ||||
2904 | if (Ivar.isUsable()) | ||||
2905 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||
2906 | cast<ObjCIvarDecl>(Ivar.get())); | ||||
2907 | |||||
2908 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||
2909 | LookupBuiltin(Lookup); | ||||
2910 | |||||
2911 | // Sentinel value saying that we didn't do anything special. | ||||
2912 | return ExprResult(false); | ||||
2913 | } | ||||
2914 | |||||
2915 | /// Cast a base object to a member's actual type. | ||||
2916 | /// | ||||
2917 | /// There are two relevant checks: | ||||
2918 | /// | ||||
2919 | /// C++ [class.access.base]p7: | ||||
2920 | /// | ||||
2921 | /// If a class member access operator [...] is used to access a non-static | ||||
2922 | /// data member or non-static member function, the reference is ill-formed if | ||||
2923 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||
2924 | /// naming class of the right operand. | ||||
2925 | /// | ||||
2926 | /// C++ [expr.ref]p7: | ||||
2927 | /// | ||||
2928 | /// If E2 is a non-static data member or a non-static member function, the | ||||
2929 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||
2930 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||
2931 | /// | ||||
2932 | /// Note that the latter check does not consider access; the access of the | ||||
2933 | /// "real" base class is checked as appropriate when checking the access of the | ||||
2934 | /// member name. | ||||
2935 | ExprResult | ||||
2936 | Sema::PerformObjectMemberConversion(Expr *From, | ||||
2937 | NestedNameSpecifier *Qualifier, | ||||
2938 | NamedDecl *FoundDecl, | ||||
2939 | NamedDecl *Member) { | ||||
2940 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||
2941 | if (!RD) | ||||
2942 | return From; | ||||
2943 | |||||
2944 | QualType DestRecordType; | ||||
2945 | QualType DestType; | ||||
2946 | QualType FromRecordType; | ||||
2947 | QualType FromType = From->getType(); | ||||
2948 | bool PointerConversions = false; | ||||
2949 | if (isa<FieldDecl>(Member)) { | ||||
2950 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||
2951 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||
2952 | DestRecordType = Context.getAddrSpaceQualType( | ||||
2953 | DestRecordType, FromPtrType | ||||
2954 | ? FromType->getPointeeType().getAddressSpace() | ||||
2955 | : FromType.getAddressSpace()); | ||||
2956 | |||||
2957 | if (FromPtrType) { | ||||
2958 | DestType = Context.getPointerType(DestRecordType); | ||||
2959 | FromRecordType = FromPtrType->getPointeeType(); | ||||
2960 | PointerConversions = true; | ||||
2961 | } else { | ||||
2962 | DestType = DestRecordType; | ||||
2963 | FromRecordType = FromType; | ||||
2964 | } | ||||
2965 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||
2966 | if (Method->isStatic()) | ||||
2967 | return From; | ||||
2968 | |||||
2969 | DestType = Method->getThisType(); | ||||
2970 | DestRecordType = DestType->getPointeeType(); | ||||
2971 | |||||
2972 | if (FromType->getAs<PointerType>()) { | ||||
2973 | FromRecordType = FromType->getPointeeType(); | ||||
2974 | PointerConversions = true; | ||||
2975 | } else { | ||||
2976 | FromRecordType = FromType; | ||||
2977 | DestType = DestRecordType; | ||||
2978 | } | ||||
2979 | |||||
2980 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||
2981 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||
2982 | if (FromAS != DestAS) { | ||||
2983 | QualType FromRecordTypeWithoutAS = | ||||
2984 | Context.removeAddrSpaceQualType(FromRecordType); | ||||
2985 | QualType FromTypeWithDestAS = | ||||
2986 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||
2987 | if (PointerConversions) | ||||
2988 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||
2989 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||
2990 | CK_AddressSpaceConversion, From->getValueKind()) | ||||
2991 | .get(); | ||||
2992 | } | ||||
2993 | } else { | ||||
2994 | // No conversion necessary. | ||||
2995 | return From; | ||||
2996 | } | ||||
2997 | |||||
2998 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||
2999 | return From; | ||||
3000 | |||||
3001 | // If the unqualified types are the same, no conversion is necessary. | ||||
3002 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3003 | return From; | ||||
3004 | |||||
3005 | SourceRange FromRange = From->getSourceRange(); | ||||
3006 | SourceLocation FromLoc = FromRange.getBegin(); | ||||
3007 | |||||
3008 | ExprValueKind VK = From->getValueKind(); | ||||
3009 | |||||
3010 | // C++ [class.member.lookup]p8: | ||||
3011 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||
3012 | // class name. | ||||
3013 | // | ||||
3014 | // If the member was a qualified name and the qualified referred to a | ||||
3015 | // specific base subobject type, we'll cast to that intermediate type | ||||
3016 | // first and then to the object in which the member is declared. That allows | ||||
3017 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||
3018 | // | ||||
3019 | // class Base { public: int x; }; | ||||
3020 | // class Derived1 : public Base { }; | ||||
3021 | // class Derived2 : public Base { }; | ||||
3022 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||
3023 | // | ||||
3024 | // void VeryDerived::f() { | ||||
3025 | // x = 17; // error: ambiguous base subobjects | ||||
3026 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||
3027 | // } | ||||
3028 | if (Qualifier && Qualifier->getAsType()) { | ||||
3029 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||
3030 | assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type" ) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3030, __PRETTY_FUNCTION__)); | ||||
3031 | |||||
3032 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | ||||
3033 | |||||
3034 | // In C++98, the qualifier type doesn't actually have to be a base | ||||
3035 | // type of the object type, in which case we just ignore it. | ||||
3036 | // Otherwise build the appropriate casts. | ||||
3037 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||
3038 | CXXCastPath BasePath; | ||||
3039 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||
3040 | FromLoc, FromRange, &BasePath)) | ||||
3041 | return ExprError(); | ||||
3042 | |||||
3043 | if (PointerConversions) | ||||
3044 | QType = Context.getPointerType(QType); | ||||
3045 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||
3046 | VK, &BasePath).get(); | ||||
3047 | |||||
3048 | FromType = QType; | ||||
3049 | FromRecordType = QRecordType; | ||||
3050 | |||||
3051 | // If the qualifier type was the same as the destination type, | ||||
3052 | // we're done. | ||||
3053 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3054 | return From; | ||||
3055 | } | ||||
3056 | } | ||||
3057 | |||||
3058 | CXXCastPath BasePath; | ||||
3059 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||
3060 | FromLoc, FromRange, &BasePath, | ||||
3061 | /*IgnoreAccess=*/true)) | ||||
3062 | return ExprError(); | ||||
3063 | |||||
3064 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||
3065 | VK, &BasePath); | ||||
3066 | } | ||||
3067 | |||||
3068 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||
3069 | const LookupResult &R, | ||||
3070 | bool HasTrailingLParen) { | ||||
3071 | // Only when used directly as the postfix-expression of a call. | ||||
3072 | if (!HasTrailingLParen) | ||||
3073 | return false; | ||||
3074 | |||||
3075 | // Never if a scope specifier was provided. | ||||
3076 | if (SS.isSet()) | ||||
3077 | return false; | ||||
3078 | |||||
3079 | // Only in C++ or ObjC++. | ||||
3080 | if (!getLangOpts().CPlusPlus) | ||||
3081 | return false; | ||||
3082 | |||||
3083 | // Turn off ADL when we find certain kinds of declarations during | ||||
3084 | // normal lookup: | ||||
3085 | for (NamedDecl *D : R) { | ||||
3086 | // C++0x [basic.lookup.argdep]p3: | ||||
3087 | // -- a declaration of a class member | ||||
3088 | // Since using decls preserve this property, we check this on the | ||||
3089 | // original decl. | ||||
3090 | if (D->isCXXClassMember()) | ||||
3091 | return false; | ||||
3092 | |||||
3093 | // C++0x [basic.lookup.argdep]p3: | ||||
3094 | // -- a block-scope function declaration that is not a | ||||
3095 | // using-declaration | ||||
3096 | // NOTE: we also trigger this for function templates (in fact, we | ||||
3097 | // don't check the decl type at all, since all other decl types | ||||
3098 | // turn off ADL anyway). | ||||
3099 | if (isa<UsingShadowDecl>(D)) | ||||
3100 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
3101 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
3102 | return false; | ||||
3103 | |||||
3104 | // C++0x [basic.lookup.argdep]p3: | ||||
3105 | // -- a declaration that is neither a function or a function | ||||
3106 | // template | ||||
3107 | // And also for builtin functions. | ||||
3108 | if (isa<FunctionDecl>(D)) { | ||||
3109 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||
3110 | |||||
3111 | // But also builtin functions. | ||||
3112 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||
3113 | return false; | ||||
3114 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||
3115 | return false; | ||||
3116 | } | ||||
3117 | |||||
3118 | return true; | ||||
3119 | } | ||||
3120 | |||||
3121 | |||||
3122 | /// Diagnoses obvious problems with the use of the given declaration | ||||
3123 | /// as an expression. This is only actually called for lookups that | ||||
3124 | /// were not overloaded, and it doesn't promise that the declaration | ||||
3125 | /// will in fact be used. | ||||
3126 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | ||||
3127 | if (D->isInvalidDecl()) | ||||
3128 | return true; | ||||
3129 | |||||
3130 | if (isa<TypedefNameDecl>(D)) { | ||||
3131 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||
3132 | return true; | ||||
3133 | } | ||||
3134 | |||||
3135 | if (isa<ObjCInterfaceDecl>(D)) { | ||||
3136 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||
3137 | return true; | ||||
3138 | } | ||||
3139 | |||||
3140 | if (isa<NamespaceDecl>(D)) { | ||||
3141 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||
3142 | return true; | ||||
3143 | } | ||||
3144 | |||||
3145 | return false; | ||||
3146 | } | ||||
3147 | |||||
3148 | // Certain multiversion types should be treated as overloaded even when there is | ||||
3149 | // only one result. | ||||
3150 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||
3151 | assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result" ) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3151, __PRETTY_FUNCTION__)); | ||||
3152 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||
3153 | return FD && | ||||
3154 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||
3155 | } | ||||
3156 | |||||
3157 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||
3158 | LookupResult &R, bool NeedsADL, | ||||
3159 | bool AcceptInvalidDecl) { | ||||
3160 | // If this is a single, fully-resolved result and we don't need ADL, | ||||
3161 | // just build an ordinary singleton decl ref. | ||||
3162 | if (!NeedsADL && R.isSingleResult() && | ||||
3163 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||
3164 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||
3165 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||
3166 | R.getRepresentativeDecl(), nullptr, | ||||
3167 | AcceptInvalidDecl); | ||||
3168 | |||||
3169 | // We only need to check the declaration if there's exactly one | ||||
3170 | // result, because in the overloaded case the results can only be | ||||
3171 | // functions and function templates. | ||||
3172 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||
3173 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | ||||
3174 | return ExprError(); | ||||
3175 | |||||
3176 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||
3177 | // any lookup-related diagnostics; we'll hash these out later, when | ||||
3178 | // we've picked a target. | ||||
3179 | R.suppressDiagnostics(); | ||||
3180 | |||||
3181 | UnresolvedLookupExpr *ULE | ||||
3182 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||
3183 | SS.getWithLocInContext(Context), | ||||
3184 | R.getLookupNameInfo(), | ||||
3185 | NeedsADL, R.isOverloadedResult(), | ||||
3186 | R.begin(), R.end()); | ||||
3187 | |||||
3188 | return ULE; | ||||
3189 | } | ||||
3190 | |||||
3191 | static void | ||||
3192 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||
3193 | ValueDecl *var, DeclContext *DC); | ||||
3194 | |||||
3195 | /// Complete semantic analysis for a reference to the given declaration. | ||||
3196 | ExprResult Sema::BuildDeclarationNameExpr( | ||||
3197 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||
3198 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||
3199 | bool AcceptInvalidDecl) { | ||||
3200 | assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast <void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3200, __PRETTY_FUNCTION__)); | ||||
3201 | assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3202, __PRETTY_FUNCTION__)) | ||||
3202 | "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3202, __PRETTY_FUNCTION__)); | ||||
3203 | |||||
3204 | SourceLocation Loc = NameInfo.getLoc(); | ||||
3205 | if (CheckDeclInExpr(*this, Loc, D)) | ||||
3206 | return ExprError(); | ||||
3207 | |||||
3208 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||
3209 | // Specifically diagnose references to class templates that are missing | ||||
3210 | // a template argument list. | ||||
3211 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||
3212 | return ExprError(); | ||||
3213 | } | ||||
3214 | |||||
3215 | // Make sure that we're referring to a value. | ||||
3216 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | ||||
3217 | if (!VD) { | ||||
3218 | Diag(Loc, diag::err_ref_non_value) | ||||
3219 | << D << SS.getRange(); | ||||
3220 | Diag(D->getLocation(), diag::note_declared_at); | ||||
3221 | return ExprError(); | ||||
3222 | } | ||||
3223 | |||||
3224 | // Check whether this declaration can be used. Note that we suppress | ||||
3225 | // this check when we're going to perform argument-dependent lookup | ||||
3226 | // on this function name, because this might not be the function | ||||
3227 | // that overload resolution actually selects. | ||||
3228 | if (DiagnoseUseOfDecl(VD, Loc)) | ||||
3229 | return ExprError(); | ||||
3230 | |||||
3231 | // Only create DeclRefExpr's for valid Decl's. | ||||
3232 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||
3233 | return ExprError(); | ||||
3234 | |||||
3235 | // Handle members of anonymous structs and unions. If we got here, | ||||
3236 | // and the reference is to a class member indirect field, then this | ||||
3237 | // must be the subject of a pointer-to-member expression. | ||||
3238 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||
3239 | if (!indirectField->isCXXClassMember()) | ||||
3240 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||
3241 | indirectField); | ||||
3242 | |||||
3243 | { | ||||
3244 | QualType type = VD->getType(); | ||||
3245 | if (type.isNull()) | ||||
3246 | return ExprError(); | ||||
3247 | ExprValueKind valueKind = VK_RValue; | ||||
3248 | |||||
3249 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||
3250 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||
3251 | // is expanded by some outer '...' in the context of the use. | ||||
3252 | type = type.getNonPackExpansionType(); | ||||
3253 | |||||
3254 | switch (D->getKind()) { | ||||
3255 | // Ignore all the non-ValueDecl kinds. | ||||
3256 | #define ABSTRACT_DECL(kind) | ||||
3257 | #define VALUE(type, base) | ||||
3258 | #define DECL(type, base) \ | ||||
3259 | case Decl::type: | ||||
3260 | #include "clang/AST/DeclNodes.inc" | ||||
3261 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3261); | ||||
3262 | |||||
3263 | // These shouldn't make it here. | ||||
3264 | case Decl::ObjCAtDefsField: | ||||
3265 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3265); | ||||
3266 | |||||
3267 | // Enum constants are always r-values and never references. | ||||
3268 | // Unresolved using declarations are dependent. | ||||
3269 | case Decl::EnumConstant: | ||||
3270 | case Decl::UnresolvedUsingValue: | ||||
3271 | case Decl::OMPDeclareReduction: | ||||
3272 | case Decl::OMPDeclareMapper: | ||||
3273 | valueKind = VK_RValue; | ||||
3274 | break; | ||||
3275 | |||||
3276 | // Fields and indirect fields that got here must be for | ||||
3277 | // pointer-to-member expressions; we just call them l-values for | ||||
3278 | // internal consistency, because this subexpression doesn't really | ||||
3279 | // exist in the high-level semantics. | ||||
3280 | case Decl::Field: | ||||
3281 | case Decl::IndirectField: | ||||
3282 | case Decl::ObjCIvar: | ||||
3283 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3284, __PRETTY_FUNCTION__)) | ||||
3284 | "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3284, __PRETTY_FUNCTION__)); | ||||
3285 | |||||
3286 | // These can't have reference type in well-formed programs, but | ||||
3287 | // for internal consistency we do this anyway. | ||||
3288 | type = type.getNonReferenceType(); | ||||
3289 | valueKind = VK_LValue; | ||||
3290 | break; | ||||
3291 | |||||
3292 | // Non-type template parameters are either l-values or r-values | ||||
3293 | // depending on the type. | ||||
3294 | case Decl::NonTypeTemplateParm: { | ||||
3295 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||
3296 | type = reftype->getPointeeType(); | ||||
3297 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||
3298 | break; | ||||
3299 | } | ||||
3300 | |||||
3301 | // [expr.prim.id.unqual]p2: | ||||
3302 | // If the entity is a template parameter object for a template | ||||
3303 | // parameter of type T, the type of the expression is const T. | ||||
3304 | // [...] The expression is an lvalue if the entity is a [...] template | ||||
3305 | // parameter object. | ||||
3306 | if (type->isRecordType()) { | ||||
3307 | type = type.getUnqualifiedType().withConst(); | ||||
3308 | valueKind = VK_LValue; | ||||
3309 | break; | ||||
3310 | } | ||||
3311 | |||||
3312 | // For non-references, we need to strip qualifiers just in case | ||||
3313 | // the template parameter was declared as 'const int' or whatever. | ||||
3314 | valueKind = VK_RValue; | ||||
3315 | type = type.getUnqualifiedType(); | ||||
3316 | break; | ||||
3317 | } | ||||
3318 | |||||
3319 | case Decl::Var: | ||||
3320 | case Decl::VarTemplateSpecialization: | ||||
3321 | case Decl::VarTemplatePartialSpecialization: | ||||
3322 | case Decl::Decomposition: | ||||
3323 | case Decl::OMPCapturedExpr: | ||||
3324 | // In C, "extern void blah;" is valid and is an r-value. | ||||
3325 | if (!getLangOpts().CPlusPlus && | ||||
3326 | !type.hasQualifiers() && | ||||
3327 | type->isVoidType()) { | ||||
3328 | valueKind = VK_RValue; | ||||
3329 | break; | ||||
3330 | } | ||||
3331 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3332 | |||||
3333 | case Decl::ImplicitParam: | ||||
3334 | case Decl::ParmVar: { | ||||
3335 | // These are always l-values. | ||||
3336 | valueKind = VK_LValue; | ||||
3337 | type = type.getNonReferenceType(); | ||||
3338 | |||||
3339 | // FIXME: Does the addition of const really only apply in | ||||
3340 | // potentially-evaluated contexts? Since the variable isn't actually | ||||
3341 | // captured in an unevaluated context, it seems that the answer is no. | ||||
3342 | if (!isUnevaluatedContext()) { | ||||
3343 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||
3344 | if (!CapturedType.isNull()) | ||||
3345 | type = CapturedType; | ||||
3346 | } | ||||
3347 | |||||
3348 | break; | ||||
3349 | } | ||||
3350 | |||||
3351 | case Decl::Binding: { | ||||
3352 | // These are always lvalues. | ||||
3353 | valueKind = VK_LValue; | ||||
3354 | type = type.getNonReferenceType(); | ||||
3355 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | ||||
3356 | // decides how that's supposed to work. | ||||
3357 | auto *BD = cast<BindingDecl>(VD); | ||||
3358 | if (BD->getDeclContext() != CurContext) { | ||||
3359 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | ||||
3360 | if (DD && DD->hasLocalStorage()) | ||||
3361 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | ||||
3362 | } | ||||
3363 | break; | ||||
3364 | } | ||||
3365 | |||||
3366 | case Decl::Function: { | ||||
3367 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||
3368 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | ||||
3369 | type = Context.BuiltinFnTy; | ||||
3370 | valueKind = VK_RValue; | ||||
3371 | break; | ||||
3372 | } | ||||
3373 | } | ||||
3374 | |||||
3375 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||
3376 | |||||
3377 | // If we're referring to a function with an __unknown_anytype | ||||
3378 | // result type, make the entire expression __unknown_anytype. | ||||
3379 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||
3380 | type = Context.UnknownAnyTy; | ||||
3381 | valueKind = VK_RValue; | ||||
3382 | break; | ||||
3383 | } | ||||
3384 | |||||
3385 | // Functions are l-values in C++. | ||||
3386 | if (getLangOpts().CPlusPlus) { | ||||
3387 | valueKind = VK_LValue; | ||||
3388 | break; | ||||
3389 | } | ||||
3390 | |||||
3391 | // C99 DR 316 says that, if a function type comes from a | ||||
3392 | // function definition (without a prototype), that type is only | ||||
3393 | // used for checking compatibility. Therefore, when referencing | ||||
3394 | // the function, we pretend that we don't have the full function | ||||
3395 | // type. | ||||
3396 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | ||||
3397 | isa<FunctionProtoType>(fty)) | ||||
3398 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||
3399 | fty->getExtInfo()); | ||||
3400 | |||||
3401 | // Functions are r-values in C. | ||||
3402 | valueKind = VK_RValue; | ||||
3403 | break; | ||||
3404 | } | ||||
3405 | |||||
3406 | case Decl::CXXDeductionGuide: | ||||
3407 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3407); | ||||
3408 | |||||
3409 | case Decl::MSProperty: | ||||
3410 | case Decl::MSGuid: | ||||
3411 | case Decl::TemplateParamObject: | ||||
3412 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||
3413 | // capture in OpenMP, or duplicated between host and device? | ||||
3414 | valueKind = VK_LValue; | ||||
3415 | break; | ||||
3416 | |||||
3417 | case Decl::CXXMethod: | ||||
3418 | // If we're referring to a method with an __unknown_anytype | ||||
3419 | // result type, make the entire expression __unknown_anytype. | ||||
3420 | // This should only be possible with a type written directly. | ||||
3421 | if (const FunctionProtoType *proto | ||||
3422 | = dyn_cast<FunctionProtoType>(VD->getType())) | ||||
3423 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||
3424 | type = Context.UnknownAnyTy; | ||||
3425 | valueKind = VK_RValue; | ||||
3426 | break; | ||||
3427 | } | ||||
3428 | |||||
3429 | // C++ methods are l-values if static, r-values if non-static. | ||||
3430 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||
3431 | valueKind = VK_LValue; | ||||
3432 | break; | ||||
3433 | } | ||||
3434 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3435 | |||||
3436 | case Decl::CXXConversion: | ||||
3437 | case Decl::CXXDestructor: | ||||
3438 | case Decl::CXXConstructor: | ||||
3439 | valueKind = VK_RValue; | ||||
3440 | break; | ||||
3441 | } | ||||
3442 | |||||
3443 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||
3444 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | ||||
3445 | TemplateArgs); | ||||
3446 | } | ||||
3447 | } | ||||
3448 | |||||
3449 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||
3450 | SmallString<32> &Target) { | ||||
3451 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||
3452 | char *ResultPtr = &Target[0]; | ||||
3453 | const llvm::UTF8 *ErrorPtr; | ||||
3454 | bool success = | ||||
3455 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||
3456 | (void)success; | ||||
3457 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3457, __PRETTY_FUNCTION__)); | ||||
3458 | Target.resize(ResultPtr - &Target[0]); | ||||
3459 | } | ||||
3460 | |||||
3461 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||
3462 | PredefinedExpr::IdentKind IK) { | ||||
3463 | // Pick the current block, lambda, captured statement or function. | ||||
3464 | Decl *currentDecl = nullptr; | ||||
3465 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||
3466 | currentDecl = BSI->TheDecl; | ||||
3467 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||
3468 | currentDecl = LSI->CallOperator; | ||||
3469 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||
3470 | currentDecl = CSI->TheCapturedDecl; | ||||
3471 | else | ||||
3472 | currentDecl = getCurFunctionOrMethodDecl(); | ||||
3473 | |||||
3474 | if (!currentDecl) { | ||||
3475 | Diag(Loc, diag::ext_predef_outside_function); | ||||
3476 | currentDecl = Context.getTranslationUnitDecl(); | ||||
3477 | } | ||||
3478 | |||||
3479 | QualType ResTy; | ||||
3480 | StringLiteral *SL = nullptr; | ||||
3481 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||
3482 | ResTy = Context.DependentTy; | ||||
3483 | else { | ||||
3484 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||
3485 | // the string. | ||||
3486 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||
3487 | unsigned Length = Str.length(); | ||||
3488 | |||||
3489 | llvm::APInt LengthI(32, Length + 1); | ||||
3490 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||
3491 | ResTy = | ||||
3492 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||
3493 | SmallString<32> RawChars; | ||||
3494 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||
3495 | Str, RawChars); | ||||
3496 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3497 | ArrayType::Normal, | ||||
3498 | /*IndexTypeQuals*/ 0); | ||||
3499 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||
3500 | /*Pascal*/ false, ResTy, Loc); | ||||
3501 | } else { | ||||
3502 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||
3503 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3504 | ArrayType::Normal, | ||||
3505 | /*IndexTypeQuals*/ 0); | ||||
3506 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | ||||
3507 | /*Pascal*/ false, ResTy, Loc); | ||||
3508 | } | ||||
3509 | } | ||||
3510 | |||||
3511 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||
3512 | } | ||||
3513 | |||||
3514 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||
3515 | PredefinedExpr::IdentKind IK; | ||||
3516 | |||||
3517 | switch (Kind) { | ||||
3518 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3518); | ||||
3519 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||
3520 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||
3521 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||
3522 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||
3523 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||
3524 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||
3525 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||
3526 | } | ||||
3527 | |||||
3528 | return BuildPredefinedExpr(Loc, IK); | ||||
3529 | } | ||||
3530 | |||||
3531 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||
3532 | SmallString<16> CharBuffer; | ||||
3533 | bool Invalid = false; | ||||
3534 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||
3535 | if (Invalid) | ||||
3536 | return ExprError(); | ||||
3537 | |||||
3538 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||
3539 | PP, Tok.getKind()); | ||||
3540 | if (Literal.hadError()) | ||||
3541 | return ExprError(); | ||||
3542 | |||||
3543 | QualType Ty; | ||||
3544 | if (Literal.isWide()) | ||||
3545 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||
3546 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||
3547 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||
3548 | else if (Literal.isUTF16()) | ||||
3549 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||
3550 | else if (Literal.isUTF32()) | ||||
3551 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||
3552 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||
3553 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||
3554 | else | ||||
3555 | Ty = Context.CharTy; // 'x' -> char in C++ | ||||
3556 | |||||
3557 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||
3558 | if (Literal.isWide()) | ||||
3559 | Kind = CharacterLiteral::Wide; | ||||
3560 | else if (Literal.isUTF16()) | ||||
3561 | Kind = CharacterLiteral::UTF16; | ||||
3562 | else if (Literal.isUTF32()) | ||||
3563 | Kind = CharacterLiteral::UTF32; | ||||
3564 | else if (Literal.isUTF8()) | ||||
3565 | Kind = CharacterLiteral::UTF8; | ||||
3566 | |||||
3567 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||
3568 | Tok.getLocation()); | ||||
3569 | |||||
3570 | if (Literal.getUDSuffix().empty()) | ||||
3571 | return Lit; | ||||
3572 | |||||
3573 | // We're building a user-defined literal. | ||||
3574 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3575 | SourceLocation UDSuffixLoc = | ||||
3576 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3577 | |||||
3578 | // Make sure we're allowed user-defined literals here. | ||||
3579 | if (!UDLScope) | ||||
3580 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||
3581 | |||||
3582 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||
3583 | // operator "" X (ch) | ||||
3584 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||
3585 | Lit, Tok.getLocation()); | ||||
3586 | } | ||||
3587 | |||||
3588 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||
3589 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3590 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||
3591 | Context.IntTy, Loc); | ||||
3592 | } | ||||
3593 | |||||
3594 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||
3595 | QualType Ty, SourceLocation Loc) { | ||||
3596 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||
3597 | |||||
3598 | using llvm::APFloat; | ||||
3599 | APFloat Val(Format); | ||||
3600 | |||||
3601 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||
3602 | |||||
3603 | // Overflow is always an error, but underflow is only an error if | ||||
3604 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||
3605 | if ((result & APFloat::opOverflow) || | ||||
3606 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||
3607 | unsigned diagnostic; | ||||
3608 | SmallString<20> buffer; | ||||
3609 | if (result & APFloat::opOverflow) { | ||||
3610 | diagnostic = diag::warn_float_overflow; | ||||
3611 | APFloat::getLargest(Format).toString(buffer); | ||||
3612 | } else { | ||||
3613 | diagnostic = diag::warn_float_underflow; | ||||
3614 | APFloat::getSmallest(Format).toString(buffer); | ||||
3615 | } | ||||
3616 | |||||
3617 | S.Diag(Loc, diagnostic) | ||||
3618 | << Ty | ||||
3619 | << StringRef(buffer.data(), buffer.size()); | ||||
3620 | } | ||||
3621 | |||||
3622 | bool isExact = (result == APFloat::opOK); | ||||
3623 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||
3624 | } | ||||
3625 | |||||
3626 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||
3627 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3627, __PRETTY_FUNCTION__)); | ||||
3628 | |||||
3629 | if (E->isValueDependent()) | ||||
3630 | return false; | ||||
3631 | |||||
3632 | QualType QT = E->getType(); | ||||
3633 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||
3634 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||
3635 | return true; | ||||
3636 | } | ||||
3637 | |||||
3638 | llvm::APSInt ValueAPS; | ||||
3639 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||
3640 | |||||
3641 | if (R.isInvalid()) | ||||
3642 | return true; | ||||
3643 | |||||
3644 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||
3645 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||
3646 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||
3647 | << ValueAPS.toString(10) << ValueIsPositive; | ||||
3648 | return true; | ||||
3649 | } | ||||
3650 | |||||
3651 | return false; | ||||
3652 | } | ||||
3653 | |||||
3654 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||
3655 | // Fast path for a single digit (which is quite common). A single digit | ||||
3656 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||
3657 | if (Tok.getLength() == 1) { | ||||
3658 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||
3659 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||
3660 | } | ||||
3661 | |||||
3662 | SmallString<128> SpellingBuffer; | ||||
3663 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||
3664 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||
3665 | // returns a StringRef to the memory buffer, it should have a null char at | ||||
3666 | // the EOF, so it is also safe. | ||||
3667 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||
3668 | |||||
3669 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||
3670 | bool Invalid = false; | ||||
3671 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||
3672 | if (Invalid) | ||||
3673 | return ExprError(); | ||||
3674 | |||||
3675 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||
3676 | PP.getSourceManager(), PP.getLangOpts(), | ||||
3677 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||
3678 | if (Literal.hadError) | ||||
3679 | return ExprError(); | ||||
3680 | |||||
3681 | if (Literal.hasUDSuffix()) { | ||||
3682 | // We're building a user-defined literal. | ||||
3683 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3684 | SourceLocation UDSuffixLoc = | ||||
3685 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3686 | |||||
3687 | // Make sure we're allowed user-defined literals here. | ||||
3688 | if (!UDLScope) | ||||
3689 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||
3690 | |||||
3691 | QualType CookedTy; | ||||
3692 | if (Literal.isFloatingLiteral()) { | ||||
3693 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||
3694 | // long double, the literal is treated as a call of the form | ||||
3695 | // operator "" X (f L) | ||||
3696 | CookedTy = Context.LongDoubleTy; | ||||
3697 | } else { | ||||
3698 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||
3699 | // unsigned long long, the literal is treated as a call of the form | ||||
3700 | // operator "" X (n ULL) | ||||
3701 | CookedTy = Context.UnsignedLongLongTy; | ||||
3702 | } | ||||
3703 | |||||
3704 | DeclarationName OpName = | ||||
3705 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
3706 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
3707 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
3708 | |||||
3709 | SourceLocation TokLoc = Tok.getLocation(); | ||||
3710 | |||||
3711 | // Perform literal operator lookup to determine if we're building a raw | ||||
3712 | // literal or a cooked one. | ||||
3713 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
3714 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||
3715 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||
3716 | /*AllowStringTemplatePack*/ false, | ||||
3717 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||
3718 | case LOLR_ErrorNoDiagnostic: | ||||
3719 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||
3720 | // GNU extension producing _Complex types. | ||||
3721 | break; | ||||
3722 | case LOLR_Error: | ||||
3723 | return ExprError(); | ||||
3724 | case LOLR_Cooked: { | ||||
3725 | Expr *Lit; | ||||
3726 | if (Literal.isFloatingLiteral()) { | ||||
3727 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||
3728 | } else { | ||||
3729 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||
3730 | if (Literal.GetIntegerValue(ResultVal)) | ||||
3731 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3732 | << /* Unsigned */ 1; | ||||
3733 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||
3734 | Tok.getLocation()); | ||||
3735 | } | ||||
3736 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3737 | } | ||||
3738 | |||||
3739 | case LOLR_Raw: { | ||||
3740 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||
3741 | // literal is treated as a call of the form | ||||
3742 | // operator "" X ("n") | ||||
3743 | unsigned Length = Literal.getUDSuffixOffset(); | ||||
3744 | QualType StrTy = Context.getConstantArrayType( | ||||
3745 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||
3746 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||
3747 | Expr *Lit = StringLiteral::Create( | ||||
3748 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | ||||
3749 | /*Pascal*/false, StrTy, &TokLoc, 1); | ||||
3750 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3751 | } | ||||
3752 | |||||
3753 | case LOLR_Template: { | ||||
3754 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||
3755 | // template), L is treated as a call fo the form | ||||
3756 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||
3757 | // where n is the source character sequence c1 c2 ... ck. | ||||
3758 | TemplateArgumentListInfo ExplicitArgs; | ||||
3759 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||
3760 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||
3761 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
3762 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||
3763 | Value = TokSpelling[I]; | ||||
3764 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||
3765 | TemplateArgumentLocInfo ArgInfo; | ||||
3766 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
3767 | } | ||||
3768 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||
3769 | &ExplicitArgs); | ||||
3770 | } | ||||
3771 | case LOLR_StringTemplatePack: | ||||
3772 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3772); | ||||
3773 | } | ||||
3774 | } | ||||
3775 | |||||
3776 | Expr *Res; | ||||
3777 | |||||
3778 | if (Literal.isFixedPointLiteral()) { | ||||
3779 | QualType Ty; | ||||
3780 | |||||
3781 | if (Literal.isAccum) { | ||||
3782 | if (Literal.isHalf) { | ||||
3783 | Ty = Context.ShortAccumTy; | ||||
3784 | } else if (Literal.isLong) { | ||||
3785 | Ty = Context.LongAccumTy; | ||||
3786 | } else { | ||||
3787 | Ty = Context.AccumTy; | ||||
3788 | } | ||||
3789 | } else if (Literal.isFract) { | ||||
3790 | if (Literal.isHalf) { | ||||
3791 | Ty = Context.ShortFractTy; | ||||
3792 | } else if (Literal.isLong) { | ||||
3793 | Ty = Context.LongFractTy; | ||||
3794 | } else { | ||||
3795 | Ty = Context.FractTy; | ||||
3796 | } | ||||
3797 | } | ||||
3798 | |||||
3799 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||
3800 | |||||
3801 | bool isSigned = !Literal.isUnsigned; | ||||
3802 | unsigned scale = Context.getFixedPointScale(Ty); | ||||
3803 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||
3804 | |||||
3805 | llvm::APInt Val(bit_width, 0, isSigned); | ||||
3806 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||
3807 | bool ValIsZero = Val.isNullValue() && !Overflowed; | ||||
3808 | |||||
3809 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||
3810 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||
3811 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||
3812 | // representable values for its type, with exception for constants of a | ||||
3813 | // fract type with a value of exactly 1; such a constant shall denote | ||||
3814 | // the maximal value for the type. | ||||
3815 | --Val; | ||||
3816 | else if (Val.ugt(MaxVal) || Overflowed) | ||||
3817 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||
3818 | |||||
3819 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||
3820 | Tok.getLocation(), scale); | ||||
3821 | } else if (Literal.isFloatingLiteral()) { | ||||
3822 | QualType Ty; | ||||
3823 | if (Literal.isHalf){ | ||||
3824 | if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) | ||||
3825 | Ty = Context.HalfTy; | ||||
3826 | else { | ||||
3827 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||
3828 | return ExprError(); | ||||
3829 | } | ||||
3830 | } else if (Literal.isFloat) | ||||
3831 | Ty = Context.FloatTy; | ||||
3832 | else if (Literal.isLong) | ||||
3833 | Ty = Context.LongDoubleTy; | ||||
3834 | else if (Literal.isFloat16) | ||||
3835 | Ty = Context.Float16Ty; | ||||
3836 | else if (Literal.isFloat128) | ||||
3837 | Ty = Context.Float128Ty; | ||||
3838 | else | ||||
3839 | Ty = Context.DoubleTy; | ||||
3840 | |||||
3841 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||
3842 | |||||
3843 | if (Ty == Context.DoubleTy) { | ||||
3844 | if (getLangOpts().SinglePrecisionConstants) { | ||||
3845 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||
3846 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3847 | } | ||||
3848 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( | ||||
3849 | "cl_khr_fp64", getLangOpts())) { | ||||
3850 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||
3851 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | ||||
3852 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3853 | } | ||||
3854 | } | ||||
3855 | } else if (!Literal.isIntegerLiteral()) { | ||||
3856 | return ExprError(); | ||||
3857 | } else { | ||||
3858 | QualType Ty; | ||||
3859 | |||||
3860 | // 'long long' is a C99 or C++11 feature. | ||||
3861 | if (!getLangOpts().C99 && Literal.isLongLong) { | ||||
3862 | if (getLangOpts().CPlusPlus) | ||||
3863 | Diag(Tok.getLocation(), | ||||
3864 | getLangOpts().CPlusPlus11 ? | ||||
3865 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||
3866 | else | ||||
3867 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||
3868 | } | ||||
3869 | |||||
3870 | // 'z/uz' literals are a C++2b feature. | ||||
3871 | if (Literal.isSizeT) | ||||
3872 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus | ||||
3873 | ? getLangOpts().CPlusPlus2b | ||||
3874 | ? diag::warn_cxx20_compat_size_t_suffix | ||||
3875 | : diag::ext_cxx2b_size_t_suffix | ||||
3876 | : diag::err_cxx2b_size_t_suffix); | ||||
3877 | |||||
3878 | // Get the value in the widest-possible width. | ||||
3879 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | ||||
3880 | llvm::APInt ResultVal(MaxWidth, 0); | ||||
3881 | |||||
3882 | if (Literal.GetIntegerValue(ResultVal)) { | ||||
3883 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||
3884 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3885 | << /* Unsigned */ 1; | ||||
3886 | Ty = Context.UnsignedLongLongTy; | ||||
3887 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3888, __PRETTY_FUNCTION__)) | ||||
3888 | "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3888, __PRETTY_FUNCTION__)); | ||||
3889 | } else { | ||||
3890 | // If this value fits into a ULL, try to figure out what else it fits into | ||||
3891 | // according to the rules of C99 6.4.4.1p5. | ||||
3892 | |||||
3893 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||
3894 | // be an unsigned int. | ||||
3895 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||
3896 | |||||
3897 | // Check from smallest to largest, picking the smallest type we can. | ||||
3898 | unsigned Width = 0; | ||||
3899 | |||||
3900 | // Microsoft specific integer suffixes are explicitly sized. | ||||
3901 | if (Literal.MicrosoftInteger) { | ||||
3902 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||
3903 | Width = 8; | ||||
3904 | Ty = Context.CharTy; | ||||
3905 | } else { | ||||
3906 | Width = Literal.MicrosoftInteger; | ||||
3907 | Ty = Context.getIntTypeForBitwidth(Width, | ||||
3908 | /*Signed=*/!Literal.isUnsigned); | ||||
3909 | } | ||||
3910 | } | ||||
3911 | |||||
3912 | // Check C++2b size_t literals. | ||||
3913 | if (Literal.isSizeT) { | ||||
3914 | assert(!Literal.MicrosoftInteger &&((!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals" ) ? static_cast<void> (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3915, __PRETTY_FUNCTION__)) | ||||
3915 | "size_t literals can't be Microsoft literals")((!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals" ) ? static_cast<void> (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 3915, __PRETTY_FUNCTION__)); | ||||
3916 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( | ||||
3917 | Context.getTargetInfo().getSizeType()); | ||||
3918 | |||||
3919 | // Does it fit in size_t? | ||||
3920 | if (ResultVal.isIntN(SizeTSize)) { | ||||
3921 | // Does it fit in ssize_t? | ||||
3922 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) | ||||
3923 | Ty = Context.getSignedSizeType(); | ||||
3924 | else if (AllowUnsigned) | ||||
3925 | Ty = Context.getSizeType(); | ||||
3926 | Width = SizeTSize; | ||||
3927 | } | ||||
3928 | } | ||||
3929 | |||||
3930 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && | ||||
3931 | !Literal.isSizeT) { | ||||
3932 | // Are int/unsigned possibilities? | ||||
3933 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3934 | |||||
3935 | // Does it fit in a unsigned int? | ||||
3936 | if (ResultVal.isIntN(IntSize)) { | ||||
3937 | // Does it fit in a signed int? | ||||
3938 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||
3939 | Ty = Context.IntTy; | ||||
3940 | else if (AllowUnsigned) | ||||
3941 | Ty = Context.UnsignedIntTy; | ||||
3942 | Width = IntSize; | ||||
3943 | } | ||||
3944 | } | ||||
3945 | |||||
3946 | // Are long/unsigned long possibilities? | ||||
3947 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { | ||||
3948 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||
3949 | |||||
3950 | // Does it fit in a unsigned long? | ||||
3951 | if (ResultVal.isIntN(LongSize)) { | ||||
3952 | // Does it fit in a signed long? | ||||
3953 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||
3954 | Ty = Context.LongTy; | ||||
3955 | else if (AllowUnsigned) | ||||
3956 | Ty = Context.UnsignedLongTy; | ||||
3957 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||
3958 | // is compatible. | ||||
3959 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||
3960 | const unsigned LongLongSize = | ||||
3961 | Context.getTargetInfo().getLongLongWidth(); | ||||
3962 | Diag(Tok.getLocation(), | ||||
3963 | getLangOpts().CPlusPlus | ||||
3964 | ? Literal.isLong | ||||
3965 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||
3966 | : /*C++98 UB*/ diag:: | ||||
3967 | ext_old_implicitly_unsigned_long_cxx | ||||
3968 | : diag::warn_old_implicitly_unsigned_long) | ||||
3969 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||
3970 | : /*will be ill-formed*/ 1); | ||||
3971 | Ty = Context.UnsignedLongTy; | ||||
3972 | } | ||||
3973 | Width = LongSize; | ||||
3974 | } | ||||
3975 | } | ||||
3976 | |||||
3977 | // Check long long if needed. | ||||
3978 | if (Ty.isNull() && !Literal.isSizeT) { | ||||
3979 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||
3980 | |||||
3981 | // Does it fit in a unsigned long long? | ||||
3982 | if (ResultVal.isIntN(LongLongSize)) { | ||||
3983 | // Does it fit in a signed long long? | ||||
3984 | // To be compatible with MSVC, hex integer literals ending with the | ||||
3985 | // LL or i64 suffix are always signed in Microsoft mode. | ||||
3986 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||
3987 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||
3988 | Ty = Context.LongLongTy; | ||||
3989 | else if (AllowUnsigned) | ||||
3990 | Ty = Context.UnsignedLongLongTy; | ||||
3991 | Width = LongLongSize; | ||||
3992 | } | ||||
3993 | } | ||||
3994 | |||||
3995 | // If we still couldn't decide a type, we either have 'size_t' literal | ||||
3996 | // that is out of range, or a decimal literal that does not fit in a | ||||
3997 | // signed long long and has no U suffix. | ||||
3998 | if (Ty.isNull()) { | ||||
3999 | if (Literal.isSizeT) | ||||
4000 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) | ||||
4001 | << Literal.isUnsigned; | ||||
4002 | else | ||||
4003 | Diag(Tok.getLocation(), | ||||
4004 | diag::ext_integer_literal_too_large_for_signed); | ||||
4005 | Ty = Context.UnsignedLongLongTy; | ||||
4006 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||
4007 | } | ||||
4008 | |||||
4009 | if (ResultVal.getBitWidth() != Width) | ||||
4010 | ResultVal = ResultVal.trunc(Width); | ||||
4011 | } | ||||
4012 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||
4013 | } | ||||
4014 | |||||
4015 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||
4016 | if (Literal.isImaginary) { | ||||
4017 | Res = new (Context) ImaginaryLiteral(Res, | ||||
4018 | Context.getComplexType(Res->getType())); | ||||
4019 | |||||
4020 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||
4021 | } | ||||
4022 | return Res; | ||||
4023 | } | ||||
4024 | |||||
4025 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||
4026 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4026, __PRETTY_FUNCTION__)); | ||||
4027 | return new (Context) ParenExpr(L, R, E); | ||||
4028 | } | ||||
4029 | |||||
4030 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||
4031 | SourceLocation Loc, | ||||
4032 | SourceRange ArgRange) { | ||||
4033 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||
4034 | // scalar or vector data type argument..." | ||||
4035 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||
4036 | // type (C99 6.2.5p18) or void. | ||||
4037 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||
4038 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||
4039 | << T << ArgRange; | ||||
4040 | return true; | ||||
4041 | } | ||||
4042 | |||||
4043 | assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4044, __PRETTY_FUNCTION__)) | ||||
4044 | "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4044, __PRETTY_FUNCTION__)); | ||||
4045 | return false; | ||||
4046 | } | ||||
4047 | |||||
4048 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||
4049 | SourceLocation Loc, | ||||
4050 | SourceRange ArgRange, | ||||
4051 | UnaryExprOrTypeTrait TraitKind) { | ||||
4052 | // Invalid types must be hard errors for SFINAE in C++. | ||||
4053 | if (S.LangOpts.CPlusPlus) | ||||
4054 | return true; | ||||
4055 | |||||
4056 | // C99 6.5.3.4p1: | ||||
4057 | if (T->isFunctionType() && | ||||
4058 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||
4059 | TraitKind == UETT_PreferredAlignOf)) { | ||||
4060 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||
4061 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||
4062 | << getTraitSpelling(TraitKind) << ArgRange; | ||||
4063 | return false; | ||||
4064 | } | ||||
4065 | |||||
4066 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||
4067 | // this is an error (OpenCL v1.1 s6.3.k) | ||||
4068 | if (T->isVoidType()) { | ||||
4069 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||
4070 | : diag::ext_sizeof_alignof_void_type; | ||||
4071 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||
4072 | return false; | ||||
4073 | } | ||||
4074 | |||||
4075 | return true; | ||||
4076 | } | ||||
4077 | |||||
4078 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||
4079 | SourceLocation Loc, | ||||
4080 | SourceRange ArgRange, | ||||
4081 | UnaryExprOrTypeTrait TraitKind) { | ||||
4082 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||
4083 | // runtime doesn't allow it. | ||||
4084 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||
4085 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||
4086 | << T << (TraitKind == UETT_SizeOf) | ||||
4087 | << ArgRange; | ||||
4088 | return true; | ||||
4089 | } | ||||
4090 | |||||
4091 | return false; | ||||
4092 | } | ||||
4093 | |||||
4094 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||
4095 | /// pointer type is equal to T) and emit a warning if it is. | ||||
4096 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||
4097 | Expr *E) { | ||||
4098 | // Don't warn if the operation changed the type. | ||||
4099 | if (T != E->getType()) | ||||
4100 | return; | ||||
4101 | |||||
4102 | // Now look for array decays. | ||||
4103 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||
4104 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||
4105 | return; | ||||
4106 | |||||
4107 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||
4108 | << ICE->getType() | ||||
4109 | << ICE->getSubExpr()->getType(); | ||||
4110 | } | ||||
4111 | |||||
4112 | /// Check the constraints on expression operands to unary type expression | ||||
4113 | /// and type traits. | ||||
4114 | /// | ||||
4115 | /// Completes any types necessary and validates the constraints on the operand | ||||
4116 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||
4117 | /// the expression as it completes the type for that expression through template | ||||
4118 | /// instantiation, etc. | ||||
4119 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||
4120 | UnaryExprOrTypeTrait ExprKind) { | ||||
4121 | QualType ExprTy = E->getType(); | ||||
4122 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4122, __PRETTY_FUNCTION__)); | ||||
4123 | |||||
4124 | bool IsUnevaluatedOperand = | ||||
4125 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||
4126 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||
4127 | if (IsUnevaluatedOperand) { | ||||
4128 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||
4129 | if (Result.isInvalid()) | ||||
4130 | return true; | ||||
4131 | E = Result.get(); | ||||
4132 | } | ||||
4133 | |||||
4134 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||
4135 | // so side effects could result in unintended consequences. | ||||
4136 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||
4137 | // used to build SFINAE gadgets. | ||||
4138 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||
4139 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||
4140 | !E->isInstantiationDependent() && | ||||
4141 | E->HasSideEffects(Context, false)) | ||||
4142 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||
4143 | |||||
4144 | if (ExprKind == UETT_VecStep) | ||||
4145 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4146 | E->getSourceRange()); | ||||
4147 | |||||
4148 | // Explicitly list some types as extensions. | ||||
4149 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4150 | E->getSourceRange(), ExprKind)) | ||||
4151 | return false; | ||||
4152 | |||||
4153 | // 'alignof' applied to an expression only requires the base element type of | ||||
4154 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||
4155 | // be complete (and will attempt to complete it if it's an array of unknown | ||||
4156 | // bound). | ||||
4157 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4158 | if (RequireCompleteSizedType( | ||||
4159 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||
4160 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4161 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4162 | return true; | ||||
4163 | } else { | ||||
4164 | if (RequireCompleteSizedExprType( | ||||
4165 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4166 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4167 | return true; | ||||
4168 | } | ||||
4169 | |||||
4170 | // Completing the expression's type may have changed it. | ||||
4171 | ExprTy = E->getType(); | ||||
4172 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4172, __PRETTY_FUNCTION__)); | ||||
4173 | |||||
4174 | if (ExprTy->isFunctionType()) { | ||||
4175 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||
4176 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||
4177 | return true; | ||||
4178 | } | ||||
4179 | |||||
4180 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||
4181 | E->getSourceRange(), ExprKind)) | ||||
4182 | return true; | ||||
4183 | |||||
4184 | if (ExprKind == UETT_SizeOf) { | ||||
4185 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
4186 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||
4187 | QualType OType = PVD->getOriginalType(); | ||||
4188 | QualType Type = PVD->getType(); | ||||
4189 | if (Type->isPointerType() && OType->isArrayType()) { | ||||
4190 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||
4191 | << Type << OType; | ||||
4192 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||
4193 | } | ||||
4194 | } | ||||
4195 | } | ||||
4196 | |||||
4197 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||
4198 | // decays into a pointer and returns an unintended result. This is most | ||||
4199 | // likely a typo for "sizeof(array) op x". | ||||
4200 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||
4201 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4202 | BO->getLHS()); | ||||
4203 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4204 | BO->getRHS()); | ||||
4205 | } | ||||
4206 | } | ||||
4207 | |||||
4208 | return false; | ||||
4209 | } | ||||
4210 | |||||
4211 | /// Check the constraints on operands to unary expression and type | ||||
4212 | /// traits. | ||||
4213 | /// | ||||
4214 | /// This will complete any types necessary, and validate the various constraints | ||||
4215 | /// on those operands. | ||||
4216 | /// | ||||
4217 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||
4218 | /// C99 6.3.2.1p[2-4] all state: | ||||
4219 | /// Except when it is the operand of the sizeof operator ... | ||||
4220 | /// | ||||
4221 | /// C++ [expr.sizeof]p4 | ||||
4222 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||
4223 | /// standard conversions are not applied to the operand of sizeof. | ||||
4224 | /// | ||||
4225 | /// This policy is followed for all of the unary trait expressions. | ||||
4226 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||
4227 | SourceLocation OpLoc, | ||||
4228 | SourceRange ExprRange, | ||||
4229 | UnaryExprOrTypeTrait ExprKind) { | ||||
4230 | if (ExprType->isDependentType()) | ||||
4231 | return false; | ||||
4232 | |||||
4233 | // C++ [expr.sizeof]p2: | ||||
4234 | // When applied to a reference or a reference type, the result | ||||
4235 | // is the size of the referenced type. | ||||
4236 | // C++11 [expr.alignof]p3: | ||||
4237 | // When alignof is applied to a reference type, the result | ||||
4238 | // shall be the alignment of the referenced type. | ||||
4239 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||
4240 | ExprType = Ref->getPointeeType(); | ||||
4241 | |||||
4242 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||
4243 | // When alignof or _Alignof is applied to an array type, the result | ||||
4244 | // is the alignment of the element type. | ||||
4245 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||
4246 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||
4247 | ExprType = Context.getBaseElementType(ExprType); | ||||
4248 | |||||
4249 | if (ExprKind == UETT_VecStep) | ||||
4250 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||
4251 | |||||
4252 | // Explicitly list some types as extensions. | ||||
4253 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||
4254 | ExprKind)) | ||||
4255 | return false; | ||||
4256 | |||||
4257 | if (RequireCompleteSizedType( | ||||
4258 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4259 | getTraitSpelling(ExprKind), ExprRange)) | ||||
4260 | return true; | ||||
4261 | |||||
4262 | if (ExprType->isFunctionType()) { | ||||
4263 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||
4264 | << getTraitSpelling(ExprKind) << ExprRange; | ||||
4265 | return true; | ||||
4266 | } | ||||
4267 | |||||
4268 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||
4269 | ExprKind)) | ||||
4270 | return true; | ||||
4271 | |||||
4272 | return false; | ||||
4273 | } | ||||
4274 | |||||
4275 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||
4276 | // Cannot know anything else if the expression is dependent. | ||||
4277 | if (E->isTypeDependent()) | ||||
4278 | return false; | ||||
4279 | |||||
4280 | if (E->getObjectKind() == OK_BitField) { | ||||
4281 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||
4282 | << 1 << E->getSourceRange(); | ||||
4283 | return true; | ||||
4284 | } | ||||
4285 | |||||
4286 | ValueDecl *D = nullptr; | ||||
4287 | Expr *Inner = E->IgnoreParens(); | ||||
4288 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||
4289 | D = DRE->getDecl(); | ||||
4290 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||
4291 | D = ME->getMemberDecl(); | ||||
4292 | } | ||||
4293 | |||||
4294 | // If it's a field, require the containing struct to have a | ||||
4295 | // complete definition so that we can compute the layout. | ||||
4296 | // | ||||
4297 | // This can happen in C++11 onwards, either by naming the member | ||||
4298 | // in a way that is not transformed into a member access expression | ||||
4299 | // (in an unevaluated operand, for instance), or by naming the member | ||||
4300 | // in a trailing-return-type. | ||||
4301 | // | ||||
4302 | // For the record, since __alignof__ on expressions is a GCC | ||||
4303 | // extension, GCC seems to permit this but always gives the | ||||
4304 | // nonsensical answer 0. | ||||
4305 | // | ||||
4306 | // We don't really need the layout here --- we could instead just | ||||
4307 | // directly check for all the appropriate alignment-lowing | ||||
4308 | // attributes --- but that would require duplicating a lot of | ||||
4309 | // logic that just isn't worth duplicating for such a marginal | ||||
4310 | // use-case. | ||||
4311 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||
4312 | // Fast path this check, since we at least know the record has a | ||||
4313 | // definition if we can find a member of it. | ||||
4314 | if (!FD->getParent()->isCompleteDefinition()) { | ||||
4315 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||
4316 | << E->getSourceRange(); | ||||
4317 | return true; | ||||
4318 | } | ||||
4319 | |||||
4320 | // Otherwise, if it's a field, and the field doesn't have | ||||
4321 | // reference type, then it must have a complete type (or be a | ||||
4322 | // flexible array member, which we explicitly want to | ||||
4323 | // white-list anyway), which makes the following checks trivial. | ||||
4324 | if (!FD->getType()->isReferenceType()) | ||||
4325 | return false; | ||||
4326 | } | ||||
4327 | |||||
4328 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||
4329 | } | ||||
4330 | |||||
4331 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||
4332 | E = E->IgnoreParens(); | ||||
4333 | |||||
4334 | // Cannot know anything else if the expression is dependent. | ||||
4335 | if (E->isTypeDependent()) | ||||
4336 | return false; | ||||
4337 | |||||
4338 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||
4339 | } | ||||
4340 | |||||
4341 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||
4342 | CapturingScopeInfo *CSI) { | ||||
4343 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4343, __PRETTY_FUNCTION__)); | ||||
4344 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4344, __PRETTY_FUNCTION__)); | ||||
4345 | |||||
4346 | // We're going to walk down into the type and look for VLA expressions. | ||||
4347 | do { | ||||
4348 | const Type *Ty = T.getTypePtr(); | ||||
4349 | switch (Ty->getTypeClass()) { | ||||
4350 | #define TYPE(Class, Base) | ||||
4351 | #define ABSTRACT_TYPE(Class, Base) | ||||
4352 | #define NON_CANONICAL_TYPE(Class, Base) | ||||
4353 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||
4354 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||
4355 | #include "clang/AST/TypeNodes.inc" | ||||
4356 | T = QualType(); | ||||
4357 | break; | ||||
4358 | // These types are never variably-modified. | ||||
4359 | case Type::Builtin: | ||||
4360 | case Type::Complex: | ||||
4361 | case Type::Vector: | ||||
4362 | case Type::ExtVector: | ||||
4363 | case Type::ConstantMatrix: | ||||
4364 | case Type::Record: | ||||
4365 | case Type::Enum: | ||||
4366 | case Type::Elaborated: | ||||
4367 | case Type::TemplateSpecialization: | ||||
4368 | case Type::ObjCObject: | ||||
4369 | case Type::ObjCInterface: | ||||
4370 | case Type::ObjCObjectPointer: | ||||
4371 | case Type::ObjCTypeParam: | ||||
4372 | case Type::Pipe: | ||||
4373 | case Type::ExtInt: | ||||
4374 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4374); | ||||
4375 | case Type::Adjusted: | ||||
4376 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||
4377 | break; | ||||
4378 | case Type::Decayed: | ||||
4379 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||
4380 | break; | ||||
4381 | case Type::Pointer: | ||||
4382 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||
4383 | break; | ||||
4384 | case Type::BlockPointer: | ||||
4385 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||
4386 | break; | ||||
4387 | case Type::LValueReference: | ||||
4388 | case Type::RValueReference: | ||||
4389 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||
4390 | break; | ||||
4391 | case Type::MemberPointer: | ||||
4392 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||
4393 | break; | ||||
4394 | case Type::ConstantArray: | ||||
4395 | case Type::IncompleteArray: | ||||
4396 | // Losing element qualification here is fine. | ||||
4397 | T = cast<ArrayType>(Ty)->getElementType(); | ||||
4398 | break; | ||||
4399 | case Type::VariableArray: { | ||||
4400 | // Losing element qualification here is fine. | ||||
4401 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||
4402 | |||||
4403 | // Unknown size indication requires no size computation. | ||||
4404 | // Otherwise, evaluate and record it. | ||||
4405 | auto Size = VAT->getSizeExpr(); | ||||
4406 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||
4407 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||
4408 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||
4409 | |||||
4410 | T = VAT->getElementType(); | ||||
4411 | break; | ||||
4412 | } | ||||
4413 | case Type::FunctionProto: | ||||
4414 | case Type::FunctionNoProto: | ||||
4415 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||
4416 | break; | ||||
4417 | case Type::Paren: | ||||
4418 | case Type::TypeOf: | ||||
4419 | case Type::UnaryTransform: | ||||
4420 | case Type::Attributed: | ||||
4421 | case Type::SubstTemplateTypeParm: | ||||
4422 | case Type::MacroQualified: | ||||
4423 | // Keep walking after single level desugaring. | ||||
4424 | T = T.getSingleStepDesugaredType(Context); | ||||
4425 | break; | ||||
4426 | case Type::Typedef: | ||||
4427 | T = cast<TypedefType>(Ty)->desugar(); | ||||
4428 | break; | ||||
4429 | case Type::Decltype: | ||||
4430 | T = cast<DecltypeType>(Ty)->desugar(); | ||||
4431 | break; | ||||
4432 | case Type::Auto: | ||||
4433 | case Type::DeducedTemplateSpecialization: | ||||
4434 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||
4435 | break; | ||||
4436 | case Type::TypeOfExpr: | ||||
4437 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||
4438 | break; | ||||
4439 | case Type::Atomic: | ||||
4440 | T = cast<AtomicType>(Ty)->getValueType(); | ||||
4441 | break; | ||||
4442 | } | ||||
4443 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||
4444 | } | ||||
4445 | |||||
4446 | /// Build a sizeof or alignof expression given a type operand. | ||||
4447 | ExprResult | ||||
4448 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||
4449 | SourceLocation OpLoc, | ||||
4450 | UnaryExprOrTypeTrait ExprKind, | ||||
4451 | SourceRange R) { | ||||
4452 | if (!TInfo) | ||||
4453 | return ExprError(); | ||||
4454 | |||||
4455 | QualType T = TInfo->getType(); | ||||
4456 | |||||
4457 | if (!T->isDependentType() && | ||||
4458 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||
4459 | return ExprError(); | ||||
4460 | |||||
4461 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||
4462 | if (auto *TT = T->getAs<TypedefType>()) { | ||||
4463 | for (auto I = FunctionScopes.rbegin(), | ||||
4464 | E = std::prev(FunctionScopes.rend()); | ||||
4465 | I != E; ++I) { | ||||
4466 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
4467 | if (CSI == nullptr) | ||||
4468 | break; | ||||
4469 | DeclContext *DC = nullptr; | ||||
4470 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
4471 | DC = LSI->CallOperator; | ||||
4472 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
4473 | DC = CRSI->TheCapturedDecl; | ||||
4474 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
4475 | DC = BSI->TheDecl; | ||||
4476 | if (DC) { | ||||
4477 | if (DC->containsDecl(TT->getDecl())) | ||||
4478 | break; | ||||
4479 | captureVariablyModifiedType(Context, T, CSI); | ||||
4480 | } | ||||
4481 | } | ||||
4482 | } | ||||
4483 | } | ||||
4484 | |||||
4485 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4486 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4487 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||
4488 | } | ||||
4489 | |||||
4490 | /// Build a sizeof or alignof expression given an expression | ||||
4491 | /// operand. | ||||
4492 | ExprResult | ||||
4493 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||
4494 | UnaryExprOrTypeTrait ExprKind) { | ||||
4495 | ExprResult PE = CheckPlaceholderExpr(E); | ||||
4496 | if (PE.isInvalid()) | ||||
4497 | return ExprError(); | ||||
4498 | |||||
4499 | E = PE.get(); | ||||
4500 | |||||
4501 | // Verify that the operand is valid. | ||||
4502 | bool isInvalid = false; | ||||
4503 | if (E->isTypeDependent()) { | ||||
4504 | // Delay type-checking for type-dependent expressions. | ||||
4505 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4506 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||
4507 | } else if (ExprKind == UETT_VecStep) { | ||||
4508 | isInvalid = CheckVecStepExpr(E); | ||||
4509 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||
4510 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||
4511 | isInvalid = true; | ||||
4512 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||
4513 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||
4514 | isInvalid = true; | ||||
4515 | } else { | ||||
4516 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||
4517 | } | ||||
4518 | |||||
4519 | if (isInvalid) | ||||
4520 | return ExprError(); | ||||
4521 | |||||
4522 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||
4523 | PE = TransformToPotentiallyEvaluated(E); | ||||
4524 | if (PE.isInvalid()) return ExprError(); | ||||
4525 | E = PE.get(); | ||||
4526 | } | ||||
4527 | |||||
4528 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4529 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4530 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||
4531 | } | ||||
4532 | |||||
4533 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||
4534 | /// expr and the same for @c alignof and @c __alignof | ||||
4535 | /// Note that the ArgRange is invalid if isType is false. | ||||
4536 | ExprResult | ||||
4537 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||
4538 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||
4539 | void *TyOrEx, SourceRange ArgRange) { | ||||
4540 | // If error parsing type, ignore. | ||||
4541 | if (!TyOrEx) return ExprError(); | ||||
4542 | |||||
4543 | if (IsType) { | ||||
4544 | TypeSourceInfo *TInfo; | ||||
4545 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||
4546 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||
4547 | } | ||||
4548 | |||||
4549 | Expr *ArgEx = (Expr *)TyOrEx; | ||||
4550 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||
4551 | return Result; | ||||
4552 | } | ||||
4553 | |||||
4554 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||
4555 | bool IsReal) { | ||||
4556 | if (V.get()->isTypeDependent()) | ||||
4557 | return S.Context.DependentTy; | ||||
4558 | |||||
4559 | // _Real and _Imag are only l-values for normal l-values. | ||||
4560 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||
4561 | V = S.DefaultLvalueConversion(V.get()); | ||||
4562 | if (V.isInvalid()) | ||||
4563 | return QualType(); | ||||
4564 | } | ||||
4565 | |||||
4566 | // These operators return the element type of a complex type. | ||||
4567 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||
4568 | return CT->getElementType(); | ||||
4569 | |||||
4570 | // Otherwise they pass through real integer and floating point types here. | ||||
4571 | if (V.get()->getType()->isArithmeticType()) | ||||
4572 | return V.get()->getType(); | ||||
4573 | |||||
4574 | // Test for placeholders. | ||||
4575 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||
4576 | if (PR.isInvalid()) return QualType(); | ||||
4577 | if (PR.get() != V.get()) { | ||||
4578 | V = PR; | ||||
4579 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||
4580 | } | ||||
4581 | |||||
4582 | // Reject anything else. | ||||
4583 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||
4584 | << (IsReal ? "__real" : "__imag"); | ||||
4585 | return QualType(); | ||||
4586 | } | ||||
4587 | |||||
4588 | |||||
4589 | |||||
4590 | ExprResult | ||||
4591 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
4592 | tok::TokenKind Kind, Expr *Input) { | ||||
4593 | UnaryOperatorKind Opc; | ||||
4594 | switch (Kind) { | ||||
4595 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4595); | ||||
4596 | case tok::plusplus: Opc = UO_PostInc; break; | ||||
4597 | case tok::minusminus: Opc = UO_PostDec; break; | ||||
4598 | } | ||||
4599 | |||||
4600 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||
4601 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||
4602 | if (Result.isInvalid()) return ExprError(); | ||||
4603 | Input = Result.get(); | ||||
4604 | |||||
4605 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||
4606 | } | ||||
4607 | |||||
4608 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||
4609 | /// | ||||
4610 | /// \return true on error | ||||
4611 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||
4612 | SourceLocation opLoc, | ||||
4613 | Expr *op) { | ||||
4614 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4614, __PRETTY_FUNCTION__)); | ||||
4615 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||
4616 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||
4617 | return false; | ||||
4618 | |||||
4619 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||
4620 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||
4621 | << op->getSourceRange(); | ||||
4622 | return true; | ||||
4623 | } | ||||
4624 | |||||
4625 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||
4626 | auto *BaseNoParens = Base->IgnoreParens(); | ||||
4627 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||
4628 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||
4629 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||
4630 | } | ||||
4631 | |||||
4632 | ExprResult | ||||
4633 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | ||||
4634 | Expr *idx, SourceLocation rbLoc) { | ||||
4635 | if (base
| ||||
4636 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | ||||
4637 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | ||||
4638 | SourceLocation(), /*Length*/ nullptr, | ||||
4639 | /*Stride=*/nullptr, rbLoc); | ||||
4640 | |||||
4641 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
4642 | if (isa<ParenListExpr>(base)) { | ||||
4643 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||
4644 | if (result.isInvalid()) return ExprError(); | ||||
4645 | base = result.get(); | ||||
4646 | } | ||||
4647 | |||||
4648 | // Check if base and idx form a MatrixSubscriptExpr. | ||||
4649 | // | ||||
4650 | // Helper to check for comma expressions, which are not allowed as indices for | ||||
4651 | // matrix subscript expressions. | ||||
4652 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||
4653 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||
4654 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||
4655 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4656 | return true; | ||||
4657 | } | ||||
4658 | return false; | ||||
4659 | }; | ||||
4660 | // The matrix subscript operator ([][])is considered a single operator. | ||||
4661 | // Separating the index expressions by parenthesis is not allowed. | ||||
4662 | if (base->getType()->isSpecificPlaceholderType( | ||||
4663 | BuiltinType::IncompleteMatrixIdx) && | ||||
4664 | !isa<MatrixSubscriptExpr>(base)) { | ||||
4665 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||
4666 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4667 | return ExprError(); | ||||
4668 | } | ||||
4669 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||
4670 | // MatrixSubscriptExpr. | ||||
4671 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||
4672 | if (matSubscriptE
| ||||
4673 | if (CheckAndReportCommaError(idx)) | ||||
4674 | return ExprError(); | ||||
4675 | |||||
4676 | assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4677, __PRETTY_FUNCTION__)) | ||||
4677 | "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4677, __PRETTY_FUNCTION__)); | ||||
4678 | return CreateBuiltinMatrixSubscriptExpr( | ||||
4679 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | ||||
4680 | } | ||||
4681 | |||||
4682 | // Handle any non-overload placeholder types in the base and index | ||||
4683 | // expressions. We can't handle overloads here because the other | ||||
4684 | // operand might be an overloadable type, in which case the overload | ||||
4685 | // resolution for the operator overload should get the first crack | ||||
4686 | // at the overload. | ||||
4687 | bool IsMSPropertySubscript = false; | ||||
4688 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||
4689 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||
4690 | if (!IsMSPropertySubscript) { | ||||
4691 | ExprResult result = CheckPlaceholderExpr(base); | ||||
4692 | if (result.isInvalid()) | ||||
4693 | return ExprError(); | ||||
4694 | base = result.get(); | ||||
4695 | } | ||||
4696 | } | ||||
4697 | |||||
4698 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||
4699 | if (base->getType()->isMatrixType()) { | ||||
4700 | if (CheckAndReportCommaError(idx)) | ||||
4701 | return ExprError(); | ||||
4702 | |||||
4703 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | ||||
4704 | } | ||||
4705 | |||||
4706 | // A comma-expression as the index is deprecated in C++2a onwards. | ||||
4707 | if (getLangOpts().CPlusPlus20 && | ||||
4708 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||
4709 | (isa<CXXOperatorCallExpr>(idx) && | ||||
4710 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | ||||
4711 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||
4712 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4713 | } | ||||
4714 | |||||
4715 | if (idx->getType()->isNonOverloadPlaceholderType()) { | ||||
4716 | ExprResult result = CheckPlaceholderExpr(idx); | ||||
4717 | if (result.isInvalid()) return ExprError(); | ||||
4718 | idx = result.get(); | ||||
4719 | } | ||||
4720 | |||||
4721 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4722 | if (getLangOpts().CPlusPlus && | ||||
4723 | (base->isTypeDependent() || idx->isTypeDependent())) { | ||||
4724 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | ||||
4725 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4726 | } | ||||
4727 | |||||
4728 | // MSDN, property (C++) | ||||
4729 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||
4730 | // This attribute can also be used in the declaration of an empty array in a | ||||
4731 | // class or structure definition. For example: | ||||
4732 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||
4733 | // The above statement indicates that x[] can be used with one or more array | ||||
4734 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||
4735 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||
4736 | if (IsMSPropertySubscript
| ||||
4737 | // Build MS property subscript expression if base is MS property reference | ||||
4738 | // or MS property subscript. | ||||
4739 | return new (Context) MSPropertySubscriptExpr( | ||||
4740 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | ||||
4741 | } | ||||
4742 | |||||
4743 | // Use C++ overloaded-operator rules if either operand has record | ||||
4744 | // type. The spec says to do this if either type is *overloadable*, | ||||
4745 | // but enum types can't declare subscript operators or conversion | ||||
4746 | // operators, so there's nothing interesting for overload resolution | ||||
4747 | // to do if there aren't any record types involved. | ||||
4748 | // | ||||
4749 | // ObjC pointers have their own subscripting logic that is not tied | ||||
4750 | // to overload resolution and so should not take this path. | ||||
4751 | if (getLangOpts().CPlusPlus
| ||||
4752 | (base->getType()->isRecordType() || | ||||
4753 | (!base->getType()->isObjCObjectPointerType() && | ||||
4754 | idx->getType()->isRecordType()))) { | ||||
4755 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | ||||
4756 | } | ||||
4757 | |||||
4758 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | ||||
4759 | |||||
4760 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||
4761 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||
4762 | |||||
4763 | return Res; | ||||
4764 | } | ||||
4765 | |||||
4766 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||
4767 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||
4768 | InitializationKind Kind = | ||||
4769 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||
4770 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||
4771 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||
4772 | } | ||||
4773 | |||||
4774 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||
4775 | Expr *ColumnIdx, | ||||
4776 | SourceLocation RBLoc) { | ||||
4777 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||
4778 | if (BaseR.isInvalid()) | ||||
4779 | return BaseR; | ||||
4780 | Base = BaseR.get(); | ||||
4781 | |||||
4782 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||
4783 | if (RowR.isInvalid()) | ||||
4784 | return RowR; | ||||
4785 | RowIdx = RowR.get(); | ||||
4786 | |||||
4787 | if (!ColumnIdx) | ||||
4788 | return new (Context) MatrixSubscriptExpr( | ||||
4789 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||
4790 | |||||
4791 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||
4792 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||
4793 | ColumnIdx->isTypeDependent()) | ||||
4794 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4795 | Context.DependentTy, RBLoc); | ||||
4796 | |||||
4797 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||
4798 | if (ColumnR.isInvalid()) | ||||
4799 | return ColumnR; | ||||
4800 | ColumnIdx = ColumnR.get(); | ||||
4801 | |||||
4802 | // Check that IndexExpr is an integer expression. If it is a constant | ||||
4803 | // expression, check that it is less than Dim (= the number of elements in the | ||||
4804 | // corresponding dimension). | ||||
4805 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||
4806 | bool IsColumnIdx) -> Expr * { | ||||
4807 | if (!IndexExpr->getType()->isIntegerType() && | ||||
4808 | !IndexExpr->isTypeDependent()) { | ||||
4809 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||
4810 | << IsColumnIdx; | ||||
4811 | return nullptr; | ||||
4812 | } | ||||
4813 | |||||
4814 | if (Optional<llvm::APSInt> Idx = | ||||
4815 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||
4816 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||
4817 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||
4818 | << IsColumnIdx << Dim; | ||||
4819 | return nullptr; | ||||
4820 | } | ||||
4821 | } | ||||
4822 | |||||
4823 | ExprResult ConvExpr = | ||||
4824 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||
4825 | assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4826, __PRETTY_FUNCTION__)) | ||||
4826 | "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 4826, __PRETTY_FUNCTION__)); | ||||
4827 | return ConvExpr.get(); | ||||
4828 | }; | ||||
4829 | |||||
4830 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||
4831 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||
4832 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||
4833 | if (!RowIdx || !ColumnIdx) | ||||
4834 | return ExprError(); | ||||
4835 | |||||
4836 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4837 | MTy->getElementType(), RBLoc); | ||||
4838 | } | ||||
4839 | |||||
4840 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||
4841 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
4842 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||
4843 | |||||
4844 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||
4845 | // checked. | ||||
4846 | const MemberExpr *Member = nullptr; | ||||
4847 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||
4848 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||
4849 | |||||
4850 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||
4851 | } | ||||
4852 | |||||
4853 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||
4854 | if (isUnevaluatedContext()) | ||||
4855 | return; | ||||
4856 | |||||
4857 | QualType ResultTy = E->getType(); | ||||
4858 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
4859 | |||||
4860 | // Bail if the element is an array since it is not memory access. | ||||
4861 | if (isa<ArrayType>(ResultTy)) | ||||
4862 | return; | ||||
4863 | |||||
4864 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||
4865 | LastRecord.PossibleDerefs.insert(E); | ||||
4866 | return; | ||||
4867 | } | ||||
4868 | |||||
4869 | // Check if the base type is a pointer to a member access of a struct | ||||
4870 | // marked with noderef. | ||||
4871 | const Expr *Base = E->getBase(); | ||||
4872 | QualType BaseTy = Base->getType(); | ||||
4873 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||
4874 | // Not a pointer access | ||||
4875 | return; | ||||
4876 | |||||
4877 | const MemberExpr *Member = nullptr; | ||||
4878 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||
4879 | Member->isArrow()) | ||||
4880 | Base = Member->getBase(); | ||||
4881 | |||||
4882 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||
4883 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||
4884 | LastRecord.PossibleDerefs.insert(E); | ||||
4885 | } | ||||
4886 | } | ||||
4887 | |||||
4888 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||
4889 | Expr *LowerBound, | ||||
4890 | SourceLocation ColonLocFirst, | ||||
4891 | SourceLocation ColonLocSecond, | ||||
4892 | Expr *Length, Expr *Stride, | ||||
4893 | SourceLocation RBLoc) { | ||||
4894 | if (Base->getType()->isPlaceholderType() && | ||||
4895 | !Base->getType()->isSpecificPlaceholderType( | ||||
4896 | BuiltinType::OMPArraySection)) { | ||||
4897 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
4898 | if (Result.isInvalid()) | ||||
4899 | return ExprError(); | ||||
4900 | Base = Result.get(); | ||||
4901 | } | ||||
4902 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||
4903 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||
4904 | if (Result.isInvalid()) | ||||
4905 | return ExprError(); | ||||
4906 | Result = DefaultLvalueConversion(Result.get()); | ||||
4907 | if (Result.isInvalid()) | ||||
4908 | return ExprError(); | ||||
4909 | LowerBound = Result.get(); | ||||
4910 | } | ||||
4911 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||
4912 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||
4913 | if (Result.isInvalid()) | ||||
4914 | return ExprError(); | ||||
4915 | Result = DefaultLvalueConversion(Result.get()); | ||||
4916 | if (Result.isInvalid()) | ||||
4917 | return ExprError(); | ||||
4918 | Length = Result.get(); | ||||
4919 | } | ||||
4920 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||
4921 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||
4922 | if (Result.isInvalid()) | ||||
4923 | return ExprError(); | ||||
4924 | Result = DefaultLvalueConversion(Result.get()); | ||||
4925 | if (Result.isInvalid()) | ||||
4926 | return ExprError(); | ||||
4927 | Stride = Result.get(); | ||||
4928 | } | ||||
4929 | |||||
4930 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4931 | if (Base->isTypeDependent() || | ||||
4932 | (LowerBound && | ||||
4933 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||
4934 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||
4935 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||
4936 | return new (Context) OMPArraySectionExpr( | ||||
4937 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||
4938 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
4939 | } | ||||
4940 | |||||
4941 | // Perform default conversions. | ||||
4942 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||
4943 | QualType ResultTy; | ||||
4944 | if (OriginalTy->isAnyPointerType()) { | ||||
4945 | ResultTy = OriginalTy->getPointeeType(); | ||||
4946 | } else if (OriginalTy->isArrayType()) { | ||||
4947 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||
4948 | } else { | ||||
4949 | return ExprError( | ||||
4950 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||
4951 | << Base->getSourceRange()); | ||||
4952 | } | ||||
4953 | // C99 6.5.2.1p1 | ||||
4954 | if (LowerBound) { | ||||
4955 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||
4956 | LowerBound); | ||||
4957 | if (Res.isInvalid()) | ||||
4958 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||
4959 | diag::err_omp_typecheck_section_not_integer) | ||||
4960 | << 0 << LowerBound->getSourceRange()); | ||||
4961 | LowerBound = Res.get(); | ||||
4962 | |||||
4963 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
4964 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
4965 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||
4966 | << 0 << LowerBound->getSourceRange(); | ||||
4967 | } | ||||
4968 | if (Length) { | ||||
4969 | auto Res = | ||||
4970 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||
4971 | if (Res.isInvalid()) | ||||
4972 | return ExprError(Diag(Length->getExprLoc(), | ||||
4973 | diag::err_omp_typecheck_section_not_integer) | ||||
4974 | << 1 << Length->getSourceRange()); | ||||
4975 | Length = Res.get(); | ||||
4976 | |||||
4977 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
4978 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
4979 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||
4980 | << 1 << Length->getSourceRange(); | ||||
4981 | } | ||||
4982 | if (Stride) { | ||||
4983 | ExprResult Res = | ||||
4984 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||
4985 | if (Res.isInvalid()) | ||||
4986 | return ExprError(Diag(Stride->getExprLoc(), | ||||
4987 | diag::err_omp_typecheck_section_not_integer) | ||||
4988 | << 1 << Stride->getSourceRange()); | ||||
4989 | Stride = Res.get(); | ||||
4990 | |||||
4991 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
4992 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
4993 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||
4994 | << 1 << Stride->getSourceRange(); | ||||
4995 | } | ||||
4996 | |||||
4997 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
4998 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
4999 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||
5000 | // incomplete types are not object types. | ||||
5001 | if (ResultTy->isFunctionType()) { | ||||
5002 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||
5003 | << ResultTy << Base->getSourceRange(); | ||||
5004 | return ExprError(); | ||||
5005 | } | ||||
5006 | |||||
5007 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||
5008 | diag::err_omp_section_incomplete_type, Base)) | ||||
5009 | return ExprError(); | ||||
5010 | |||||
5011 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||
5012 | Expr::EvalResult Result; | ||||
5013 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||
5014 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5015 | // The array section must be a subset of the original array. | ||||
5016 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||
5017 | if (LowerBoundValue.isNegative()) { | ||||
5018 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||
5019 | << LowerBound->getSourceRange(); | ||||
5020 | return ExprError(); | ||||
5021 | } | ||||
5022 | } | ||||
5023 | } | ||||
5024 | |||||
5025 | if (Length) { | ||||
5026 | Expr::EvalResult Result; | ||||
5027 | if (Length->EvaluateAsInt(Result, Context)) { | ||||
5028 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5029 | // The length must evaluate to non-negative integers. | ||||
5030 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||
5031 | if (LengthValue.isNegative()) { | ||||
5032 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||
5033 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||
5034 | << Length->getSourceRange(); | ||||
5035 | return ExprError(); | ||||
5036 | } | ||||
5037 | } | ||||
5038 | } else if (ColonLocFirst.isValid() && | ||||
5039 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||
5040 | !OriginalTy->isVariableArrayType()))) { | ||||
5041 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5042 | // When the size of the array dimension is not known, the length must be | ||||
5043 | // specified explicitly. | ||||
5044 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||
5045 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||
5046 | return ExprError(); | ||||
5047 | } | ||||
5048 | |||||
5049 | if (Stride) { | ||||
5050 | Expr::EvalResult Result; | ||||
5051 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||
5052 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5053 | // The stride must evaluate to a positive integer. | ||||
5054 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||
5055 | if (!StrideValue.isStrictlyPositive()) { | ||||
5056 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||
5057 | << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||
5058 | << Stride->getSourceRange(); | ||||
5059 | return ExprError(); | ||||
5060 | } | ||||
5061 | } | ||||
5062 | } | ||||
5063 | |||||
5064 | if (!Base->getType()->isSpecificPlaceholderType( | ||||
5065 | BuiltinType::OMPArraySection)) { | ||||
5066 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||
5067 | if (Result.isInvalid()) | ||||
5068 | return ExprError(); | ||||
5069 | Base = Result.get(); | ||||
5070 | } | ||||
5071 | return new (Context) OMPArraySectionExpr( | ||||
5072 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||
5073 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5074 | } | ||||
5075 | |||||
5076 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||
5077 | SourceLocation RParenLoc, | ||||
5078 | ArrayRef<Expr *> Dims, | ||||
5079 | ArrayRef<SourceRange> Brackets) { | ||||
5080 | if (Base->getType()->isPlaceholderType()) { | ||||
5081 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5082 | if (Result.isInvalid()) | ||||
5083 | return ExprError(); | ||||
5084 | Result = DefaultLvalueConversion(Result.get()); | ||||
5085 | if (Result.isInvalid()) | ||||
5086 | return ExprError(); | ||||
5087 | Base = Result.get(); | ||||
5088 | } | ||||
5089 | QualType BaseTy = Base->getType(); | ||||
5090 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||
5091 | // required. | ||||
5092 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||
5093 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||
5094 | LParenLoc, RParenLoc, Dims, Brackets); | ||||
5095 | if (!BaseTy->isPointerType() || | ||||
5096 | (!Base->isTypeDependent() && | ||||
5097 | BaseTy->getPointeeType()->isIncompleteType())) | ||||
5098 | return ExprError(Diag(Base->getExprLoc(), | ||||
5099 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||
5100 | << Base->getSourceRange()); | ||||
5101 | |||||
5102 | SmallVector<Expr *, 4> NewDims; | ||||
5103 | bool ErrorFound = false; | ||||
5104 | for (Expr *Dim : Dims) { | ||||
5105 | if (Dim->getType()->isPlaceholderType()) { | ||||
5106 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||
5107 | if (Result.isInvalid()) { | ||||
5108 | ErrorFound = true; | ||||
5109 | continue; | ||||
5110 | } | ||||
5111 | Result = DefaultLvalueConversion(Result.get()); | ||||
5112 | if (Result.isInvalid()) { | ||||
5113 | ErrorFound = true; | ||||
5114 | continue; | ||||
5115 | } | ||||
5116 | Dim = Result.get(); | ||||
5117 | } | ||||
5118 | if (!Dim->isTypeDependent()) { | ||||
5119 | ExprResult Result = | ||||
5120 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||
5121 | if (Result.isInvalid()) { | ||||
5122 | ErrorFound = true; | ||||
5123 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||
5124 | << Dim->getSourceRange(); | ||||
5125 | continue; | ||||
5126 | } | ||||
5127 | Dim = Result.get(); | ||||
5128 | Expr::EvalResult EvResult; | ||||
5129 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||
5130 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||
5131 | // Each si is an integral type expression that must evaluate to a | ||||
5132 | // positive integer. | ||||
5133 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||
5134 | if (!Value.isStrictlyPositive()) { | ||||
5135 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||
5136 | << Value.toString(/*Radix=*/10, /*Signed=*/true) | ||||
5137 | << Dim->getSourceRange(); | ||||
5138 | ErrorFound = true; | ||||
5139 | continue; | ||||
5140 | } | ||||
5141 | } | ||||
5142 | } | ||||
5143 | NewDims.push_back(Dim); | ||||
5144 | } | ||||
5145 | if (ErrorFound) | ||||
5146 | return ExprError(); | ||||
5147 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||
5148 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||
5149 | } | ||||
5150 | |||||
5151 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||
5152 | SourceLocation LLoc, SourceLocation RLoc, | ||||
5153 | ArrayRef<OMPIteratorData> Data) { | ||||
5154 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||
5155 | bool IsCorrect = true; | ||||
5156 | for (const OMPIteratorData &D : Data) { | ||||
5157 | TypeSourceInfo *TInfo = nullptr; | ||||
5158 | SourceLocation StartLoc; | ||||
5159 | QualType DeclTy; | ||||
5160 | if (!D.Type.getAsOpaquePtr()) { | ||||
5161 | // OpenMP 5.0, 2.1.6 Iterators | ||||
5162 | // In an iterator-specifier, if the iterator-type is not specified then | ||||
5163 | // the type of that iterator is of int type. | ||||
5164 | DeclTy = Context.IntTy; | ||||
5165 | StartLoc = D.DeclIdentLoc; | ||||
5166 | } else { | ||||
5167 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||
5168 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
5169 | } | ||||
5170 | |||||
5171 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||
5172 | DeclTy->containsUnexpandedParameterPack() || | ||||
5173 | DeclTy->isInstantiationDependentType(); | ||||
5174 | if (!IsDeclTyDependent) { | ||||
5175 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||
5176 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5177 | // The iterator-type must be an integral or pointer type. | ||||
5178 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5179 | << DeclTy; | ||||
5180 | IsCorrect = false; | ||||
5181 | continue; | ||||
5182 | } | ||||
5183 | if (DeclTy.isConstant(Context)) { | ||||
5184 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5185 | // The iterator-type must not be const qualified. | ||||
5186 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5187 | << DeclTy; | ||||
5188 | IsCorrect = false; | ||||
5189 | continue; | ||||
5190 | } | ||||
5191 | } | ||||
5192 | |||||
5193 | // Iterator declaration. | ||||
5194 | assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast <void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5194, __PRETTY_FUNCTION__)); | ||||
5195 | // Always try to create iterator declarator to avoid extra error messages | ||||
5196 | // about unknown declarations use. | ||||
5197 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||
5198 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||
5199 | VD->setImplicit(); | ||||
5200 | if (S) { | ||||
5201 | // Check for conflicting previous declaration. | ||||
5202 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||
5203 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5204 | ForVisibleRedeclaration); | ||||
5205 | Previous.suppressDiagnostics(); | ||||
5206 | LookupName(Previous, S); | ||||
5207 | |||||
5208 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||
5209 | /*AllowInlineNamespace=*/false); | ||||
5210 | if (!Previous.empty()) { | ||||
5211 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||
5212 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||
5213 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
5214 | } else { | ||||
5215 | PushOnScopeChains(VD, S); | ||||
5216 | } | ||||
5217 | } else { | ||||
5218 | CurContext->addDecl(VD); | ||||
5219 | } | ||||
5220 | Expr *Begin = D.Range.Begin; | ||||
5221 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||
5222 | ExprResult BeginRes = | ||||
5223 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||
5224 | Begin = BeginRes.get(); | ||||
5225 | } | ||||
5226 | Expr *End = D.Range.End; | ||||
5227 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||
5228 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||
5229 | End = EndRes.get(); | ||||
5230 | } | ||||
5231 | Expr *Step = D.Range.Step; | ||||
5232 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||
5233 | if (!Step->getType()->isIntegralType(Context)) { | ||||
5234 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||
5235 | << Step << Step->getSourceRange(); | ||||
5236 | IsCorrect = false; | ||||
5237 | continue; | ||||
5238 | } | ||||
5239 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||
5240 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||
5241 | // If the step expression of a range-specification equals zero, the | ||||
5242 | // behavior is unspecified. | ||||
5243 | if (Result && Result->isNullValue()) { | ||||
5244 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||
5245 | << Step << Step->getSourceRange(); | ||||
5246 | IsCorrect = false; | ||||
5247 | continue; | ||||
5248 | } | ||||
5249 | } | ||||
5250 | if (!Begin || !End || !IsCorrect) { | ||||
5251 | IsCorrect = false; | ||||
5252 | continue; | ||||
5253 | } | ||||
5254 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||
5255 | IDElem.IteratorDecl = VD; | ||||
5256 | IDElem.AssignmentLoc = D.AssignLoc; | ||||
5257 | IDElem.Range.Begin = Begin; | ||||
5258 | IDElem.Range.End = End; | ||||
5259 | IDElem.Range.Step = Step; | ||||
5260 | IDElem.ColonLoc = D.ColonLoc; | ||||
5261 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||
5262 | } | ||||
5263 | if (!IsCorrect) { | ||||
5264 | // Invalidate all created iterator declarations if error is found. | ||||
5265 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5266 | if (Decl *ID = D.IteratorDecl) | ||||
5267 | ID->setInvalidDecl(); | ||||
5268 | } | ||||
5269 | return ExprError(); | ||||
5270 | } | ||||
5271 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||
5272 | if (!CurContext->isDependentContext()) { | ||||
5273 | // Build number of ityeration for each iteration range. | ||||
5274 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||
5275 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||
5276 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5277 | // (Endi - Begini) | ||||
5278 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||
5279 | D.Range.Begin); | ||||
5280 | if(!Res.isUsable()) { | ||||
5281 | IsCorrect = false; | ||||
5282 | continue; | ||||
5283 | } | ||||
5284 | ExprResult St, St1; | ||||
5285 | if (D.Range.Step) { | ||||
5286 | St = D.Range.Step; | ||||
5287 | // (Endi - Begini) + Stepi | ||||
5288 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||
5289 | if (!Res.isUsable()) { | ||||
5290 | IsCorrect = false; | ||||
5291 | continue; | ||||
5292 | } | ||||
5293 | // (Endi - Begini) + Stepi - 1 | ||||
5294 | Res = | ||||
5295 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||
5296 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5297 | if (!Res.isUsable()) { | ||||
5298 | IsCorrect = false; | ||||
5299 | continue; | ||||
5300 | } | ||||
5301 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||
5302 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||
5303 | if (!Res.isUsable()) { | ||||
5304 | IsCorrect = false; | ||||
5305 | continue; | ||||
5306 | } | ||||
5307 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||
5308 | // (Begini - Endi) | ||||
5309 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||
5310 | D.Range.Begin, D.Range.End); | ||||
5311 | if (!Res1.isUsable()) { | ||||
5312 | IsCorrect = false; | ||||
5313 | continue; | ||||
5314 | } | ||||
5315 | // (Begini - Endi) - Stepi | ||||
5316 | Res1 = | ||||
5317 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||
5318 | if (!Res1.isUsable()) { | ||||
5319 | IsCorrect = false; | ||||
5320 | continue; | ||||
5321 | } | ||||
5322 | // (Begini - Endi) - Stepi - 1 | ||||
5323 | Res1 = | ||||
5324 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||
5325 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5326 | if (!Res1.isUsable()) { | ||||
5327 | IsCorrect = false; | ||||
5328 | continue; | ||||
5329 | } | ||||
5330 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||
5331 | Res1 = | ||||
5332 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||
5333 | if (!Res1.isUsable()) { | ||||
5334 | IsCorrect = false; | ||||
5335 | continue; | ||||
5336 | } | ||||
5337 | // Stepi > 0. | ||||
5338 | ExprResult CmpRes = | ||||
5339 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||
5340 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||
5341 | if (!CmpRes.isUsable()) { | ||||
5342 | IsCorrect = false; | ||||
5343 | continue; | ||||
5344 | } | ||||
5345 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||
5346 | Res.get(), Res1.get()); | ||||
5347 | if (!Res.isUsable()) { | ||||
5348 | IsCorrect = false; | ||||
5349 | continue; | ||||
5350 | } | ||||
5351 | } | ||||
5352 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||
5353 | if (!Res.isUsable()) { | ||||
5354 | IsCorrect = false; | ||||
5355 | continue; | ||||
5356 | } | ||||
5357 | |||||
5358 | // Build counter update. | ||||
5359 | // Build counter. | ||||
5360 | auto *CounterVD = | ||||
5361 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||
5362 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||
5363 | Res.get()->getType(), nullptr, SC_None); | ||||
5364 | CounterVD->setImplicit(); | ||||
5365 | ExprResult RefRes = | ||||
5366 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||
5367 | D.IteratorDecl->getBeginLoc()); | ||||
5368 | // Build counter update. | ||||
5369 | // I = Begini + counter * Stepi; | ||||
5370 | ExprResult UpdateRes; | ||||
5371 | if (D.Range.Step) { | ||||
5372 | UpdateRes = CreateBuiltinBinOp( | ||||
5373 | D.AssignmentLoc, BO_Mul, | ||||
5374 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||
5375 | } else { | ||||
5376 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||
5377 | } | ||||
5378 | if (!UpdateRes.isUsable()) { | ||||
5379 | IsCorrect = false; | ||||
5380 | continue; | ||||
5381 | } | ||||
5382 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||
5383 | UpdateRes.get()); | ||||
5384 | if (!UpdateRes.isUsable()) { | ||||
5385 | IsCorrect = false; | ||||
5386 | continue; | ||||
5387 | } | ||||
5388 | ExprResult VDRes = | ||||
5389 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||
5390 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||
5391 | D.IteratorDecl->getBeginLoc()); | ||||
5392 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||
5393 | UpdateRes.get()); | ||||
5394 | if (!UpdateRes.isUsable()) { | ||||
5395 | IsCorrect = false; | ||||
5396 | continue; | ||||
5397 | } | ||||
5398 | UpdateRes = | ||||
5399 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||
5400 | if (!UpdateRes.isUsable()) { | ||||
5401 | IsCorrect = false; | ||||
5402 | continue; | ||||
5403 | } | ||||
5404 | ExprResult CounterUpdateRes = | ||||
5405 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||
5406 | if (!CounterUpdateRes.isUsable()) { | ||||
5407 | IsCorrect = false; | ||||
5408 | continue; | ||||
5409 | } | ||||
5410 | CounterUpdateRes = | ||||
5411 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||
5412 | if (!CounterUpdateRes.isUsable()) { | ||||
5413 | IsCorrect = false; | ||||
5414 | continue; | ||||
5415 | } | ||||
5416 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||
5417 | HD.CounterVD = CounterVD; | ||||
5418 | HD.Upper = Res.get(); | ||||
5419 | HD.Update = UpdateRes.get(); | ||||
5420 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||
5421 | } | ||||
5422 | } else { | ||||
5423 | Helpers.assign(ID.size(), {}); | ||||
5424 | } | ||||
5425 | if (!IsCorrect) { | ||||
5426 | // Invalidate all created iterator declarations if error is found. | ||||
5427 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5428 | if (Decl *ID = D.IteratorDecl) | ||||
5429 | ID->setInvalidDecl(); | ||||
5430 | } | ||||
5431 | return ExprError(); | ||||
5432 | } | ||||
5433 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||
5434 | LLoc, RLoc, ID, Helpers); | ||||
5435 | } | ||||
5436 | |||||
5437 | ExprResult | ||||
5438 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||
5439 | Expr *Idx, SourceLocation RLoc) { | ||||
5440 | Expr *LHSExp = Base; | ||||
5441 | Expr *RHSExp = Idx; | ||||
5442 | |||||
5443 | ExprValueKind VK = VK_LValue; | ||||
5444 | ExprObjectKind OK = OK_Ordinary; | ||||
5445 | |||||
5446 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||
5447 | // a non-lvalue array, and an lvalue otherwise. | ||||
5448 | if (getLangOpts().CPlusPlus11) { | ||||
5449 | for (auto *Op : {LHSExp, RHSExp}) { | ||||
5450 | Op = Op->IgnoreImplicit(); | ||||
5451 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||
5452 | VK = VK_XValue; | ||||
5453 | } | ||||
5454 | } | ||||
5455 | |||||
5456 | // Perform default conversions. | ||||
5457 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||
5458 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||
5459 | if (Result.isInvalid()) | ||||
5460 | return ExprError(); | ||||
5461 | LHSExp = Result.get(); | ||||
5462 | } | ||||
5463 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||
5464 | if (Result.isInvalid()) | ||||
5465 | return ExprError(); | ||||
5466 | RHSExp = Result.get(); | ||||
5467 | |||||
5468 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||
5469 | |||||
5470 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||
5471 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||
5472 | // in the subscript position. As a result, we need to derive the array base | ||||
5473 | // and index from the expression types. | ||||
5474 | Expr *BaseExpr, *IndexExpr; | ||||
5475 | QualType ResultType; | ||||
5476 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||
5477 | BaseExpr = LHSExp; | ||||
5478 | IndexExpr = RHSExp; | ||||
5479 | ResultType = Context.DependentTy; | ||||
5480 | } else if (const PointerType *PTy
| ||||
5481 | BaseExpr = LHSExp; | ||||
5482 | IndexExpr = RHSExp; | ||||
5483 | ResultType = PTy->getPointeeType(); | ||||
5484 | } else if (const ObjCObjectPointerType *PTy
| ||||
5485 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5486 | BaseExpr = LHSExp; | ||||
5487 | IndexExpr = RHSExp; | ||||
5488 | |||||
5489 | // Use custom logic if this should be the pseudo-object subscript | ||||
5490 | // expression. | ||||
5491 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||
5492 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||
5493 | nullptr); | ||||
5494 | |||||
5495 | ResultType = PTy->getPointeeType(); | ||||
5496 | } else if (const PointerType *PTy
| ||||
5497 | // Handle the uncommon case of "123[Ptr]". | ||||
5498 | BaseExpr = RHSExp; | ||||
5499 | IndexExpr = LHSExp; | ||||
5500 | ResultType = PTy->getPointeeType(); | ||||
5501 | } else if (const ObjCObjectPointerType *PTy
| ||||
5502 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5503 | // Handle the uncommon case of "123[Ptr]". | ||||
5504 | BaseExpr = RHSExp; | ||||
5505 | IndexExpr = LHSExp; | ||||
5506 | ResultType = PTy->getPointeeType(); | ||||
5507 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||
5508 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||
5509 | << ResultType << BaseExpr->getSourceRange(); | ||||
5510 | return ExprError(); | ||||
5511 | } | ||||
5512 | } else if (const VectorType *VTy
| ||||
5513 | BaseExpr = LHSExp; // vectors: V[123] | ||||
5514 | IndexExpr = RHSExp; | ||||
5515 | // We apply C++ DR1213 to vector subscripting too. | ||||
5516 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | ||||
5517 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5518 | if (Materialized.isInvalid()) | ||||
5519 | return ExprError(); | ||||
5520 | LHSExp = Materialized.get(); | ||||
5521 | } | ||||
5522 | VK = LHSExp->getValueKind(); | ||||
5523 | if (VK != VK_RValue) | ||||
5524 | OK = OK_VectorComponent; | ||||
5525 | |||||
5526 | ResultType = VTy->getElementType(); | ||||
5527 | QualType BaseType = BaseExpr->getType(); | ||||
5528 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5529 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5530 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5531 | if (Combined != MemberQuals) | ||||
5532 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5533 | } else if (LHSTy->isArrayType()) { | ||||
5534 | // If we see an array that wasn't promoted by | ||||
5535 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||
5536 | // wasn't promoted because of the C90 rule that doesn't | ||||
5537 | // allow promoting non-lvalue arrays. Warn, then | ||||
5538 | // force the promotion here. | ||||
5539 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5540 | << LHSExp->getSourceRange(); | ||||
5541 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||
5542 | CK_ArrayToPointerDecay).get(); | ||||
5543 | LHSTy = LHSExp->getType(); | ||||
5544 | |||||
5545 | BaseExpr = LHSExp; | ||||
5546 | IndexExpr = RHSExp; | ||||
5547 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | ||||
| |||||
5548 | } else if (RHSTy->isArrayType()) { | ||||
5549 | // Same as previous, except for 123[f().a] case | ||||
5550 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5551 | << RHSExp->getSourceRange(); | ||||
5552 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||
5553 | CK_ArrayToPointerDecay).get(); | ||||
5554 | RHSTy = RHSExp->getType(); | ||||
5555 | |||||
5556 | BaseExpr = RHSExp; | ||||
5557 | IndexExpr = LHSExp; | ||||
5558 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | ||||
5559 | } else { | ||||
5560 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||
5561 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5562 | } | ||||
5563 | // C99 6.5.2.1p1 | ||||
5564 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||
5565 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||
5566 | << IndexExpr->getSourceRange()); | ||||
5567 | |||||
5568 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5569 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5570 | && !IndexExpr->isTypeDependent()) | ||||
5571 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||
5572 | |||||
5573 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5574 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5575 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||
5576 | // incomplete types are not object types. | ||||
5577 | if (ResultType->isFunctionType()) { | ||||
5578 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||
5579 | << ResultType << BaseExpr->getSourceRange(); | ||||
5580 | return ExprError(); | ||||
5581 | } | ||||
5582 | |||||
5583 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||
5584 | // GNU extension: subscripting on pointer to void | ||||
5585 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||
5586 | << BaseExpr->getSourceRange(); | ||||
5587 | |||||
5588 | // C forbids expressions of unqualified void type from being l-values. | ||||
5589 | // See IsCForbiddenLValueType. | ||||
5590 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | ||||
5591 | } else if (!ResultType->isDependentType() && | ||||
5592 | RequireCompleteSizedType( | ||||
5593 | LLoc, ResultType, | ||||
5594 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||
5595 | return ExprError(); | ||||
5596 | |||||
5597 | assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5598, __PRETTY_FUNCTION__)) | ||||
5598 | !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5598, __PRETTY_FUNCTION__)); | ||||
5599 | |||||
5600 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||
5601 | FunctionScopes.size() > 1) { | ||||
5602 | if (auto *TT = | ||||
5603 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||
5604 | for (auto I = FunctionScopes.rbegin(), | ||||
5605 | E = std::prev(FunctionScopes.rend()); | ||||
5606 | I != E; ++I) { | ||||
5607 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
5608 | if (CSI == nullptr) | ||||
5609 | break; | ||||
5610 | DeclContext *DC = nullptr; | ||||
5611 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
5612 | DC = LSI->CallOperator; | ||||
5613 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
5614 | DC = CRSI->TheCapturedDecl; | ||||
5615 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
5616 | DC = BSI->TheDecl; | ||||
5617 | if (DC) { | ||||
5618 | if (DC->containsDecl(TT->getDecl())) | ||||
5619 | break; | ||||
5620 | captureVariablyModifiedType( | ||||
5621 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||
5622 | } | ||||
5623 | } | ||||
5624 | } | ||||
5625 | } | ||||
5626 | |||||
5627 | return new (Context) | ||||
5628 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||
5629 | } | ||||
5630 | |||||
5631 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||
5632 | ParmVarDecl *Param) { | ||||
5633 | if (Param->hasUnparsedDefaultArg()) { | ||||
5634 | // If we've already cleared out the location for the default argument, | ||||
5635 | // that means we're parsing it right now. | ||||
5636 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||
5637 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||
5638 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||
5639 | Param->setInvalidDecl(); | ||||
5640 | return true; | ||||
5641 | } | ||||
5642 | |||||
5643 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||
5644 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||
5645 | Diag(UnparsedDefaultArgLocs[Param], | ||||
5646 | diag::note_default_argument_declared_here); | ||||
5647 | return true; | ||||
5648 | } | ||||
5649 | |||||
5650 | if (Param->hasUninstantiatedDefaultArg() && | ||||
5651 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||
5652 | return true; | ||||
5653 | |||||
5654 | assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?" ) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5654, __PRETTY_FUNCTION__)); | ||||
5655 | |||||
5656 | // If the default expression creates temporaries, we need to | ||||
5657 | // push them to the current stack of expression temporaries so they'll | ||||
5658 | // be properly destroyed. | ||||
5659 | // FIXME: We should really be rebuilding the default argument with new | ||||
5660 | // bound temporaries; see the comment in PR5810. | ||||
5661 | // We don't need to do that with block decls, though, because | ||||
5662 | // blocks in default argument expression can never capture anything. | ||||
5663 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||
5664 | // Set the "needs cleanups" bit regardless of whether there are | ||||
5665 | // any explicit objects. | ||||
5666 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||
5667 | |||||
5668 | // Append all the objects to the cleanup list. Right now, this | ||||
5669 | // should always be a no-op, because blocks in default argument | ||||
5670 | // expressions should never be able to capture anything. | ||||
5671 | assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5672, __PRETTY_FUNCTION__)) | ||||
5672 | "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5672, __PRETTY_FUNCTION__)); | ||||
5673 | } | ||||
5674 | |||||
5675 | // We already type-checked the argument, so we know it works. | ||||
5676 | // Just mark all of the declarations in this potentially-evaluated expression | ||||
5677 | // as being "referenced". | ||||
5678 | EnterExpressionEvaluationContext EvalContext( | ||||
5679 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||
5680 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||
5681 | /*SkipLocalVariables=*/true); | ||||
5682 | return false; | ||||
5683 | } | ||||
5684 | |||||
5685 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||
5686 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||
5687 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg" ) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5687, __PRETTY_FUNCTION__)); | ||||
5688 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||
5689 | return ExprError(); | ||||
5690 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||
5691 | } | ||||
5692 | |||||
5693 | Sema::VariadicCallType | ||||
5694 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||
5695 | Expr *Fn) { | ||||
5696 | if (Proto && Proto->isVariadic()) { | ||||
5697 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | ||||
5698 | return VariadicConstructor; | ||||
5699 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||
5700 | return VariadicBlock; | ||||
5701 | else if (FDecl) { | ||||
5702 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
5703 | if (Method->isInstance()) | ||||
5704 | return VariadicMethod; | ||||
5705 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||
5706 | return VariadicMethod; | ||||
5707 | return VariadicFunction; | ||||
5708 | } | ||||
5709 | return VariadicDoesNotApply; | ||||
5710 | } | ||||
5711 | |||||
5712 | namespace { | ||||
5713 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||
5714 | public: | ||||
5715 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||
5716 | unsigned NumArgs, MemberExpr *ME) | ||||
5717 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||
5718 | FunctionName(FuncName) {} | ||||
5719 | |||||
5720 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
5721 | if (!candidate.getCorrectionSpecifier() || | ||||
5722 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||
5723 | return false; | ||||
5724 | } | ||||
5725 | |||||
5726 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||
5727 | } | ||||
5728 | |||||
5729 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
5730 | return std::make_unique<FunctionCallCCC>(*this); | ||||
5731 | } | ||||
5732 | |||||
5733 | private: | ||||
5734 | const IdentifierInfo *const FunctionName; | ||||
5735 | }; | ||||
5736 | } | ||||
5737 | |||||
5738 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||
5739 | FunctionDecl *FDecl, | ||||
5740 | ArrayRef<Expr *> Args) { | ||||
5741 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||
5742 | DeclarationName FuncName = FDecl->getDeclName(); | ||||
5743 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||
5744 | |||||
5745 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||
5746 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||
5747 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||
5748 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||
5749 | Sema::CTK_ErrorRecovery)) { | ||||
5750 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||
5751 | if (Corrected.isOverloaded()) { | ||||
5752 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||
5753 | OverloadCandidateSet::iterator Best; | ||||
5754 | for (NamedDecl *CD : Corrected) { | ||||
5755 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
5756 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||
5757 | OCS); | ||||
5758 | } | ||||
5759 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||
5760 | case OR_Success: | ||||
5761 | ND = Best->FoundDecl; | ||||
5762 | Corrected.setCorrectionDecl(ND); | ||||
5763 | break; | ||||
5764 | default: | ||||
5765 | break; | ||||
5766 | } | ||||
5767 | } | ||||
5768 | ND = ND->getUnderlyingDecl(); | ||||
5769 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||
5770 | return Corrected; | ||||
5771 | } | ||||
5772 | } | ||||
5773 | return TypoCorrection(); | ||||
5774 | } | ||||
5775 | |||||
5776 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||
5777 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||
5778 | /// function prototype Proto. Call is the call expression itself, and | ||||
5779 | /// Fn is the function expression. For a C++ member function, this | ||||
5780 | /// routine does not attempt to convert the object argument. Returns | ||||
5781 | /// true if the call is ill-formed. | ||||
5782 | bool | ||||
5783 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||
5784 | FunctionDecl *FDecl, | ||||
5785 | const FunctionProtoType *Proto, | ||||
5786 | ArrayRef<Expr *> Args, | ||||
5787 | SourceLocation RParenLoc, | ||||
5788 | bool IsExecConfig) { | ||||
5789 | // Bail out early if calling a builtin with custom typechecking. | ||||
5790 | if (FDecl) | ||||
5791 | if (unsigned ID = FDecl->getBuiltinID()) | ||||
5792 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||
5793 | return false; | ||||
5794 | |||||
5795 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||
5796 | // assignment, to the types of the corresponding parameter, ... | ||||
5797 | unsigned NumParams = Proto->getNumParams(); | ||||
5798 | bool Invalid = false; | ||||
5799 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||
5800 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||
5801 | ? 1 /* block */ | ||||
5802 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||
5803 | : 0 /* function */); | ||||
5804 | |||||
5805 | // If too few arguments are available (and we don't have default | ||||
5806 | // arguments for the remaining parameters), don't make the call. | ||||
5807 | if (Args.size() < NumParams) { | ||||
5808 | if (Args.size() < MinArgs) { | ||||
5809 | TypoCorrection TC; | ||||
5810 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
5811 | unsigned diag_id = | ||||
5812 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5813 | ? diag::err_typecheck_call_too_few_args_suggest | ||||
5814 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||
5815 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||
5816 | << static_cast<unsigned>(Args.size()) | ||||
5817 | << TC.getCorrectionRange()); | ||||
5818 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||
5819 | Diag(RParenLoc, | ||||
5820 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5821 | ? diag::err_typecheck_call_too_few_args_one | ||||
5822 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||
5823 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||
5824 | else | ||||
5825 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||
5826 | ? diag::err_typecheck_call_too_few_args | ||||
5827 | : diag::err_typecheck_call_too_few_args_at_least) | ||||
5828 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||
5829 | << Fn->getSourceRange(); | ||||
5830 | |||||
5831 | // Emit the location of the prototype. | ||||
5832 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
5833 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
5834 | |||||
5835 | return true; | ||||
5836 | } | ||||
5837 | // We reserve space for the default arguments when we create | ||||
5838 | // the call expression, before calling ConvertArgumentsForCall. | ||||
5839 | assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5840, __PRETTY_FUNCTION__)) | ||||
5840 | "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5840, __PRETTY_FUNCTION__)); | ||||
5841 | } | ||||
5842 | |||||
5843 | // If too many are passed and not variadic, error on the extras and drop | ||||
5844 | // them. | ||||
5845 | if (Args.size() > NumParams) { | ||||
5846 | if (!Proto->isVariadic()) { | ||||
5847 | TypoCorrection TC; | ||||
5848 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
5849 | unsigned diag_id = | ||||
5850 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5851 | ? diag::err_typecheck_call_too_many_args_suggest | ||||
5852 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||
5853 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||
5854 | << static_cast<unsigned>(Args.size()) | ||||
5855 | << TC.getCorrectionRange()); | ||||
5856 | } else if (NumParams == 1 && FDecl && | ||||
5857 | FDecl->getParamDecl(0)->getDeclName()) | ||||
5858 | Diag(Args[NumParams]->getBeginLoc(), | ||||
5859 | MinArgs == NumParams | ||||
5860 | ? diag::err_typecheck_call_too_many_args_one | ||||
5861 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||
5862 | << FnKind << FDecl->getParamDecl(0) | ||||
5863 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||
5864 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
5865 | Args.back()->getEndLoc()); | ||||
5866 | else | ||||
5867 | Diag(Args[NumParams]->getBeginLoc(), | ||||
5868 | MinArgs == NumParams | ||||
5869 | ? diag::err_typecheck_call_too_many_args | ||||
5870 | : diag::err_typecheck_call_too_many_args_at_most) | ||||
5871 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||
5872 | << Fn->getSourceRange() | ||||
5873 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
5874 | Args.back()->getEndLoc()); | ||||
5875 | |||||
5876 | // Emit the location of the prototype. | ||||
5877 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
5878 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
5879 | |||||
5880 | // This deletes the extra arguments. | ||||
5881 | Call->shrinkNumArgs(NumParams); | ||||
5882 | return true; | ||||
5883 | } | ||||
5884 | } | ||||
5885 | SmallVector<Expr *, 8> AllArgs; | ||||
5886 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||
5887 | |||||
5888 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||
5889 | AllArgs, CallType); | ||||
5890 | if (Invalid) | ||||
5891 | return true; | ||||
5892 | unsigned TotalNumArgs = AllArgs.size(); | ||||
5893 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||
5894 | Call->setArg(i, AllArgs[i]); | ||||
5895 | |||||
5896 | return false; | ||||
5897 | } | ||||
5898 | |||||
5899 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||
5900 | const FunctionProtoType *Proto, | ||||
5901 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||
5902 | SmallVectorImpl<Expr *> &AllArgs, | ||||
5903 | VariadicCallType CallType, bool AllowExplicit, | ||||
5904 | bool IsListInitialization) { | ||||
5905 | unsigned NumParams = Proto->getNumParams(); | ||||
5906 | bool Invalid = false; | ||||
5907 | size_t ArgIx = 0; | ||||
5908 | // Continue to check argument types (even if we have too few/many args). | ||||
5909 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||
5910 | QualType ProtoArgType = Proto->getParamType(i); | ||||
5911 | |||||
5912 | Expr *Arg; | ||||
5913 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||
5914 | if (ArgIx < Args.size()) { | ||||
5915 | Arg = Args[ArgIx++]; | ||||
5916 | |||||
5917 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||
5918 | diag::err_call_incomplete_argument, Arg)) | ||||
5919 | return true; | ||||
5920 | |||||
5921 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
5922 | bool CFAudited = false; | ||||
5923 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||
5924 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
5925 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
5926 | Arg = stripARCUnbridgedCast(Arg); | ||||
5927 | else if (getLangOpts().ObjCAutoRefCount && | ||||
5928 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
5929 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
5930 | CFAudited = true; | ||||
5931 | |||||
5932 | if (Proto->getExtParameterInfo(i).isNoEscape()) | ||||
5933 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||
5934 | BE->getBlockDecl()->setDoesNotEscape(); | ||||
5935 | |||||
5936 | InitializedEntity Entity = | ||||
5937 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||
5938 | ProtoArgType) | ||||
5939 | : InitializedEntity::InitializeParameter( | ||||
5940 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||
5941 | |||||
5942 | // Remember that parameter belongs to a CF audited API. | ||||
5943 | if (CFAudited) | ||||
5944 | Entity.setParameterCFAudited(); | ||||
5945 | |||||
5946 | ExprResult ArgE = PerformCopyInitialization( | ||||
5947 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||
5948 | if (ArgE.isInvalid()) | ||||
5949 | return true; | ||||
5950 | |||||
5951 | Arg = ArgE.getAs<Expr>(); | ||||
5952 | } else { | ||||
5953 | assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee" ) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 5953, __PRETTY_FUNCTION__)); | ||||
5954 | |||||
5955 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||
5956 | if (ArgExpr.isInvalid()) | ||||
5957 | return true; | ||||
5958 | |||||
5959 | Arg = ArgExpr.getAs<Expr>(); | ||||
5960 | } | ||||
5961 | |||||
5962 | // Check for array bounds violations for each argument to the call. This | ||||
5963 | // check only triggers warnings when the argument isn't a more complex Expr | ||||
5964 | // with its own checking, such as a BinaryOperator. | ||||
5965 | CheckArrayAccess(Arg); | ||||
5966 | |||||
5967 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||
5968 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||
5969 | |||||
5970 | AllArgs.push_back(Arg); | ||||
5971 | } | ||||
5972 | |||||
5973 | // If this is a variadic call, handle args passed through "...". | ||||
5974 | if (CallType != VariadicDoesNotApply) { | ||||
5975 | // Assume that extern "C" functions with variadic arguments that | ||||
5976 | // return __unknown_anytype aren't *really* variadic. | ||||
5977 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||
5978 | FDecl->isExternC()) { | ||||
5979 | for (Expr *A : Args.slice(ArgIx)) { | ||||
5980 | QualType paramType; // ignored | ||||
5981 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | ||||
5982 | Invalid |= arg.isInvalid(); | ||||
5983 | AllArgs.push_back(arg.get()); | ||||
5984 | } | ||||
5985 | |||||
5986 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | ||||
5987 | } else { | ||||
5988 | for (Expr *A : Args.slice(ArgIx)) { | ||||
5989 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | ||||
5990 | Invalid |= Arg.isInvalid(); | ||||
5991 | AllArgs.push_back(Arg.get()); | ||||
5992 | } | ||||
5993 | } | ||||
5994 | |||||
5995 | // Check for array bounds violations. | ||||
5996 | for (Expr *A : Args.slice(ArgIx)) | ||||
5997 | CheckArrayAccess(A); | ||||
5998 | } | ||||
5999 | return Invalid; | ||||
6000 | } | ||||
6001 | |||||
6002 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | ||||
6003 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | ||||
6004 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | ||||
6005 | TL = DTL.getOriginalLoc(); | ||||
6006 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | ||||
6007 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | ||||
6008 | << ATL.getLocalSourceRange(); | ||||
6009 | } | ||||
6010 | |||||
6011 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | ||||
6012 | /// array parameter, check that it is non-null, and that if it is formed by | ||||
6013 | /// array-to-pointer decay, the underlying array is sufficiently large. | ||||
6014 | /// | ||||
6015 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | ||||
6016 | /// array type derivation, then for each call to the function, the value of the | ||||
6017 | /// corresponding actual argument shall provide access to the first element of | ||||
6018 | /// an array with at least as many elements as specified by the size expression. | ||||
6019 | void | ||||
6020 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | ||||
6021 | ParmVarDecl *Param, | ||||
6022 | const Expr *ArgExpr) { | ||||
6023 | // Static array parameters are not supported in C++. | ||||
6024 | if (!Param || getLangOpts().CPlusPlus) | ||||
6025 | return; | ||||
6026 | |||||
6027 | QualType OrigTy = Param->getOriginalType(); | ||||
6028 | |||||
6029 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | ||||
6030 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | ||||
6031 | return; | ||||
6032 | |||||
6033 | if (ArgExpr->isNullPointerConstant(Context, | ||||
6034 | Expr::NPC_NeverValueDependent)) { | ||||
6035 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | ||||
6036 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6037 | return; | ||||
6038 | } | ||||
6039 | |||||
6040 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | ||||
6041 | if (!CAT) | ||||
6042 | return; | ||||
6043 | |||||
6044 | const ConstantArrayType *ArgCAT = | ||||
6045 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | ||||
6046 | if (!ArgCAT) | ||||
6047 | return; | ||||
6048 | |||||
6049 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | ||||
6050 | ArgCAT->getElementType())) { | ||||
6051 | if (ArgCAT->getSize().ult(CAT->getSize())) { | ||||
6052 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6053 | << ArgExpr->getSourceRange() | ||||
6054 | << (unsigned)ArgCAT->getSize().getZExtValue() | ||||
6055 | << (unsigned)CAT->getSize().getZExtValue() << 0; | ||||
6056 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6057 | } | ||||
6058 | return; | ||||
6059 | } | ||||
6060 | |||||
6061 | Optional<CharUnits> ArgSize = | ||||
6062 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | ||||
6063 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | ||||
6064 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | ||||
6065 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6066 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | ||||
6067 | << (unsigned)ParmSize->getQuantity() << 1; | ||||
6068 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6069 | } | ||||
6070 | } | ||||
6071 | |||||
6072 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
6073 | /// to have a function type. | ||||
6074 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | ||||
6075 | |||||
6076 | /// Is the given type a placeholder that we need to lower out | ||||
6077 | /// immediately during argument processing? | ||||
6078 | static bool isPlaceholderToRemoveAsArg(QualType type) { | ||||
6079 | // Placeholders are never sugared. | ||||
6080 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | ||||
6081 | if (!placeholder) return false; | ||||
6082 | |||||
6083 | switch (placeholder->getKind()) { | ||||
6084 | // Ignore all the non-placeholder types. | ||||
6085 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
6086 | case BuiltinType::Id: | ||||
6087 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
6088 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
6089 | case BuiltinType::Id: | ||||
6090 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
6091 | // In practice we'll never use this, since all SVE types are sugared | ||||
6092 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | ||||
6093 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
6094 | case BuiltinType::Id: | ||||
6095 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
6096 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
6097 | case BuiltinType::Id: | ||||
6098 | #include "clang/Basic/PPCTypes.def" | ||||
6099 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
6100 | #include "clang/Basic/RISCVVTypes.def" | ||||
6101 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | ||||
6102 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | ||||
6103 | #include "clang/AST/BuiltinTypes.def" | ||||
6104 | return false; | ||||
6105 | |||||
6106 | // We cannot lower out overload sets; they might validly be resolved | ||||
6107 | // by the call machinery. | ||||
6108 | case BuiltinType::Overload: | ||||
6109 | return false; | ||||
6110 | |||||
6111 | // Unbridged casts in ARC can be handled in some call positions and | ||||
6112 | // should be left in place. | ||||
6113 | case BuiltinType::ARCUnbridgedCast: | ||||
6114 | return false; | ||||
6115 | |||||
6116 | // Pseudo-objects should be converted as soon as possible. | ||||
6117 | case BuiltinType::PseudoObject: | ||||
6118 | return true; | ||||
6119 | |||||
6120 | // The debugger mode could theoretically but currently does not try | ||||
6121 | // to resolve unknown-typed arguments based on known parameter types. | ||||
6122 | case BuiltinType::UnknownAny: | ||||
6123 | return true; | ||||
6124 | |||||
6125 | // These are always invalid as call arguments and should be reported. | ||||
6126 | case BuiltinType::BoundMember: | ||||
6127 | case BuiltinType::BuiltinFn: | ||||
6128 | case BuiltinType::IncompleteMatrixIdx: | ||||
6129 | case BuiltinType::OMPArraySection: | ||||
6130 | case BuiltinType::OMPArrayShaping: | ||||
6131 | case BuiltinType::OMPIterator: | ||||
6132 | return true; | ||||
6133 | |||||
6134 | } | ||||
6135 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6135); | ||||
6136 | } | ||||
6137 | |||||
6138 | /// Check an argument list for placeholders that we won't try to | ||||
6139 | /// handle later. | ||||
6140 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | ||||
6141 | // Apply this processing to all the arguments at once instead of | ||||
6142 | // dying at the first failure. | ||||
6143 | bool hasInvalid = false; | ||||
6144 | for (size_t i = 0, e = args.size(); i != e; i++) { | ||||
6145 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | ||||
6146 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | ||||
6147 | if (result.isInvalid()) hasInvalid = true; | ||||
6148 | else args[i] = result.get(); | ||||
6149 | } | ||||
6150 | } | ||||
6151 | return hasInvalid; | ||||
6152 | } | ||||
6153 | |||||
6154 | /// If a builtin function has a pointer argument with no explicit address | ||||
6155 | /// space, then it should be able to accept a pointer to any address | ||||
6156 | /// space as input. In order to do this, we need to replace the | ||||
6157 | /// standard builtin declaration with one that uses the same address space | ||||
6158 | /// as the call. | ||||
6159 | /// | ||||
6160 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | ||||
6161 | /// it does not contain any pointer arguments without | ||||
6162 | /// an address space qualifer. Otherwise the rewritten | ||||
6163 | /// FunctionDecl is returned. | ||||
6164 | /// TODO: Handle pointer return types. | ||||
6165 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | ||||
6166 | FunctionDecl *FDecl, | ||||
6167 | MultiExprArg ArgExprs) { | ||||
6168 | |||||
6169 | QualType DeclType = FDecl->getType(); | ||||
6170 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | ||||
6171 | |||||
6172 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | ||||
6173 | ArgExprs.size() < FT->getNumParams()) | ||||
6174 | return nullptr; | ||||
6175 | |||||
6176 | bool NeedsNewDecl = false; | ||||
6177 | unsigned i = 0; | ||||
6178 | SmallVector<QualType, 8> OverloadParams; | ||||
6179 | |||||
6180 | for (QualType ParamType : FT->param_types()) { | ||||
6181 | |||||
6182 | // Convert array arguments to pointer to simplify type lookup. | ||||
6183 | ExprResult ArgRes = | ||||
6184 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | ||||
6185 | if (ArgRes.isInvalid()) | ||||
6186 | return nullptr; | ||||
6187 | Expr *Arg = ArgRes.get(); | ||||
6188 | QualType ArgType = Arg->getType(); | ||||
6189 | if (!ParamType->isPointerType() || | ||||
6190 | ParamType.hasAddressSpace() || | ||||
6191 | !ArgType->isPointerType() || | ||||
6192 | !ArgType->getPointeeType().hasAddressSpace()) { | ||||
6193 | OverloadParams.push_back(ParamType); | ||||
6194 | continue; | ||||
6195 | } | ||||
6196 | |||||
6197 | QualType PointeeType = ParamType->getPointeeType(); | ||||
6198 | if (PointeeType.hasAddressSpace()) | ||||
6199 | continue; | ||||
6200 | |||||
6201 | NeedsNewDecl = true; | ||||
6202 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | ||||
6203 | |||||
6204 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | ||||
6205 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | ||||
6206 | } | ||||
6207 | |||||
6208 | if (!NeedsNewDecl) | ||||
6209 | return nullptr; | ||||
6210 | |||||
6211 | FunctionProtoType::ExtProtoInfo EPI; | ||||
6212 | EPI.Variadic = FT->isVariadic(); | ||||
6213 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | ||||
6214 | OverloadParams, EPI); | ||||
6215 | DeclContext *Parent = FDecl->getParent(); | ||||
6216 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, | ||||
6217 | FDecl->getLocation(), | ||||
6218 | FDecl->getLocation(), | ||||
6219 | FDecl->getIdentifier(), | ||||
6220 | OverloadTy, | ||||
6221 | /*TInfo=*/nullptr, | ||||
6222 | SC_Extern, false, | ||||
6223 | /*hasPrototype=*/true); | ||||
6224 | SmallVector<ParmVarDecl*, 16> Params; | ||||
6225 | FT = cast<FunctionProtoType>(OverloadTy); | ||||
6226 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
6227 | QualType ParamType = FT->getParamType(i); | ||||
6228 | ParmVarDecl *Parm = | ||||
6229 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | ||||
6230 | SourceLocation(), nullptr, ParamType, | ||||
6231 | /*TInfo=*/nullptr, SC_None, nullptr); | ||||
6232 | Parm->setScopeInfo(0, i); | ||||
6233 | Params.push_back(Parm); | ||||
6234 | } | ||||
6235 | OverloadDecl->setParams(Params); | ||||
6236 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | ||||
6237 | return OverloadDecl; | ||||
6238 | } | ||||
6239 | |||||
6240 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | ||||
6241 | FunctionDecl *Callee, | ||||
6242 | MultiExprArg ArgExprs) { | ||||
6243 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | ||||
6244 | // similar attributes) really don't like it when functions are called with an | ||||
6245 | // invalid number of args. | ||||
6246 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | ||||
6247 | /*PartialOverloading=*/false) && | ||||
6248 | !Callee->isVariadic()) | ||||
6249 | return; | ||||
6250 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | ||||
6251 | return; | ||||
6252 | |||||
6253 | if (const EnableIfAttr *Attr = | ||||
6254 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | ||||
6255 | S.Diag(Fn->getBeginLoc(), | ||||
6256 | isa<CXXMethodDecl>(Callee) | ||||
6257 | ? diag::err_ovl_no_viable_member_function_in_call | ||||
6258 | : diag::err_ovl_no_viable_function_in_call) | ||||
6259 | << Callee << Callee->getSourceRange(); | ||||
6260 | S.Diag(Callee->getLocation(), | ||||
6261 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | ||||
6262 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | ||||
6263 | return; | ||||
6264 | } | ||||
6265 | } | ||||
6266 | |||||
6267 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | ||||
6268 | const UnresolvedMemberExpr *const UME, Sema &S) { | ||||
6269 | |||||
6270 | const auto GetFunctionLevelDCIfCXXClass = | ||||
6271 | [](Sema &S) -> const CXXRecordDecl * { | ||||
6272 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | ||||
6273 | if (!DC || !DC->getParent()) | ||||
6274 | return nullptr; | ||||
6275 | |||||
6276 | // If the call to some member function was made from within a member | ||||
6277 | // function body 'M' return return 'M's parent. | ||||
6278 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
6279 | return MD->getParent()->getCanonicalDecl(); | ||||
6280 | // else the call was made from within a default member initializer of a | ||||
6281 | // class, so return the class. | ||||
6282 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
6283 | return RD->getCanonicalDecl(); | ||||
6284 | return nullptr; | ||||
6285 | }; | ||||
6286 | // If our DeclContext is neither a member function nor a class (in the | ||||
6287 | // case of a lambda in a default member initializer), we can't have an | ||||
6288 | // enclosing 'this'. | ||||
6289 | |||||
6290 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | ||||
6291 | if (!CurParentClass) | ||||
6292 | return false; | ||||
6293 | |||||
6294 | // The naming class for implicit member functions call is the class in which | ||||
6295 | // name lookup starts. | ||||
6296 | const CXXRecordDecl *const NamingClass = | ||||
6297 | UME->getNamingClass()->getCanonicalDecl(); | ||||
6298 | assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access" ) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6298, __PRETTY_FUNCTION__)); | ||||
6299 | |||||
6300 | // If the unresolved member functions were found in a 'naming class' that is | ||||
6301 | // related (either the same or derived from) to the class that contains the | ||||
6302 | // member function that itself contained the implicit member access. | ||||
6303 | |||||
6304 | return CurParentClass == NamingClass || | ||||
6305 | CurParentClass->isDerivedFrom(NamingClass); | ||||
6306 | } | ||||
6307 | |||||
6308 | static void | ||||
6309 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6310 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | ||||
6311 | |||||
6312 | if (!UME) | ||||
6313 | return; | ||||
6314 | |||||
6315 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | ||||
6316 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | ||||
6317 | // already been captured, or if this is an implicit member function call (if | ||||
6318 | // it isn't, an attempt to capture 'this' should already have been made). | ||||
6319 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | ||||
6320 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | ||||
6321 | return; | ||||
6322 | |||||
6323 | // Check if the naming class in which the unresolved members were found is | ||||
6324 | // related (same as or is a base of) to the enclosing class. | ||||
6325 | |||||
6326 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | ||||
6327 | return; | ||||
6328 | |||||
6329 | |||||
6330 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | ||||
6331 | // If the enclosing function is not dependent, then this lambda is | ||||
6332 | // capture ready, so if we can capture this, do so. | ||||
6333 | if (!EnclosingFunctionCtx->isDependentContext()) { | ||||
6334 | // If the current lambda and all enclosing lambdas can capture 'this' - | ||||
6335 | // then go ahead and capture 'this' (since our unresolved overload set | ||||
6336 | // contains at least one non-static member function). | ||||
6337 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | ||||
6338 | S.CheckCXXThisCapture(CallLoc); | ||||
6339 | } else if (S.CurContext->isDependentContext()) { | ||||
6340 | // ... since this is an implicit member reference, that might potentially | ||||
6341 | // involve a 'this' capture, mark 'this' for potential capture in | ||||
6342 | // enclosing lambdas. | ||||
6343 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | ||||
6344 | CurLSI->addPotentialThisCapture(CallLoc); | ||||
6345 | } | ||||
6346 | } | ||||
6347 | |||||
6348 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6349 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6350 | Expr *ExecConfig) { | ||||
6351 | ExprResult Call = | ||||
6352 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6353 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); | ||||
6354 | if (Call.isInvalid()) | ||||
6355 | return Call; | ||||
6356 | |||||
6357 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | ||||
6358 | // language modes. | ||||
6359 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | ||||
6360 | if (ULE->hasExplicitTemplateArgs() && | ||||
6361 | ULE->decls_begin() == ULE->decls_end()) { | ||||
6362 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | ||||
6363 | ? diag::warn_cxx17_compat_adl_only_template_id | ||||
6364 | : diag::ext_adl_only_template_id) | ||||
6365 | << ULE->getName(); | ||||
6366 | } | ||||
6367 | } | ||||
6368 | |||||
6369 | if (LangOpts.OpenMP) | ||||
6370 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | ||||
6371 | ExecConfig); | ||||
6372 | |||||
6373 | return Call; | ||||
6374 | } | ||||
6375 | |||||
6376 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | ||||
6377 | /// This provides the location of the left/right parens and a list of comma | ||||
6378 | /// locations. | ||||
6379 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6380 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6381 | Expr *ExecConfig, bool IsExecConfig, | ||||
6382 | bool AllowRecovery) { | ||||
6383 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
6384 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | ||||
6385 | if (Result.isInvalid()) return ExprError(); | ||||
6386 | Fn = Result.get(); | ||||
6387 | |||||
6388 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
6389 | return ExprError(); | ||||
6390 | |||||
6391 | if (getLangOpts().CPlusPlus) { | ||||
6392 | // If this is a pseudo-destructor expression, build the call immediately. | ||||
6393 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | ||||
6394 | if (!ArgExprs.empty()) { | ||||
6395 | // Pseudo-destructor calls should not have any arguments. | ||||
6396 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | ||||
6397 | << FixItHint::CreateRemoval( | ||||
6398 | SourceRange(ArgExprs.front()->getBeginLoc(), | ||||
6399 | ArgExprs.back()->getEndLoc())); | ||||
6400 | } | ||||
6401 | |||||
6402 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | ||||
6403 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6404 | } | ||||
6405 | if (Fn->getType() == Context.PseudoObjectTy) { | ||||
6406 | ExprResult result = CheckPlaceholderExpr(Fn); | ||||
6407 | if (result.isInvalid()) return ExprError(); | ||||
6408 | Fn = result.get(); | ||||
6409 | } | ||||
6410 | |||||
6411 | // Determine whether this is a dependent call inside a C++ template, | ||||
6412 | // in which case we won't do any semantic analysis now. | ||||
6413 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | ||||
6414 | if (ExecConfig) { | ||||
6415 | return CUDAKernelCallExpr::Create( | ||||
6416 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, | ||||
6417 | Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6418 | } else { | ||||
6419 | |||||
6420 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6421 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | ||||
6422 | Fn->getBeginLoc()); | ||||
6423 | |||||
6424 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6425 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6426 | } | ||||
6427 | } | ||||
6428 | |||||
6429 | // Determine whether this is a call to an object (C++ [over.call.object]). | ||||
6430 | if (Fn->getType()->isRecordType()) | ||||
6431 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | ||||
6432 | RParenLoc); | ||||
6433 | |||||
6434 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6435 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6436 | if (result.isInvalid()) return ExprError(); | ||||
6437 | Fn = result.get(); | ||||
6438 | } | ||||
6439 | |||||
6440 | if (Fn->getType() == Context.BoundMemberTy) { | ||||
6441 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6442 | RParenLoc, AllowRecovery); | ||||
6443 | } | ||||
6444 | } | ||||
6445 | |||||
6446 | // Check for overloaded calls. This can happen even in C due to extensions. | ||||
6447 | if (Fn->getType() == Context.OverloadTy) { | ||||
6448 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | ||||
6449 | |||||
6450 | // We aren't supposed to apply this logic if there's an '&' involved. | ||||
6451 | if (!find.HasFormOfMemberPointer) { | ||||
6452 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | ||||
6453 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6454 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6455 | OverloadExpr *ovl = find.Expression; | ||||
6456 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | ||||
6457 | return BuildOverloadedCallExpr( | ||||
6458 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6459 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | ||||
6460 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6461 | RParenLoc, AllowRecovery); | ||||
6462 | } | ||||
6463 | } | ||||
6464 | |||||
6465 | // If we're directly calling a function, get the appropriate declaration. | ||||
6466 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6467 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6468 | if (result.isInvalid()) return ExprError(); | ||||
6469 | Fn = result.get(); | ||||
6470 | } | ||||
6471 | |||||
6472 | Expr *NakedFn = Fn->IgnoreParens(); | ||||
6473 | |||||
6474 | bool CallingNDeclIndirectly = false; | ||||
6475 | NamedDecl *NDecl = nullptr; | ||||
6476 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | ||||
6477 | if (UnOp->getOpcode() == UO_AddrOf) { | ||||
6478 | CallingNDeclIndirectly = true; | ||||
6479 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | ||||
6480 | } | ||||
6481 | } | ||||
6482 | |||||
6483 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | ||||
6484 | NDecl = DRE->getDecl(); | ||||
6485 | |||||
6486 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | ||||
6487 | if (FDecl && FDecl->getBuiltinID()) { | ||||
6488 | // Rewrite the function decl for this builtin by replacing parameters | ||||
6489 | // with no explicit address space with the address space of the arguments | ||||
6490 | // in ArgExprs. | ||||
6491 | if ((FDecl = | ||||
6492 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | ||||
6493 | NDecl = FDecl; | ||||
6494 | Fn = DeclRefExpr::Create( | ||||
6495 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | ||||
6496 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | ||||
6497 | nullptr, DRE->isNonOdrUse()); | ||||
6498 | } | ||||
6499 | } | ||||
6500 | } else if (isa<MemberExpr>(NakedFn)) | ||||
6501 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | ||||
6502 | |||||
6503 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | ||||
6504 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | ||||
6505 | FD, /*Complain=*/true, Fn->getBeginLoc())) | ||||
6506 | return ExprError(); | ||||
6507 | |||||
6508 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) | ||||
6509 | return ExprError(); | ||||
6510 | |||||
6511 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | ||||
6512 | } | ||||
6513 | |||||
6514 | if (Context.isDependenceAllowed() && | ||||
6515 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
6516 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6516, __PRETTY_FUNCTION__)); | ||||
6517 | assert((Fn->containsErrors() ||(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6520, __PRETTY_FUNCTION__)) | ||||
6518 | llvm::any_of(ArgExprs,(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6520, __PRETTY_FUNCTION__)) | ||||
6519 | [](clang::Expr *E) { return E->containsErrors(); })) &&(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6520, __PRETTY_FUNCTION__)) | ||||
6520 | "should only occur in error-recovery path.")(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6520, __PRETTY_FUNCTION__)); | ||||
6521 | QualType ReturnType = | ||||
6522 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | ||||
6523 | ? cast<FunctionDecl>(NDecl)->getCallResultType() | ||||
6524 | : Context.DependentTy; | ||||
6525 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | ||||
6526 | Expr::getValueKindForType(ReturnType), RParenLoc, | ||||
6527 | CurFPFeatureOverrides()); | ||||
6528 | } | ||||
6529 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | ||||
6530 | ExecConfig, IsExecConfig); | ||||
6531 | } | ||||
6532 | |||||
6533 | /// Parse a __builtin_astype expression. | ||||
6534 | /// | ||||
6535 | /// __builtin_astype( value, dst type ) | ||||
6536 | /// | ||||
6537 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6538 | SourceLocation BuiltinLoc, | ||||
6539 | SourceLocation RParenLoc) { | ||||
6540 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | ||||
6541 | return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); | ||||
6542 | } | ||||
6543 | |||||
6544 | /// Create a new AsTypeExpr node (bitcast) from the arguments. | ||||
6545 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, | ||||
6546 | SourceLocation BuiltinLoc, | ||||
6547 | SourceLocation RParenLoc) { | ||||
6548 | ExprValueKind VK = VK_RValue; | ||||
6549 | ExprObjectKind OK = OK_Ordinary; | ||||
6550 | QualType SrcTy = E->getType(); | ||||
6551 | if (!SrcTy->isDependentType() && | ||||
6552 | Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) | ||||
6553 | return ExprError( | ||||
6554 | Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) | ||||
6555 | << DestTy << SrcTy << E->getSourceRange()); | ||||
6556 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); | ||||
6557 | } | ||||
6558 | |||||
6559 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | ||||
6560 | /// provided arguments. | ||||
6561 | /// | ||||
6562 | /// __builtin_convertvector( value, dst type ) | ||||
6563 | /// | ||||
6564 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6565 | SourceLocation BuiltinLoc, | ||||
6566 | SourceLocation RParenLoc) { | ||||
6567 | TypeSourceInfo *TInfo; | ||||
6568 | GetTypeFromParser(ParsedDestTy, &TInfo); | ||||
6569 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | ||||
6570 | } | ||||
6571 | |||||
6572 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | ||||
6573 | /// i.e. an expression not of \p OverloadTy. The expression should | ||||
6574 | /// unary-convert to an expression of function-pointer or | ||||
6575 | /// block-pointer type. | ||||
6576 | /// | ||||
6577 | /// \param NDecl the declaration being called, if available | ||||
6578 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | ||||
6579 | SourceLocation LParenLoc, | ||||
6580 | ArrayRef<Expr *> Args, | ||||
6581 | SourceLocation RParenLoc, Expr *Config, | ||||
6582 | bool IsExecConfig, ADLCallKind UsesADL) { | ||||
6583 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | ||||
6584 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | ||||
6585 | |||||
6586 | // Functions with 'interrupt' attribute cannot be called directly. | ||||
6587 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | ||||
6588 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | ||||
6589 | return ExprError(); | ||||
6590 | } | ||||
6591 | |||||
6592 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | ||||
6593 | // so there's some risk when calling out to non-interrupt handler functions | ||||
6594 | // that the callee might not preserve them. This is easy to diagnose here, | ||||
6595 | // but can be very challenging to debug. | ||||
6596 | // Likewise, X86 interrupt handlers may only call routines with attribute | ||||
6597 | // no_caller_saved_registers since there is no efficient way to | ||||
6598 | // save and restore the non-GPR state. | ||||
6599 | if (auto *Caller = getCurFunctionDecl()) { | ||||
6600 | if (Caller->hasAttr<ARMInterruptAttr>()) { | ||||
6601 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | ||||
6602 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { | ||||
6603 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | ||||
6604 | if (FDecl) | ||||
6605 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6606 | } | ||||
6607 | } | ||||
6608 | if (Caller->hasAttr<AnyX86InterruptAttr>() && | ||||
6609 | ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { | ||||
6610 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_regsave); | ||||
6611 | if (FDecl) | ||||
6612 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6613 | } | ||||
6614 | } | ||||
6615 | |||||
6616 | // Promote the function operand. | ||||
6617 | // We special-case function promotion here because we only allow promoting | ||||
6618 | // builtin functions to function pointers in the callee of a call. | ||||
6619 | ExprResult Result; | ||||
6620 | QualType ResultTy; | ||||
6621 | if (BuiltinID && | ||||
6622 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | ||||
6623 | // Extract the return type from the (builtin) function pointer type. | ||||
6624 | // FIXME Several builtins still have setType in | ||||
6625 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | ||||
6626 | // Builtins.def to ensure they are correct before removing setType calls. | ||||
6627 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | ||||
6628 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | ||||
6629 | ResultTy = FDecl->getCallResultType(); | ||||
6630 | } else { | ||||
6631 | Result = CallExprUnaryConversions(Fn); | ||||
6632 | ResultTy = Context.BoolTy; | ||||
6633 | } | ||||
6634 | if (Result.isInvalid()) | ||||
6635 | return ExprError(); | ||||
6636 | Fn = Result.get(); | ||||
6637 | |||||
6638 | // Check for a valid function type, but only if it is not a builtin which | ||||
6639 | // requires custom type checking. These will be handled by | ||||
6640 | // CheckBuiltinFunctionCall below just after creation of the call expression. | ||||
6641 | const FunctionType *FuncT = nullptr; | ||||
6642 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | ||||
6643 | retry: | ||||
6644 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | ||||
6645 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | ||||
6646 | // have type pointer to function". | ||||
6647 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | ||||
6648 | if (!FuncT) | ||||
6649 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6650 | << Fn->getType() << Fn->getSourceRange()); | ||||
6651 | } else if (const BlockPointerType *BPT = | ||||
6652 | Fn->getType()->getAs<BlockPointerType>()) { | ||||
6653 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | ||||
6654 | } else { | ||||
6655 | // Handle calls to expressions of unknown-any type. | ||||
6656 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6657 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | ||||
6658 | if (rewrite.isInvalid()) | ||||
6659 | return ExprError(); | ||||
6660 | Fn = rewrite.get(); | ||||
6661 | goto retry; | ||||
6662 | } | ||||
6663 | |||||
6664 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6665 | << Fn->getType() << Fn->getSourceRange()); | ||||
6666 | } | ||||
6667 | } | ||||
6668 | |||||
6669 | // Get the number of parameters in the function prototype, if any. | ||||
6670 | // We will allocate space for max(Args.size(), NumParams) arguments | ||||
6671 | // in the call expression. | ||||
6672 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | ||||
6673 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; | ||||
6674 | |||||
6675 | CallExpr *TheCall; | ||||
6676 | if (Config) { | ||||
6677 | assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6678, __PRETTY_FUNCTION__)) | ||||
6678 | "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6678, __PRETTY_FUNCTION__)); | ||||
6679 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | ||||
6680 | Args, ResultTy, VK_RValue, RParenLoc, | ||||
6681 | CurFPFeatureOverrides(), NumParams); | ||||
6682 | } else { | ||||
6683 | TheCall = | ||||
6684 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | ||||
6685 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
6686 | } | ||||
6687 | |||||
6688 | if (!Context.isDependenceAllowed()) { | ||||
6689 | // Forget about the nulled arguments since typo correction | ||||
6690 | // do not handle them well. | ||||
6691 | TheCall->shrinkNumArgs(Args.size()); | ||||
6692 | // C cannot always handle TypoExpr nodes in builtin calls and direct | ||||
6693 | // function calls as their argument checking don't necessarily handle | ||||
6694 | // dependent types properly, so make sure any TypoExprs have been | ||||
6695 | // dealt with. | ||||
6696 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | ||||
6697 | if (!Result.isUsable()) return ExprError(); | ||||
6698 | CallExpr *TheOldCall = TheCall; | ||||
6699 | TheCall = dyn_cast<CallExpr>(Result.get()); | ||||
6700 | bool CorrectedTypos = TheCall != TheOldCall; | ||||
6701 | if (!TheCall) return Result; | ||||
6702 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | ||||
6703 | |||||
6704 | // A new call expression node was created if some typos were corrected. | ||||
6705 | // However it may not have been constructed with enough storage. In this | ||||
6706 | // case, rebuild the node with enough storage. The waste of space is | ||||
6707 | // immaterial since this only happens when some typos were corrected. | ||||
6708 | if (CorrectedTypos && Args.size() < NumParams) { | ||||
6709 | if (Config) | ||||
6710 | TheCall = CUDAKernelCallExpr::Create( | ||||
6711 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, | ||||
6712 | RParenLoc, CurFPFeatureOverrides(), NumParams); | ||||
6713 | else | ||||
6714 | TheCall = | ||||
6715 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | ||||
6716 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
6717 | } | ||||
6718 | // We can now handle the nulled arguments for the default arguments. | ||||
6719 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | ||||
6720 | } | ||||
6721 | |||||
6722 | // Bail out early if calling a builtin with custom type checking. | ||||
6723 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | ||||
6724 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
6725 | |||||
6726 | if (getLangOpts().CUDA) { | ||||
6727 | if (Config) { | ||||
6728 | // CUDA: Kernel calls must be to global functions | ||||
6729 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
6730 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | ||||
6731 | << FDecl << Fn->getSourceRange()); | ||||
6732 | |||||
6733 | // CUDA: Kernel function must have 'void' return type | ||||
6734 | if (!FuncT->getReturnType()->isVoidType() && | ||||
6735 | !FuncT->getReturnType()->getAs<AutoType>() && | ||||
6736 | !FuncT->getReturnType()->isInstantiationDependentType()) | ||||
6737 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | ||||
6738 | << Fn->getType() << Fn->getSourceRange()); | ||||
6739 | } else { | ||||
6740 | // CUDA: Calls to global functions must be configured | ||||
6741 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
6742 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | ||||
6743 | << FDecl << Fn->getSourceRange()); | ||||
6744 | } | ||||
6745 | } | ||||
6746 | |||||
6747 | // Check for a valid return type | ||||
6748 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | ||||
6749 | FDecl)) | ||||
6750 | return ExprError(); | ||||
6751 | |||||
6752 | // We know the result type of the call, set it. | ||||
6753 | TheCall->setType(FuncT->getCallResultType(Context)); | ||||
6754 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | ||||
6755 | |||||
6756 | if (Proto) { | ||||
6757 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | ||||
6758 | IsExecConfig)) | ||||
6759 | return ExprError(); | ||||
6760 | } else { | ||||
6761 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6761, __PRETTY_FUNCTION__)); | ||||
6762 | |||||
6763 | if (FDecl) { | ||||
6764 | // Check if we have too few/too many template arguments, based | ||||
6765 | // on our knowledge of the function definition. | ||||
6766 | const FunctionDecl *Def = nullptr; | ||||
6767 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | ||||
6768 | Proto = Def->getType()->getAs<FunctionProtoType>(); | ||||
6769 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | ||||
6770 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | ||||
6771 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | ||||
6772 | } | ||||
6773 | |||||
6774 | // If the function we're calling isn't a function prototype, but we have | ||||
6775 | // a function prototype from a prior declaratiom, use that prototype. | ||||
6776 | if (!FDecl->hasPrototype()) | ||||
6777 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | ||||
6778 | } | ||||
6779 | |||||
6780 | // Promote the arguments (C99 6.5.2.2p6). | ||||
6781 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
6782 | Expr *Arg = Args[i]; | ||||
6783 | |||||
6784 | if (Proto && i < Proto->getNumParams()) { | ||||
6785 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
6786 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | ||||
6787 | ExprResult ArgE = | ||||
6788 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | ||||
6789 | if (ArgE.isInvalid()) | ||||
6790 | return true; | ||||
6791 | |||||
6792 | Arg = ArgE.getAs<Expr>(); | ||||
6793 | |||||
6794 | } else { | ||||
6795 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | ||||
6796 | |||||
6797 | if (ArgE.isInvalid()) | ||||
6798 | return true; | ||||
6799 | |||||
6800 | Arg = ArgE.getAs<Expr>(); | ||||
6801 | } | ||||
6802 | |||||
6803 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | ||||
6804 | diag::err_call_incomplete_argument, Arg)) | ||||
6805 | return ExprError(); | ||||
6806 | |||||
6807 | TheCall->setArg(i, Arg); | ||||
6808 | } | ||||
6809 | } | ||||
6810 | |||||
6811 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
6812 | if (!Method->isStatic()) | ||||
6813 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | ||||
6814 | << Fn->getSourceRange()); | ||||
6815 | |||||
6816 | // Check for sentinels | ||||
6817 | if (NDecl) | ||||
6818 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | ||||
6819 | |||||
6820 | // Warn for unions passing across security boundary (CMSE). | ||||
6821 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | ||||
6822 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
6823 | if (const auto *RT = | ||||
6824 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | ||||
6825 | if (RT->getDecl()->isOrContainsUnion()) | ||||
6826 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | ||||
6827 | << 0 << i; | ||||
6828 | } | ||||
6829 | } | ||||
6830 | } | ||||
6831 | |||||
6832 | // Do special checking on direct calls to functions. | ||||
6833 | if (FDecl) { | ||||
6834 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | ||||
6835 | return ExprError(); | ||||
6836 | |||||
6837 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | ||||
6838 | |||||
6839 | if (BuiltinID) | ||||
6840 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
6841 | } else if (NDecl) { | ||||
6842 | if (CheckPointerCall(NDecl, TheCall, Proto)) | ||||
6843 | return ExprError(); | ||||
6844 | } else { | ||||
6845 | if (CheckOtherCall(TheCall, Proto)) | ||||
6846 | return ExprError(); | ||||
6847 | } | ||||
6848 | |||||
6849 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | ||||
6850 | } | ||||
6851 | |||||
6852 | ExprResult | ||||
6853 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | ||||
6854 | SourceLocation RParenLoc, Expr *InitExpr) { | ||||
6855 | assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast <void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6855, __PRETTY_FUNCTION__)); | ||||
6856 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 6856, __PRETTY_FUNCTION__)); | ||||
6857 | |||||
6858 | TypeSourceInfo *TInfo; | ||||
6859 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | ||||
6860 | if (!TInfo) | ||||
6861 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | ||||
6862 | |||||
6863 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | ||||
6864 | } | ||||
6865 | |||||
6866 | ExprResult | ||||
6867 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | ||||
6868 | SourceLocation RParenLoc, Expr *LiteralExpr) { | ||||
6869 | QualType literalType = TInfo->getType(); | ||||
6870 | |||||
6871 | if (literalType->isArrayType()) { | ||||
6872 | if (RequireCompleteSizedType( | ||||
6873 | LParenLoc, Context.getBaseElementType(literalType), | ||||
6874 | diag::err_array_incomplete_or_sizeless_type, | ||||
6875 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
6876 | return ExprError(); | ||||
6877 | if (literalType->isVariableArrayType()) | ||||
6878 | return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) | ||||
6879 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); | ||||
6880 | } else if (!literalType->isDependentType() && | ||||
6881 | RequireCompleteType(LParenLoc, literalType, | ||||
6882 | diag::err_typecheck_decl_incomplete_type, | ||||
6883 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
6884 | return ExprError(); | ||||
6885 | |||||
6886 | InitializedEntity Entity | ||||
6887 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | ||||
6888 | InitializationKind Kind | ||||
6889 | = InitializationKind::CreateCStyleCast(LParenLoc, | ||||
6890 | SourceRange(LParenLoc, RParenLoc), | ||||
6891 | /*InitList=*/true); | ||||
6892 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | ||||
6893 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | ||||
6894 | &literalType); | ||||
6895 | if (Result.isInvalid()) | ||||
6896 | return ExprError(); | ||||
6897 | LiteralExpr = Result.get(); | ||||
6898 | |||||
6899 | bool isFileScope = !CurContext->isFunctionOrMethod(); | ||||
6900 | |||||
6901 | // In C, compound literals are l-values for some reason. | ||||
6902 | // For GCC compatibility, in C++, file-scope array compound literals with | ||||
6903 | // constant initializers are also l-values, and compound literals are | ||||
6904 | // otherwise prvalues. | ||||
6905 | // | ||||
6906 | // (GCC also treats C++ list-initialized file-scope array prvalues with | ||||
6907 | // constant initializers as l-values, but that's non-conforming, so we don't | ||||
6908 | // follow it there.) | ||||
6909 | // | ||||
6910 | // FIXME: It would be better to handle the lvalue cases as materializing and | ||||
6911 | // lifetime-extending a temporary object, but our materialized temporaries | ||||
6912 | // representation only supports lifetime extension from a variable, not "out | ||||
6913 | // of thin air". | ||||
6914 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | ||||
6915 | // is bound to the result of applying array-to-pointer decay to the compound | ||||
6916 | // literal. | ||||
6917 | // FIXME: GCC supports compound literals of reference type, which should | ||||
6918 | // obviously have a value kind derived from the kind of reference involved. | ||||
6919 | ExprValueKind VK = | ||||
6920 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | ||||
6921 | ? VK_RValue | ||||
6922 | : VK_LValue; | ||||
6923 | |||||
6924 | if (isFileScope) | ||||
6925 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | ||||
6926 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | ||||
6927 | Expr *Init = ILE->getInit(i); | ||||
6928 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | ||||
6929 | } | ||||
6930 | |||||
6931 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | ||||
6932 | VK, LiteralExpr, isFileScope); | ||||
6933 | if (isFileScope) { | ||||
6934 | if (!LiteralExpr->isTypeDependent() && | ||||
6935 | !LiteralExpr->isValueDependent() && | ||||
6936 | !literalType->isDependentType()) // C99 6.5.2.5p3 | ||||
6937 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | ||||
6938 | return ExprError(); | ||||
6939 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | ||||
6940 | literalType.getAddressSpace() != LangAS::Default) { | ||||
6941 | // Embedded-C extensions to C99 6.5.2.5: | ||||
6942 | // "If the compound literal occurs inside the body of a function, the | ||||
6943 | // type name shall not be qualified by an address-space qualifier." | ||||
6944 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | ||||
6945 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | ||||
6946 | return ExprError(); | ||||
6947 | } | ||||
6948 | |||||
6949 | if (!isFileScope && !getLangOpts().CPlusPlus) { | ||||
6950 | // Compound literals that have automatic storage duration are destroyed at | ||||
6951 | // the end of the scope in C; in C++, they're just temporaries. | ||||
6952 | |||||
6953 | // Emit diagnostics if it is or contains a C union type that is non-trivial | ||||
6954 | // to destruct. | ||||
6955 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | ||||
6956 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
6957 | NTCUC_CompoundLiteral, NTCUK_Destruct); | ||||
6958 | |||||
6959 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | ||||
6960 | if (literalType.isDestructedType()) { | ||||
6961 | Cleanup.setExprNeedsCleanups(true); | ||||
6962 | ExprCleanupObjects.push_back(E); | ||||
6963 | getCurFunction()->setHasBranchProtectedScope(); | ||||
6964 | } | ||||
6965 | } | ||||
6966 | |||||
6967 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
6968 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
6969 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | ||||
6970 | E->getInitializer()->getExprLoc()); | ||||
6971 | |||||
6972 | return MaybeBindToTemporary(E); | ||||
6973 | } | ||||
6974 | |||||
6975 | ExprResult | ||||
6976 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
6977 | SourceLocation RBraceLoc) { | ||||
6978 | // Only produce each kind of designated initialization diagnostic once. | ||||
6979 | SourceLocation FirstDesignator; | ||||
6980 | bool DiagnosedArrayDesignator = false; | ||||
6981 | bool DiagnosedNestedDesignator = false; | ||||
6982 | bool DiagnosedMixedDesignator = false; | ||||
6983 | |||||
6984 | // Check that any designated initializers are syntactically valid in the | ||||
6985 | // current language mode. | ||||
6986 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
6987 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | ||||
6988 | if (FirstDesignator.isInvalid()) | ||||
6989 | FirstDesignator = DIE->getBeginLoc(); | ||||
6990 | |||||
6991 | if (!getLangOpts().CPlusPlus) | ||||
6992 | break; | ||||
6993 | |||||
6994 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | ||||
6995 | DiagnosedNestedDesignator = true; | ||||
6996 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | ||||
6997 | << DIE->getDesignatorsSourceRange(); | ||||
6998 | } | ||||
6999 | |||||
7000 | for (auto &Desig : DIE->designators()) { | ||||
7001 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | ||||
7002 | DiagnosedArrayDesignator = true; | ||||
7003 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | ||||
7004 | << Desig.getSourceRange(); | ||||
7005 | } | ||||
7006 | } | ||||
7007 | |||||
7008 | if (!DiagnosedMixedDesignator && | ||||
7009 | !isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7010 | DiagnosedMixedDesignator = true; | ||||
7011 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7012 | << DIE->getSourceRange(); | ||||
7013 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7014 | << InitArgList[0]->getSourceRange(); | ||||
7015 | } | ||||
7016 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | ||||
7017 | isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7018 | DiagnosedMixedDesignator = true; | ||||
7019 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | ||||
7020 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7021 | << DIE->getSourceRange(); | ||||
7022 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7023 | << InitArgList[I]->getSourceRange(); | ||||
7024 | } | ||||
7025 | } | ||||
7026 | |||||
7027 | if (FirstDesignator.isValid()) { | ||||
7028 | // Only diagnose designated initiaization as a C++20 extension if we didn't | ||||
7029 | // already diagnose use of (non-C++20) C99 designator syntax. | ||||
7030 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | ||||
7031 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | ||||
7032 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | ||||
7033 | ? diag::warn_cxx17_compat_designated_init | ||||
7034 | : diag::ext_cxx_designated_init); | ||||
7035 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | ||||
7036 | Diag(FirstDesignator, diag::ext_designated_init); | ||||
7037 | } | ||||
7038 | } | ||||
7039 | |||||
7040 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | ||||
7041 | } | ||||
7042 | |||||
7043 | ExprResult | ||||
7044 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7045 | SourceLocation RBraceLoc) { | ||||
7046 | // Semantic analysis for initializers is done by ActOnDeclarator() and | ||||
7047 | // CheckInitializer() - it requires knowledge of the object being initialized. | ||||
7048 | |||||
7049 | // Immediately handle non-overload placeholders. Overloads can be | ||||
7050 | // resolved contextually, but everything else here can't. | ||||
7051 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7052 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | ||||
7053 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | ||||
7054 | |||||
7055 | // Ignore failures; dropping the entire initializer list because | ||||
7056 | // of one failure would be terrible for indexing/etc. | ||||
7057 | if (result.isInvalid()) continue; | ||||
7058 | |||||
7059 | InitArgList[I] = result.get(); | ||||
7060 | } | ||||
7061 | } | ||||
7062 | |||||
7063 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | ||||
7064 | RBraceLoc); | ||||
7065 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | ||||
7066 | return E; | ||||
7067 | } | ||||
7068 | |||||
7069 | /// Do an explicit extend of the given block pointer if we're in ARC. | ||||
7070 | void Sema::maybeExtendBlockObject(ExprResult &E) { | ||||
7071 | assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast <void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7071, __PRETTY_FUNCTION__)); | ||||
7072 | assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail ("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7072, __PRETTY_FUNCTION__)); | ||||
7073 | |||||
7074 | // Only do this in an r-value context. | ||||
7075 | if (!getLangOpts().ObjCAutoRefCount) return; | ||||
7076 | |||||
7077 | E = ImplicitCastExpr::Create( | ||||
7078 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | ||||
7079 | /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); | ||||
7080 | Cleanup.setExprNeedsCleanups(true); | ||||
7081 | } | ||||
7082 | |||||
7083 | /// Prepare a conversion of the given expression to an ObjC object | ||||
7084 | /// pointer type. | ||||
7085 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | ||||
7086 | QualType type = E.get()->getType(); | ||||
7087 | if (type->isObjCObjectPointerType()) { | ||||
7088 | return CK_BitCast; | ||||
7089 | } else if (type->isBlockPointerType()) { | ||||
7090 | maybeExtendBlockObject(E); | ||||
7091 | return CK_BlockPointerToObjCPointerCast; | ||||
7092 | } else { | ||||
7093 | assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail ("type->isPointerType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7093, __PRETTY_FUNCTION__)); | ||||
7094 | return CK_CPointerToObjCPointerCast; | ||||
7095 | } | ||||
7096 | } | ||||
7097 | |||||
7098 | /// Prepares for a scalar cast, performing all the necessary stages | ||||
7099 | /// except the final cast and returning the kind required. | ||||
7100 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | ||||
7101 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | ||||
7102 | // Also, callers should have filtered out the invalid cases with | ||||
7103 | // pointers. Everything else should be possible. | ||||
7104 | |||||
7105 | QualType SrcTy = Src.get()->getType(); | ||||
7106 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | ||||
7107 | return CK_NoOp; | ||||
7108 | |||||
7109 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | ||||
7110 | case Type::STK_MemberPointer: | ||||
7111 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7111); | ||||
7112 | |||||
7113 | case Type::STK_CPointer: | ||||
7114 | case Type::STK_BlockPointer: | ||||
7115 | case Type::STK_ObjCObjectPointer: | ||||
7116 | switch (DestTy->getScalarTypeKind()) { | ||||
7117 | case Type::STK_CPointer: { | ||||
7118 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | ||||
7119 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | ||||
7120 | if (SrcAS != DestAS) | ||||
7121 | return CK_AddressSpaceConversion; | ||||
7122 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | ||||
7123 | return CK_NoOp; | ||||
7124 | return CK_BitCast; | ||||
7125 | } | ||||
7126 | case Type::STK_BlockPointer: | ||||
7127 | return (SrcKind == Type::STK_BlockPointer | ||||
7128 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | ||||
7129 | case Type::STK_ObjCObjectPointer: | ||||
7130 | if (SrcKind == Type::STK_ObjCObjectPointer) | ||||
7131 | return CK_BitCast; | ||||
7132 | if (SrcKind == Type::STK_CPointer) | ||||
7133 | return CK_CPointerToObjCPointerCast; | ||||
7134 | maybeExtendBlockObject(Src); | ||||
7135 | return CK_BlockPointerToObjCPointerCast; | ||||
7136 | case Type::STK_Bool: | ||||
7137 | return CK_PointerToBoolean; | ||||
7138 | case Type::STK_Integral: | ||||
7139 | return CK_PointerToIntegral; | ||||
7140 | case Type::STK_Floating: | ||||
7141 | case Type::STK_FloatingComplex: | ||||
7142 | case Type::STK_IntegralComplex: | ||||
7143 | case Type::STK_MemberPointer: | ||||
7144 | case Type::STK_FixedPoint: | ||||
7145 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7145); | ||||
7146 | } | ||||
7147 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7147); | ||||
7148 | |||||
7149 | case Type::STK_FixedPoint: | ||||
7150 | switch (DestTy->getScalarTypeKind()) { | ||||
7151 | case Type::STK_FixedPoint: | ||||
7152 | return CK_FixedPointCast; | ||||
7153 | case Type::STK_Bool: | ||||
7154 | return CK_FixedPointToBoolean; | ||||
7155 | case Type::STK_Integral: | ||||
7156 | return CK_FixedPointToIntegral; | ||||
7157 | case Type::STK_Floating: | ||||
7158 | return CK_FixedPointToFloating; | ||||
7159 | case Type::STK_IntegralComplex: | ||||
7160 | case Type::STK_FloatingComplex: | ||||
7161 | Diag(Src.get()->getExprLoc(), | ||||
7162 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7163 | << DestTy; | ||||
7164 | return CK_IntegralCast; | ||||
7165 | case Type::STK_CPointer: | ||||
7166 | case Type::STK_ObjCObjectPointer: | ||||
7167 | case Type::STK_BlockPointer: | ||||
7168 | case Type::STK_MemberPointer: | ||||
7169 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7169); | ||||
7170 | } | ||||
7171 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7171); | ||||
7172 | |||||
7173 | case Type::STK_Bool: // casting from bool is like casting from an integer | ||||
7174 | case Type::STK_Integral: | ||||
7175 | switch (DestTy->getScalarTypeKind()) { | ||||
7176 | case Type::STK_CPointer: | ||||
7177 | case Type::STK_ObjCObjectPointer: | ||||
7178 | case Type::STK_BlockPointer: | ||||
7179 | if (Src.get()->isNullPointerConstant(Context, | ||||
7180 | Expr::NPC_ValueDependentIsNull)) | ||||
7181 | return CK_NullToPointer; | ||||
7182 | return CK_IntegralToPointer; | ||||
7183 | case Type::STK_Bool: | ||||
7184 | return CK_IntegralToBoolean; | ||||
7185 | case Type::STK_Integral: | ||||
7186 | return CK_IntegralCast; | ||||
7187 | case Type::STK_Floating: | ||||
7188 | return CK_IntegralToFloating; | ||||
7189 | case Type::STK_IntegralComplex: | ||||
7190 | Src = ImpCastExprToType(Src.get(), | ||||
7191 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7192 | CK_IntegralCast); | ||||
7193 | return CK_IntegralRealToComplex; | ||||
7194 | case Type::STK_FloatingComplex: | ||||
7195 | Src = ImpCastExprToType(Src.get(), | ||||
7196 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7197 | CK_IntegralToFloating); | ||||
7198 | return CK_FloatingRealToComplex; | ||||
7199 | case Type::STK_MemberPointer: | ||||
7200 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7200); | ||||
7201 | case Type::STK_FixedPoint: | ||||
7202 | return CK_IntegralToFixedPoint; | ||||
7203 | } | ||||
7204 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7204); | ||||
7205 | |||||
7206 | case Type::STK_Floating: | ||||
7207 | switch (DestTy->getScalarTypeKind()) { | ||||
7208 | case Type::STK_Floating: | ||||
7209 | return CK_FloatingCast; | ||||
7210 | case Type::STK_Bool: | ||||
7211 | return CK_FloatingToBoolean; | ||||
7212 | case Type::STK_Integral: | ||||
7213 | return CK_FloatingToIntegral; | ||||
7214 | case Type::STK_FloatingComplex: | ||||
7215 | Src = ImpCastExprToType(Src.get(), | ||||
7216 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7217 | CK_FloatingCast); | ||||
7218 | return CK_FloatingRealToComplex; | ||||
7219 | case Type::STK_IntegralComplex: | ||||
7220 | Src = ImpCastExprToType(Src.get(), | ||||
7221 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7222 | CK_FloatingToIntegral); | ||||
7223 | return CK_IntegralRealToComplex; | ||||
7224 | case Type::STK_CPointer: | ||||
7225 | case Type::STK_ObjCObjectPointer: | ||||
7226 | case Type::STK_BlockPointer: | ||||
7227 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7227); | ||||
7228 | case Type::STK_MemberPointer: | ||||
7229 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7229); | ||||
7230 | case Type::STK_FixedPoint: | ||||
7231 | return CK_FloatingToFixedPoint; | ||||
7232 | } | ||||
7233 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7233); | ||||
7234 | |||||
7235 | case Type::STK_FloatingComplex: | ||||
7236 | switch (DestTy->getScalarTypeKind()) { | ||||
7237 | case Type::STK_FloatingComplex: | ||||
7238 | return CK_FloatingComplexCast; | ||||
7239 | case Type::STK_IntegralComplex: | ||||
7240 | return CK_FloatingComplexToIntegralComplex; | ||||
7241 | case Type::STK_Floating: { | ||||
7242 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7243 | if (Context.hasSameType(ET, DestTy)) | ||||
7244 | return CK_FloatingComplexToReal; | ||||
7245 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | ||||
7246 | return CK_FloatingCast; | ||||
7247 | } | ||||
7248 | case Type::STK_Bool: | ||||
7249 | return CK_FloatingComplexToBoolean; | ||||
7250 | case Type::STK_Integral: | ||||
7251 | Src = ImpCastExprToType(Src.get(), | ||||
7252 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7253 | CK_FloatingComplexToReal); | ||||
7254 | return CK_FloatingToIntegral; | ||||
7255 | case Type::STK_CPointer: | ||||
7256 | case Type::STK_ObjCObjectPointer: | ||||
7257 | case Type::STK_BlockPointer: | ||||
7258 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7258); | ||||
7259 | case Type::STK_MemberPointer: | ||||
7260 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7260); | ||||
7261 | case Type::STK_FixedPoint: | ||||
7262 | Diag(Src.get()->getExprLoc(), | ||||
7263 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7264 | << SrcTy; | ||||
7265 | return CK_IntegralCast; | ||||
7266 | } | ||||
7267 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7267); | ||||
7268 | |||||
7269 | case Type::STK_IntegralComplex: | ||||
7270 | switch (DestTy->getScalarTypeKind()) { | ||||
7271 | case Type::STK_FloatingComplex: | ||||
7272 | return CK_IntegralComplexToFloatingComplex; | ||||
7273 | case Type::STK_IntegralComplex: | ||||
7274 | return CK_IntegralComplexCast; | ||||
7275 | case Type::STK_Integral: { | ||||
7276 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7277 | if (Context.hasSameType(ET, DestTy)) | ||||
7278 | return CK_IntegralComplexToReal; | ||||
7279 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | ||||
7280 | return CK_IntegralCast; | ||||
7281 | } | ||||
7282 | case Type::STK_Bool: | ||||
7283 | return CK_IntegralComplexToBoolean; | ||||
7284 | case Type::STK_Floating: | ||||
7285 | Src = ImpCastExprToType(Src.get(), | ||||
7286 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7287 | CK_IntegralComplexToReal); | ||||
7288 | return CK_IntegralToFloating; | ||||
7289 | case Type::STK_CPointer: | ||||
7290 | case Type::STK_ObjCObjectPointer: | ||||
7291 | case Type::STK_BlockPointer: | ||||
7292 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7292); | ||||
7293 | case Type::STK_MemberPointer: | ||||
7294 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7294); | ||||
7295 | case Type::STK_FixedPoint: | ||||
7296 | Diag(Src.get()->getExprLoc(), | ||||
7297 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7298 | << SrcTy; | ||||
7299 | return CK_IntegralCast; | ||||
7300 | } | ||||
7301 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7301); | ||||
7302 | } | ||||
7303 | |||||
7304 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7304); | ||||
7305 | } | ||||
7306 | |||||
7307 | static bool breakDownVectorType(QualType type, uint64_t &len, | ||||
7308 | QualType &eltType) { | ||||
7309 | // Vectors are simple. | ||||
7310 | if (const VectorType *vecType = type->getAs<VectorType>()) { | ||||
7311 | len = vecType->getNumElements(); | ||||
7312 | eltType = vecType->getElementType(); | ||||
7313 | assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) : __assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7313, __PRETTY_FUNCTION__)); | ||||
7314 | return true; | ||||
7315 | } | ||||
7316 | |||||
7317 | // We allow lax conversion to and from non-vector types, but only if | ||||
7318 | // they're real types (i.e. non-complex, non-pointer scalar types). | ||||
7319 | if (!type->isRealType()) return false; | ||||
7320 | |||||
7321 | len = 1; | ||||
7322 | eltType = type; | ||||
7323 | return true; | ||||
7324 | } | ||||
7325 | |||||
7326 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | ||||
7327 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | ||||
7328 | /// allowed? | ||||
7329 | /// | ||||
7330 | /// This will also return false if the two given types do not make sense from | ||||
7331 | /// the perspective of SVE bitcasts. | ||||
7332 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | ||||
7333 | assert(srcTy->isVectorType() || destTy->isVectorType())((srcTy->isVectorType() || destTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7333, __PRETTY_FUNCTION__)); | ||||
7334 | |||||
7335 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | ||||
7336 | if (!FirstType->isSizelessBuiltinType()) | ||||
7337 | return false; | ||||
7338 | |||||
7339 | const auto *VecTy = SecondType->getAs<VectorType>(); | ||||
7340 | return VecTy && | ||||
7341 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | ||||
7342 | }; | ||||
7343 | |||||
7344 | return ValidScalableConversion(srcTy, destTy) || | ||||
7345 | ValidScalableConversion(destTy, srcTy); | ||||
7346 | } | ||||
7347 | |||||
7348 | /// Are the two types lax-compatible vector types? That is, given | ||||
7349 | /// that one of them is a vector, do they have equal storage sizes, | ||||
7350 | /// where the storage size is the number of elements times the element | ||||
7351 | /// size? | ||||
7352 | /// | ||||
7353 | /// This will also return false if either of the types is neither a | ||||
7354 | /// vector nor a real type. | ||||
7355 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | ||||
7356 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7356, __PRETTY_FUNCTION__)); | ||||
7357 | |||||
7358 | // Disallow lax conversions between scalars and ExtVectors (these | ||||
7359 | // conversions are allowed for other vector types because common headers | ||||
7360 | // depend on them). Most scalar OP ExtVector cases are handled by the | ||||
7361 | // splat path anyway, which does what we want (convert, not bitcast). | ||||
7362 | // What this rules out for ExtVectors is crazy things like char4*float. | ||||
7363 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | ||||
7364 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | ||||
7365 | |||||
7366 | uint64_t srcLen, destLen; | ||||
7367 | QualType srcEltTy, destEltTy; | ||||
7368 | if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; | ||||
7369 | if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; | ||||
7370 | |||||
7371 | // ASTContext::getTypeSize will return the size rounded up to a | ||||
7372 | // power of 2, so instead of using that, we need to use the raw | ||||
7373 | // element size multiplied by the element count. | ||||
7374 | uint64_t srcEltSize = Context.getTypeSize(srcEltTy); | ||||
7375 | uint64_t destEltSize = Context.getTypeSize(destEltTy); | ||||
7376 | |||||
7377 | return (srcLen * srcEltSize == destLen * destEltSize); | ||||
7378 | } | ||||
7379 | |||||
7380 | /// Is this a legal conversion between two types, one of which is | ||||
7381 | /// known to be a vector type? | ||||
7382 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | ||||
7383 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7383, __PRETTY_FUNCTION__)); | ||||
7384 | |||||
7385 | switch (Context.getLangOpts().getLaxVectorConversions()) { | ||||
7386 | case LangOptions::LaxVectorConversionKind::None: | ||||
7387 | return false; | ||||
7388 | |||||
7389 | case LangOptions::LaxVectorConversionKind::Integer: | ||||
7390 | if (!srcTy->isIntegralOrEnumerationType()) { | ||||
7391 | auto *Vec = srcTy->getAs<VectorType>(); | ||||
7392 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7393 | return false; | ||||
7394 | } | ||||
7395 | if (!destTy->isIntegralOrEnumerationType()) { | ||||
7396 | auto *Vec = destTy->getAs<VectorType>(); | ||||
7397 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7398 | return false; | ||||
7399 | } | ||||
7400 | // OK, integer (vector) -> integer (vector) bitcast. | ||||
7401 | break; | ||||
7402 | |||||
7403 | case LangOptions::LaxVectorConversionKind::All: | ||||
7404 | break; | ||||
7405 | } | ||||
7406 | |||||
7407 | return areLaxCompatibleVectorTypes(srcTy, destTy); | ||||
7408 | } | ||||
7409 | |||||
7410 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | ||||
7411 | CastKind &Kind) { | ||||
7412 | assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!" ) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7412, __PRETTY_FUNCTION__)); | ||||
7413 | |||||
7414 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | ||||
7415 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | ||||
7416 | return Diag(R.getBegin(), | ||||
7417 | Ty->isVectorType() ? | ||||
7418 | diag::err_invalid_conversion_between_vectors : | ||||
7419 | diag::err_invalid_conversion_between_vector_and_integer) | ||||
7420 | << VectorTy << Ty << R; | ||||
7421 | } else | ||||
7422 | return Diag(R.getBegin(), | ||||
7423 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7424 | << VectorTy << Ty << R; | ||||
7425 | |||||
7426 | Kind = CK_BitCast; | ||||
7427 | return false; | ||||
7428 | } | ||||
7429 | |||||
7430 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | ||||
7431 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | ||||
7432 | |||||
7433 | if (DestElemTy == SplattedExpr->getType()) | ||||
7434 | return SplattedExpr; | ||||
7435 | |||||
7436 | assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7437, __PRETTY_FUNCTION__)) | ||||
7437 | DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7437, __PRETTY_FUNCTION__)); | ||||
7438 | |||||
7439 | CastKind CK; | ||||
7440 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | ||||
7441 | // OpenCL requires that we convert `true` boolean expressions to -1, but | ||||
7442 | // only when splatting vectors. | ||||
7443 | if (DestElemTy->isFloatingType()) { | ||||
7444 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | ||||
7445 | // in two steps: boolean to signed integral, then to floating. | ||||
7446 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | ||||
7447 | CK_BooleanToSignedIntegral); | ||||
7448 | SplattedExpr = CastExprRes.get(); | ||||
7449 | CK = CK_IntegralToFloating; | ||||
7450 | } else { | ||||
7451 | CK = CK_BooleanToSignedIntegral; | ||||
7452 | } | ||||
7453 | } else { | ||||
7454 | ExprResult CastExprRes = SplattedExpr; | ||||
7455 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | ||||
7456 | if (CastExprRes.isInvalid()) | ||||
7457 | return ExprError(); | ||||
7458 | SplattedExpr = CastExprRes.get(); | ||||
7459 | } | ||||
7460 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | ||||
7461 | } | ||||
7462 | |||||
7463 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | ||||
7464 | Expr *CastExpr, CastKind &Kind) { | ||||
7465 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!" ) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7465, __PRETTY_FUNCTION__)); | ||||
7466 | |||||
7467 | QualType SrcTy = CastExpr->getType(); | ||||
7468 | |||||
7469 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | ||||
7470 | // an ExtVectorType. | ||||
7471 | // In OpenCL, casts between vectors of different types are not allowed. | ||||
7472 | // (See OpenCL 6.2). | ||||
7473 | if (SrcTy->isVectorType()) { | ||||
7474 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | ||||
7475 | (getLangOpts().OpenCL && | ||||
7476 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | ||||
7477 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | ||||
7478 | << DestTy << SrcTy << R; | ||||
7479 | return ExprError(); | ||||
7480 | } | ||||
7481 | Kind = CK_BitCast; | ||||
7482 | return CastExpr; | ||||
7483 | } | ||||
7484 | |||||
7485 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | ||||
7486 | // conversion will take place first from scalar to elt type, and then | ||||
7487 | // splat from elt type to vector. | ||||
7488 | if (SrcTy->isPointerType()) | ||||
7489 | return Diag(R.getBegin(), | ||||
7490 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7491 | << DestTy << SrcTy << R; | ||||
7492 | |||||
7493 | Kind = CK_VectorSplat; | ||||
7494 | return prepareVectorSplat(DestTy, CastExpr); | ||||
7495 | } | ||||
7496 | |||||
7497 | ExprResult | ||||
7498 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | ||||
7499 | Declarator &D, ParsedType &Ty, | ||||
7500 | SourceLocation RParenLoc, Expr *CastExpr) { | ||||
7501 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7502, __PRETTY_FUNCTION__)) | ||||
7502 | "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7502, __PRETTY_FUNCTION__)); | ||||
7503 | |||||
7504 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | ||||
7505 | if (D.isInvalidType()) | ||||
7506 | return ExprError(); | ||||
7507 | |||||
7508 | if (getLangOpts().CPlusPlus) { | ||||
7509 | // Check that there are no default arguments (C++ only). | ||||
7510 | CheckExtraCXXDefaultArguments(D); | ||||
7511 | } else { | ||||
7512 | // Make sure any TypoExprs have been dealt with. | ||||
7513 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | ||||
7514 | if (!Res.isUsable()) | ||||
7515 | return ExprError(); | ||||
7516 | CastExpr = Res.get(); | ||||
7517 | } | ||||
7518 | |||||
7519 | checkUnusedDeclAttributes(D); | ||||
7520 | |||||
7521 | QualType castType = castTInfo->getType(); | ||||
7522 | Ty = CreateParsedType(castType, castTInfo); | ||||
7523 | |||||
7524 | bool isVectorLiteral = false; | ||||
7525 | |||||
7526 | // Check for an altivec or OpenCL literal, | ||||
7527 | // i.e. all the elements are integer constants. | ||||
7528 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | ||||
7529 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | ||||
7530 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | ||||
7531 | && castType->isVectorType() && (PE || PLE)) { | ||||
7532 | if (PLE && PLE->getNumExprs() == 0) { | ||||
7533 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | ||||
7534 | return ExprError(); | ||||
7535 | } | ||||
7536 | if (PE || PLE->getNumExprs() == 1) { | ||||
7537 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | ||||
7538 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | ||||
7539 | isVectorLiteral = true; | ||||
7540 | } | ||||
7541 | else | ||||
7542 | isVectorLiteral = true; | ||||
7543 | } | ||||
7544 | |||||
7545 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | ||||
7546 | // then handle it as such. | ||||
7547 | if (isVectorLiteral) | ||||
7548 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | ||||
7549 | |||||
7550 | // If the Expr being casted is a ParenListExpr, handle it specially. | ||||
7551 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | ||||
7552 | // sequence of BinOp comma operators. | ||||
7553 | if (isa<ParenListExpr>(CastExpr)) { | ||||
7554 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | ||||
7555 | if (Result.isInvalid()) return ExprError(); | ||||
7556 | CastExpr = Result.get(); | ||||
7557 | } | ||||
7558 | |||||
7559 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && | ||||
7560 | !getSourceManager().isInSystemMacro(LParenLoc)) | ||||
7561 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | ||||
7562 | |||||
7563 | CheckTollFreeBridgeCast(castType, CastExpr); | ||||
7564 | |||||
7565 | CheckObjCBridgeRelatedCast(castType, CastExpr); | ||||
7566 | |||||
7567 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | ||||
7568 | |||||
7569 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | ||||
7570 | } | ||||
7571 | |||||
7572 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | ||||
7573 | SourceLocation RParenLoc, Expr *E, | ||||
7574 | TypeSourceInfo *TInfo) { | ||||
7575 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7576, __PRETTY_FUNCTION__)) | ||||
7576 | "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7576, __PRETTY_FUNCTION__)); | ||||
7577 | |||||
7578 | Expr **exprs; | ||||
7579 | unsigned numExprs; | ||||
7580 | Expr *subExpr; | ||||
7581 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | ||||
7582 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | ||||
7583 | LiteralLParenLoc = PE->getLParenLoc(); | ||||
7584 | LiteralRParenLoc = PE->getRParenLoc(); | ||||
7585 | exprs = PE->getExprs(); | ||||
7586 | numExprs = PE->getNumExprs(); | ||||
7587 | } else { // isa<ParenExpr> by assertion at function entrance | ||||
7588 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | ||||
7589 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | ||||
7590 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | ||||
7591 | exprs = &subExpr; | ||||
7592 | numExprs = 1; | ||||
7593 | } | ||||
7594 | |||||
7595 | QualType Ty = TInfo->getType(); | ||||
7596 | assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast <void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 7596, __PRETTY_FUNCTION__)); | ||||
7597 | |||||
7598 | SmallVector<Expr *, 8> initExprs; | ||||
7599 | const VectorType *VTy = Ty->castAs<VectorType>(); | ||||
7600 | unsigned numElems = VTy->getNumElements(); | ||||
7601 | |||||
7602 | // '(...)' form of vector initialization in AltiVec: the number of | ||||
7603 | // initializers must be one or must match the size of the vector. | ||||
7604 | // If a single value is specified in the initializer then it will be | ||||
7605 | // replicated to all the components of the vector | ||||
7606 | if (VTy->getVectorKind() == VectorType::AltiVecVector) { | ||||
7607 | // The number of initializers must be one or must match the size of the | ||||
7608 | // vector. If a single value is specified in the initializer then it will | ||||
7609 | // be replicated to all the components of the vector | ||||
7610 | if (numExprs == 1) { | ||||
7611 | QualType ElemTy = VTy->getElementType(); | ||||
7612 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
7613 | if (Literal.isInvalid()) | ||||
7614 | return ExprError(); | ||||
7615 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
7616 | PrepareScalarCast(Literal, ElemTy)); | ||||
7617 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
7618 | } | ||||
7619 | else if (numExprs < numElems) { | ||||
7620 | Diag(E->getExprLoc(), | ||||
7621 | diag::err_incorrect_number_of_vector_initializers); | ||||
7622 | return ExprError(); | ||||
7623 | } | ||||
7624 | else | ||||
7625 | initExprs.append(exprs, exprs + numExprs); | ||||
7626 | } | ||||
7627 | else { | ||||
7628 | // For OpenCL, when the number of initializers is a single value, | ||||
7629 | // it will be replicated to all components of the vector. | ||||
7630 | if (getLangOpts().OpenCL && | ||||
7631 | VTy->getVectorKind() == VectorType::GenericVector && | ||||
7632 | numExprs == 1) { | ||||
7633 | QualType ElemTy = VTy->getElementType(); | ||||
7634 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
7635 | if (Literal.isInvalid()) | ||||
7636 | return ExprError(); | ||||
7637 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
7638 | PrepareScalarCast(Literal, ElemTy)); | ||||
7639 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
7640 | } | ||||
7641 | |||||
7642 | initExprs.append(exprs, exprs + numExprs); | ||||
7643 | } | ||||
7644 | // FIXME: This means that pretty-printing the final AST will produce curly | ||||
7645 | // braces instead of the original commas. | ||||
7646 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | ||||
7647 | initExprs, LiteralRParenLoc); | ||||
7648 | initE->setType(Ty); | ||||
7649 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | ||||
7650 | } | ||||
7651 | |||||
7652 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | ||||
7653 | /// the ParenListExpr into a sequence of comma binary operators. | ||||
7654 | ExprResult | ||||
7655 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | ||||
7656 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | ||||
7657 | if (!E) | ||||
7658 | return OrigExpr; | ||||
7659 | |||||
7660 | ExprResult Result(E->getExpr(0)); | ||||
7661 | |||||
7662 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | ||||
7663 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | ||||
7664 | E->getExpr(i)); | ||||
7665 | |||||
7666 | if (Result.isInvalid()) return ExprError(); | ||||
7667 | |||||
7668 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | ||||
7669 | } | ||||
7670 | |||||
7671 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | ||||
7672 | SourceLocation R, | ||||
7673 | MultiExprArg Val) { | ||||
7674 | return ParenListExpr::Create(Context, L, Val, R); | ||||
7675 | } | ||||
7676 | |||||
7677 | /// Emit a specialized diagnostic when one expression is a null pointer | ||||
7678 | /// constant and the other is not a pointer. Returns true if a diagnostic is | ||||
7679 | /// emitted. | ||||
7680 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | ||||
7681 | SourceLocation QuestionLoc) { | ||||
7682 | Expr *NullExpr = LHSExpr; | ||||
7683 | Expr *NonPointerExpr = RHSExpr; | ||||
7684 | Expr::NullPointerConstantKind NullKind = | ||||
7685 | NullExpr->isNullPointerConstant(Context, | ||||
7686 | Expr::NPC_ValueDependentIsNotNull); | ||||
7687 | |||||
7688 | if (NullKind == Expr::NPCK_NotNull) { | ||||
7689 | NullExpr = RHSExpr; | ||||
7690 | NonPointerExpr = LHSExpr; | ||||
7691 | NullKind = | ||||
7692 | NullExpr->isNullPointerConstant(Context, | ||||
7693 | Expr::NPC_ValueDependentIsNotNull); | ||||
7694 | } | ||||
7695 | |||||
7696 | if (NullKind == Expr::NPCK_NotNull) | ||||
7697 | return false; | ||||
7698 | |||||
7699 | if (NullKind == Expr::NPCK_ZeroExpression) | ||||
7700 | return false; | ||||
7701 | |||||
7702 | if (NullKind == Expr::NPCK_ZeroLiteral) { | ||||
7703 | // In this case, check to make sure that we got here from a "NULL" | ||||
7704 | // string in the source code. | ||||
7705 | NullExpr = NullExpr->IgnoreParenImpCasts(); | ||||
7706 | SourceLocation loc = NullExpr->getExprLoc(); | ||||
7707 | if (!findMacroSpelling(loc, "NULL")) | ||||
7708 | return false; | ||||
7709 | } | ||||
7710 | |||||
7711 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | ||||
7712 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | ||||
7713 | << NonPointerExpr->getType() << DiagType | ||||
7714 | << NonPointerExpr->getSourceRange(); | ||||
7715 | return true; | ||||
7716 | } | ||||
7717 | |||||
7718 | /// Return false if the condition expression is valid, true otherwise. | ||||
7719 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | ||||
7720 | QualType CondTy = Cond->getType(); | ||||
7721 | |||||
7722 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | ||||
7723 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | ||||
7724 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
7725 | << CondTy << Cond->getSourceRange(); | ||||
7726 | return true; | ||||
7727 | } | ||||
7728 | |||||
7729 | // C99 6.5.15p2 | ||||
7730 | if (CondTy->isScalarType()) return false; | ||||
7731 | |||||
7732 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | ||||
7733 | << CondTy << Cond->getSourceRange(); | ||||
7734 | return true; | ||||
7735 | } | ||||
7736 | |||||
7737 | /// Handle when one or both operands are void type. | ||||
7738 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | ||||
7739 | ExprResult &RHS) { | ||||
7740 | Expr *LHSExpr = LHS.get(); | ||||
7741 | Expr *RHSExpr = RHS.get(); | ||||
7742 | |||||
7743 | if (!LHSExpr->getType()->isVoidType()) | ||||
7744 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
7745 | << RHSExpr->getSourceRange(); | ||||
7746 | if (!RHSExpr->getType()->isVoidType()) | ||||
7747 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
7748 | << LHSExpr->getSourceRange(); | ||||
7749 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||
7750 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||
7751 | return S.Context.VoidTy; | ||||
7752 | } | ||||
7753 | |||||
7754 | /// Return false if the NullExpr can be promoted to PointerTy, | ||||
7755 | /// true otherwise. | ||||
7756 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | ||||
7757 | QualType PointerTy) { | ||||
7758 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | ||||
7759 | !NullExpr.get()->isNullPointerConstant(S.Context, | ||||
7760 | Expr::NPC_ValueDependentIsNull)) | ||||
7761 | return true; | ||||
7762 | |||||
7763 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | ||||
7764 | return false; | ||||
7765 | } | ||||
7766 | |||||
7767 | /// Checks compatibility between two pointers and return the resulting | ||||
7768 | /// type. | ||||
7769 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | ||||
7770 | ExprResult &RHS, | ||||
7771 | SourceLocation Loc) { | ||||
7772 | QualType LHSTy = LHS.get()->getType(); | ||||
7773 | QualType RHSTy = RHS.get()->getType(); | ||||
7774 | |||||
7775 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | ||||
7776 | // Two identical pointers types are always compatible. | ||||
7777 | return LHSTy; | ||||
7778 | } | ||||
7779 | |||||
7780 | QualType lhptee, rhptee; | ||||
7781 | |||||
7782 | // Get the pointee types. | ||||
7783 | bool IsBlockPointer = false; | ||||
7784 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | ||||
7785 | lhptee = LHSBTy->getPointeeType(); | ||||
7786 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | ||||
7787 | IsBlockPointer = true; | ||||
7788 | } else { | ||||
7789 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7790 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7791 | } | ||||
7792 | |||||
7793 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | ||||
7794 | // differently qualified versions of compatible types, the result type is | ||||
7795 | // a pointer to an appropriately qualified version of the composite | ||||
7796 | // type. | ||||
7797 | |||||
7798 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | ||||
7799 | // clause doesn't make sense for our extensions. E.g. address space 2 should | ||||
7800 | // be incompatible with address space 3: they may live on different devices or | ||||
7801 | // anything. | ||||
7802 | Qualifiers lhQual = lhptee.getQualifiers(); | ||||
7803 | Qualifiers rhQual = rhptee.getQualifiers(); | ||||
7804 | |||||
7805 | LangAS ResultAddrSpace = LangAS::Default; | ||||
7806 | LangAS LAddrSpace = lhQual.getAddressSpace(); | ||||
7807 | LangAS RAddrSpace = rhQual.getAddressSpace(); | ||||
7808 | |||||
7809 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | ||||
7810 | // spaces is disallowed. | ||||
7811 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | ||||
7812 | ResultAddrSpace = LAddrSpace; | ||||
7813 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | ||||
7814 | ResultAddrSpace = RAddrSpace; | ||||
7815 | else { | ||||
7816 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
7817 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | ||||
7818 | << RHS.get()->getSourceRange(); | ||||
7819 | return QualType(); | ||||
7820 | } | ||||
7821 | |||||
7822 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | ||||
7823 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | ||||
7824 | lhQual.removeCVRQualifiers(); | ||||
7825 | rhQual.removeCVRQualifiers(); | ||||
7826 | |||||
7827 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | ||||
7828 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | ||||
7829 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | ||||
7830 | // qual types are compatible iff | ||||
7831 | // * corresponded types are compatible | ||||
7832 | // * CVR qualifiers are equal | ||||
7833 | // * address spaces are equal | ||||
7834 | // Thus for conditional operator we merge CVR and address space unqualified | ||||
7835 | // pointees and if there is a composite type we return a pointer to it with | ||||
7836 | // merged qualifiers. | ||||
7837 | LHSCastKind = | ||||
7838 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
7839 | RHSCastKind = | ||||
7840 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
7841 | lhQual.removeAddressSpace(); | ||||
7842 | rhQual.removeAddressSpace(); | ||||
7843 | |||||
7844 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | ||||
7845 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | ||||
7846 | |||||
7847 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | ||||
7848 | |||||
7849 | if (CompositeTy.isNull()) { | ||||
7850 | // In this situation, we assume void* type. No especially good | ||||
7851 | // reason, but this is what gcc does, and we do have to pick | ||||
7852 | // to get a consistent AST. | ||||
7853 | QualType incompatTy; | ||||
7854 | incompatTy = S.Context.getPointerType( | ||||
7855 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | ||||
7856 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | ||||
7857 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | ||||
7858 | |||||
7859 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | ||||
7860 | // for casts between types with incompatible address space qualifiers. | ||||
7861 | // For the following code the compiler produces casts between global and | ||||
7862 | // local address spaces of the corresponded innermost pointees: | ||||
7863 | // local int *global *a; | ||||
7864 | // global int *global *b; | ||||
7865 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | ||||
7866 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | ||||
7867 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
7868 | << RHS.get()->getSourceRange(); | ||||
7869 | |||||
7870 | return incompatTy; | ||||
7871 | } | ||||
7872 | |||||
7873 | // The pointer types are compatible. | ||||
7874 | // In case of OpenCL ResultTy should have the address space qualifier | ||||
7875 | // which is a superset of address spaces of both the 2nd and the 3rd | ||||
7876 | // operands of the conditional operator. | ||||
7877 | QualType ResultTy = [&, ResultAddrSpace]() { | ||||
7878 | if (S.getLangOpts().OpenCL) { | ||||
7879 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | ||||
7880 | CompositeQuals.setAddressSpace(ResultAddrSpace); | ||||
7881 | return S.Context | ||||
7882 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | ||||
7883 | .withCVRQualifiers(MergedCVRQual); | ||||
7884 | } | ||||
7885 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | ||||
7886 | }(); | ||||
7887 | if (IsBlockPointer) | ||||
7888 | ResultTy = S.Context.getBlockPointerType(ResultTy); | ||||
7889 | else | ||||
7890 | ResultTy = S.Context.getPointerType(ResultTy); | ||||
7891 | |||||
7892 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | ||||
7893 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | ||||
7894 | return ResultTy; | ||||
7895 | } | ||||
7896 | |||||
7897 | /// Return the resulting type when the operands are both block pointers. | ||||
7898 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | ||||
7899 | ExprResult &LHS, | ||||
7900 | ExprResult &RHS, | ||||
7901 | SourceLocation Loc) { | ||||
7902 | QualType LHSTy = LHS.get()->getType(); | ||||
7903 | QualType RHSTy = RHS.get()->getType(); | ||||
7904 | |||||
7905 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | ||||
7906 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | ||||
7907 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | ||||
7908 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
7909 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
7910 | return destType; | ||||
7911 | } | ||||
7912 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | ||||
7913 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
7914 | << RHS.get()->getSourceRange(); | ||||
7915 | return QualType(); | ||||
7916 | } | ||||
7917 | |||||
7918 | // We have 2 block pointer types. | ||||
7919 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
7920 | } | ||||
7921 | |||||
7922 | /// Return the resulting type when the operands are both pointers. | ||||
7923 | static QualType | ||||
7924 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | ||||
7925 | ExprResult &RHS, | ||||
7926 | SourceLocation Loc) { | ||||
7927 | // get the pointer types | ||||
7928 | QualType LHSTy = LHS.get()->getType(); | ||||
7929 | QualType RHSTy = RHS.get()->getType(); | ||||
7930 | |||||
7931 | // get the "pointed to" types | ||||
7932 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7933 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7934 | |||||
7935 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | ||||
7936 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | ||||
7937 | // Figure out necessary qualifiers (C99 6.5.15p6) | ||||
7938 | QualType destPointee | ||||
7939 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
7940 | QualType destType = S.Context.getPointerType(destPointee); | ||||
7941 | // Add qualifiers if necessary. | ||||
7942 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
7943 | // Promote to void*. | ||||
7944 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
7945 | return destType; | ||||
7946 | } | ||||
7947 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | ||||
7948 | QualType destPointee | ||||
7949 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
7950 | QualType destType = S.Context.getPointerType(destPointee); | ||||
7951 | // Add qualifiers if necessary. | ||||
7952 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
7953 | // Promote to void*. | ||||
7954 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
7955 | return destType; | ||||
7956 | } | ||||
7957 | |||||
7958 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
7959 | } | ||||
7960 | |||||
7961 | /// Return false if the first expression is not an integer and the second | ||||
7962 | /// expression is not a pointer, true otherwise. | ||||
7963 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | ||||
7964 | Expr* PointerExpr, SourceLocation Loc, | ||||
7965 | bool IsIntFirstExpr) { | ||||
7966 | if (!PointerExpr->getType()->isPointerType() || | ||||
7967 | !Int.get()->getType()->isIntegerType()) | ||||
7968 | return false; | ||||
7969 | |||||
7970 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | ||||
7971 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | ||||
7972 | |||||
7973 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | ||||
7974 | << Expr1->getType() << Expr2->getType() | ||||
7975 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | ||||
7976 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | ||||
7977 | CK_IntegralToPointer); | ||||
7978 | return true; | ||||
7979 | } | ||||
7980 | |||||
7981 | /// Simple conversion between integer and floating point types. | ||||
7982 | /// | ||||
7983 | /// Used when handling the OpenCL conditional operator where the | ||||
7984 | /// condition is a vector while the other operands are scalar. | ||||
7985 | /// | ||||
7986 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | ||||
7987 | /// types are either integer or floating type. Between the two | ||||
7988 | /// operands, the type with the higher rank is defined as the "result | ||||
7989 | /// type". The other operand needs to be promoted to the same type. No | ||||
7990 | /// other type promotion is allowed. We cannot use | ||||
7991 | /// UsualArithmeticConversions() for this purpose, since it always | ||||
7992 | /// promotes promotable types. | ||||
7993 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | ||||
7994 | ExprResult &RHS, | ||||
7995 | SourceLocation QuestionLoc) { | ||||
7996 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
7997 | if (LHS.isInvalid()) | ||||
7998 | return QualType(); | ||||
7999 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
8000 | if (RHS.isInvalid()) | ||||
8001 | return QualType(); | ||||
8002 | |||||
8003 | // For conversion purposes, we ignore any qualifiers. | ||||
8004 | // For example, "const float" and "float" are equivalent. | ||||
8005 | QualType LHSType = | ||||
8006 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
8007 | QualType RHSType = | ||||
8008 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
8009 | |||||
8010 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | ||||
8011 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8012 | << LHSType << LHS.get()->getSourceRange(); | ||||
8013 | return QualType(); | ||||
8014 | } | ||||
8015 | |||||
8016 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | ||||
8017 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8018 | << RHSType << RHS.get()->getSourceRange(); | ||||
8019 | return QualType(); | ||||
8020 | } | ||||
8021 | |||||
8022 | // If both types are identical, no conversion is needed. | ||||
8023 | if (LHSType == RHSType) | ||||
8024 | return LHSType; | ||||
8025 | |||||
8026 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
8027 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
8028 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
8029 | /*IsCompAssign = */ false); | ||||
8030 | |||||
8031 | // Finally, we have two differing integer types. | ||||
8032 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
8033 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | ||||
8034 | } | ||||
8035 | |||||
8036 | /// Convert scalar operands to a vector that matches the | ||||
8037 | /// condition in length. | ||||
8038 | /// | ||||
8039 | /// Used when handling the OpenCL conditional operator where the | ||||
8040 | /// condition is a vector while the other operands are scalar. | ||||
8041 | /// | ||||
8042 | /// We first compute the "result type" for the scalar operands | ||||
8043 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | ||||
8044 | /// into a vector of that type where the length matches the condition | ||||
8045 | /// vector type. s6.11.6 requires that the element types of the result | ||||
8046 | /// and the condition must have the same number of bits. | ||||
8047 | static QualType | ||||
8048 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
8049 | QualType CondTy, SourceLocation QuestionLoc) { | ||||
8050 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | ||||
8051 | if (ResTy.isNull()) return QualType(); | ||||
8052 | |||||
8053 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8054 | assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8054, __PRETTY_FUNCTION__)); | ||||
8055 | |||||
8056 | // Determine the vector result type | ||||
8057 | unsigned NumElements = CV->getNumElements(); | ||||
8058 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | ||||
8059 | |||||
8060 | // Ensure that all types have the same number of bits | ||||
8061 | if (S.Context.getTypeSize(CV->getElementType()) | ||||
8062 | != S.Context.getTypeSize(ResTy)) { | ||||
8063 | // Since VectorTy is created internally, it does not pretty print | ||||
8064 | // with an OpenCL name. Instead, we just print a description. | ||||
8065 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | ||||
8066 | SmallString<64> Str; | ||||
8067 | llvm::raw_svector_ostream OS(Str); | ||||
8068 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | ||||
8069 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8070 | << CondTy << OS.str(); | ||||
8071 | return QualType(); | ||||
8072 | } | ||||
8073 | |||||
8074 | // Convert operands to the vector result type | ||||
8075 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | ||||
8076 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | ||||
8077 | |||||
8078 | return VectorTy; | ||||
8079 | } | ||||
8080 | |||||
8081 | /// Return false if this is a valid OpenCL condition vector | ||||
8082 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | ||||
8083 | SourceLocation QuestionLoc) { | ||||
8084 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | ||||
8085 | // integral type. | ||||
8086 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | ||||
8087 | assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8087, __PRETTY_FUNCTION__)); | ||||
8088 | QualType EleTy = CondTy->getElementType(); | ||||
8089 | if (EleTy->isIntegerType()) return false; | ||||
8090 | |||||
8091 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8092 | << Cond->getType() << Cond->getSourceRange(); | ||||
8093 | return true; | ||||
8094 | } | ||||
8095 | |||||
8096 | /// Return false if the vector condition type and the vector | ||||
8097 | /// result type are compatible. | ||||
8098 | /// | ||||
8099 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | ||||
8100 | /// number of elements, and their element types have the same number | ||||
8101 | /// of bits. | ||||
8102 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | ||||
8103 | SourceLocation QuestionLoc) { | ||||
8104 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8105 | const VectorType *RV = VecResTy->getAs<VectorType>(); | ||||
8106 | assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail ("CV && RV", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8106, __PRETTY_FUNCTION__)); | ||||
8107 | |||||
8108 | if (CV->getNumElements() != RV->getNumElements()) { | ||||
8109 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | ||||
8110 | << CondTy << VecResTy; | ||||
8111 | return true; | ||||
8112 | } | ||||
8113 | |||||
8114 | QualType CVE = CV->getElementType(); | ||||
8115 | QualType RVE = RV->getElementType(); | ||||
8116 | |||||
8117 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | ||||
8118 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8119 | << CondTy << VecResTy; | ||||
8120 | return true; | ||||
8121 | } | ||||
8122 | |||||
8123 | return false; | ||||
8124 | } | ||||
8125 | |||||
8126 | /// Return the resulting type for the conditional operator in | ||||
8127 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | ||||
8128 | /// s6.3.i) when the condition is a vector type. | ||||
8129 | static QualType | ||||
8130 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | ||||
8131 | ExprResult &LHS, ExprResult &RHS, | ||||
8132 | SourceLocation QuestionLoc) { | ||||
8133 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | ||||
8134 | if (Cond.isInvalid()) | ||||
8135 | return QualType(); | ||||
8136 | QualType CondTy = Cond.get()->getType(); | ||||
8137 | |||||
8138 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | ||||
8139 | return QualType(); | ||||
8140 | |||||
8141 | // If either operand is a vector then find the vector type of the | ||||
8142 | // result as specified in OpenCL v1.1 s6.3.i. | ||||
8143 | if (LHS.get()->getType()->isVectorType() || | ||||
8144 | RHS.get()->getType()->isVectorType()) { | ||||
8145 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | ||||
8146 | /*isCompAssign*/false, | ||||
8147 | /*AllowBothBool*/true, | ||||
8148 | /*AllowBoolConversions*/false); | ||||
8149 | if (VecResTy.isNull()) return QualType(); | ||||
8150 | // The result type must match the condition type as specified in | ||||
8151 | // OpenCL v1.1 s6.11.6. | ||||
8152 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | ||||
8153 | return QualType(); | ||||
8154 | return VecResTy; | ||||
8155 | } | ||||
8156 | |||||
8157 | // Both operands are scalar. | ||||
8158 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | ||||
8159 | } | ||||
8160 | |||||
8161 | /// Return true if the Expr is block type | ||||
8162 | static bool checkBlockType(Sema &S, const Expr *E) { | ||||
8163 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
8164 | QualType Ty = CE->getCallee()->getType(); | ||||
8165 | if (Ty->isBlockPointerType()) { | ||||
8166 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | ||||
8167 | return true; | ||||
8168 | } | ||||
8169 | } | ||||
8170 | return false; | ||||
8171 | } | ||||
8172 | |||||
8173 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | ||||
8174 | /// In that case, LHS = cond. | ||||
8175 | /// C99 6.5.15 | ||||
8176 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | ||||
8177 | ExprResult &RHS, ExprValueKind &VK, | ||||
8178 | ExprObjectKind &OK, | ||||
8179 | SourceLocation QuestionLoc) { | ||||
8180 | |||||
8181 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | ||||
8182 | if (!LHSResult.isUsable()) return QualType(); | ||||
8183 | LHS = LHSResult; | ||||
8184 | |||||
8185 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | ||||
8186 | if (!RHSResult.isUsable()) return QualType(); | ||||
8187 | RHS = RHSResult; | ||||
8188 | |||||
8189 | // C++ is sufficiently different to merit its own checker. | ||||
8190 | if (getLangOpts().CPlusPlus) | ||||
8191 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | ||||
8192 | |||||
8193 | VK = VK_RValue; | ||||
8194 | OK = OK_Ordinary; | ||||
8195 | |||||
8196 | if (Context.isDependenceAllowed() && | ||||
8197 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | ||||
8198 | RHS.get()->isTypeDependent())) { | ||||
8199 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8199, __PRETTY_FUNCTION__)); | ||||
8200 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8202, __PRETTY_FUNCTION__)) | ||||
8201 | RHS.get()->containsErrors()) &&(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8202, __PRETTY_FUNCTION__)) | ||||
8202 | "should only occur in error-recovery path.")(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8202, __PRETTY_FUNCTION__)); | ||||
8203 | return Context.DependentTy; | ||||
8204 | } | ||||
8205 | |||||
8206 | // The OpenCL operator with a vector condition is sufficiently | ||||
8207 | // different to merit its own checker. | ||||
8208 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | ||||
8209 | Cond.get()->getType()->isExtVectorType()) | ||||
8210 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | ||||
8211 | |||||
8212 | // First, check the condition. | ||||
8213 | Cond = UsualUnaryConversions(Cond.get()); | ||||
8214 | if (Cond.isInvalid()) | ||||
8215 | return QualType(); | ||||
8216 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | ||||
8217 | return QualType(); | ||||
8218 | |||||
8219 | // Now check the two expressions. | ||||
8220 | if (LHS.get()->getType()->isVectorType() || | ||||
8221 | RHS.get()->getType()->isVectorType()) | ||||
8222 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | ||||
8223 | /*AllowBothBool*/true, | ||||
8224 | /*AllowBoolConversions*/false); | ||||
8225 | |||||
8226 | QualType ResTy = | ||||
8227 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | ||||
8228 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8229 | return QualType(); | ||||
8230 | |||||
8231 | QualType LHSTy = LHS.get()->getType(); | ||||
8232 | QualType RHSTy = RHS.get()->getType(); | ||||
8233 | |||||
8234 | // Diagnose attempts to convert between __float128 and long double where | ||||
8235 | // such conversions currently can't be handled. | ||||
8236 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | ||||
8237 | Diag(QuestionLoc, | ||||
8238 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | ||||
8239 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8240 | return QualType(); | ||||
8241 | } | ||||
8242 | |||||
8243 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | ||||
8244 | // selection operator (?:). | ||||
8245 | if (getLangOpts().OpenCL && | ||||
8246 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { | ||||
8247 | return QualType(); | ||||
8248 | } | ||||
8249 | |||||
8250 | // If both operands have arithmetic type, do the usual arithmetic conversions | ||||
8251 | // to find a common type: C99 6.5.15p3,5. | ||||
8252 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | ||||
8253 | // Disallow invalid arithmetic conversions, such as those between ExtInts of | ||||
8254 | // different sizes, or between ExtInts and other types. | ||||
8255 | if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { | ||||
8256 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8257 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8258 | << RHS.get()->getSourceRange(); | ||||
8259 | return QualType(); | ||||
8260 | } | ||||
8261 | |||||
8262 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | ||||
8263 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | ||||
8264 | |||||
8265 | return ResTy; | ||||
8266 | } | ||||
8267 | |||||
8268 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | ||||
8269 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | ||||
8270 | return LHSTy; | ||||
8271 | } | ||||
8272 | |||||
8273 | // If both operands are the same structure or union type, the result is that | ||||
8274 | // type. | ||||
8275 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | ||||
8276 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | ||||
8277 | if (LHSRT->getDecl() == RHSRT->getDecl()) | ||||
8278 | // "If both the operands have structure or union type, the result has | ||||
8279 | // that type." This implies that CV qualifiers are dropped. | ||||
8280 | return LHSTy.getUnqualifiedType(); | ||||
8281 | // FIXME: Type of conditional expression must be complete in C mode. | ||||
8282 | } | ||||
8283 | |||||
8284 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | ||||
8285 | // The following || allows only one side to be void (a GCC-ism). | ||||
8286 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | ||||
8287 | return checkConditionalVoidType(*this, LHS, RHS); | ||||
8288 | } | ||||
8289 | |||||
8290 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | ||||
8291 | // the type of the other operand." | ||||
8292 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | ||||
8293 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | ||||
8294 | |||||
8295 | // All objective-c pointer type analysis is done here. | ||||
8296 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | ||||
8297 | QuestionLoc); | ||||
8298 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8299 | return QualType(); | ||||
8300 | if (!compositeType.isNull()) | ||||
8301 | return compositeType; | ||||
8302 | |||||
8303 | |||||
8304 | // Handle block pointer types. | ||||
8305 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | ||||
8306 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | ||||
8307 | QuestionLoc); | ||||
8308 | |||||
8309 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | ||||
8310 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | ||||
8311 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | ||||
8312 | QuestionLoc); | ||||
8313 | |||||
8314 | // GCC compatibility: soften pointer/integer mismatch. Note that | ||||
8315 | // null pointers have been filtered out by this point. | ||||
8316 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | ||||
8317 | /*IsIntFirstExpr=*/true)) | ||||
8318 | return RHSTy; | ||||
8319 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | ||||
8320 | /*IsIntFirstExpr=*/false)) | ||||
8321 | return LHSTy; | ||||
8322 | |||||
8323 | // Allow ?: operations in which both operands have the same | ||||
8324 | // built-in sizeless type. | ||||
8325 | if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) | ||||
8326 | return LHSTy; | ||||
8327 | |||||
8328 | // Emit a better diagnostic if one of the expressions is a null pointer | ||||
8329 | // constant and the other is not a pointer type. In this case, the user most | ||||
8330 | // likely forgot to take the address of the other expression. | ||||
8331 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | ||||
8332 | return QualType(); | ||||
8333 | |||||
8334 | // Otherwise, the operands are not compatible. | ||||
8335 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8336 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8337 | << RHS.get()->getSourceRange(); | ||||
8338 | return QualType(); | ||||
8339 | } | ||||
8340 | |||||
8341 | /// FindCompositeObjCPointerType - Helper method to find composite type of | ||||
8342 | /// two objective-c pointer types of the two input expressions. | ||||
8343 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | ||||
8344 | SourceLocation QuestionLoc) { | ||||
8345 | QualType LHSTy = LHS.get()->getType(); | ||||
8346 | QualType RHSTy = RHS.get()->getType(); | ||||
8347 | |||||
8348 | // Handle things like Class and struct objc_class*. Here we case the result | ||||
8349 | // to the pseudo-builtin, because that will be implicitly cast back to the | ||||
8350 | // redefinition type if an attempt is made to access its fields. | ||||
8351 | if (LHSTy->isObjCClassType() && | ||||
8352 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8353 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8354 | return LHSTy; | ||||
8355 | } | ||||
8356 | if (RHSTy->isObjCClassType() && | ||||
8357 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8358 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8359 | return RHSTy; | ||||
8360 | } | ||||
8361 | // And the same for struct objc_object* / id | ||||
8362 | if (LHSTy->isObjCIdType() && | ||||
8363 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8364 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8365 | return LHSTy; | ||||
8366 | } | ||||
8367 | if (RHSTy->isObjCIdType() && | ||||
8368 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8369 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8370 | return RHSTy; | ||||
8371 | } | ||||
8372 | // And the same for struct objc_selector* / SEL | ||||
8373 | if (Context.isObjCSelType(LHSTy) && | ||||
8374 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8375 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | ||||
8376 | return LHSTy; | ||||
8377 | } | ||||
8378 | if (Context.isObjCSelType(RHSTy) && | ||||
8379 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8380 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | ||||
8381 | return RHSTy; | ||||
8382 | } | ||||
8383 | // Check constraints for Objective-C object pointers types. | ||||
8384 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8385 | |||||
8386 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | ||||
8387 | // Two identical object pointer types are always compatible. | ||||
8388 | return LHSTy; | ||||
8389 | } | ||||
8390 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | ||||
8391 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | ||||
8392 | QualType compositeType = LHSTy; | ||||
8393 | |||||
8394 | // If both operands are interfaces and either operand can be | ||||
8395 | // assigned to the other, use that type as the composite | ||||
8396 | // type. This allows | ||||
8397 | // xxx ? (A*) a : (B*) b | ||||
8398 | // where B is a subclass of A. | ||||
8399 | // | ||||
8400 | // Additionally, as for assignment, if either type is 'id' | ||||
8401 | // allow silent coercion. Finally, if the types are | ||||
8402 | // incompatible then make sure to use 'id' as the composite | ||||
8403 | // type so the result is acceptable for sending messages to. | ||||
8404 | |||||
8405 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | ||||
8406 | // It could return the composite type. | ||||
8407 | if (!(compositeType = | ||||
8408 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | ||||
8409 | // Nothing more to do. | ||||
8410 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | ||||
8411 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | ||||
8412 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | ||||
8413 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | ||||
8414 | } else if ((LHSOPT->isObjCQualifiedIdType() || | ||||
8415 | RHSOPT->isObjCQualifiedIdType()) && | ||||
8416 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | ||||
8417 | true)) { | ||||
8418 | // Need to handle "id<xx>" explicitly. | ||||
8419 | // GCC allows qualified id and any Objective-C type to devolve to | ||||
8420 | // id. Currently localizing to here until clear this should be | ||||
8421 | // part of ObjCQualifiedIdTypesAreCompatible. | ||||
8422 | compositeType = Context.getObjCIdType(); | ||||
8423 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | ||||
8424 | compositeType = Context.getObjCIdType(); | ||||
8425 | } else { | ||||
8426 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | ||||
8427 | << LHSTy << RHSTy | ||||
8428 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8429 | QualType incompatTy = Context.getObjCIdType(); | ||||
8430 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | ||||
8431 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | ||||
8432 | return incompatTy; | ||||
8433 | } | ||||
8434 | // The object pointer types are compatible. | ||||
8435 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | ||||
8436 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | ||||
8437 | return compositeType; | ||||
8438 | } | ||||
8439 | // Check Objective-C object pointer types and 'void *' | ||||
8440 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8441 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8442 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8443 | // so these types are not compatible. | ||||
8444 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8445 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8446 | LHS = RHS = true; | ||||
8447 | return QualType(); | ||||
8448 | } | ||||
8449 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8450 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8451 | QualType destPointee | ||||
8452 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8453 | QualType destType = Context.getPointerType(destPointee); | ||||
8454 | // Add qualifiers if necessary. | ||||
8455 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8456 | // Promote to void*. | ||||
8457 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8458 | return destType; | ||||
8459 | } | ||||
8460 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | ||||
8461 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8462 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8463 | // so these types are not compatible. | ||||
8464 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8465 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8466 | LHS = RHS = true; | ||||
8467 | return QualType(); | ||||
8468 | } | ||||
8469 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8470 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8471 | QualType destPointee | ||||
8472 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8473 | QualType destType = Context.getPointerType(destPointee); | ||||
8474 | // Add qualifiers if necessary. | ||||
8475 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8476 | // Promote to void*. | ||||
8477 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8478 | return destType; | ||||
8479 | } | ||||
8480 | return QualType(); | ||||
8481 | } | ||||
8482 | |||||
8483 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | ||||
8484 | /// ParenRange in parentheses. | ||||
8485 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | ||||
8486 | const PartialDiagnostic &Note, | ||||
8487 | SourceRange ParenRange) { | ||||
8488 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | ||||
8489 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | ||||
8490 | EndLoc.isValid()) { | ||||
8491 | Self.Diag(Loc, Note) | ||||
8492 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | ||||
8493 | << FixItHint::CreateInsertion(EndLoc, ")"); | ||||
8494 | } else { | ||||
8495 | // We can't display the parentheses, so just show the bare note. | ||||
8496 | Self.Diag(Loc, Note) << ParenRange; | ||||
8497 | } | ||||
8498 | } | ||||
8499 | |||||
8500 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | ||||
8501 | return BinaryOperator::isAdditiveOp(Opc) || | ||||
8502 | BinaryOperator::isMultiplicativeOp(Opc) || | ||||
8503 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | ||||
8504 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | ||||
8505 | // not any of the logical operators. Bitwise-xor is commonly used as a | ||||
8506 | // logical-xor because there is no logical-xor operator. The logical | ||||
8507 | // operators, including uses of xor, have a high false positive rate for | ||||
8508 | // precedence warnings. | ||||
8509 | } | ||||
8510 | |||||
8511 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | ||||
8512 | /// expression, either using a built-in or overloaded operator, | ||||
8513 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | ||||
8514 | /// expression. | ||||
8515 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | ||||
8516 | Expr **RHSExprs) { | ||||
8517 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | ||||
8518 | E = E->IgnoreImpCasts(); | ||||
8519 | E = E->IgnoreConversionOperatorSingleStep(); | ||||
8520 | E = E->IgnoreImpCasts(); | ||||
8521 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | ||||
8522 | E = MTE->getSubExpr(); | ||||
8523 | E = E->IgnoreImpCasts(); | ||||
8524 | } | ||||
8525 | |||||
8526 | // Built-in binary operator. | ||||
8527 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | ||||
8528 | if (IsArithmeticOp(OP->getOpcode())) { | ||||
8529 | *Opcode = OP->getOpcode(); | ||||
8530 | *RHSExprs = OP->getRHS(); | ||||
8531 | return true; | ||||
8532 | } | ||||
8533 | } | ||||
8534 | |||||
8535 | // Overloaded operator. | ||||
8536 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
8537 | if (Call->getNumArgs() != 2) | ||||
8538 | return false; | ||||
8539 | |||||
8540 | // Make sure this is really a binary operator that is safe to pass into | ||||
8541 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | ||||
8542 | OverloadedOperatorKind OO = Call->getOperator(); | ||||
8543 | if (OO < OO_Plus || OO > OO_Arrow || | ||||
8544 | OO == OO_PlusPlus || OO == OO_MinusMinus) | ||||
8545 | return false; | ||||
8546 | |||||
8547 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | ||||
8548 | if (IsArithmeticOp(OpKind)) { | ||||
8549 | *Opcode = OpKind; | ||||
8550 | *RHSExprs = Call->getArg(1); | ||||
8551 | return true; | ||||
8552 | } | ||||
8553 | } | ||||
8554 | |||||
8555 | return false; | ||||
8556 | } | ||||
8557 | |||||
8558 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | ||||
8559 | /// or is a logical expression such as (x==y) which has int type, but is | ||||
8560 | /// commonly interpreted as boolean. | ||||
8561 | static bool ExprLooksBoolean(Expr *E) { | ||||
8562 | E = E->IgnoreParenImpCasts(); | ||||
8563 | |||||
8564 | if (E->getType()->isBooleanType()) | ||||
8565 | return true; | ||||
8566 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | ||||
8567 | return OP->isComparisonOp() || OP->isLogicalOp(); | ||||
8568 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | ||||
8569 | return OP->getOpcode() == UO_LNot; | ||||
8570 | if (E->getType()->isPointerType()) | ||||
8571 | return true; | ||||
8572 | // FIXME: What about overloaded operator calls returning "unspecified boolean | ||||
8573 | // type"s (commonly pointer-to-members)? | ||||
8574 | |||||
8575 | return false; | ||||
8576 | } | ||||
8577 | |||||
8578 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | ||||
8579 | /// and binary operator are mixed in a way that suggests the programmer assumed | ||||
8580 | /// the conditional operator has higher precedence, for example: | ||||
8581 | /// "int x = a + someBinaryCondition ? 1 : 2". | ||||
8582 | static void DiagnoseConditionalPrecedence(Sema &Self, | ||||
8583 | SourceLocation OpLoc, | ||||
8584 | Expr *Condition, | ||||
8585 | Expr *LHSExpr, | ||||
8586 | Expr *RHSExpr) { | ||||
8587 | BinaryOperatorKind CondOpcode; | ||||
8588 | Expr *CondRHS; | ||||
8589 | |||||
8590 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | ||||
8591 | return; | ||||
8592 | if (!ExprLooksBoolean(CondRHS)) | ||||
8593 | return; | ||||
8594 | |||||
8595 | // The condition is an arithmetic binary expression, with a right- | ||||
8596 | // hand side that looks boolean, so warn. | ||||
8597 | |||||
8598 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | ||||
8599 | ? diag::warn_precedence_bitwise_conditional | ||||
8600 | : diag::warn_precedence_conditional; | ||||
8601 | |||||
8602 | Self.Diag(OpLoc, DiagID) | ||||
8603 | << Condition->getSourceRange() | ||||
8604 | << BinaryOperator::getOpcodeStr(CondOpcode); | ||||
8605 | |||||
8606 | SuggestParentheses( | ||||
8607 | Self, OpLoc, | ||||
8608 | Self.PDiag(diag::note_precedence_silence) | ||||
8609 | << BinaryOperator::getOpcodeStr(CondOpcode), | ||||
8610 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | ||||
8611 | |||||
8612 | SuggestParentheses(Self, OpLoc, | ||||
8613 | Self.PDiag(diag::note_precedence_conditional_first), | ||||
8614 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
8615 | } | ||||
8616 | |||||
8617 | /// Compute the nullability of a conditional expression. | ||||
8618 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | ||||
8619 | QualType LHSTy, QualType RHSTy, | ||||
8620 | ASTContext &Ctx) { | ||||
8621 | if (!ResTy->isAnyPointerType()) | ||||
8622 | return ResTy; | ||||
8623 | |||||
8624 | auto GetNullability = [&Ctx](QualType Ty) { | ||||
8625 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | ||||
8626 | if (Kind) { | ||||
8627 | // For our purposes, treat _Nullable_result as _Nullable. | ||||
8628 | if (*Kind == NullabilityKind::NullableResult) | ||||
8629 | return NullabilityKind::Nullable; | ||||
8630 | return *Kind; | ||||
8631 | } | ||||
8632 | return NullabilityKind::Unspecified; | ||||
8633 | }; | ||||
8634 | |||||
8635 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | ||||
8636 | NullabilityKind MergedKind; | ||||
8637 | |||||
8638 | // Compute nullability of a binary conditional expression. | ||||
8639 | if (IsBin) { | ||||
8640 | if (LHSKind == NullabilityKind::NonNull) | ||||
8641 | MergedKind = NullabilityKind::NonNull; | ||||
8642 | else | ||||
8643 | MergedKind = RHSKind; | ||||
8644 | // Compute nullability of a normal conditional expression. | ||||
8645 | } else { | ||||
8646 | if (LHSKind == NullabilityKind::Nullable || | ||||
8647 | RHSKind == NullabilityKind::Nullable) | ||||
8648 | MergedKind = NullabilityKind::Nullable; | ||||
8649 | else if (LHSKind == NullabilityKind::NonNull) | ||||
8650 | MergedKind = RHSKind; | ||||
8651 | else if (RHSKind == NullabilityKind::NonNull) | ||||
8652 | MergedKind = LHSKind; | ||||
8653 | else | ||||
8654 | MergedKind = NullabilityKind::Unspecified; | ||||
8655 | } | ||||
8656 | |||||
8657 | // Return if ResTy already has the correct nullability. | ||||
8658 | if (GetNullability(ResTy) == MergedKind) | ||||
8659 | return ResTy; | ||||
8660 | |||||
8661 | // Strip all nullability from ResTy. | ||||
8662 | while (ResTy->getNullability(Ctx)) | ||||
8663 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | ||||
8664 | |||||
8665 | // Create a new AttributedType with the new nullability kind. | ||||
8666 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | ||||
8667 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | ||||
8668 | } | ||||
8669 | |||||
8670 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | ||||
8671 | /// in the case of a the GNU conditional expr extension. | ||||
8672 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | ||||
8673 | SourceLocation ColonLoc, | ||||
8674 | Expr *CondExpr, Expr *LHSExpr, | ||||
8675 | Expr *RHSExpr) { | ||||
8676 | if (!Context.isDependenceAllowed()) { | ||||
8677 | // C cannot handle TypoExpr nodes in the condition because it | ||||
8678 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
8679 | // been dealt with before checking the operands. | ||||
8680 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | ||||
8681 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | ||||
8682 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | ||||
8683 | |||||
8684 | if (!CondResult.isUsable()) | ||||
8685 | return ExprError(); | ||||
8686 | |||||
8687 | if (LHSExpr) { | ||||
8688 | if (!LHSResult.isUsable()) | ||||
8689 | return ExprError(); | ||||
8690 | } | ||||
8691 | |||||
8692 | if (!RHSResult.isUsable()) | ||||
8693 | return ExprError(); | ||||
8694 | |||||
8695 | CondExpr = CondResult.get(); | ||||
8696 | LHSExpr = LHSResult.get(); | ||||
8697 | RHSExpr = RHSResult.get(); | ||||
8698 | } | ||||
8699 | |||||
8700 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | ||||
8701 | // was the condition. | ||||
8702 | OpaqueValueExpr *opaqueValue = nullptr; | ||||
8703 | Expr *commonExpr = nullptr; | ||||
8704 | if (!LHSExpr) { | ||||
8705 | commonExpr = CondExpr; | ||||
8706 | // Lower out placeholder types first. This is important so that we don't | ||||
8707 | // try to capture a placeholder. This happens in few cases in C++; such | ||||
8708 | // as Objective-C++'s dictionary subscripting syntax. | ||||
8709 | if (commonExpr->hasPlaceholderType()) { | ||||
8710 | ExprResult result = CheckPlaceholderExpr(commonExpr); | ||||
8711 | if (!result.isUsable()) return ExprError(); | ||||
8712 | commonExpr = result.get(); | ||||
8713 | } | ||||
8714 | // We usually want to apply unary conversions *before* saving, except | ||||
8715 | // in the special case of a C++ l-value conditional. | ||||
8716 | if (!(getLangOpts().CPlusPlus | ||||
8717 | && !commonExpr->isTypeDependent() | ||||
8718 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | ||||
8719 | && commonExpr->isGLValue() | ||||
8720 | && commonExpr->isOrdinaryOrBitFieldObject() | ||||
8721 | && RHSExpr->isOrdinaryOrBitFieldObject() | ||||
8722 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | ||||
8723 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | ||||
8724 | if (commonRes.isInvalid()) | ||||
8725 | return ExprError(); | ||||
8726 | commonExpr = commonRes.get(); | ||||
8727 | } | ||||
8728 | |||||
8729 | // If the common expression is a class or array prvalue, materialize it | ||||
8730 | // so that we can safely refer to it multiple times. | ||||
8731 | if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || | ||||
8732 | commonExpr->getType()->isArrayType())) { | ||||
8733 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | ||||
8734 | if (MatExpr.isInvalid()) | ||||
8735 | return ExprError(); | ||||
8736 | commonExpr = MatExpr.get(); | ||||
8737 | } | ||||
8738 | |||||
8739 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | ||||
8740 | commonExpr->getType(), | ||||
8741 | commonExpr->getValueKind(), | ||||
8742 | commonExpr->getObjectKind(), | ||||
8743 | commonExpr); | ||||
8744 | LHSExpr = CondExpr = opaqueValue; | ||||
8745 | } | ||||
8746 | |||||
8747 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | ||||
8748 | ExprValueKind VK = VK_RValue; | ||||
8749 | ExprObjectKind OK = OK_Ordinary; | ||||
8750 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | ||||
8751 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | ||||
8752 | VK, OK, QuestionLoc); | ||||
8753 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | ||||
8754 | RHS.isInvalid()) | ||||
8755 | return ExprError(); | ||||
8756 | |||||
8757 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | ||||
8758 | RHS.get()); | ||||
8759 | |||||
8760 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | ||||
8761 | |||||
8762 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | ||||
8763 | Context); | ||||
8764 | |||||
8765 | if (!commonExpr) | ||||
8766 | return new (Context) | ||||
8767 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | ||||
8768 | RHS.get(), result, VK, OK); | ||||
8769 | |||||
8770 | return new (Context) BinaryConditionalOperator( | ||||
8771 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | ||||
8772 | ColonLoc, result, VK, OK); | ||||
8773 | } | ||||
8774 | |||||
8775 | // Check if we have a conversion between incompatible cmse function pointer | ||||
8776 | // types, that is, a conversion between a function pointer with the | ||||
8777 | // cmse_nonsecure_call attribute and one without. | ||||
8778 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | ||||
8779 | QualType ToType) { | ||||
8780 | if (const auto *ToFn = | ||||
8781 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | ||||
8782 | if (const auto *FromFn = | ||||
8783 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | ||||
8784 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | ||||
8785 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | ||||
8786 | |||||
8787 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | ||||
8788 | } | ||||
8789 | } | ||||
8790 | return false; | ||||
8791 | } | ||||
8792 | |||||
8793 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | ||||
8794 | // being closely modeled after the C99 spec:-). The odd characteristic of this | ||||
8795 | // routine is it effectively iqnores the qualifiers on the top level pointee. | ||||
8796 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | ||||
8797 | // FIXME: add a couple examples in this comment. | ||||
8798 | static Sema::AssignConvertType | ||||
8799 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | ||||
8800 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8800, __PRETTY_FUNCTION__)); | ||||
8801 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8801, __PRETTY_FUNCTION__)); | ||||
8802 | |||||
8803 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
8804 | const Type *lhptee, *rhptee; | ||||
8805 | Qualifiers lhq, rhq; | ||||
8806 | std::tie(lhptee, lhq) = | ||||
8807 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | ||||
8808 | std::tie(rhptee, rhq) = | ||||
8809 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | ||||
8810 | |||||
8811 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
8812 | |||||
8813 | // C99 6.5.16.1p1: This following citation is common to constraints | ||||
8814 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | ||||
8815 | // qualifiers of the type *pointed to* by the right; | ||||
8816 | |||||
8817 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | ||||
8818 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | ||||
8819 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | ||||
8820 | // Ignore lifetime for further calculation. | ||||
8821 | lhq.removeObjCLifetime(); | ||||
8822 | rhq.removeObjCLifetime(); | ||||
8823 | } | ||||
8824 | |||||
8825 | if (!lhq.compatiblyIncludes(rhq)) { | ||||
8826 | // Treat address-space mismatches as fatal. | ||||
8827 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | ||||
8828 | return Sema::IncompatiblePointerDiscardsQualifiers; | ||||
8829 | |||||
8830 | // It's okay to add or remove GC or lifetime qualifiers when converting to | ||||
8831 | // and from void*. | ||||
8832 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | ||||
8833 | .compatiblyIncludes( | ||||
8834 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | ||||
8835 | && (lhptee->isVoidType() || rhptee->isVoidType())) | ||||
8836 | ; // keep old | ||||
8837 | |||||
8838 | // Treat lifetime mismatches as fatal. | ||||
8839 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | ||||
8840 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | ||||
8841 | |||||
8842 | // For GCC/MS compatibility, other qualifier mismatches are treated | ||||
8843 | // as still compatible in C. | ||||
8844 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
8845 | } | ||||
8846 | |||||
8847 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | ||||
8848 | // incomplete type and the other is a pointer to a qualified or unqualified | ||||
8849 | // version of void... | ||||
8850 | if (lhptee->isVoidType()) { | ||||
8851 | if (rhptee->isIncompleteOrObjectType()) | ||||
8852 | return ConvTy; | ||||
8853 | |||||
8854 | // As an extension, we allow cast to/from void* to function pointer. | ||||
8855 | assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8855, __PRETTY_FUNCTION__)); | ||||
8856 | return Sema::FunctionVoidPointer; | ||||
8857 | } | ||||
8858 | |||||
8859 | if (rhptee->isVoidType()) { | ||||
8860 | if (lhptee->isIncompleteOrObjectType()) | ||||
8861 | return ConvTy; | ||||
8862 | |||||
8863 | // As an extension, we allow cast to/from void* to function pointer. | ||||
8864 | assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8864, __PRETTY_FUNCTION__)); | ||||
8865 | return Sema::FunctionVoidPointer; | ||||
8866 | } | ||||
8867 | |||||
8868 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | ||||
8869 | // unqualified versions of compatible types, ... | ||||
8870 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | ||||
8871 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | ||||
8872 | // Check if the pointee types are compatible ignoring the sign. | ||||
8873 | // We explicitly check for char so that we catch "char" vs | ||||
8874 | // "unsigned char" on systems where "char" is unsigned. | ||||
8875 | if (lhptee->isCharType()) | ||||
8876 | ltrans = S.Context.UnsignedCharTy; | ||||
8877 | else if (lhptee->hasSignedIntegerRepresentation()) | ||||
8878 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | ||||
8879 | |||||
8880 | if (rhptee->isCharType()) | ||||
8881 | rtrans = S.Context.UnsignedCharTy; | ||||
8882 | else if (rhptee->hasSignedIntegerRepresentation()) | ||||
8883 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | ||||
8884 | |||||
8885 | if (ltrans == rtrans) { | ||||
8886 | // Types are compatible ignoring the sign. Qualifier incompatibility | ||||
8887 | // takes priority over sign incompatibility because the sign | ||||
8888 | // warning can be disabled. | ||||
8889 | if (ConvTy != Sema::Compatible) | ||||
8890 | return ConvTy; | ||||
8891 | |||||
8892 | return Sema::IncompatiblePointerSign; | ||||
8893 | } | ||||
8894 | |||||
8895 | // If we are a multi-level pointer, it's possible that our issue is simply | ||||
8896 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | ||||
8897 | // the eventual target type is the same and the pointers have the same | ||||
8898 | // level of indirection, this must be the issue. | ||||
8899 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | ||||
8900 | do { | ||||
8901 | std::tie(lhptee, lhq) = | ||||
8902 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | ||||
8903 | std::tie(rhptee, rhq) = | ||||
8904 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | ||||
8905 | |||||
8906 | // Inconsistent address spaces at this point is invalid, even if the | ||||
8907 | // address spaces would be compatible. | ||||
8908 | // FIXME: This doesn't catch address space mismatches for pointers of | ||||
8909 | // different nesting levels, like: | ||||
8910 | // __local int *** a; | ||||
8911 | // int ** b = a; | ||||
8912 | // It's not clear how to actually determine when such pointers are | ||||
8913 | // invalidly incompatible. | ||||
8914 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | ||||
8915 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | ||||
8916 | |||||
8917 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | ||||
8918 | |||||
8919 | if (lhptee == rhptee) | ||||
8920 | return Sema::IncompatibleNestedPointerQualifiers; | ||||
8921 | } | ||||
8922 | |||||
8923 | // General pointer incompatibility takes priority over qualifiers. | ||||
8924 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | ||||
8925 | return Sema::IncompatibleFunctionPointer; | ||||
8926 | return Sema::IncompatiblePointer; | ||||
8927 | } | ||||
8928 | if (!S.getLangOpts().CPlusPlus && | ||||
8929 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | ||||
8930 | return Sema::IncompatibleFunctionPointer; | ||||
8931 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | ||||
8932 | return Sema::IncompatibleFunctionPointer; | ||||
8933 | return ConvTy; | ||||
8934 | } | ||||
8935 | |||||
8936 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | ||||
8937 | /// block pointer types are compatible or whether a block and normal pointer | ||||
8938 | /// are compatible. It is more restrict than comparing two function pointer | ||||
8939 | // types. | ||||
8940 | static Sema::AssignConvertType | ||||
8941 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
8942 | QualType RHSType) { | ||||
8943 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8943, __PRETTY_FUNCTION__)); | ||||
8944 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8944, __PRETTY_FUNCTION__)); | ||||
8945 | |||||
8946 | QualType lhptee, rhptee; | ||||
8947 | |||||
8948 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
8949 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | ||||
8950 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | ||||
8951 | |||||
8952 | // In C++, the types have to match exactly. | ||||
8953 | if (S.getLangOpts().CPlusPlus) | ||||
8954 | return Sema::IncompatibleBlockPointer; | ||||
8955 | |||||
8956 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
8957 | |||||
8958 | // For blocks we enforce that qualifiers are identical. | ||||
8959 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | ||||
8960 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | ||||
8961 | if (S.getLangOpts().OpenCL) { | ||||
8962 | LQuals.removeAddressSpace(); | ||||
8963 | RQuals.removeAddressSpace(); | ||||
8964 | } | ||||
8965 | if (LQuals != RQuals) | ||||
8966 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
8967 | |||||
8968 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | ||||
8969 | // assignment. | ||||
8970 | // The current behavior is similar to C++ lambdas. A block might be | ||||
8971 | // assigned to a variable iff its return type and parameters are compatible | ||||
8972 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | ||||
8973 | // an assignment. Presumably it should behave in way that a function pointer | ||||
8974 | // assignment does in C, so for each parameter and return type: | ||||
8975 | // * CVR and address space of LHS should be a superset of CVR and address | ||||
8976 | // space of RHS. | ||||
8977 | // * unqualified types should be compatible. | ||||
8978 | if (S.getLangOpts().OpenCL) { | ||||
8979 | if (!S.Context.typesAreBlockPointerCompatible( | ||||
8980 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | ||||
8981 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | ||||
8982 | return Sema::IncompatibleBlockPointer; | ||||
8983 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | ||||
8984 | return Sema::IncompatibleBlockPointer; | ||||
8985 | |||||
8986 | return ConvTy; | ||||
8987 | } | ||||
8988 | |||||
8989 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | ||||
8990 | /// for assignment compatibility. | ||||
8991 | static Sema::AssignConvertType | ||||
8992 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
8993 | QualType RHSType) { | ||||
8994 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8994, __PRETTY_FUNCTION__)); | ||||
8995 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 8995, __PRETTY_FUNCTION__)); | ||||
8996 | |||||
8997 | if (LHSType->isObjCBuiltinType()) { | ||||
8998 | // Class is not compatible with ObjC object pointers. | ||||
8999 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | ||||
9000 | !RHSType->isObjCQualifiedClassType()) | ||||
9001 | return Sema::IncompatiblePointer; | ||||
9002 | return Sema::Compatible; | ||||
9003 | } | ||||
9004 | if (RHSType->isObjCBuiltinType()) { | ||||
9005 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | ||||
9006 | !LHSType->isObjCQualifiedClassType()) | ||||
9007 | return Sema::IncompatiblePointer; | ||||
9008 | return Sema::Compatible; | ||||
9009 | } | ||||
9010 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9011 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9012 | |||||
9013 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | ||||
9014 | // make an exception for id<P> | ||||
9015 | !LHSType->isObjCQualifiedIdType()) | ||||
9016 | return Sema::CompatiblePointerDiscardsQualifiers; | ||||
9017 | |||||
9018 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | ||||
9019 | return Sema::Compatible; | ||||
9020 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | ||||
9021 | return Sema::IncompatibleObjCQualifiedId; | ||||
9022 | return Sema::IncompatiblePointer; | ||||
9023 | } | ||||
9024 | |||||
9025 | Sema::AssignConvertType | ||||
9026 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | ||||
9027 | QualType LHSType, QualType RHSType) { | ||||
9028 | // Fake up an opaque expression. We don't actually care about what | ||||
9029 | // cast operations are required, so if CheckAssignmentConstraints | ||||
9030 | // adds casts to this they'll be wasted, but fortunately that doesn't | ||||
9031 | // usually happen on valid code. | ||||
9032 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); | ||||
9033 | ExprResult RHSPtr = &RHSExpr; | ||||
9034 | CastKind K; | ||||
9035 | |||||
9036 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | ||||
9037 | } | ||||
9038 | |||||
9039 | /// This helper function returns true if QT is a vector type that has element | ||||
9040 | /// type ElementType. | ||||
9041 | static bool isVector(QualType QT, QualType ElementType) { | ||||
9042 | if (const VectorType *VT = QT->getAs<VectorType>()) | ||||
9043 | return VT->getElementType().getCanonicalType() == ElementType; | ||||
9044 | return false; | ||||
9045 | } | ||||
9046 | |||||
9047 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | ||||
9048 | /// has code to accommodate several GCC extensions when type checking | ||||
9049 | /// pointers. Here are some objectionable examples that GCC considers warnings: | ||||
9050 | /// | ||||
9051 | /// int a, *pint; | ||||
9052 | /// short *pshort; | ||||
9053 | /// struct foo *pfoo; | ||||
9054 | /// | ||||
9055 | /// pint = pshort; // warning: assignment from incompatible pointer type | ||||
9056 | /// a = pint; // warning: assignment makes integer from pointer without a cast | ||||
9057 | /// pint = a; // warning: assignment makes pointer from integer without a cast | ||||
9058 | /// pint = pfoo; // warning: assignment from incompatible pointer type | ||||
9059 | /// | ||||
9060 | /// As a result, the code for dealing with pointers is more complex than the | ||||
9061 | /// C99 spec dictates. | ||||
9062 | /// | ||||
9063 | /// Sets 'Kind' for any result kind except Incompatible. | ||||
9064 | Sema::AssignConvertType | ||||
9065 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | ||||
9066 | CastKind &Kind, bool ConvertRHS) { | ||||
9067 | QualType RHSType = RHS.get()->getType(); | ||||
9068 | QualType OrigLHSType = LHSType; | ||||
9069 | |||||
9070 | // Get canonical types. We're not formatting these types, just comparing | ||||
9071 | // them. | ||||
9072 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | ||||
9073 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | ||||
9074 | |||||
9075 | // Common case: no conversion required. | ||||
9076 | if (LHSType == RHSType) { | ||||
9077 | Kind = CK_NoOp; | ||||
9078 | return Compatible; | ||||
9079 | } | ||||
9080 | |||||
9081 | // If we have an atomic type, try a non-atomic assignment, then just add an | ||||
9082 | // atomic qualification step. | ||||
9083 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { | ||||
9084 | Sema::AssignConvertType result = | ||||
9085 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | ||||
9086 | if (result != Compatible) | ||||
9087 | return result; | ||||
9088 | if (Kind != CK_NoOp && ConvertRHS) | ||||
9089 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | ||||
9090 | Kind = CK_NonAtomicToAtomic; | ||||
9091 | return Compatible; | ||||
9092 | } | ||||
9093 | |||||
9094 | // If the left-hand side is a reference type, then we are in a | ||||
9095 | // (rare!) case where we've allowed the use of references in C, | ||||
9096 | // e.g., as a parameter type in a built-in function. In this case, | ||||
9097 | // just make sure that the type referenced is compatible with the | ||||
9098 | // right-hand side type. The caller is responsible for adjusting | ||||
9099 | // LHSType so that the resulting expression does not have reference | ||||
9100 | // type. | ||||
9101 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { | ||||
9102 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | ||||
9103 | Kind = CK_LValueBitCast; | ||||
9104 | return Compatible; | ||||
9105 | } | ||||
9106 | return Incompatible; | ||||
9107 | } | ||||
9108 | |||||
9109 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | ||||
9110 | // to the same ExtVector type. | ||||
9111 | if (LHSType->isExtVectorType()) { | ||||
9112 | if (RHSType->isExtVectorType()) | ||||
9113 | return Incompatible; | ||||
9114 | if (RHSType->isArithmeticType()) { | ||||
9115 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | ||||
9116 | if (ConvertRHS) | ||||
9117 | RHS = prepareVectorSplat(LHSType, RHS.get()); | ||||
9118 | Kind = CK_VectorSplat; | ||||
9119 | return Compatible; | ||||
9120 | } | ||||
9121 | } | ||||
9122 | |||||
9123 | // Conversions to or from vector type. | ||||
9124 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | ||||
9125 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | ||||
9126 | // Allow assignments of an AltiVec vector type to an equivalent GCC | ||||
9127 | // vector type and vice versa | ||||
9128 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9129 | Kind = CK_BitCast; | ||||
9130 | return Compatible; | ||||
9131 | } | ||||
9132 | |||||
9133 | // If we are allowing lax vector conversions, and LHS and RHS are both | ||||
9134 | // vectors, the total size only needs to be the same. This is a bitcast; | ||||
9135 | // no bits are changed but the result type is different. | ||||
9136 | if (isLaxVectorConversion(RHSType, LHSType)) { | ||||
9137 | Kind = CK_BitCast; | ||||
9138 | return IncompatibleVectors; | ||||
9139 | } | ||||
9140 | } | ||||
9141 | |||||
9142 | // When the RHS comes from another lax conversion (e.g. binops between | ||||
9143 | // scalars and vectors) the result is canonicalized as a vector. When the | ||||
9144 | // LHS is also a vector, the lax is allowed by the condition above. Handle | ||||
9145 | // the case where LHS is a scalar. | ||||
9146 | if (LHSType->isScalarType()) { | ||||
9147 | const VectorType *VecType = RHSType->getAs<VectorType>(); | ||||
9148 | if (VecType && VecType->getNumElements() == 1 && | ||||
9149 | isLaxVectorConversion(RHSType, LHSType)) { | ||||
9150 | ExprResult *VecExpr = &RHS; | ||||
9151 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | ||||
9152 | Kind = CK_BitCast; | ||||
9153 | return Compatible; | ||||
9154 | } | ||||
9155 | } | ||||
9156 | |||||
9157 | // Allow assignments between fixed-length and sizeless SVE vectors. | ||||
9158 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | ||||
9159 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | ||||
9160 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | ||||
9161 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | ||||
9162 | Kind = CK_BitCast; | ||||
9163 | return Compatible; | ||||
9164 | } | ||||
9165 | |||||
9166 | return Incompatible; | ||||
9167 | } | ||||
9168 | |||||
9169 | // Diagnose attempts to convert between __float128 and long double where | ||||
9170 | // such conversions currently can't be handled. | ||||
9171 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
9172 | return Incompatible; | ||||
9173 | |||||
9174 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | ||||
9175 | // discards the imaginary part. | ||||
9176 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | ||||
9177 | !LHSType->getAs<ComplexType>()) | ||||
9178 | return Incompatible; | ||||
9179 | |||||
9180 | // Arithmetic conversions. | ||||
9181 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | ||||
9182 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | ||||
9183 | if (ConvertRHS) | ||||
9184 | Kind = PrepareScalarCast(RHS, LHSType); | ||||
9185 | return Compatible; | ||||
9186 | } | ||||
9187 | |||||
9188 | // Conversions to normal pointers. | ||||
9189 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { | ||||
9190 | // U* -> T* | ||||
9191 | if (isa<PointerType>(RHSType)) { | ||||
9192 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9193 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | ||||
9194 | if (AddrSpaceL != AddrSpaceR) | ||||
9195 | Kind = CK_AddressSpaceConversion; | ||||
9196 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | ||||
9197 | Kind = CK_NoOp; | ||||
9198 | else | ||||
9199 | Kind = CK_BitCast; | ||||
9200 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9201 | } | ||||
9202 | |||||
9203 | // int -> T* | ||||
9204 | if (RHSType->isIntegerType()) { | ||||
9205 | Kind = CK_IntegralToPointer; // FIXME: null? | ||||
9206 | return IntToPointer; | ||||
9207 | } | ||||
9208 | |||||
9209 | // C pointers are not compatible with ObjC object pointers, | ||||
9210 | // with two exceptions: | ||||
9211 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9212 | // - conversions to void* | ||||
9213 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9214 | Kind = CK_BitCast; | ||||
9215 | return Compatible; | ||||
9216 | } | ||||
9217 | |||||
9218 | // - conversions from 'Class' to the redefinition type | ||||
9219 | if (RHSType->isObjCClassType() && | ||||
9220 | Context.hasSameType(LHSType, | ||||
9221 | Context.getObjCClassRedefinitionType())) { | ||||
9222 | Kind = CK_BitCast; | ||||
9223 | return Compatible; | ||||
9224 | } | ||||
9225 | |||||
9226 | Kind = CK_BitCast; | ||||
9227 | return IncompatiblePointer; | ||||
9228 | } | ||||
9229 | |||||
9230 | // U^ -> void* | ||||
9231 | if (RHSType->getAs<BlockPointerType>()) { | ||||
9232 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9233 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9234 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9235 | ->getPointeeType() | ||||
9236 | .getAddressSpace(); | ||||
9237 | Kind = | ||||
9238 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9239 | return Compatible; | ||||
9240 | } | ||||
9241 | } | ||||
9242 | |||||
9243 | return Incompatible; | ||||
9244 | } | ||||
9245 | |||||
9246 | // Conversions to block pointers. | ||||
9247 | if (isa<BlockPointerType>(LHSType)) { | ||||
9248 | // U^ -> T^ | ||||
9249 | if (RHSType->isBlockPointerType()) { | ||||
9250 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | ||||
9251 | ->getPointeeType() | ||||
9252 | .getAddressSpace(); | ||||
9253 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9254 | ->getPointeeType() | ||||
9255 | .getAddressSpace(); | ||||
9256 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9257 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9258 | } | ||||
9259 | |||||
9260 | // int or null -> T^ | ||||
9261 | if (RHSType->isIntegerType()) { | ||||
9262 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9263 | return IntToBlockPointer; | ||||
9264 | } | ||||
9265 | |||||
9266 | // id -> T^ | ||||
9267 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | ||||
9268 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9269 | return Compatible; | ||||
9270 | } | ||||
9271 | |||||
9272 | // void* -> T^ | ||||
9273 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | ||||
9274 | if (RHSPT->getPointeeType()->isVoidType()) { | ||||
9275 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9276 | return Compatible; | ||||
9277 | } | ||||
9278 | |||||
9279 | return Incompatible; | ||||
9280 | } | ||||
9281 | |||||
9282 | // Conversions to Objective-C pointers. | ||||
9283 | if (isa<ObjCObjectPointerType>(LHSType)) { | ||||
9284 | // A* -> B* | ||||
9285 | if (RHSType->isObjCObjectPointerType()) { | ||||
9286 | Kind = CK_BitCast; | ||||
9287 | Sema::AssignConvertType result = | ||||
9288 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9289 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9290 | result == Compatible && | ||||
9291 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | ||||
9292 | result = IncompatibleObjCWeakRef; | ||||
9293 | return result; | ||||
9294 | } | ||||
9295 | |||||
9296 | // int or null -> A* | ||||
9297 | if (RHSType->isIntegerType()) { | ||||
9298 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9299 | return IntToPointer; | ||||
9300 | } | ||||
9301 | |||||
9302 | // In general, C pointers are not compatible with ObjC object pointers, | ||||
9303 | // with two exceptions: | ||||
9304 | if (isa<PointerType>(RHSType)) { | ||||
9305 | Kind = CK_CPointerToObjCPointerCast; | ||||
9306 | |||||
9307 | // - conversions from 'void*' | ||||
9308 | if (RHSType->isVoidPointerType()) { | ||||
9309 | return Compatible; | ||||
9310 | } | ||||
9311 | |||||
9312 | // - conversions to 'Class' from its redefinition type | ||||
9313 | if (LHSType->isObjCClassType() && | ||||
9314 | Context.hasSameType(RHSType, | ||||
9315 | Context.getObjCClassRedefinitionType())) { | ||||
9316 | return Compatible; | ||||
9317 | } | ||||
9318 | |||||
9319 | return IncompatiblePointer; | ||||
9320 | } | ||||
9321 | |||||
9322 | // Only under strict condition T^ is compatible with an Objective-C pointer. | ||||
9323 | if (RHSType->isBlockPointerType() && | ||||
9324 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
9325 | if (ConvertRHS) | ||||
9326 | maybeExtendBlockObject(RHS); | ||||
9327 | Kind = CK_BlockPointerToObjCPointerCast; | ||||
9328 | return Compatible; | ||||
9329 | } | ||||
9330 | |||||
9331 | return Incompatible; | ||||
9332 | } | ||||
9333 | |||||
9334 | // Conversions from pointers that are not covered by the above. | ||||
9335 | if (isa<PointerType>(RHSType)) { | ||||
9336 | // T* -> _Bool | ||||
9337 | if (LHSType == Context.BoolTy) { | ||||
9338 | Kind = CK_PointerToBoolean; | ||||
9339 | return Compatible; | ||||
9340 | } | ||||
9341 | |||||
9342 | // T* -> int | ||||
9343 | if (LHSType->isIntegerType()) { | ||||
9344 | Kind = CK_PointerToIntegral; | ||||
9345 | return PointerToInt; | ||||
9346 | } | ||||
9347 | |||||
9348 | return Incompatible; | ||||
9349 | } | ||||
9350 | |||||
9351 | // Conversions from Objective-C pointers that are not covered by the above. | ||||
9352 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9353 | // T* -> _Bool | ||||
9354 | if (LHSType == Context.BoolTy) { | ||||
9355 | Kind = CK_PointerToBoolean; | ||||
9356 | return Compatible; | ||||
9357 | } | ||||
9358 | |||||
9359 | // T* -> int | ||||
9360 | if (LHSType->isIntegerType()) { | ||||
9361 | Kind = CK_PointerToIntegral; | ||||
9362 | return PointerToInt; | ||||
9363 | } | ||||
9364 | |||||
9365 | return Incompatible; | ||||
9366 | } | ||||
9367 | |||||
9368 | // struct A -> struct B | ||||
9369 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | ||||
9370 | if (Context.typesAreCompatible(LHSType, RHSType)) { | ||||
9371 | Kind = CK_NoOp; | ||||
9372 | return Compatible; | ||||
9373 | } | ||||
9374 | } | ||||
9375 | |||||
9376 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | ||||
9377 | Kind = CK_IntToOCLSampler; | ||||
9378 | return Compatible; | ||||
9379 | } | ||||
9380 | |||||
9381 | return Incompatible; | ||||
9382 | } | ||||
9383 | |||||
9384 | /// Constructs a transparent union from an expression that is | ||||
9385 | /// used to initialize the transparent union. | ||||
9386 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | ||||
9387 | ExprResult &EResult, QualType UnionType, | ||||
9388 | FieldDecl *Field) { | ||||
9389 | // Build an initializer list that designates the appropriate member | ||||
9390 | // of the transparent union. | ||||
9391 | Expr *E = EResult.get(); | ||||
9392 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | ||||
9393 | E, SourceLocation()); | ||||
9394 | Initializer->setType(UnionType); | ||||
9395 | Initializer->setInitializedFieldInUnion(Field); | ||||
9396 | |||||
9397 | // Build a compound literal constructing a value of the transparent | ||||
9398 | // union type from this initializer list. | ||||
9399 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | ||||
9400 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | ||||
9401 | VK_RValue, Initializer, false); | ||||
9402 | } | ||||
9403 | |||||
9404 | Sema::AssignConvertType | ||||
9405 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | ||||
9406 | ExprResult &RHS) { | ||||
9407 | QualType RHSType = RHS.get()->getType(); | ||||
9408 | |||||
9409 | // If the ArgType is a Union type, we want to handle a potential | ||||
9410 | // transparent_union GCC extension. | ||||
9411 | const RecordType *UT = ArgType->getAsUnionType(); | ||||
9412 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | ||||
9413 | return Incompatible; | ||||
9414 | |||||
9415 | // The field to initialize within the transparent union. | ||||
9416 | RecordDecl *UD = UT->getDecl(); | ||||
9417 | FieldDecl *InitField = nullptr; | ||||
9418 | // It's compatible if the expression matches any of the fields. | ||||
9419 | for (auto *it : UD->fields()) { | ||||
9420 | if (it->getType()->isPointerType()) { | ||||
9421 | // If the transparent union contains a pointer type, we allow: | ||||
9422 | // 1) void pointer | ||||
9423 | // 2) null pointer constant | ||||
9424 | if (RHSType->isPointerType()) | ||||
9425 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | ||||
9426 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | ||||
9427 | InitField = it; | ||||
9428 | break; | ||||
9429 | } | ||||
9430 | |||||
9431 | if (RHS.get()->isNullPointerConstant(Context, | ||||
9432 | Expr::NPC_ValueDependentIsNull)) { | ||||
9433 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | ||||
9434 | CK_NullToPointer); | ||||
9435 | InitField = it; | ||||
9436 | break; | ||||
9437 | } | ||||
9438 | } | ||||
9439 | |||||
9440 | CastKind Kind; | ||||
9441 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | ||||
9442 | == Compatible) { | ||||
9443 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | ||||
9444 | InitField = it; | ||||
9445 | break; | ||||
9446 | } | ||||
9447 | } | ||||
9448 | |||||
9449 | if (!InitField) | ||||
9450 | return Incompatible; | ||||
9451 | |||||
9452 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | ||||
9453 | return Compatible; | ||||
9454 | } | ||||
9455 | |||||
9456 | Sema::AssignConvertType | ||||
9457 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | ||||
9458 | bool Diagnose, | ||||
9459 | bool DiagnoseCFAudited, | ||||
9460 | bool ConvertRHS) { | ||||
9461 | // We need to be able to tell the caller whether we diagnosed a problem, if | ||||
9462 | // they ask us to issue diagnostics. | ||||
9463 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 9463, __PRETTY_FUNCTION__)); | ||||
9464 | |||||
9465 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | ||||
9466 | // we can't avoid *all* modifications at the moment, so we need some somewhere | ||||
9467 | // to put the updated value. | ||||
9468 | ExprResult LocalRHS = CallerRHS; | ||||
9469 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | ||||
9470 | |||||
9471 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | ||||
9472 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | ||||
9473 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||
9474 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
9475 | Diag(RHS.get()->getExprLoc(), | ||||
9476 | diag::warn_noderef_to_dereferenceable_pointer) | ||||
9477 | << RHS.get()->getSourceRange(); | ||||
9478 | } | ||||
9479 | } | ||||
9480 | } | ||||
9481 | |||||
9482 | if (getLangOpts().CPlusPlus) { | ||||
9483 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | ||||
9484 | // C++ 5.17p3: If the left operand is not of class type, the | ||||
9485 | // expression is implicitly converted (C++ 4) to the | ||||
9486 | // cv-unqualified type of the left operand. | ||||
9487 | QualType RHSType = RHS.get()->getType(); | ||||
9488 | if (Diagnose) { | ||||
9489 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9490 | AA_Assigning); | ||||
9491 | } else { | ||||
9492 | ImplicitConversionSequence ICS = | ||||
9493 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9494 | /*SuppressUserConversions=*/false, | ||||
9495 | AllowedExplicit::None, | ||||
9496 | /*InOverloadResolution=*/false, | ||||
9497 | /*CStyle=*/false, | ||||
9498 | /*AllowObjCWritebackConversion=*/false); | ||||
9499 | if (ICS.isFailure()) | ||||
9500 | return Incompatible; | ||||
9501 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9502 | ICS, AA_Assigning); | ||||
9503 | } | ||||
9504 | if (RHS.isInvalid()) | ||||
9505 | return Incompatible; | ||||
9506 | Sema::AssignConvertType result = Compatible; | ||||
9507 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9508 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | ||||
9509 | result = IncompatibleObjCWeakRef; | ||||
9510 | return result; | ||||
9511 | } | ||||
9512 | |||||
9513 | // FIXME: Currently, we fall through and treat C++ classes like C | ||||
9514 | // structures. | ||||
9515 | // FIXME: We also fall through for atomics; not sure what should | ||||
9516 | // happen there, though. | ||||
9517 | } else if (RHS.get()->getType() == Context.OverloadTy) { | ||||
9518 | // As a set of extensions to C, we support overloading on functions. These | ||||
9519 | // functions need to be resolved here. | ||||
9520 | DeclAccessPair DAP; | ||||
9521 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | ||||
9522 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | ||||
9523 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | ||||
9524 | else | ||||
9525 | return Incompatible; | ||||
9526 | } | ||||
9527 | |||||
9528 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | ||||
9529 | // a null pointer constant. | ||||
9530 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | ||||
9531 | LHSType->isBlockPointerType()) && | ||||
9532 | RHS.get()->isNullPointerConstant(Context, | ||||
9533 | Expr::NPC_ValueDependentIsNull)) { | ||||
9534 | if (Diagnose || ConvertRHS) { | ||||
9535 | CastKind Kind; | ||||
9536 | CXXCastPath Path; | ||||
9537 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | ||||
9538 | /*IgnoreBaseAccess=*/false, Diagnose); | ||||
9539 | if (ConvertRHS) | ||||
9540 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); | ||||
9541 | } | ||||
9542 | return Compatible; | ||||
9543 | } | ||||
9544 | |||||
9545 | // OpenCL queue_t type assignment. | ||||
9546 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | ||||
9547 | Context, Expr::NPC_ValueDependentIsNull)) { | ||||
9548 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
9549 | return Compatible; | ||||
9550 | } | ||||
9551 | |||||
9552 | // This check seems unnatural, however it is necessary to ensure the proper | ||||
9553 | // conversion of functions/arrays. If the conversion were done for all | ||||
9554 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | ||||
9555 | // expressions that suppress this implicit conversion (&, sizeof). | ||||
9556 | // | ||||
9557 | // Suppress this for references: C++ 8.5.3p5. | ||||
9558 | if (!LHSType->isReferenceType()) { | ||||
9559 | // FIXME: We potentially allocate here even if ConvertRHS is false. | ||||
9560 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | ||||
9561 | if (RHS.isInvalid()) | ||||
9562 | return Incompatible; | ||||
9563 | } | ||||
9564 | CastKind Kind; | ||||
9565 | Sema::AssignConvertType result = | ||||
9566 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | ||||
9567 | |||||
9568 | // C99 6.5.16.1p2: The value of the right operand is converted to the | ||||
9569 | // type of the assignment expression. | ||||
9570 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | ||||
9571 | // so that we can use references in built-in functions even in C. | ||||
9572 | // The getNonReferenceType() call makes sure that the resulting expression | ||||
9573 | // does not have reference type. | ||||
9574 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | ||||
9575 | QualType Ty = LHSType.getNonLValueExprType(Context); | ||||
9576 | Expr *E = RHS.get(); | ||||
9577 | |||||
9578 | // Check for various Objective-C errors. If we are not reporting | ||||
9579 | // diagnostics and just checking for errors, e.g., during overload | ||||
9580 | // resolution, return Incompatible to indicate the failure. | ||||
9581 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9582 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | ||||
9583 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | ||||
9584 | if (!Diagnose) | ||||
9585 | return Incompatible; | ||||
9586 | } | ||||
9587 | if (getLangOpts().ObjC && | ||||
9588 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | ||||
9589 | E->getType(), E, Diagnose) || | ||||
9590 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | ||||
9591 | if (!Diagnose) | ||||
9592 | return Incompatible; | ||||
9593 | // Replace the expression with a corrected version and continue so we | ||||
9594 | // can find further errors. | ||||
9595 | RHS = E; | ||||
9596 | return Compatible; | ||||
9597 | } | ||||
9598 | |||||
9599 | if (ConvertRHS) | ||||
9600 | RHS = ImpCastExprToType(E, Ty, Kind); | ||||
9601 | } | ||||
9602 | |||||
9603 | return result; | ||||
9604 | } | ||||
9605 | |||||
9606 | namespace { | ||||
9607 | /// The original operand to an operator, prior to the application of the usual | ||||
9608 | /// arithmetic conversions and converting the arguments of a builtin operator | ||||
9609 | /// candidate. | ||||
9610 | struct OriginalOperand { | ||||
9611 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | ||||
9612 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | ||||
9613 | Op = MTE->getSubExpr(); | ||||
9614 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | ||||
9615 | Op = BTE->getSubExpr(); | ||||
9616 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | ||||
9617 | Orig = ICE->getSubExprAsWritten(); | ||||
9618 | Conversion = ICE->getConversionFunction(); | ||||
9619 | } | ||||
9620 | } | ||||
9621 | |||||
9622 | QualType getType() const { return Orig->getType(); } | ||||
9623 | |||||
9624 | Expr *Orig; | ||||
9625 | NamedDecl *Conversion; | ||||
9626 | }; | ||||
9627 | } | ||||
9628 | |||||
9629 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | ||||
9630 | ExprResult &RHS) { | ||||
9631 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | ||||
9632 | |||||
9633 | Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
9634 | << OrigLHS.getType() << OrigRHS.getType() | ||||
9635 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
9636 | |||||
9637 | // If a user-defined conversion was applied to either of the operands prior | ||||
9638 | // to applying the built-in operator rules, tell the user about it. | ||||
9639 | if (OrigLHS.Conversion) { | ||||
9640 | Diag(OrigLHS.Conversion->getLocation(), | ||||
9641 | diag::note_typecheck_invalid_operands_converted) | ||||
9642 | << 0 << LHS.get()->getType(); | ||||
9643 | } | ||||
9644 | if (OrigRHS.Conversion) { | ||||
9645 | Diag(OrigRHS.Conversion->getLocation(), | ||||
9646 | diag::note_typecheck_invalid_operands_converted) | ||||
9647 | << 1 << RHS.get()->getType(); | ||||
9648 | } | ||||
9649 | |||||
9650 | return QualType(); | ||||
9651 | } | ||||
9652 | |||||
9653 | // Diagnose cases where a scalar was implicitly converted to a vector and | ||||
9654 | // diagnose the underlying types. Otherwise, diagnose the error | ||||
9655 | // as invalid vector logical operands for non-C++ cases. | ||||
9656 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | ||||
9657 | ExprResult &RHS) { | ||||
9658 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | ||||
9659 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | ||||
9660 | |||||
9661 | bool LHSNatVec = LHSType->isVectorType(); | ||||
9662 | bool RHSNatVec = RHSType->isVectorType(); | ||||
9663 | |||||
9664 | if (!(LHSNatVec && RHSNatVec)) { | ||||
9665 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | ||||
9666 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | ||||
9667 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
9668 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | ||||
9669 | << Vector->getSourceRange(); | ||||
9670 | return QualType(); | ||||
9671 | } | ||||
9672 | |||||
9673 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
9674 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
9675 | << RHS.get()->getSourceRange(); | ||||
9676 | |||||
9677 | return QualType(); | ||||
9678 | } | ||||
9679 | |||||
9680 | /// Try to convert a value of non-vector type to a vector type by converting | ||||
9681 | /// the type to the element type of the vector and then performing a splat. | ||||
9682 | /// If the language is OpenCL, we only use conversions that promote scalar | ||||
9683 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | ||||
9684 | /// for float->int. | ||||
9685 | /// | ||||
9686 | /// OpenCL V2.0 6.2.6.p2: | ||||
9687 | /// An error shall occur if any scalar operand type has greater rank | ||||
9688 | /// than the type of the vector element. | ||||
9689 | /// | ||||
9690 | /// \param scalar - if non-null, actually perform the conversions | ||||
9691 | /// \return true if the operation fails (but without diagnosing the failure) | ||||
9692 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | ||||
9693 | QualType scalarTy, | ||||
9694 | QualType vectorEltTy, | ||||
9695 | QualType vectorTy, | ||||
9696 | unsigned &DiagID) { | ||||
9697 | // The conversion to apply to the scalar before splatting it, | ||||
9698 | // if necessary. | ||||
9699 | CastKind scalarCast = CK_NoOp; | ||||
9700 | |||||
9701 | if (vectorEltTy->isIntegralType(S.Context)) { | ||||
9702 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | ||||
9703 | (scalarTy->isIntegerType() && | ||||
9704 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | ||||
9705 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
9706 | return true; | ||||
9707 | } | ||||
9708 | if (!scalarTy->isIntegralType(S.Context)) | ||||
9709 | return true; | ||||
9710 | scalarCast = CK_IntegralCast; | ||||
9711 | } else if (vectorEltTy->isRealFloatingType()) { | ||||
9712 | if (scalarTy->isRealFloatingType()) { | ||||
9713 | if (S.getLangOpts().OpenCL && | ||||
9714 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | ||||
9715 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
9716 | return true; | ||||
9717 | } | ||||
9718 | scalarCast = CK_FloatingCast; | ||||
9719 | } | ||||
9720 | else if (scalarTy->isIntegralType(S.Context)) | ||||
9721 | scalarCast = CK_IntegralToFloating; | ||||
9722 | else | ||||
9723 | return true; | ||||
9724 | } else { | ||||
9725 | return true; | ||||
9726 | } | ||||
9727 | |||||
9728 | // Adjust scalar if desired. | ||||
9729 | if (scalar) { | ||||
9730 | if (scalarCast != CK_NoOp) | ||||
9731 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | ||||
9732 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | ||||
9733 | } | ||||
9734 | return false; | ||||
9735 | } | ||||
9736 | |||||
9737 | /// Convert vector E to a vector with the same number of elements but different | ||||
9738 | /// element type. | ||||
9739 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | ||||
9740 | const auto *VecTy = E->getType()->getAs<VectorType>(); | ||||
9741 | assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast <void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 9741, __PRETTY_FUNCTION__)); | ||||
9742 | QualType NewVecTy = S.Context.getVectorType(ElementType, | ||||
9743 | VecTy->getNumElements(), | ||||
9744 | VecTy->getVectorKind()); | ||||
9745 | |||||
9746 | // Look through the implicit cast. Return the subexpression if its type is | ||||
9747 | // NewVecTy. | ||||
9748 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
9749 | if (ICE->getSubExpr()->getType() == NewVecTy) | ||||
9750 | return ICE->getSubExpr(); | ||||
9751 | |||||
9752 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | ||||
9753 | return S.ImpCastExprToType(E, NewVecTy, Cast); | ||||
9754 | } | ||||
9755 | |||||
9756 | /// Test if a (constant) integer Int can be casted to another integer type | ||||
9757 | /// IntTy without losing precision. | ||||
9758 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | ||||
9759 | QualType OtherIntTy) { | ||||
9760 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
9761 | |||||
9762 | // Reject cases where the value of the Int is unknown as that would | ||||
9763 | // possibly cause truncation, but accept cases where the scalar can be | ||||
9764 | // demoted without loss of precision. | ||||
9765 | Expr::EvalResult EVResult; | ||||
9766 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
9767 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | ||||
9768 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | ||||
9769 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | ||||
9770 | |||||
9771 | if (CstInt) { | ||||
9772 | // If the scalar is constant and is of a higher order and has more active | ||||
9773 | // bits that the vector element type, reject it. | ||||
9774 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
9775 | unsigned NumBits = IntSigned | ||||
9776 | ? (Result.isNegative() ? Result.getMinSignedBits() | ||||
9777 | : Result.getActiveBits()) | ||||
9778 | : Result.getActiveBits(); | ||||
9779 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | ||||
9780 | return true; | ||||
9781 | |||||
9782 | // If the signedness of the scalar type and the vector element type | ||||
9783 | // differs and the number of bits is greater than that of the vector | ||||
9784 | // element reject it. | ||||
9785 | return (IntSigned != OtherIntSigned && | ||||
9786 | NumBits > S.Context.getIntWidth(OtherIntTy)); | ||||
9787 | } | ||||
9788 | |||||
9789 | // Reject cases where the value of the scalar is not constant and it's | ||||
9790 | // order is greater than that of the vector element type. | ||||
9791 | return (Order < 0); | ||||
9792 | } | ||||
9793 | |||||
9794 | /// Test if a (constant) integer Int can be casted to floating point type | ||||
9795 | /// FloatTy without losing precision. | ||||
9796 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | ||||
9797 | QualType FloatTy) { | ||||
9798 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
9799 | |||||
9800 | // Determine if the integer constant can be expressed as a floating point | ||||
9801 | // number of the appropriate type. | ||||
9802 | Expr::EvalResult EVResult; | ||||
9803 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
9804 | |||||
9805 | uint64_t Bits = 0; | ||||
9806 | if (CstInt) { | ||||
9807 | // Reject constants that would be truncated if they were converted to | ||||
9808 | // the floating point type. Test by simple to/from conversion. | ||||
9809 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | ||||
9810 | // could be avoided if there was a convertFromAPInt method | ||||
9811 | // which could signal back if implicit truncation occurred. | ||||
9812 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
9813 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | ||||
9814 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | ||||
9815 | llvm::APFloat::rmTowardZero); | ||||
9816 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | ||||
9817 | !IntTy->hasSignedIntegerRepresentation()); | ||||
9818 | bool Ignored = false; | ||||
9819 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | ||||
9820 | &Ignored); | ||||
9821 | if (Result != ConvertBack) | ||||
9822 | return true; | ||||
9823 | } else { | ||||
9824 | // Reject types that cannot be fully encoded into the mantissa of | ||||
9825 | // the float. | ||||
9826 | Bits = S.Context.getTypeSize(IntTy); | ||||
9827 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | ||||
9828 | S.Context.getFloatTypeSemantics(FloatTy)); | ||||
9829 | if (Bits > FloatPrec) | ||||
9830 | return true; | ||||
9831 | } | ||||
9832 | |||||
9833 | return false; | ||||
9834 | } | ||||
9835 | |||||
9836 | /// Attempt to convert and splat Scalar into a vector whose types matches | ||||
9837 | /// Vector following GCC conversion rules. The rule is that implicit | ||||
9838 | /// conversion can occur when Scalar can be casted to match Vector's element | ||||
9839 | /// type without causing truncation of Scalar. | ||||
9840 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | ||||
9841 | ExprResult *Vector) { | ||||
9842 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | ||||
9843 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | ||||
9844 | const VectorType *VT = VectorTy->getAs<VectorType>(); | ||||
9845 | |||||
9846 | assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 9847, __PRETTY_FUNCTION__)) | ||||
9847 | "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 9847, __PRETTY_FUNCTION__)); | ||||
9848 | |||||
9849 | QualType VectorEltTy = VT->getElementType(); | ||||
9850 | |||||
9851 | // Reject cases where the vector element type or the scalar element type are | ||||
9852 | // not integral or floating point types. | ||||
9853 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | ||||
9854 | return true; | ||||
9855 | |||||
9856 | // The conversion to apply to the scalar before splatting it, | ||||
9857 | // if necessary. | ||||
9858 | CastKind ScalarCast = CK_NoOp; | ||||
9859 | |||||
9860 | // Accept cases where the vector elements are integers and the scalar is | ||||
9861 | // an integer. | ||||
9862 | // FIXME: Notionally if the scalar was a floating point value with a precise | ||||
9863 | // integral representation, we could cast it to an appropriate integer | ||||
9864 | // type and then perform the rest of the checks here. GCC will perform | ||||
9865 | // this conversion in some cases as determined by the input language. | ||||
9866 | // We should accept it on a language independent basis. | ||||
9867 | if (VectorEltTy->isIntegralType(S.Context) && | ||||
9868 | ScalarTy->isIntegralType(S.Context) && | ||||
9869 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | ||||
9870 | |||||
9871 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | ||||
9872 | return true; | ||||
9873 | |||||
9874 | ScalarCast = CK_IntegralCast; | ||||
9875 | } else if (VectorEltTy->isIntegralType(S.Context) && | ||||
9876 | ScalarTy->isRealFloatingType()) { | ||||
9877 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | ||||
9878 | ScalarCast = CK_FloatingToIntegral; | ||||
9879 | else | ||||
9880 | return true; | ||||
9881 | } else if (VectorEltTy->isRealFloatingType()) { | ||||
9882 | if (ScalarTy->isRealFloatingType()) { | ||||
9883 | |||||
9884 | // Reject cases where the scalar type is not a constant and has a higher | ||||
9885 | // Order than the vector element type. | ||||
9886 | llvm::APFloat Result(0.0); | ||||
9887 | |||||
9888 | // Determine whether this is a constant scalar. In the event that the | ||||
9889 | // value is dependent (and thus cannot be evaluated by the constant | ||||
9890 | // evaluator), skip the evaluation. This will then diagnose once the | ||||
9891 | // expression is instantiated. | ||||
9892 | bool CstScalar = Scalar->get()->isValueDependent() || | ||||
9893 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | ||||
9894 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | ||||
9895 | if (!CstScalar && Order < 0) | ||||
9896 | return true; | ||||
9897 | |||||
9898 | // If the scalar cannot be safely casted to the vector element type, | ||||
9899 | // reject it. | ||||
9900 | if (CstScalar) { | ||||
9901 | bool Truncated = false; | ||||
9902 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | ||||
9903 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | ||||
9904 | if (Truncated) | ||||
9905 | return true; | ||||
9906 | } | ||||
9907 | |||||
9908 | ScalarCast = CK_FloatingCast; | ||||
9909 | } else if (ScalarTy->isIntegralType(S.Context)) { | ||||
9910 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | ||||
9911 | return true; | ||||
9912 | |||||
9913 | ScalarCast = CK_IntegralToFloating; | ||||
9914 | } else | ||||
9915 | return true; | ||||
9916 | } else if (ScalarTy->isEnumeralType()) | ||||
9917 | return true; | ||||
9918 | |||||
9919 | // Adjust scalar if desired. | ||||
9920 | if (Scalar) { | ||||
9921 | if (ScalarCast != CK_NoOp) | ||||
9922 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | ||||
9923 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | ||||
9924 | } | ||||
9925 | return false; | ||||
9926 | } | ||||
9927 | |||||
9928 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
9929 | SourceLocation Loc, bool IsCompAssign, | ||||
9930 | bool AllowBothBool, | ||||
9931 | bool AllowBoolConversions) { | ||||
9932 | if (!IsCompAssign) { | ||||
9933 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
9934 | if (LHS.isInvalid()) | ||||
9935 | return QualType(); | ||||
9936 | } | ||||
9937 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
9938 | if (RHS.isInvalid()) | ||||
9939 | return QualType(); | ||||
9940 | |||||
9941 | // For conversion purposes, we ignore any qualifiers. | ||||
9942 | // For example, "const float" and "float" are equivalent. | ||||
9943 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
9944 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
9945 | |||||
9946 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | ||||
9947 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | ||||
9948 | assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail ("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 9948, __PRETTY_FUNCTION__)); | ||||
9949 | |||||
9950 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | ||||
9951 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | ||||
9952 | return InvalidOperands(Loc, LHS, RHS); | ||||
9953 | |||||
9954 | // AltiVec-style "vector bool op vector bool" combinations are allowed | ||||
9955 | // for some operators but not others. | ||||
9956 | if (!AllowBothBool && | ||||
9957 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
9958 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
9959 | return InvalidOperands(Loc, LHS, RHS); | ||||
9960 | |||||
9961 | // If the vector types are identical, return. | ||||
9962 | if (Context.hasSameType(LHSType, RHSType)) | ||||
9963 | return LHSType; | ||||
9964 | |||||
9965 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | ||||
9966 | if (LHSVecType && RHSVecType && | ||||
9967 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9968 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
9969 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
9970 | return LHSType; | ||||
9971 | } | ||||
9972 | |||||
9973 | if (!IsCompAssign) | ||||
9974 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
9975 | return RHSType; | ||||
9976 | } | ||||
9977 | |||||
9978 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | ||||
9979 | // can be mixed, with the result being the non-bool type. The non-bool | ||||
9980 | // operand must have integer element type. | ||||
9981 | if (AllowBoolConversions && LHSVecType && RHSVecType && | ||||
9982 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | ||||
9983 | (Context.getTypeSize(LHSVecType->getElementType()) == | ||||
9984 | Context.getTypeSize(RHSVecType->getElementType()))) { | ||||
9985 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
9986 | LHSVecType->getElementType()->isIntegerType() && | ||||
9987 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | ||||
9988 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
9989 | return LHSType; | ||||
9990 | } | ||||
9991 | if (!IsCompAssign && | ||||
9992 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
9993 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
9994 | RHSVecType->getElementType()->isIntegerType()) { | ||||
9995 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
9996 | return RHSType; | ||||
9997 | } | ||||
9998 | } | ||||
9999 | |||||
10000 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | ||||
10001 | // since the ambiguity can affect the ABI. | ||||
10002 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | ||||
10003 | const VectorType *VecType = SecondType->getAs<VectorType>(); | ||||
10004 | return FirstType->isSizelessBuiltinType() && VecType && | ||||
10005 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | ||||
10006 | VecType->getVectorKind() == | ||||
10007 | VectorType::SveFixedLengthPredicateVector); | ||||
10008 | }; | ||||
10009 | |||||
10010 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | ||||
10011 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | ||||
10012 | return QualType(); | ||||
10013 | } | ||||
10014 | |||||
10015 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | ||||
10016 | // since the ambiguity can affect the ABI. | ||||
10017 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | ||||
10018 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | ||||
10019 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | ||||
10020 | |||||
10021 | if (FirstVecType && SecondVecType) | ||||
10022 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | ||||
10023 | (SecondVecType->getVectorKind() == | ||||
10024 | VectorType::SveFixedLengthDataVector || | ||||
10025 | SecondVecType->getVectorKind() == | ||||
10026 | VectorType::SveFixedLengthPredicateVector); | ||||
10027 | |||||
10028 | return FirstType->isSizelessBuiltinType() && SecondVecType && | ||||
10029 | SecondVecType->getVectorKind() == VectorType::GenericVector; | ||||
10030 | }; | ||||
10031 | |||||
10032 | if (IsSveGnuConversion(LHSType, RHSType) || | ||||
10033 | IsSveGnuConversion(RHSType, LHSType)) { | ||||
10034 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | ||||
10035 | return QualType(); | ||||
10036 | } | ||||
10037 | |||||
10038 | // If there's a vector type and a scalar, try to convert the scalar to | ||||
10039 | // the vector element type and splat. | ||||
10040 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | ||||
10041 | if (!RHSVecType) { | ||||
10042 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10043 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | ||||
10044 | LHSVecType->getElementType(), LHSType, | ||||
10045 | DiagID)) | ||||
10046 | return LHSType; | ||||
10047 | } else { | ||||
10048 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
10049 | return LHSType; | ||||
10050 | } | ||||
10051 | } | ||||
10052 | if (!LHSVecType) { | ||||
10053 | if (isa<ExtVectorType>(RHSVecType)) { | ||||
10054 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | ||||
10055 | LHSType, RHSVecType->getElementType(), | ||||
10056 | RHSType, DiagID)) | ||||
10057 | return RHSType; | ||||
10058 | } else { | ||||
10059 | if (LHS.get()->getValueKind() == VK_LValue || | ||||
10060 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10061 | return RHSType; | ||||
10062 | } | ||||
10063 | } | ||||
10064 | |||||
10065 | // FIXME: The code below also handles conversion between vectors and | ||||
10066 | // non-scalars, we should break this down into fine grained specific checks | ||||
10067 | // and emit proper diagnostics. | ||||
10068 | QualType VecType = LHSVecType ? LHSType : RHSType; | ||||
10069 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | ||||
10070 | QualType OtherType = LHSVecType ? RHSType : LHSType; | ||||
10071 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | ||||
10072 | if (isLaxVectorConversion(OtherType, VecType)) { | ||||
10073 | // If we're allowing lax vector conversions, only the total (data) size | ||||
10074 | // needs to be the same. For non compound assignment, if one of the types is | ||||
10075 | // scalar, the result is always the vector type. | ||||
10076 | if (!IsCompAssign) { | ||||
10077 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | ||||
10078 | return VecType; | ||||
10079 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | ||||
10080 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | ||||
10081 | // type. Note that this is already done by non-compound assignments in | ||||
10082 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | ||||
10083 | // <1 x T> -> T. The result is also a vector type. | ||||
10084 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | ||||
10085 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | ||||
10086 | ExprResult *RHSExpr = &RHS; | ||||
10087 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | ||||
10088 | return VecType; | ||||
10089 | } | ||||
10090 | } | ||||
10091 | |||||
10092 | // Okay, the expression is invalid. | ||||
10093 | |||||
10094 | // If there's a non-vector, non-real operand, diagnose that. | ||||
10095 | if ((!RHSVecType && !RHSType->isRealType()) || | ||||
10096 | (!LHSVecType && !LHSType->isRealType())) { | ||||
10097 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10098 | << LHSType << RHSType | ||||
10099 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10100 | return QualType(); | ||||
10101 | } | ||||
10102 | |||||
10103 | // OpenCL V1.1 6.2.6.p1: | ||||
10104 | // If the operands are of more than one vector type, then an error shall | ||||
10105 | // occur. Implicit conversions between vector types are not permitted, per | ||||
10106 | // section 6.2.1. | ||||
10107 | if (getLangOpts().OpenCL && | ||||
10108 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | ||||
10109 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | ||||
10110 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | ||||
10111 | << RHSType; | ||||
10112 | return QualType(); | ||||
10113 | } | ||||
10114 | |||||
10115 | |||||
10116 | // If there is a vector type that is not a ExtVector and a scalar, we reach | ||||
10117 | // this point if scalar could not be converted to the vector's element type | ||||
10118 | // without truncation. | ||||
10119 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | ||||
10120 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | ||||
10121 | QualType Scalar = LHSVecType ? RHSType : LHSType; | ||||
10122 | QualType Vector = LHSVecType ? LHSType : RHSType; | ||||
10123 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | ||||
10124 | Diag(Loc, | ||||
10125 | diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10126 | << ScalarOrVector << Scalar << Vector; | ||||
10127 | |||||
10128 | return QualType(); | ||||
10129 | } | ||||
10130 | |||||
10131 | // Otherwise, use the generic diagnostic. | ||||
10132 | Diag(Loc, DiagID) | ||||
10133 | << LHSType << RHSType | ||||
10134 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10135 | return QualType(); | ||||
10136 | } | ||||
10137 | |||||
10138 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | ||||
10139 | // expression. These are mainly cases where the null pointer is used as an | ||||
10140 | // integer instead of a pointer. | ||||
10141 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10142 | SourceLocation Loc, bool IsCompare) { | ||||
10143 | // The canonical way to check for a GNU null is with isNullPointerConstant, | ||||
10144 | // but we use a bit of a hack here for speed; this is a relatively | ||||
10145 | // hot path, and isNullPointerConstant is slow. | ||||
10146 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | ||||
10147 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | ||||
10148 | |||||
10149 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | ||||
10150 | |||||
10151 | // Avoid analyzing cases where the result will either be invalid (and | ||||
10152 | // diagnosed as such) or entirely valid and not something to warn about. | ||||
10153 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | ||||
10154 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | ||||
10155 | return; | ||||
10156 | |||||
10157 | // Comparison operations would not make sense with a null pointer no matter | ||||
10158 | // what the other expression is. | ||||
10159 | if (!IsCompare) { | ||||
10160 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | ||||
10161 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | ||||
10162 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | ||||
10163 | return; | ||||
10164 | } | ||||
10165 | |||||
10166 | // The rest of the operations only make sense with a null pointer | ||||
10167 | // if the other expression is a pointer. | ||||
10168 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | ||||
10169 | NonNullType->canDecayToPointerType()) | ||||
10170 | return; | ||||
10171 | |||||
10172 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | ||||
10173 | << LHSNull /* LHS is NULL */ << NonNullType | ||||
10174 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10175 | } | ||||
10176 | |||||
10177 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | ||||
10178 | SourceLocation Loc) { | ||||
10179 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | ||||
10180 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | ||||
10181 | if (!LUE || !RUE) | ||||
10182 | return; | ||||
10183 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | ||||
10184 | RUE->getKind() != UETT_SizeOf) | ||||
10185 | return; | ||||
10186 | |||||
10187 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | ||||
10188 | QualType LHSTy = LHSArg->getType(); | ||||
10189 | QualType RHSTy; | ||||
10190 | |||||
10191 | if (RUE->isArgumentType()) | ||||
10192 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | ||||
10193 | else | ||||
10194 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | ||||
10195 | |||||
10196 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | ||||
10197 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | ||||
10198 | return; | ||||
10199 | |||||
10200 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | ||||
10201 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10202 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10203 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | ||||
10204 | << LHSArgDecl; | ||||
10205 | } | ||||
10206 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | ||||
10207 | QualType ArrayElemTy = ArrayTy->getElementType(); | ||||
10208 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | ||||
10209 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | ||||
10210 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | ||||
10211 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | ||||
10212 | return; | ||||
10213 | S.Diag(Loc, diag::warn_division_sizeof_array) | ||||
10214 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | ||||
10215 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10216 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10217 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | ||||
10218 | << LHSArgDecl; | ||||
10219 | } | ||||
10220 | |||||
10221 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | ||||
10222 | } | ||||
10223 | } | ||||
10224 | |||||
10225 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | ||||
10226 | ExprResult &RHS, | ||||
10227 | SourceLocation Loc, bool IsDiv) { | ||||
10228 | // Check for division/remainder by zero. | ||||
10229 | Expr::EvalResult RHSValue; | ||||
10230 | if (!RHS.get()->isValueDependent() && | ||||
10231 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | ||||
10232 | RHSValue.Val.getInt() == 0) | ||||
10233 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10234 | S.PDiag(diag::warn_remainder_division_by_zero) | ||||
10235 | << IsDiv << RHS.get()->getSourceRange()); | ||||
10236 | } | ||||
10237 | |||||
10238 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10239 | SourceLocation Loc, | ||||
10240 | bool IsCompAssign, bool IsDiv) { | ||||
10241 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10242 | |||||
10243 | QualType LHSTy = LHS.get()->getType(); | ||||
10244 | QualType RHSTy = RHS.get()->getType(); | ||||
10245 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) | ||||
10246 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10247 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10248 | /*AllowBoolConversions*/false); | ||||
10249 | if (!IsDiv && | ||||
10250 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) | ||||
10251 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10252 | // For division, only matrix-by-scalar is supported. Other combinations with | ||||
10253 | // matrix types are invalid. | ||||
10254 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) | ||||
10255 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10256 | |||||
10257 | QualType compType = UsualArithmeticConversions( | ||||
10258 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10259 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10260 | return QualType(); | ||||
10261 | |||||
10262 | |||||
10263 | if (compType.isNull() || !compType->isArithmeticType()) | ||||
10264 | return InvalidOperands(Loc, LHS, RHS); | ||||
10265 | if (IsDiv) { | ||||
10266 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | ||||
10267 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | ||||
10268 | } | ||||
10269 | return compType; | ||||
10270 | } | ||||
10271 | |||||
10272 | QualType Sema::CheckRemainderOperands( | ||||
10273 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | ||||
10274 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10275 | |||||
10276 | if (LHS.get()->getType()->isVectorType() || | ||||
10277 | RHS.get()->getType()->isVectorType()) { | ||||
10278 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
10279 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
10280 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10281 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10282 | /*AllowBoolConversions*/false); | ||||
10283 | return InvalidOperands(Loc, LHS, RHS); | ||||
10284 | } | ||||
10285 | |||||
10286 | QualType compType = UsualArithmeticConversions( | ||||
10287 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10288 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10289 | return QualType(); | ||||
10290 | |||||
10291 | if (compType.isNull() || !compType->isIntegerType()) | ||||
10292 | return InvalidOperands(Loc, LHS, RHS); | ||||
10293 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | ||||
10294 | return compType; | ||||
10295 | } | ||||
10296 | |||||
10297 | /// Diagnose invalid arithmetic on two void pointers. | ||||
10298 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | ||||
10299 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10300 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10301 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10302 | : diag::ext_gnu_void_ptr) | ||||
10303 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | ||||
10304 | << RHSExpr->getSourceRange(); | ||||
10305 | } | ||||
10306 | |||||
10307 | /// Diagnose invalid arithmetic on a void pointer. | ||||
10308 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | ||||
10309 | Expr *Pointer) { | ||||
10310 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10311 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10312 | : diag::ext_gnu_void_ptr) | ||||
10313 | << 0 /* one pointer */ << Pointer->getSourceRange(); | ||||
10314 | } | ||||
10315 | |||||
10316 | /// Diagnose invalid arithmetic on a null pointer. | ||||
10317 | /// | ||||
10318 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | ||||
10319 | /// idiom, which we recognize as a GNU extension. | ||||
10320 | /// | ||||
10321 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | ||||
10322 | Expr *Pointer, bool IsGNUIdiom) { | ||||
10323 | if (IsGNUIdiom) | ||||
10324 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | ||||
10325 | << Pointer->getSourceRange(); | ||||
10326 | else | ||||
10327 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | ||||
10328 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||
10329 | } | ||||
10330 | |||||
10331 | /// Diagnose invalid arithmetic on two function pointers. | ||||
10332 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | ||||
10333 | Expr *LHS, Expr *RHS) { | ||||
10334 | assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10334, __PRETTY_FUNCTION__)); | ||||
10335 | assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10335, __PRETTY_FUNCTION__)); | ||||
10336 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10337 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10338 | : diag::ext_gnu_ptr_func_arith) | ||||
10339 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | ||||
10340 | // We only show the second type if it differs from the first. | ||||
10341 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | ||||
10342 | RHS->getType()) | ||||
10343 | << RHS->getType()->getPointeeType() | ||||
10344 | << LHS->getSourceRange() << RHS->getSourceRange(); | ||||
10345 | } | ||||
10346 | |||||
10347 | /// Diagnose invalid arithmetic on a function pointer. | ||||
10348 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | ||||
10349 | Expr *Pointer) { | ||||
10350 | assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10350, __PRETTY_FUNCTION__)); | ||||
10351 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10352 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10353 | : diag::ext_gnu_ptr_func_arith) | ||||
10354 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | ||||
10355 | << 0 /* one pointer, so only one type */ | ||||
10356 | << Pointer->getSourceRange(); | ||||
10357 | } | ||||
10358 | |||||
10359 | /// Emit error if Operand is incomplete pointer type | ||||
10360 | /// | ||||
10361 | /// \returns True if pointer has incomplete type | ||||
10362 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | ||||
10363 | Expr *Operand) { | ||||
10364 | QualType ResType = Operand->getType(); | ||||
10365 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10366 | ResType = ResAtomicType->getValueType(); | ||||
10367 | |||||
10368 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType ()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10368, __PRETTY_FUNCTION__)); | ||||
10369 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10370 | return S.RequireCompleteSizedType( | ||||
10371 | Loc, PointeeTy, | ||||
10372 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | ||||
10373 | Operand->getSourceRange()); | ||||
10374 | } | ||||
10375 | |||||
10376 | /// Check the validity of an arithmetic pointer operand. | ||||
10377 | /// | ||||
10378 | /// If the operand has pointer type, this code will check for pointer types | ||||
10379 | /// which are invalid in arithmetic operations. These will be diagnosed | ||||
10380 | /// appropriately, including whether or not the use is supported as an | ||||
10381 | /// extension. | ||||
10382 | /// | ||||
10383 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10384 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | ||||
10385 | Expr *Operand) { | ||||
10386 | QualType ResType = Operand->getType(); | ||||
10387 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10388 | ResType = ResAtomicType->getValueType(); | ||||
10389 | |||||
10390 | if (!ResType->isAnyPointerType()) return true; | ||||
10391 | |||||
10392 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10393 | if (PointeeTy->isVoidType()) { | ||||
10394 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | ||||
10395 | return !S.getLangOpts().CPlusPlus; | ||||
10396 | } | ||||
10397 | if (PointeeTy->isFunctionType()) { | ||||
10398 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | ||||
10399 | return !S.getLangOpts().CPlusPlus; | ||||
10400 | } | ||||
10401 | |||||
10402 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | ||||
10403 | |||||
10404 | return true; | ||||
10405 | } | ||||
10406 | |||||
10407 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | ||||
10408 | /// operands. | ||||
10409 | /// | ||||
10410 | /// This routine will diagnose any invalid arithmetic on pointer operands much | ||||
10411 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | ||||
10412 | /// for emitting a single diagnostic even for operations where both LHS and RHS | ||||
10413 | /// are (potentially problematic) pointers. | ||||
10414 | /// | ||||
10415 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10416 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | ||||
10417 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10418 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | ||||
10419 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | ||||
10420 | if (!isLHSPointer && !isRHSPointer) return true; | ||||
10421 | |||||
10422 | QualType LHSPointeeTy, RHSPointeeTy; | ||||
10423 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | ||||
10424 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | ||||
10425 | |||||
10426 | // if both are pointers check if operation is valid wrt address spaces | ||||
10427 | if (isLHSPointer && isRHSPointer) { | ||||
10428 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | ||||
10429 | S.Diag(Loc, | ||||
10430 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
10431 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | ||||
10432 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | ||||
10433 | return false; | ||||
10434 | } | ||||
10435 | } | ||||
10436 | |||||
10437 | // Check for arithmetic on pointers to incomplete types. | ||||
10438 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | ||||
10439 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | ||||
10440 | if (isLHSVoidPtr || isRHSVoidPtr) { | ||||
10441 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | ||||
10442 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | ||||
10443 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | ||||
10444 | |||||
10445 | return !S.getLangOpts().CPlusPlus; | ||||
10446 | } | ||||
10447 | |||||
10448 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | ||||
10449 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | ||||
10450 | if (isLHSFuncPtr || isRHSFuncPtr) { | ||||
10451 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | ||||
10452 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | ||||
10453 | RHSExpr); | ||||
10454 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | ||||
10455 | |||||
10456 | return !S.getLangOpts().CPlusPlus; | ||||
10457 | } | ||||
10458 | |||||
10459 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | ||||
10460 | return false; | ||||
10461 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | ||||
10462 | return false; | ||||
10463 | |||||
10464 | return true; | ||||
10465 | } | ||||
10466 | |||||
10467 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | ||||
10468 | /// literal. | ||||
10469 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | ||||
10470 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10471 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
10472 | Expr* IndexExpr = RHSExpr; | ||||
10473 | if (!StrExpr) { | ||||
10474 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
10475 | IndexExpr = LHSExpr; | ||||
10476 | } | ||||
10477 | |||||
10478 | bool IsStringPlusInt = StrExpr && | ||||
10479 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | ||||
10480 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | ||||
10481 | return; | ||||
10482 | |||||
10483 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
10484 | Self.Diag(OpLoc, diag::warn_string_plus_int) | ||||
10485 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | ||||
10486 | |||||
10487 | // Only print a fixit for "str" + int, not for int + "str". | ||||
10488 | if (IndexExpr == RHSExpr) { | ||||
10489 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
10490 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
10491 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
10492 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
10493 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
10494 | } else | ||||
10495 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
10496 | } | ||||
10497 | |||||
10498 | /// Emit a warning when adding a char literal to a string. | ||||
10499 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | ||||
10500 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10501 | const Expr *StringRefExpr = LHSExpr; | ||||
10502 | const CharacterLiteral *CharExpr = | ||||
10503 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
10504 | |||||
10505 | if (!CharExpr) { | ||||
10506 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
10507 | StringRefExpr = RHSExpr; | ||||
10508 | } | ||||
10509 | |||||
10510 | if (!CharExpr || !StringRefExpr) | ||||
10511 | return; | ||||
10512 | |||||
10513 | const QualType StringType = StringRefExpr->getType(); | ||||
10514 | |||||
10515 | // Return if not a PointerType. | ||||
10516 | if (!StringType->isAnyPointerType()) | ||||
10517 | return; | ||||
10518 | |||||
10519 | // Return if not a CharacterType. | ||||
10520 | if (!StringType->getPointeeType()->isAnyCharacterType()) | ||||
10521 | return; | ||||
10522 | |||||
10523 | ASTContext &Ctx = Self.getASTContext(); | ||||
10524 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
10525 | |||||
10526 | const QualType CharType = CharExpr->getType(); | ||||
10527 | if (!CharType->isAnyCharacterType() && | ||||
10528 | CharType->isIntegerType() && | ||||
10529 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | ||||
10530 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
10531 | << DiagRange << Ctx.CharTy; | ||||
10532 | } else { | ||||
10533 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
10534 | << DiagRange << CharExpr->getType(); | ||||
10535 | } | ||||
10536 | |||||
10537 | // Only print a fixit for str + char, not for char + str. | ||||
10538 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | ||||
10539 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
10540 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
10541 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
10542 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
10543 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
10544 | } else { | ||||
10545 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
10546 | } | ||||
10547 | } | ||||
10548 | |||||
10549 | /// Emit error when two pointers are incompatible. | ||||
10550 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | ||||
10551 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10552 | assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10552, __PRETTY_FUNCTION__)); | ||||
10553 | assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10553, __PRETTY_FUNCTION__)); | ||||
10554 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | ||||
10555 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | ||||
10556 | << RHSExpr->getSourceRange(); | ||||
10557 | } | ||||
10558 | |||||
10559 | // C99 6.5.6 | ||||
10560 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10561 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10562 | QualType* CompLHSTy) { | ||||
10563 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10564 | |||||
10565 | if (LHS.get()->getType()->isVectorType() || | ||||
10566 | RHS.get()->getType()->isVectorType()) { | ||||
10567 | QualType compType = CheckVectorOperands( | ||||
10568 | LHS, RHS, Loc, CompLHSTy, | ||||
10569 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10570 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
10571 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10572 | return compType; | ||||
10573 | } | ||||
10574 | |||||
10575 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
10576 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
10577 | QualType compType = | ||||
10578 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
10579 | if (CompLHSTy) | ||||
10580 | *CompLHSTy = compType; | ||||
10581 | return compType; | ||||
10582 | } | ||||
10583 | |||||
10584 | QualType compType = UsualArithmeticConversions( | ||||
10585 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
10586 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10587 | return QualType(); | ||||
10588 | |||||
10589 | // Diagnose "string literal" '+' int and string '+' "char literal". | ||||
10590 | if (Opc == BO_Add) { | ||||
10591 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | ||||
10592 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | ||||
10593 | } | ||||
10594 | |||||
10595 | // handle the common case first (both operands are arithmetic). | ||||
10596 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
10597 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10598 | return compType; | ||||
10599 | } | ||||
10600 | |||||
10601 | // Type-checking. Ultimately the pointer's going to be in PExp; | ||||
10602 | // note that we bias towards the LHS being the pointer. | ||||
10603 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | ||||
10604 | |||||
10605 | bool isObjCPointer; | ||||
10606 | if (PExp->getType()->isPointerType()) { | ||||
10607 | isObjCPointer = false; | ||||
10608 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
10609 | isObjCPointer = true; | ||||
10610 | } else { | ||||
10611 | std::swap(PExp, IExp); | ||||
10612 | if (PExp->getType()->isPointerType()) { | ||||
10613 | isObjCPointer = false; | ||||
10614 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
10615 | isObjCPointer = true; | ||||
10616 | } else { | ||||
10617 | return InvalidOperands(Loc, LHS, RHS); | ||||
10618 | } | ||||
10619 | } | ||||
10620 | assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10620, __PRETTY_FUNCTION__)); | ||||
10621 | |||||
10622 | if (!IExp->getType()->isIntegerType()) | ||||
10623 | return InvalidOperands(Loc, LHS, RHS); | ||||
10624 | |||||
10625 | // Adding to a null pointer results in undefined behavior. | ||||
10626 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | ||||
10627 | Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||
10628 | // In C++ adding zero to a null pointer is defined. | ||||
10629 | Expr::EvalResult KnownVal; | ||||
10630 | if (!getLangOpts().CPlusPlus || | ||||
10631 | (!IExp->isValueDependent() && | ||||
10632 | (!IExp->EvaluateAsInt(KnownVal, Context) || | ||||
10633 | KnownVal.Val.getInt() != 0))) { | ||||
10634 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | ||||
10635 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | ||||
10636 | Context, BO_Add, PExp, IExp); | ||||
10637 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | ||||
10638 | } | ||||
10639 | } | ||||
10640 | |||||
10641 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | ||||
10642 | return QualType(); | ||||
10643 | |||||
10644 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | ||||
10645 | return QualType(); | ||||
10646 | |||||
10647 | // Check array bounds for pointer arithemtic | ||||
10648 | CheckArrayAccess(PExp, IExp); | ||||
10649 | |||||
10650 | if (CompLHSTy) { | ||||
10651 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | ||||
10652 | if (LHSTy.isNull()) { | ||||
10653 | LHSTy = LHS.get()->getType(); | ||||
10654 | if (LHSTy->isPromotableIntegerType()) | ||||
10655 | LHSTy = Context.getPromotedIntegerType(LHSTy); | ||||
10656 | } | ||||
10657 | *CompLHSTy = LHSTy; | ||||
10658 | } | ||||
10659 | |||||
10660 | return PExp->getType(); | ||||
10661 | } | ||||
10662 | |||||
10663 | // C99 6.5.6 | ||||
10664 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10665 | SourceLocation Loc, | ||||
10666 | QualType* CompLHSTy) { | ||||
10667 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10668 | |||||
10669 | if (LHS.get()->getType()->isVectorType() || | ||||
10670 | RHS.get()->getType()->isVectorType()) { | ||||
10671 | QualType compType = CheckVectorOperands( | ||||
10672 | LHS, RHS, Loc, CompLHSTy, | ||||
10673 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10674 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
10675 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10676 | return compType; | ||||
10677 | } | ||||
10678 | |||||
10679 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
10680 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
10681 | QualType compType = | ||||
10682 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
10683 | if (CompLHSTy) | ||||
10684 | *CompLHSTy = compType; | ||||
10685 | return compType; | ||||
10686 | } | ||||
10687 | |||||
10688 | QualType compType = UsualArithmeticConversions( | ||||
10689 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
10690 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10691 | return QualType(); | ||||
10692 | |||||
10693 | // Enforce type constraints: C99 6.5.6p3. | ||||
10694 | |||||
10695 | // Handle the common case first (both operands are arithmetic). | ||||
10696 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
10697 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10698 | return compType; | ||||
10699 | } | ||||
10700 | |||||
10701 | // Either ptr - int or ptr - ptr. | ||||
10702 | if (LHS.get()->getType()->isAnyPointerType()) { | ||||
10703 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | ||||
10704 | |||||
10705 | // Diagnose bad cases where we step over interface counts. | ||||
10706 | if (LHS.get()->getType()->isObjCObjectPointerType() && | ||||
10707 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | ||||
10708 | return QualType(); | ||||
10709 | |||||
10710 | // The result type of a pointer-int computation is the pointer type. | ||||
10711 | if (RHS.get()->getType()->isIntegerType()) { | ||||
10712 | // Subtracting from a null pointer should produce a warning. | ||||
10713 | // The last argument to the diagnose call says this doesn't match the | ||||
10714 | // GNU int-to-pointer idiom. | ||||
10715 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | ||||
10716 | Expr::NPC_ValueDependentIsNotNull)) { | ||||
10717 | // In C++ adding zero to a null pointer is defined. | ||||
10718 | Expr::EvalResult KnownVal; | ||||
10719 | if (!getLangOpts().CPlusPlus || | ||||
10720 | (!RHS.get()->isValueDependent() && | ||||
10721 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | ||||
10722 | KnownVal.Val.getInt() != 0))) { | ||||
10723 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | ||||
10724 | } | ||||
10725 | } | ||||
10726 | |||||
10727 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | ||||
10728 | return QualType(); | ||||
10729 | |||||
10730 | // Check array bounds for pointer arithemtic | ||||
10731 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | ||||
10732 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | ||||
10733 | |||||
10734 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
10735 | return LHS.get()->getType(); | ||||
10736 | } | ||||
10737 | |||||
10738 | // Handle pointer-pointer subtractions. | ||||
10739 | if (const PointerType *RHSPTy | ||||
10740 | = RHS.get()->getType()->getAs<PointerType>()) { | ||||
10741 | QualType rpointee = RHSPTy->getPointeeType(); | ||||
10742 | |||||
10743 | if (getLangOpts().CPlusPlus) { | ||||
10744 | // Pointee types must be the same: C++ [expr.add] | ||||
10745 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | ||||
10746 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
10747 | } | ||||
10748 | } else { | ||||
10749 | // Pointee types must be compatible C99 6.5.6p3 | ||||
10750 | if (!Context.typesAreCompatible( | ||||
10751 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | ||||
10752 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | ||||
10753 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
10754 | return QualType(); | ||||
10755 | } | ||||
10756 | } | ||||
10757 | |||||
10758 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | ||||
10759 | LHS.get(), RHS.get())) | ||||
10760 | return QualType(); | ||||
10761 | |||||
10762 | // FIXME: Add warnings for nullptr - ptr. | ||||
10763 | |||||
10764 | // The pointee type may have zero size. As an extension, a structure or | ||||
10765 | // union may have zero size or an array may have zero length. In this | ||||
10766 | // case subtraction does not make sense. | ||||
10767 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | ||||
10768 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | ||||
10769 | if (ElementSize.isZero()) { | ||||
10770 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | ||||
10771 | << rpointee.getUnqualifiedType() | ||||
10772 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10773 | } | ||||
10774 | } | ||||
10775 | |||||
10776 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
10777 | return Context.getPointerDiffType(); | ||||
10778 | } | ||||
10779 | } | ||||
10780 | |||||
10781 | return InvalidOperands(Loc, LHS, RHS); | ||||
10782 | } | ||||
10783 | |||||
10784 | static bool isScopedEnumerationType(QualType T) { | ||||
10785 | if (const EnumType *ET = T->getAs<EnumType>()) | ||||
10786 | return ET->getDecl()->isScoped(); | ||||
10787 | return false; | ||||
10788 | } | ||||
10789 | |||||
10790 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | ||||
10791 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10792 | QualType LHSType) { | ||||
10793 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | ||||
10794 | // so skip remaining warnings as we don't want to modify values within Sema. | ||||
10795 | if (S.getLangOpts().OpenCL) | ||||
10796 | return; | ||||
10797 | |||||
10798 | // Check right/shifter operand | ||||
10799 | Expr::EvalResult RHSResult; | ||||
10800 | if (RHS.get()->isValueDependent() || | ||||
10801 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | ||||
10802 | return; | ||||
10803 | llvm::APSInt Right = RHSResult.Val.getInt(); | ||||
10804 | |||||
10805 | if (Right.isNegative()) { | ||||
10806 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10807 | S.PDiag(diag::warn_shift_negative) | ||||
10808 | << RHS.get()->getSourceRange()); | ||||
10809 | return; | ||||
10810 | } | ||||
10811 | |||||
10812 | QualType LHSExprType = LHS.get()->getType(); | ||||
10813 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | ||||
10814 | if (LHSExprType->isExtIntType()) | ||||
10815 | LeftSize = S.Context.getIntWidth(LHSExprType); | ||||
10816 | else if (LHSExprType->isFixedPointType()) { | ||||
10817 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | ||||
10818 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | ||||
10819 | } | ||||
10820 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | ||||
10821 | if (Right.uge(LeftBits)) { | ||||
10822 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10823 | S.PDiag(diag::warn_shift_gt_typewidth) | ||||
10824 | << RHS.get()->getSourceRange()); | ||||
10825 | return; | ||||
10826 | } | ||||
10827 | |||||
10828 | // FIXME: We probably need to handle fixed point types specially here. | ||||
10829 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | ||||
10830 | return; | ||||
10831 | |||||
10832 | // When left shifting an ICE which is signed, we can check for overflow which | ||||
10833 | // according to C++ standards prior to C++2a has undefined behavior | ||||
10834 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | ||||
10835 | // more than the maximum value representable in the result type, so never | ||||
10836 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | ||||
10837 | // expression is still probably a bug.) | ||||
10838 | Expr::EvalResult LHSResult; | ||||
10839 | if (LHS.get()->isValueDependent() || | ||||
10840 | LHSType->hasUnsignedIntegerRepresentation() || | ||||
10841 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | ||||
10842 | return; | ||||
10843 | llvm::APSInt Left = LHSResult.Val.getInt(); | ||||
10844 | |||||
10845 | // If LHS does not have a signed type and non-negative value | ||||
10846 | // then, the behavior is undefined before C++2a. Warn about it. | ||||
10847 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && | ||||
10848 | !S.getLangOpts().CPlusPlus20) { | ||||
10849 | S.DiagRuntimeBehavior(Loc, LHS.get(), | ||||
10850 | S.PDiag(diag::warn_shift_lhs_negative) | ||||
10851 | << LHS.get()->getSourceRange()); | ||||
10852 | return; | ||||
10853 | } | ||||
10854 | |||||
10855 | llvm::APInt ResultBits = | ||||
10856 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | ||||
10857 | if (LeftBits.uge(ResultBits)) | ||||
10858 | return; | ||||
10859 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | ||||
10860 | Result = Result.shl(Right); | ||||
10861 | |||||
10862 | // Print the bit representation of the signed integer as an unsigned | ||||
10863 | // hexadecimal number. | ||||
10864 | SmallString<40> HexResult; | ||||
10865 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | ||||
10866 | |||||
10867 | // If we are only missing a sign bit, this is less likely to result in actual | ||||
10868 | // bugs -- if the result is cast back to an unsigned type, it will have the | ||||
10869 | // expected value. Thus we place this behind a different warning that can be | ||||
10870 | // turned off separately if needed. | ||||
10871 | if (LeftBits == ResultBits - 1) { | ||||
10872 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | ||||
10873 | << HexResult << LHSType | ||||
10874 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10875 | return; | ||||
10876 | } | ||||
10877 | |||||
10878 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | ||||
10879 | << HexResult.str() << Result.getMinSignedBits() << LHSType | ||||
10880 | << Left.getBitWidth() << LHS.get()->getSourceRange() | ||||
10881 | << RHS.get()->getSourceRange(); | ||||
10882 | } | ||||
10883 | |||||
10884 | /// Return the resulting type when a vector is shifted | ||||
10885 | /// by a scalar or vector shift amount. | ||||
10886 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10887 | SourceLocation Loc, bool IsCompAssign) { | ||||
10888 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | ||||
10889 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | ||||
10890 | !LHS.get()->getType()->isVectorType()) { | ||||
10891 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | ||||
10892 | << RHS.get()->getType() << LHS.get()->getType() | ||||
10893 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10894 | return QualType(); | ||||
10895 | } | ||||
10896 | |||||
10897 | if (!IsCompAssign) { | ||||
10898 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
10899 | if (LHS.isInvalid()) return QualType(); | ||||
10900 | } | ||||
10901 | |||||
10902 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
10903 | if (RHS.isInvalid()) return QualType(); | ||||
10904 | |||||
10905 | QualType LHSType = LHS.get()->getType(); | ||||
10906 | // Note that LHS might be a scalar because the routine calls not only in | ||||
10907 | // OpenCL case. | ||||
10908 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | ||||
10909 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | ||||
10910 | |||||
10911 | // Note that RHS might not be a vector. | ||||
10912 | QualType RHSType = RHS.get()->getType(); | ||||
10913 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | ||||
10914 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | ||||
10915 | |||||
10916 | // The operands need to be integers. | ||||
10917 | if (!LHSEleType->isIntegerType()) { | ||||
10918 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
10919 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
10920 | return QualType(); | ||||
10921 | } | ||||
10922 | |||||
10923 | if (!RHSEleType->isIntegerType()) { | ||||
10924 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
10925 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
10926 | return QualType(); | ||||
10927 | } | ||||
10928 | |||||
10929 | if (!LHSVecTy) { | ||||
10930 | assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 10930, __PRETTY_FUNCTION__)); | ||||
10931 | if (IsCompAssign) | ||||
10932 | return RHSType; | ||||
10933 | if (LHSEleType != RHSEleType) { | ||||
10934 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | ||||
10935 | LHSEleType = RHSEleType; | ||||
10936 | } | ||||
10937 | QualType VecTy = | ||||
10938 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | ||||
10939 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | ||||
10940 | LHSType = VecTy; | ||||
10941 | } else if (RHSVecTy) { | ||||
10942 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | ||||
10943 | // are applied component-wise. So if RHS is a vector, then ensure | ||||
10944 | // that the number of elements is the same as LHS... | ||||
10945 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | ||||
10946 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
10947 | << LHS.get()->getType() << RHS.get()->getType() | ||||
10948 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10949 | return QualType(); | ||||
10950 | } | ||||
10951 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | ||||
10952 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | ||||
10953 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | ||||
10954 | if (LHSBT != RHSBT && | ||||
10955 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | ||||
10956 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | ||||
10957 | << LHS.get()->getType() << RHS.get()->getType() | ||||
10958 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10959 | } | ||||
10960 | } | ||||
10961 | } else { | ||||
10962 | // ...else expand RHS to match the number of elements in LHS. | ||||
10963 | QualType VecTy = | ||||
10964 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | ||||
10965 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
10966 | } | ||||
10967 | |||||
10968 | return LHSType; | ||||
10969 | } | ||||
10970 | |||||
10971 | // C99 6.5.7 | ||||
10972 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10973 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10974 | bool IsCompAssign) { | ||||
10975 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10976 | |||||
10977 | // Vector shifts promote their scalar inputs to vector type. | ||||
10978 | if (LHS.get()->getType()->isVectorType() || | ||||
10979 | RHS.get()->getType()->isVectorType()) { | ||||
10980 | if (LangOpts.ZVector) { | ||||
10981 | // The shift operators for the z vector extensions work basically | ||||
10982 | // like general shifts, except that neither the LHS nor the RHS is | ||||
10983 | // allowed to be a "vector bool". | ||||
10984 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | ||||
10985 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10986 | return InvalidOperands(Loc, LHS, RHS); | ||||
10987 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | ||||
10988 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10989 | return InvalidOperands(Loc, LHS, RHS); | ||||
10990 | } | ||||
10991 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
10992 | } | ||||
10993 | |||||
10994 | // Shifts don't perform usual arithmetic conversions, they just do integer | ||||
10995 | // promotions on each operand. C99 6.5.7p3 | ||||
10996 | |||||
10997 | // For the LHS, do usual unary conversions, but then reset them away | ||||
10998 | // if this is a compound assignment. | ||||
10999 | ExprResult OldLHS = LHS; | ||||
11000 | LHS = UsualUnaryConversions(LHS.get()); | ||||
11001 | if (LHS.isInvalid()) | ||||
11002 | return QualType(); | ||||
11003 | QualType LHSType = LHS.get()->getType(); | ||||
11004 | if (IsCompAssign) LHS = OldLHS; | ||||
11005 | |||||
11006 | // The RHS is simpler. | ||||
11007 | RHS = UsualUnaryConversions(RHS.get()); | ||||
11008 | if (RHS.isInvalid()) | ||||
11009 | return QualType(); | ||||
11010 | QualType RHSType = RHS.get()->getType(); | ||||
11011 | |||||
11012 | // C99 6.5.7p2: Each of the operands shall have integer type. | ||||
11013 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | ||||
11014 | if ((!LHSType->isFixedPointOrIntegerType() && | ||||
11015 | !LHSType->hasIntegerRepresentation()) || | ||||
11016 | !RHSType->hasIntegerRepresentation()) | ||||
11017 | return InvalidOperands(Loc, LHS, RHS); | ||||
11018 | |||||
11019 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | ||||
11020 | // hasIntegerRepresentation() above instead of this. | ||||
11021 | if (isScopedEnumerationType(LHSType) || | ||||
11022 | isScopedEnumerationType(RHSType)) { | ||||
11023 | return InvalidOperands(Loc, LHS, RHS); | ||||
11024 | } | ||||
11025 | // Sanity-check shift operands | ||||
11026 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | ||||
11027 | |||||
11028 | // "The type of the result is that of the promoted left operand." | ||||
11029 | return LHSType; | ||||
11030 | } | ||||
11031 | |||||
11032 | /// Diagnose bad pointer comparisons. | ||||
11033 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | ||||
11034 | ExprResult &LHS, ExprResult &RHS, | ||||
11035 | bool IsError) { | ||||
11036 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | ||||
11037 | : diag::ext_typecheck_comparison_of_distinct_pointers) | ||||
11038 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11039 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11040 | } | ||||
11041 | |||||
11042 | /// Returns false if the pointers are converted to a composite type, | ||||
11043 | /// true otherwise. | ||||
11044 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | ||||
11045 | ExprResult &LHS, ExprResult &RHS) { | ||||
11046 | // C++ [expr.rel]p2: | ||||
11047 | // [...] Pointer conversions (4.10) and qualification | ||||
11048 | // conversions (4.4) are performed on pointer operands (or on | ||||
11049 | // a pointer operand and a null pointer constant) to bring | ||||
11050 | // them to their composite pointer type. [...] | ||||
11051 | // | ||||
11052 | // C++ [expr.eq]p1 uses the same notion for (in)equality | ||||
11053 | // comparisons of pointers. | ||||
11054 | |||||
11055 | QualType LHSType = LHS.get()->getType(); | ||||
11056 | QualType RHSType = RHS.get()->getType(); | ||||
11057 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11058, __PRETTY_FUNCTION__)) | ||||
11058 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11058, __PRETTY_FUNCTION__)); | ||||
11059 | |||||
11060 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | ||||
11061 | if (T.isNull()) { | ||||
11062 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | ||||
11063 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | ||||
11064 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | ||||
11065 | else | ||||
11066 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11067 | return true; | ||||
11068 | } | ||||
11069 | |||||
11070 | return false; | ||||
11071 | } | ||||
11072 | |||||
11073 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | ||||
11074 | ExprResult &LHS, | ||||
11075 | ExprResult &RHS, | ||||
11076 | bool IsError) { | ||||
11077 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | ||||
11078 | : diag::ext_typecheck_comparison_of_fptr_to_void) | ||||
11079 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11080 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11081 | } | ||||
11082 | |||||
11083 | static bool isObjCObjectLiteral(ExprResult &E) { | ||||
11084 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | ||||
11085 | case Stmt::ObjCArrayLiteralClass: | ||||
11086 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11087 | case Stmt::ObjCStringLiteralClass: | ||||
11088 | case Stmt::ObjCBoxedExprClass: | ||||
11089 | return true; | ||||
11090 | default: | ||||
11091 | // Note that ObjCBoolLiteral is NOT an object literal! | ||||
11092 | return false; | ||||
11093 | } | ||||
11094 | } | ||||
11095 | |||||
11096 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | ||||
11097 | const ObjCObjectPointerType *Type = | ||||
11098 | LHS->getType()->getAs<ObjCObjectPointerType>(); | ||||
11099 | |||||
11100 | // If this is not actually an Objective-C object, bail out. | ||||
11101 | if (!Type) | ||||
11102 | return false; | ||||
11103 | |||||
11104 | // Get the LHS object's interface type. | ||||
11105 | QualType InterfaceType = Type->getPointeeType(); | ||||
11106 | |||||
11107 | // If the RHS isn't an Objective-C object, bail out. | ||||
11108 | if (!RHS->getType()->isObjCObjectPointerType()) | ||||
11109 | return false; | ||||
11110 | |||||
11111 | // Try to find the -isEqual: method. | ||||
11112 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | ||||
11113 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | ||||
11114 | InterfaceType, | ||||
11115 | /*IsInstance=*/true); | ||||
11116 | if (!Method) { | ||||
11117 | if (Type->isObjCIdType()) { | ||||
11118 | // For 'id', just check the global pool. | ||||
11119 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | ||||
11120 | /*receiverId=*/true); | ||||
11121 | } else { | ||||
11122 | // Check protocols. | ||||
11123 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | ||||
11124 | /*IsInstance=*/true); | ||||
11125 | } | ||||
11126 | } | ||||
11127 | |||||
11128 | if (!Method) | ||||
11129 | return false; | ||||
11130 | |||||
11131 | QualType T = Method->parameters()[0]->getType(); | ||||
11132 | if (!T->isObjCObjectPointerType()) | ||||
11133 | return false; | ||||
11134 | |||||
11135 | QualType R = Method->getReturnType(); | ||||
11136 | if (!R->isScalarType()) | ||||
11137 | return false; | ||||
11138 | |||||
11139 | return true; | ||||
11140 | } | ||||
11141 | |||||
11142 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | ||||
11143 | FromE = FromE->IgnoreParenImpCasts(); | ||||
11144 | switch (FromE->getStmtClass()) { | ||||
11145 | default: | ||||
11146 | break; | ||||
11147 | case Stmt::ObjCStringLiteralClass: | ||||
11148 | // "string literal" | ||||
11149 | return LK_String; | ||||
11150 | case Stmt::ObjCArrayLiteralClass: | ||||
11151 | // "array literal" | ||||
11152 | return LK_Array; | ||||
11153 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11154 | // "dictionary literal" | ||||
11155 | return LK_Dictionary; | ||||
11156 | case Stmt::BlockExprClass: | ||||
11157 | return LK_Block; | ||||
11158 | case Stmt::ObjCBoxedExprClass: { | ||||
11159 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | ||||
11160 | switch (Inner->getStmtClass()) { | ||||
11161 | case Stmt::IntegerLiteralClass: | ||||
11162 | case Stmt::FloatingLiteralClass: | ||||
11163 | case Stmt::CharacterLiteralClass: | ||||
11164 | case Stmt::ObjCBoolLiteralExprClass: | ||||
11165 | case Stmt::CXXBoolLiteralExprClass: | ||||
11166 | // "numeric literal" | ||||
11167 | return LK_Numeric; | ||||
11168 | case Stmt::ImplicitCastExprClass: { | ||||
11169 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | ||||
11170 | // Boolean literals can be represented by implicit casts. | ||||
11171 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | ||||
11172 | return LK_Numeric; | ||||
11173 | break; | ||||
11174 | } | ||||
11175 | default: | ||||
11176 | break; | ||||
11177 | } | ||||
11178 | return LK_Boxed; | ||||
11179 | } | ||||
11180 | } | ||||
11181 | return LK_None; | ||||
11182 | } | ||||
11183 | |||||
11184 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | ||||
11185 | ExprResult &LHS, ExprResult &RHS, | ||||
11186 | BinaryOperator::Opcode Opc){ | ||||
11187 | Expr *Literal; | ||||
11188 | Expr *Other; | ||||
11189 | if (isObjCObjectLiteral(LHS)) { | ||||
11190 | Literal = LHS.get(); | ||||
11191 | Other = RHS.get(); | ||||
11192 | } else { | ||||
11193 | Literal = RHS.get(); | ||||
11194 | Other = LHS.get(); | ||||
11195 | } | ||||
11196 | |||||
11197 | // Don't warn on comparisons against nil. | ||||
11198 | Other = Other->IgnoreParenCasts(); | ||||
11199 | if (Other->isNullPointerConstant(S.getASTContext(), | ||||
11200 | Expr::NPC_ValueDependentIsNotNull)) | ||||
11201 | return; | ||||
11202 | |||||
11203 | // This should be kept in sync with warn_objc_literal_comparison. | ||||
11204 | // LK_String should always be after the other literals, since it has its own | ||||
11205 | // warning flag. | ||||
11206 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | ||||
11207 | assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0 ) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11207, __PRETTY_FUNCTION__)); | ||||
11208 | if (LiteralKind == Sema::LK_None) { | ||||
11209 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11209); | ||||
11210 | } | ||||
11211 | |||||
11212 | if (LiteralKind == Sema::LK_String) | ||||
11213 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | ||||
11214 | << Literal->getSourceRange(); | ||||
11215 | else | ||||
11216 | S.Diag(Loc, diag::warn_objc_literal_comparison) | ||||
11217 | << LiteralKind << Literal->getSourceRange(); | ||||
11218 | |||||
11219 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
11220 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | ||||
11221 | SourceLocation Start = LHS.get()->getBeginLoc(); | ||||
11222 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
11223 | CharSourceRange OpRange = | ||||
11224 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
11225 | |||||
11226 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | ||||
11227 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | ||||
11228 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | ||||
11229 | << FixItHint::CreateInsertion(End, "]"); | ||||
11230 | } | ||||
11231 | } | ||||
11232 | |||||
11233 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | ||||
11234 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | ||||
11235 | ExprResult &RHS, SourceLocation Loc, | ||||
11236 | BinaryOperatorKind Opc) { | ||||
11237 | // Check that left hand side is !something. | ||||
11238 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | ||||
11239 | if (!UO || UO->getOpcode() != UO_LNot) return; | ||||
11240 | |||||
11241 | // Only check if the right hand side is non-bool arithmetic type. | ||||
11242 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | ||||
11243 | |||||
11244 | // Make sure that the something in !something is not bool. | ||||
11245 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | ||||
11246 | if (SubExpr->isKnownToHaveBooleanValue()) return; | ||||
11247 | |||||
11248 | // Emit warning. | ||||
11249 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | ||||
11250 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | ||||
11251 | << Loc << IsBitwiseOp; | ||||
11252 | |||||
11253 | // First note suggest !(x < y) | ||||
11254 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | ||||
11255 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | ||||
11256 | FirstClose = S.getLocForEndOfToken(FirstClose); | ||||
11257 | if (FirstClose.isInvalid()) | ||||
11258 | FirstOpen = SourceLocation(); | ||||
11259 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | ||||
11260 | << IsBitwiseOp | ||||
11261 | << FixItHint::CreateInsertion(FirstOpen, "(") | ||||
11262 | << FixItHint::CreateInsertion(FirstClose, ")"); | ||||
11263 | |||||
11264 | // Second note suggests (!x) < y | ||||
11265 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | ||||
11266 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | ||||
11267 | SecondClose = S.getLocForEndOfToken(SecondClose); | ||||
11268 | if (SecondClose.isInvalid()) | ||||
11269 | SecondOpen = SourceLocation(); | ||||
11270 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | ||||
11271 | << FixItHint::CreateInsertion(SecondOpen, "(") | ||||
11272 | << FixItHint::CreateInsertion(SecondClose, ")"); | ||||
11273 | } | ||||
11274 | |||||
11275 | // Returns true if E refers to a non-weak array. | ||||
11276 | static bool checkForArray(const Expr *E) { | ||||
11277 | const ValueDecl *D = nullptr; | ||||
11278 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | ||||
11279 | D = DR->getDecl(); | ||||
11280 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | ||||
11281 | if (Mem->isImplicitAccess()) | ||||
11282 | D = Mem->getMemberDecl(); | ||||
11283 | } | ||||
11284 | if (!D) | ||||
11285 | return false; | ||||
11286 | return D->getType()->isArrayType() && !D->isWeak(); | ||||
11287 | } | ||||
11288 | |||||
11289 | /// Diagnose some forms of syntactically-obvious tautological comparison. | ||||
11290 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | ||||
11291 | Expr *LHS, Expr *RHS, | ||||
11292 | BinaryOperatorKind Opc) { | ||||
11293 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | ||||
11294 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | ||||
11295 | |||||
11296 | QualType LHSType = LHS->getType(); | ||||
11297 | QualType RHSType = RHS->getType(); | ||||
11298 | if (LHSType->hasFloatingRepresentation() || | ||||
11299 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | ||||
11300 | S.inTemplateInstantiation()) | ||||
11301 | return; | ||||
11302 | |||||
11303 | // Comparisons between two array types are ill-formed for operator<=>, so | ||||
11304 | // we shouldn't emit any additional warnings about it. | ||||
11305 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | ||||
11306 | return; | ||||
11307 | |||||
11308 | // For non-floating point types, check for self-comparisons of the form | ||||
11309 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
11310 | // often indicate logic errors in the program. | ||||
11311 | // | ||||
11312 | // NOTE: Don't warn about comparison expressions resulting from macro | ||||
11313 | // expansion. Also don't warn about comparisons which are only self | ||||
11314 | // comparisons within a template instantiation. The warnings should catch | ||||
11315 | // obvious cases in the definition of the template anyways. The idea is to | ||||
11316 | // warn when the typed comparison operator will always evaluate to the same | ||||
11317 | // result. | ||||
11318 | |||||
11319 | // Used for indexing into %select in warn_comparison_always | ||||
11320 | enum { | ||||
11321 | AlwaysConstant, | ||||
11322 | AlwaysTrue, | ||||
11323 | AlwaysFalse, | ||||
11324 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | ||||
11325 | }; | ||||
11326 | |||||
11327 | // C++2a [depr.array.comp]: | ||||
11328 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | ||||
11329 | // operands of array type are deprecated. | ||||
11330 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | ||||
11331 | RHSStripped->getType()->isArrayType()) { | ||||
11332 | S.Diag(Loc, diag::warn_depr_array_comparison) | ||||
11333 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
11334 | << LHSStripped->getType() << RHSStripped->getType(); | ||||
11335 | // Carry on to produce the tautological comparison warning, if this | ||||
11336 | // expression is potentially-evaluated, we can resolve the array to a | ||||
11337 | // non-weak declaration, and so on. | ||||
11338 | } | ||||
11339 | |||||
11340 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | ||||
11341 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | ||||
11342 | unsigned Result; | ||||
11343 | switch (Opc) { | ||||
11344 | case BO_EQ: | ||||
11345 | case BO_LE: | ||||
11346 | case BO_GE: | ||||
11347 | Result = AlwaysTrue; | ||||
11348 | break; | ||||
11349 | case BO_NE: | ||||
11350 | case BO_LT: | ||||
11351 | case BO_GT: | ||||
11352 | Result = AlwaysFalse; | ||||
11353 | break; | ||||
11354 | case BO_Cmp: | ||||
11355 | Result = AlwaysEqual; | ||||
11356 | break; | ||||
11357 | default: | ||||
11358 | Result = AlwaysConstant; | ||||
11359 | break; | ||||
11360 | } | ||||
11361 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11362 | S.PDiag(diag::warn_comparison_always) | ||||
11363 | << 0 /*self-comparison*/ | ||||
11364 | << Result); | ||||
11365 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | ||||
11366 | // What is it always going to evaluate to? | ||||
11367 | unsigned Result; | ||||
11368 | switch (Opc) { | ||||
11369 | case BO_EQ: // e.g. array1 == array2 | ||||
11370 | Result = AlwaysFalse; | ||||
11371 | break; | ||||
11372 | case BO_NE: // e.g. array1 != array2 | ||||
11373 | Result = AlwaysTrue; | ||||
11374 | break; | ||||
11375 | default: // e.g. array1 <= array2 | ||||
11376 | // The best we can say is 'a constant' | ||||
11377 | Result = AlwaysConstant; | ||||
11378 | break; | ||||
11379 | } | ||||
11380 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11381 | S.PDiag(diag::warn_comparison_always) | ||||
11382 | << 1 /*array comparison*/ | ||||
11383 | << Result); | ||||
11384 | } | ||||
11385 | } | ||||
11386 | |||||
11387 | if (isa<CastExpr>(LHSStripped)) | ||||
11388 | LHSStripped = LHSStripped->IgnoreParenCasts(); | ||||
11389 | if (isa<CastExpr>(RHSStripped)) | ||||
11390 | RHSStripped = RHSStripped->IgnoreParenCasts(); | ||||
11391 | |||||
11392 | // Warn about comparisons against a string constant (unless the other | ||||
11393 | // operand is null); the user probably wants string comparison function. | ||||
11394 | Expr *LiteralString = nullptr; | ||||
11395 | Expr *LiteralStringStripped = nullptr; | ||||
11396 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | ||||
11397 | !RHSStripped->isNullPointerConstant(S.Context, | ||||
11398 | Expr::NPC_ValueDependentIsNull)) { | ||||
11399 | LiteralString = LHS; | ||||
11400 | LiteralStringStripped = LHSStripped; | ||||
11401 | } else if ((isa<StringLiteral>(RHSStripped) || | ||||
11402 | isa<ObjCEncodeExpr>(RHSStripped)) && | ||||
11403 | !LHSStripped->isNullPointerConstant(S.Context, | ||||
11404 | Expr::NPC_ValueDependentIsNull)) { | ||||
11405 | LiteralString = RHS; | ||||
11406 | LiteralStringStripped = RHSStripped; | ||||
11407 | } | ||||
11408 | |||||
11409 | if (LiteralString) { | ||||
11410 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11411 | S.PDiag(diag::warn_stringcompare) | ||||
11412 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | ||||
11413 | << LiteralString->getSourceRange()); | ||||
11414 | } | ||||
11415 | } | ||||
11416 | |||||
11417 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | ||||
11418 | switch (CK) { | ||||
11419 | default: { | ||||
11420 | #ifndef NDEBUG | ||||
11421 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | ||||
11422 | << "\n"; | ||||
11423 | #endif | ||||
11424 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11424); | ||||
11425 | } | ||||
11426 | case CK_UserDefinedConversion: | ||||
11427 | return ICK_Identity; | ||||
11428 | case CK_LValueToRValue: | ||||
11429 | return ICK_Lvalue_To_Rvalue; | ||||
11430 | case CK_ArrayToPointerDecay: | ||||
11431 | return ICK_Array_To_Pointer; | ||||
11432 | case CK_FunctionToPointerDecay: | ||||
11433 | return ICK_Function_To_Pointer; | ||||
11434 | case CK_IntegralCast: | ||||
11435 | return ICK_Integral_Conversion; | ||||
11436 | case CK_FloatingCast: | ||||
11437 | return ICK_Floating_Conversion; | ||||
11438 | case CK_IntegralToFloating: | ||||
11439 | case CK_FloatingToIntegral: | ||||
11440 | return ICK_Floating_Integral; | ||||
11441 | case CK_IntegralComplexCast: | ||||
11442 | case CK_FloatingComplexCast: | ||||
11443 | case CK_FloatingComplexToIntegralComplex: | ||||
11444 | case CK_IntegralComplexToFloatingComplex: | ||||
11445 | return ICK_Complex_Conversion; | ||||
11446 | case CK_FloatingComplexToReal: | ||||
11447 | case CK_FloatingRealToComplex: | ||||
11448 | case CK_IntegralComplexToReal: | ||||
11449 | case CK_IntegralRealToComplex: | ||||
11450 | return ICK_Complex_Real; | ||||
11451 | } | ||||
11452 | } | ||||
11453 | |||||
11454 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | ||||
11455 | QualType FromType, | ||||
11456 | SourceLocation Loc) { | ||||
11457 | // Check for a narrowing implicit conversion. | ||||
11458 | StandardConversionSequence SCS; | ||||
11459 | SCS.setAsIdentityConversion(); | ||||
11460 | SCS.setToType(0, FromType); | ||||
11461 | SCS.setToType(1, ToType); | ||||
11462 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
11463 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | ||||
11464 | |||||
11465 | APValue PreNarrowingValue; | ||||
11466 | QualType PreNarrowingType; | ||||
11467 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | ||||
11468 | PreNarrowingType, | ||||
11469 | /*IgnoreFloatToIntegralConversion*/ true)) { | ||||
11470 | case NK_Dependent_Narrowing: | ||||
11471 | // Implicit conversion to a narrower type, but the expression is | ||||
11472 | // value-dependent so we can't tell whether it's actually narrowing. | ||||
11473 | case NK_Not_Narrowing: | ||||
11474 | return false; | ||||
11475 | |||||
11476 | case NK_Constant_Narrowing: | ||||
11477 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
11478 | // expression. | ||||
11479 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
11480 | << /*Constant*/ 1 | ||||
11481 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | ||||
11482 | return true; | ||||
11483 | |||||
11484 | case NK_Variable_Narrowing: | ||||
11485 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
11486 | // expression. | ||||
11487 | case NK_Type_Narrowing: | ||||
11488 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
11489 | << /*Constant*/ 0 << FromType << ToType; | ||||
11490 | // TODO: It's not a constant expression, but what if the user intended it | ||||
11491 | // to be? Can we produce notes to help them figure out why it isn't? | ||||
11492 | return true; | ||||
11493 | } | ||||
11494 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11494); | ||||
11495 | } | ||||
11496 | |||||
11497 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | ||||
11498 | ExprResult &LHS, | ||||
11499 | ExprResult &RHS, | ||||
11500 | SourceLocation Loc) { | ||||
11501 | QualType LHSType = LHS.get()->getType(); | ||||
11502 | QualType RHSType = RHS.get()->getType(); | ||||
11503 | // Dig out the original argument type and expression before implicit casts | ||||
11504 | // were applied. These are the types/expressions we need to check the | ||||
11505 | // [expr.spaceship] requirements against. | ||||
11506 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | ||||
11507 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | ||||
11508 | QualType LHSStrippedType = LHSStripped.get()->getType(); | ||||
11509 | QualType RHSStrippedType = RHSStripped.get()->getType(); | ||||
11510 | |||||
11511 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | ||||
11512 | // other is not, the program is ill-formed. | ||||
11513 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | ||||
11514 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
11515 | return QualType(); | ||||
11516 | } | ||||
11517 | |||||
11518 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | ||||
11519 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | ||||
11520 | RHSStrippedType->isEnumeralType(); | ||||
11521 | if (NumEnumArgs == 1) { | ||||
11522 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | ||||
11523 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | ||||
11524 | if (OtherTy->hasFloatingRepresentation()) { | ||||
11525 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
11526 | return QualType(); | ||||
11527 | } | ||||
11528 | } | ||||
11529 | if (NumEnumArgs == 2) { | ||||
11530 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | ||||
11531 | // type E, the operator yields the result of converting the operands | ||||
11532 | // to the underlying type of E and applying <=> to the converted operands. | ||||
11533 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | ||||
11534 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11535 | return QualType(); | ||||
11536 | } | ||||
11537 | QualType IntType = | ||||
11538 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | ||||
11539 | assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> ( 0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11539, __PRETTY_FUNCTION__)); | ||||
11540 | |||||
11541 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | ||||
11542 | // promote the boolean type, and all other promotable integer types, to | ||||
11543 | // avoid this. | ||||
11544 | if (IntType->isPromotableIntegerType()) | ||||
11545 | IntType = S.Context.getPromotedIntegerType(IntType); | ||||
11546 | |||||
11547 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | ||||
11548 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | ||||
11549 | LHSType = RHSType = IntType; | ||||
11550 | } | ||||
11551 | |||||
11552 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | ||||
11553 | // usual arithmetic conversions are applied to the operands. | ||||
11554 | QualType Type = | ||||
11555 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
11556 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11557 | return QualType(); | ||||
11558 | if (Type.isNull()) | ||||
11559 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11560 | |||||
11561 | Optional<ComparisonCategoryType> CCT = | ||||
11562 | getComparisonCategoryForBuiltinCmp(Type); | ||||
11563 | if (!CCT) | ||||
11564 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11565 | |||||
11566 | bool HasNarrowing = checkThreeWayNarrowingConversion( | ||||
11567 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | ||||
11568 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | ||||
11569 | RHS.get()->getBeginLoc()); | ||||
11570 | if (HasNarrowing) | ||||
11571 | return QualType(); | ||||
11572 | |||||
11573 | assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set" ) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11573, __PRETTY_FUNCTION__)); | ||||
11574 | |||||
11575 | return S.CheckComparisonCategoryType( | ||||
11576 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | ||||
11577 | } | ||||
11578 | |||||
11579 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | ||||
11580 | ExprResult &RHS, | ||||
11581 | SourceLocation Loc, | ||||
11582 | BinaryOperatorKind Opc) { | ||||
11583 | if (Opc == BO_Cmp) | ||||
11584 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | ||||
11585 | |||||
11586 | // C99 6.5.8p3 / C99 6.5.9p4 | ||||
11587 | QualType Type = | ||||
11588 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
11589 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11590 | return QualType(); | ||||
11591 | if (Type.isNull()) | ||||
11592 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11593 | assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ? static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11593, __PRETTY_FUNCTION__)); | ||||
11594 | |||||
11595 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | ||||
11596 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11597 | |||||
11598 | // Check for comparisons of floating point operands using != and ==. | ||||
11599 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | ||||
11600 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||
11601 | |||||
11602 | // The result of comparisons is 'bool' in C++, 'int' in C. | ||||
11603 | return S.Context.getLogicalOperationType(); | ||||
11604 | } | ||||
11605 | |||||
11606 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | ||||
11607 | if (!NullE.get()->getType()->isAnyPointerType()) | ||||
11608 | return; | ||||
11609 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | ||||
11610 | if (!E.get()->getType()->isAnyPointerType() && | ||||
11611 | E.get()->isNullPointerConstant(Context, | ||||
11612 | Expr::NPC_ValueDependentIsNotNull) == | ||||
11613 | Expr::NPCK_ZeroExpression) { | ||||
11614 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | ||||
11615 | if (CL->getValue() == 0) | ||||
11616 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
11617 | << NullValue | ||||
11618 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
11619 | NullValue ? "NULL" : "(void *)0"); | ||||
11620 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | ||||
11621 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | ||||
11622 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | ||||
11623 | if (T == Context.CharTy) | ||||
11624 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
11625 | << NullValue | ||||
11626 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
11627 | NullValue ? "NULL" : "(void *)0"); | ||||
11628 | } | ||||
11629 | } | ||||
11630 | } | ||||
11631 | |||||
11632 | // C99 6.5.8, C++ [expr.rel] | ||||
11633 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11634 | SourceLocation Loc, | ||||
11635 | BinaryOperatorKind Opc) { | ||||
11636 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | ||||
11637 | bool IsThreeWay = Opc == BO_Cmp; | ||||
11638 | bool IsOrdered = IsRelational || IsThreeWay; | ||||
11639 | auto IsAnyPointerType = [](ExprResult E) { | ||||
11640 | QualType Ty = E.get()->getType(); | ||||
11641 | return Ty->isPointerType() || Ty->isMemberPointerType(); | ||||
11642 | }; | ||||
11643 | |||||
11644 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | ||||
11645 | // type, array-to-pointer, ..., conversions are performed on both operands to | ||||
11646 | // bring them to their composite type. | ||||
11647 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | ||||
11648 | // any type-related checks. | ||||
11649 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | ||||
11650 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
11651 | if (LHS.isInvalid()) | ||||
11652 | return QualType(); | ||||
11653 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
11654 | if (RHS.isInvalid()) | ||||
11655 | return QualType(); | ||||
11656 | } else { | ||||
11657 | LHS = DefaultLvalueConversion(LHS.get()); | ||||
11658 | if (LHS.isInvalid()) | ||||
11659 | return QualType(); | ||||
11660 | RHS = DefaultLvalueConversion(RHS.get()); | ||||
11661 | if (RHS.isInvalid()) | ||||
11662 | return QualType(); | ||||
11663 | } | ||||
11664 | |||||
11665 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | ||||
11666 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | ||||
11667 | CheckPtrComparisonWithNullChar(LHS, RHS); | ||||
11668 | CheckPtrComparisonWithNullChar(RHS, LHS); | ||||
11669 | } | ||||
11670 | |||||
11671 | // Handle vector comparisons separately. | ||||
11672 | if (LHS.get()->getType()->isVectorType() || | ||||
11673 | RHS.get()->getType()->isVectorType()) | ||||
11674 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
11675 | |||||
11676 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
11677 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
11678 | |||||
11679 | QualType LHSType = LHS.get()->getType(); | ||||
11680 | QualType RHSType = RHS.get()->getType(); | ||||
11681 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | ||||
11682 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | ||||
11683 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | ||||
11684 | |||||
11685 | const Expr::NullPointerConstantKind LHSNullKind = | ||||
11686 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
11687 | const Expr::NullPointerConstantKind RHSNullKind = | ||||
11688 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
11689 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | ||||
11690 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | ||||
11691 | |||||
11692 | auto computeResultTy = [&]() { | ||||
11693 | if (Opc != BO_Cmp) | ||||
11694 | return Context.getLogicalOperationType(); | ||||
11695 | assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11695, __PRETTY_FUNCTION__)); | ||||
11696 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()-> getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11696, __PRETTY_FUNCTION__)); | ||||
11697 | |||||
11698 | QualType CompositeTy = LHS.get()->getType(); | ||||
11699 | assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void> (0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 11699, __PRETTY_FUNCTION__)); | ||||
11700 | |||||
11701 | Optional<ComparisonCategoryType> CCT = | ||||
11702 | getComparisonCategoryForBuiltinCmp(CompositeTy); | ||||
11703 | if (!CCT) | ||||
11704 | return InvalidOperands(Loc, LHS, RHS); | ||||
11705 | |||||
11706 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | ||||
11707 | // P0946R0: Comparisons between a null pointer constant and an object | ||||
11708 | // pointer result in std::strong_equality, which is ill-formed under | ||||
11709 | // P1959R0. | ||||
11710 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | ||||
11711 | << (LHSIsNull ? LHS.get()->getSourceRange() | ||||
11712 | : RHS.get()->getSourceRange()); | ||||
11713 | return QualType(); | ||||
11714 | } | ||||
11715 | |||||
11716 | return CheckComparisonCategoryType( | ||||
11717 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | ||||
11718 | }; | ||||
11719 | |||||
11720 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | ||||
11721 | bool IsEquality = Opc == BO_EQ; | ||||
11722 | if (RHSIsNull) | ||||
11723 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | ||||
11724 | RHS.get()->getSourceRange()); | ||||
11725 | else | ||||
11726 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | ||||
11727 | LHS.get()->getSourceRange()); | ||||
11728 | } | ||||
11729 | |||||
11730 | if ((LHSType->isIntegerType() && !LHSIsNull) || | ||||
11731 | (RHSType->isIntegerType() && !RHSIsNull)) { | ||||
11732 | // Skip normal pointer conversion checks in this case; we have better | ||||
11733 | // diagnostics for this below. | ||||
11734 | } else if (getLangOpts().CPlusPlus) { | ||||
11735 | // Equality comparison of a function pointer to a void pointer is invalid, | ||||
11736 | // but we allow it as an extension. | ||||
11737 | // FIXME: If we really want to allow this, should it be part of composite | ||||
11738 | // pointer type computation so it works in conditionals too? | ||||
11739 | if (!IsOrdered && | ||||
11740 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | ||||
11741 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | ||||
11742 | // This is a gcc extension compatibility comparison. | ||||
11743 | // In a SFINAE context, we treat this as a hard error to maintain | ||||
11744 | // conformance with the C++ standard. | ||||
11745 | diagnoseFunctionPointerToVoidComparison( | ||||
11746 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | ||||
11747 | |||||
11748 | if (isSFINAEContext()) | ||||
11749 | return QualType(); | ||||
11750 | |||||
11751 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11752 | return computeResultTy(); | ||||
11753 | } | ||||
11754 | |||||
11755 | // C++ [expr.eq]p2: | ||||
11756 | // If at least one operand is a pointer [...] bring them to their | ||||
11757 | // composite pointer type. | ||||
11758 | // C++ [expr.spaceship]p6 | ||||
11759 | // If at least one of the operands is of pointer type, [...] bring them | ||||
11760 | // to their composite pointer type. | ||||
11761 | // C++ [expr.rel]p2: | ||||
11762 | // If both operands are pointers, [...] bring them to their composite | ||||
11763 | // pointer type. | ||||
11764 | // For <=>, the only valid non-pointer types are arrays and functions, and | ||||
11765 | // we already decayed those, so this is really the same as the relational | ||||
11766 | // comparison rule. | ||||
11767 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | ||||
11768 | (IsOrdered ? 2 : 1) && | ||||
11769 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | ||||
11770 | RHSType->isObjCObjectPointerType()))) { | ||||
11771 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
11772 | return QualType(); | ||||
11773 | return computeResultTy(); | ||||
11774 | } | ||||
11775 | } else if (LHSType->isPointerType() && | ||||
11776 | RHSType->isPointerType()) { // C99 6.5.8p2 | ||||
11777 | // All of the following pointer-related warnings are GCC extensions, except | ||||
11778 | // when handling null pointer constants. | ||||
11779 | QualType LCanPointeeTy = | ||||
11780 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
11781 | QualType RCanPointeeTy = | ||||
11782 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
11783 | |||||
11784 | // C99 6.5.9p2 and C99 6.5.8p2 | ||||
11785 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | ||||
11786 | RCanPointeeTy.getUnqualifiedType())) { | ||||
11787 | if (IsRelational) { | ||||
11788 | // Pointers both need to point to complete or incomplete types | ||||
11789 | if ((LCanPointeeTy->isIncompleteType() != | ||||
11790 | RCanPointeeTy->isIncompleteType()) && | ||||
11791 | !getLangOpts().C11) { | ||||
11792 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | ||||
11793 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | ||||
11794 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | ||||
11795 | << RCanPointeeTy->isIncompleteType(); | ||||
11796 | } | ||||
11797 | if (LCanPointeeTy->isFunctionType()) { | ||||
11798 | // Valid unless a relational comparison of function pointers | ||||
11799 | Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) | ||||
11800 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11801 | << RHS.get()->getSourceRange(); | ||||
11802 | } | ||||
11803 | } | ||||
11804 | } else if (!IsRelational && | ||||
11805 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | ||||
11806 | // Valid unless comparison between non-null pointer and function pointer | ||||
11807 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | ||||
11808 | && !LHSIsNull && !RHSIsNull) | ||||
11809 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | ||||
11810 | /*isError*/false); | ||||
11811 | } else { | ||||
11812 | // Invalid | ||||
11813 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | ||||
11814 | } | ||||
11815 | if (LCanPointeeTy != RCanPointeeTy) { | ||||
11816 | // Treat NULL constant as a special case in OpenCL. | ||||
11817 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | ||||
11818 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | ||||
11819 | Diag(Loc, | ||||
11820 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
11821 | << LHSType << RHSType << 0 /* comparison */ | ||||
11822 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11823 | } | ||||
11824 | } | ||||
11825 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | ||||
11826 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | ||||
11827 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | ||||
11828 | : CK_BitCast; | ||||
11829 | if (LHSIsNull && !RHSIsNull) | ||||
11830 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | ||||
11831 | else | ||||
11832 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | ||||
11833 | } | ||||
11834 | return computeResultTy(); | ||||
11835 | } | ||||
11836 | |||||
11837 | if (getLangOpts().CPlusPlus) { | ||||
11838 | // C++ [expr.eq]p4: | ||||
11839 | // Two operands of type std::nullptr_t or one operand of type | ||||
11840 | // std::nullptr_t and the other a null pointer constant compare equal. | ||||
11841 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | ||||
11842 | if (LHSType->isNullPtrType()) { | ||||
11843 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11844 | return computeResultTy(); | ||||
11845 | } | ||||
11846 | if (RHSType->isNullPtrType()) { | ||||
11847 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11848 | return computeResultTy(); | ||||
11849 | } | ||||
11850 | } | ||||
11851 | |||||
11852 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | ||||
11853 | // These aren't covered by the composite pointer type rules. | ||||
11854 | if (!IsOrdered && RHSType->isNullPtrType() && | ||||
11855 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | ||||
11856 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11857 | return computeResultTy(); | ||||
11858 | } | ||||
11859 | if (!IsOrdered && LHSType->isNullPtrType() && | ||||
11860 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | ||||
11861 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11862 | return computeResultTy(); | ||||
11863 | } | ||||
11864 | |||||
11865 | if (IsRelational && | ||||
11866 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | ||||
11867 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | ||||
11868 | // HACK: Relational comparison of nullptr_t against a pointer type is | ||||
11869 | // invalid per DR583, but we allow it within std::less<> and friends, | ||||
11870 | // since otherwise common uses of it break. | ||||
11871 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | ||||
11872 | // friends to have std::nullptr_t overload candidates. | ||||
11873 | DeclContext *DC = CurContext; | ||||
11874 | if (isa<FunctionDecl>(DC)) | ||||
11875 | DC = DC->getParent(); | ||||
11876 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | ||||
11877 | if (CTSD->isInStdNamespace() && | ||||
11878 | llvm::StringSwitch<bool>(CTSD->getName()) | ||||
11879 | .Cases("less", "less_equal", "greater", "greater_equal", true) | ||||
11880 | .Default(false)) { | ||||
11881 | if (RHSType->isNullPtrType()) | ||||
11882 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11883 | else | ||||
11884 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11885 | return computeResultTy(); | ||||
11886 | } | ||||
11887 | } | ||||
11888 | } | ||||
11889 | |||||
11890 | // C++ [expr.eq]p2: | ||||
11891 | // If at least one operand is a pointer to member, [...] bring them to | ||||
11892 | // their composite pointer type. | ||||
11893 | if (!IsOrdered && | ||||
11894 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | ||||
11895 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
11896 | return QualType(); | ||||
11897 | else | ||||
11898 | return computeResultTy(); | ||||
11899 | } | ||||
11900 | } | ||||
11901 | |||||
11902 | // Handle block pointer types. | ||||
11903 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
11904 | RHSType->isBlockPointerType()) { | ||||
11905 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
11906 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
11907 | |||||
11908 | if (!LHSIsNull && !RHSIsNull && | ||||
11909 | !Context.typesAreCompatible(lpointee, rpointee)) { | ||||
11910 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
11911 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11912 | << RHS.get()->getSourceRange(); | ||||
11913 | } | ||||
11914 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11915 | return computeResultTy(); | ||||
11916 | } | ||||
11917 | |||||
11918 | // Allow block pointers to be compared with null pointer constants. | ||||
11919 | if (!IsOrdered | ||||
11920 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | ||||
11921 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | ||||
11922 | if (!LHSIsNull && !RHSIsNull) { | ||||
11923 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | ||||
11924 | ->getPointeeType()->isVoidType()) | ||||
11925 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | ||||
11926 | ->getPointeeType()->isVoidType()))) | ||||
11927 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
11928 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11929 | << RHS.get()->getSourceRange(); | ||||
11930 | } | ||||
11931 | if (LHSIsNull && !RHSIsNull) | ||||
11932 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
11933 | RHSType->isPointerType() ? CK_BitCast | ||||
11934 | : CK_AnyPointerToBlockPointerCast); | ||||
11935 | else | ||||
11936 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
11937 | LHSType->isPointerType() ? CK_BitCast | ||||
11938 | : CK_AnyPointerToBlockPointerCast); | ||||
11939 | return computeResultTy(); | ||||
11940 | } | ||||
11941 | |||||
11942 | if (LHSType->isObjCObjectPointerType() || | ||||
11943 | RHSType->isObjCObjectPointerType()) { | ||||
11944 | const PointerType *LPT = LHSType->getAs<PointerType>(); | ||||
11945 | const PointerType *RPT = RHSType->getAs<PointerType>(); | ||||
11946 | if (LPT || RPT) { | ||||
11947 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | ||||
11948 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | ||||
11949 | |||||
11950 | if (!LPtrToVoid && !RPtrToVoid && | ||||
11951 | !Context.typesAreCompatible(LHSType, RHSType)) { | ||||
11952 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
11953 | /*isError*/false); | ||||
11954 | } | ||||
11955 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | ||||
11956 | // the RHS, but we have test coverage for this behavior. | ||||
11957 | // FIXME: Consider using convertPointersToCompositeType in C++. | ||||
11958 | if (LHSIsNull && !RHSIsNull) { | ||||
11959 | Expr *E = LHS.get(); | ||||
11960 | if (getLangOpts().ObjCAutoRefCount) | ||||
11961 | CheckObjCConversion(SourceRange(), RHSType, E, | ||||
11962 | CCK_ImplicitConversion); | ||||
11963 | LHS = ImpCastExprToType(E, RHSType, | ||||
11964 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
11965 | } | ||||
11966 | else { | ||||
11967 | Expr *E = RHS.get(); | ||||
11968 | if (getLangOpts().ObjCAutoRefCount) | ||||
11969 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | ||||
11970 | /*Diagnose=*/true, | ||||
11971 | /*DiagnoseCFAudited=*/false, Opc); | ||||
11972 | RHS = ImpCastExprToType(E, LHSType, | ||||
11973 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
11974 | } | ||||
11975 | return computeResultTy(); | ||||
11976 | } | ||||
11977 | if (LHSType->isObjCObjectPointerType() && | ||||
11978 | RHSType->isObjCObjectPointerType()) { | ||||
11979 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | ||||
11980 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
11981 | /*isError*/false); | ||||
11982 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | ||||
11983 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | ||||
11984 | |||||
11985 | if (LHSIsNull && !RHSIsNull) | ||||
11986 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
11987 | else | ||||
11988 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11989 | return computeResultTy(); | ||||
11990 | } | ||||
11991 | |||||
11992 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
11993 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
11994 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
11995 | CK_BlockPointerToObjCPointerCast); | ||||
11996 | return computeResultTy(); | ||||
11997 | } else if (!IsOrdered && | ||||
11998 | LHSType->isBlockCompatibleObjCPointerType(Context) && | ||||
11999 | RHSType->isBlockPointerType()) { | ||||
12000 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12001 | CK_BlockPointerToObjCPointerCast); | ||||
12002 | return computeResultTy(); | ||||
12003 | } | ||||
12004 | } | ||||
12005 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | ||||
12006 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | ||||
12007 | unsigned DiagID = 0; | ||||
12008 | bool isError = false; | ||||
12009 | if (LangOpts.DebuggerSupport) { | ||||
12010 | // Under a debugger, allow the comparison of pointers to integers, | ||||
12011 | // since users tend to want to compare addresses. | ||||
12012 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | ||||
12013 | (RHSIsNull && RHSType->isIntegerType())) { | ||||
12014 | if (IsOrdered) { | ||||
12015 | isError = getLangOpts().CPlusPlus; | ||||
12016 | DiagID = | ||||
12017 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | ||||
12018 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | ||||
12019 | } | ||||
12020 | } else if (getLangOpts().CPlusPlus) { | ||||
12021 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | ||||
12022 | isError = true; | ||||
12023 | } else if (IsOrdered) | ||||
12024 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | ||||
12025 | else | ||||
12026 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | ||||
12027 | |||||
12028 | if (DiagID) { | ||||
12029 | Diag(Loc, DiagID) | ||||
12030 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12031 | << RHS.get()->getSourceRange(); | ||||
12032 | if (isError) | ||||
12033 | return QualType(); | ||||
12034 | } | ||||
12035 | |||||
12036 | if (LHSType->isIntegerType()) | ||||
12037 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12038 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
12039 | else | ||||
12040 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12041 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
12042 | return computeResultTy(); | ||||
12043 | } | ||||
12044 | |||||
12045 | // Handle block pointers. | ||||
12046 | if (!IsOrdered && RHSIsNull | ||||
12047 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | ||||
12048 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12049 | return computeResultTy(); | ||||
12050 | } | ||||
12051 | if (!IsOrdered && LHSIsNull | ||||
12052 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | ||||
12053 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12054 | return computeResultTy(); | ||||
12055 | } | ||||
12056 | |||||
12057 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||
12058 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | ||||
12059 | return computeResultTy(); | ||||
12060 | } | ||||
12061 | |||||
12062 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | ||||
12063 | return computeResultTy(); | ||||
12064 | } | ||||
12065 | |||||
12066 | if (LHSIsNull && RHSType->isQueueT()) { | ||||
12067 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12068 | return computeResultTy(); | ||||
12069 | } | ||||
12070 | |||||
12071 | if (LHSType->isQueueT() && RHSIsNull) { | ||||
12072 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12073 | return computeResultTy(); | ||||
12074 | } | ||||
12075 | } | ||||
12076 | |||||
12077 | return InvalidOperands(Loc, LHS, RHS); | ||||
12078 | } | ||||
12079 | |||||
12080 | // Return a signed ext_vector_type that is of identical size and number of | ||||
12081 | // elements. For floating point vectors, return an integer type of identical | ||||
12082 | // size and number of elements. In the non ext_vector_type case, search from | ||||
12083 | // the largest type to the smallest type to avoid cases where long long == long, | ||||
12084 | // where long gets picked over long long. | ||||
12085 | QualType Sema::GetSignedVectorType(QualType V) { | ||||
12086 | const VectorType *VTy = V->castAs<VectorType>(); | ||||
12087 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | ||||
12088 | |||||
12089 | if (isa<ExtVectorType>(VTy)) { | ||||
12090 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | ||||
12091 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | ||||
12092 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12093 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | ||||
12094 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12095 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | ||||
12096 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12097 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | ||||
12098 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12099, __PRETTY_FUNCTION__)) | ||||
12099 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12099, __PRETTY_FUNCTION__)); | ||||
12100 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | ||||
12101 | } | ||||
12102 | |||||
12103 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | ||||
12104 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | ||||
12105 | VectorType::GenericVector); | ||||
12106 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12107 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | ||||
12108 | VectorType::GenericVector); | ||||
12109 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12110 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | ||||
12111 | VectorType::GenericVector); | ||||
12112 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12113 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | ||||
12114 | VectorType::GenericVector); | ||||
12115 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12116, __PRETTY_FUNCTION__)) | ||||
12116 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12116, __PRETTY_FUNCTION__)); | ||||
12117 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | ||||
12118 | VectorType::GenericVector); | ||||
12119 | } | ||||
12120 | |||||
12121 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | ||||
12122 | /// operates on extended vector types. Instead of producing an IntTy result, | ||||
12123 | /// like a scalar comparison, a vector comparison produces a vector of integer | ||||
12124 | /// types. | ||||
12125 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12126 | SourceLocation Loc, | ||||
12127 | BinaryOperatorKind Opc) { | ||||
12128 | if (Opc == BO_Cmp) { | ||||
12129 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
12130 | return QualType(); | ||||
12131 | } | ||||
12132 | |||||
12133 | // Check to make sure we're operating on vectors of the same type and width, | ||||
12134 | // Allowing one side to be a scalar of element type. | ||||
12135 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | ||||
12136 | /*AllowBothBool*/true, | ||||
12137 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
12138 | if (vType.isNull()) | ||||
12139 | return vType; | ||||
12140 | |||||
12141 | QualType LHSType = LHS.get()->getType(); | ||||
12142 | |||||
12143 | // If AltiVec, the comparison results in a numeric type, i.e. | ||||
12144 | // bool for C++, int for C | ||||
12145 | if (getLangOpts().AltiVec && | ||||
12146 | vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) | ||||
12147 | return Context.getLogicalOperationType(); | ||||
12148 | |||||
12149 | // For non-floating point types, check for self-comparisons of the form | ||||
12150 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12151 | // often indicate logic errors in the program. | ||||
12152 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12153 | |||||
12154 | // Check for comparisons of floating point operands using != and ==. | ||||
12155 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
12156 | LHSType->hasFloatingRepresentation()) { | ||||
12157 | assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast <void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12157, __PRETTY_FUNCTION__)); | ||||
12158 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||
12159 | } | ||||
12160 | |||||
12161 | // Return a signed type for the vector. | ||||
12162 | return GetSignedVectorType(vType); | ||||
12163 | } | ||||
12164 | |||||
12165 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | ||||
12166 | const ExprResult &XorRHS, | ||||
12167 | const SourceLocation Loc) { | ||||
12168 | // Do not diagnose macros. | ||||
12169 | if (Loc.isMacroID()) | ||||
12170 | return; | ||||
12171 | |||||
12172 | // Do not diagnose if both LHS and RHS are macros. | ||||
12173 | if (XorLHS.get()->getExprLoc().isMacroID() && | ||||
12174 | XorRHS.get()->getExprLoc().isMacroID()) | ||||
12175 | return; | ||||
12176 | |||||
12177 | bool Negative = false; | ||||
12178 | bool ExplicitPlus = false; | ||||
12179 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | ||||
12180 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | ||||
12181 | |||||
12182 | if (!LHSInt) | ||||
12183 | return; | ||||
12184 | if (!RHSInt) { | ||||
12185 | // Check negative literals. | ||||
12186 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | ||||
12187 | UnaryOperatorKind Opc = UO->getOpcode(); | ||||
12188 | if (Opc != UO_Minus && Opc != UO_Plus) | ||||
12189 | return; | ||||
12190 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | ||||
12191 | if (!RHSInt) | ||||
12192 | return; | ||||
12193 | Negative = (Opc == UO_Minus); | ||||
12194 | ExplicitPlus = !Negative; | ||||
12195 | } else { | ||||
12196 | return; | ||||
12197 | } | ||||
12198 | } | ||||
12199 | |||||
12200 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | ||||
12201 | llvm::APInt RightSideValue = RHSInt->getValue(); | ||||
12202 | if (LeftSideValue != 2 && LeftSideValue != 10) | ||||
12203 | return; | ||||
12204 | |||||
12205 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | ||||
12206 | return; | ||||
12207 | |||||
12208 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | ||||
12209 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | ||||
12210 | llvm::StringRef ExprStr = | ||||
12211 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | ||||
12212 | |||||
12213 | CharSourceRange XorRange = | ||||
12214 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
12215 | llvm::StringRef XorStr = | ||||
12216 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | ||||
12217 | // Do not diagnose if xor keyword/macro is used. | ||||
12218 | if (XorStr == "xor") | ||||
12219 | return; | ||||
12220 | |||||
12221 | std::string LHSStr = std::string(Lexer::getSourceText( | ||||
12222 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | ||||
12223 | S.getSourceManager(), S.getLangOpts())); | ||||
12224 | std::string RHSStr = std::string(Lexer::getSourceText( | ||||
12225 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | ||||
12226 | S.getSourceManager(), S.getLangOpts())); | ||||
12227 | |||||
12228 | if (Negative) { | ||||
12229 | RightSideValue = -RightSideValue; | ||||
12230 | RHSStr = "-" + RHSStr; | ||||
12231 | } else if (ExplicitPlus) { | ||||
12232 | RHSStr = "+" + RHSStr; | ||||
12233 | } | ||||
12234 | |||||
12235 | StringRef LHSStrRef = LHSStr; | ||||
12236 | StringRef RHSStrRef = RHSStr; | ||||
12237 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | ||||
12238 | // literals. | ||||
12239 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | ||||
12240 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | ||||
12241 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | ||||
12242 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | ||||
12243 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | ||||
12244 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | ||||
12245 | LHSStrRef.find('\'') != StringRef::npos || | ||||
12246 | RHSStrRef.find('\'') != StringRef::npos) | ||||
12247 | return; | ||||
12248 | |||||
12249 | bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | ||||
12250 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | ||||
12251 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | ||||
12252 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | ||||
12253 | std::string SuggestedExpr = "1 << " + RHSStr; | ||||
12254 | bool Overflow = false; | ||||
12255 | llvm::APInt One = (LeftSideValue - 1); | ||||
12256 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | ||||
12257 | if (Overflow) { | ||||
12258 | if (RightSideIntValue < 64) | ||||
12259 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
12260 | << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) | ||||
12261 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | ||||
12262 | else if (RightSideIntValue == 64) | ||||
12263 | S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); | ||||
12264 | else | ||||
12265 | return; | ||||
12266 | } else { | ||||
12267 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | ||||
12268 | << ExprStr << XorValue.toString(10, true) << SuggestedExpr | ||||
12269 | << PowValue.toString(10, true) | ||||
12270 | << FixItHint::CreateReplacement( | ||||
12271 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | ||||
12272 | } | ||||
12273 | |||||
12274 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; | ||||
12275 | } else if (LeftSideValue == 10) { | ||||
12276 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | ||||
12277 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
12278 | << ExprStr << XorValue.toString(10, true) << SuggestedValue | ||||
12279 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | ||||
12280 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; | ||||
12281 | } | ||||
12282 | } | ||||
12283 | |||||
12284 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12285 | SourceLocation Loc) { | ||||
12286 | // Ensure that either both operands are of the same vector type, or | ||||
12287 | // one operand is of a vector type and the other is of its element type. | ||||
12288 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | ||||
12289 | /*AllowBothBool*/true, | ||||
12290 | /*AllowBoolConversions*/false); | ||||
12291 | if (vType.isNull()) | ||||
12292 | return InvalidOperands(Loc, LHS, RHS); | ||||
12293 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && | ||||
12294 | !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) | ||||
12295 | return InvalidOperands(Loc, LHS, RHS); | ||||
12296 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | ||||
12297 | // usage of the logical operators && and || with vectors in C. This | ||||
12298 | // check could be notionally dropped. | ||||
12299 | if (!getLangOpts().CPlusPlus && | ||||
12300 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | ||||
12301 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | ||||
12302 | |||||
12303 | return GetSignedVectorType(LHS.get()->getType()); | ||||
12304 | } | ||||
12305 | |||||
12306 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12307 | SourceLocation Loc, | ||||
12308 | bool IsCompAssign) { | ||||
12309 | if (!IsCompAssign) { | ||||
12310 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12311 | if (LHS.isInvalid()) | ||||
12312 | return QualType(); | ||||
12313 | } | ||||
12314 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12315 | if (RHS.isInvalid()) | ||||
12316 | return QualType(); | ||||
12317 | |||||
12318 | // For conversion purposes, we ignore any qualifiers. | ||||
12319 | // For example, "const float" and "float" are equivalent. | ||||
12320 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
12321 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
12322 | |||||
12323 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | ||||
12324 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | ||||
12325 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12325, __PRETTY_FUNCTION__)); | ||||
12326 | |||||
12327 | if (Context.hasSameType(LHSType, RHSType)) | ||||
12328 | return LHSType; | ||||
12329 | |||||
12330 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | ||||
12331 | // case we have to return InvalidOperands. | ||||
12332 | ExprResult OriginalLHS = LHS; | ||||
12333 | ExprResult OriginalRHS = RHS; | ||||
12334 | if (LHSMatType && !RHSMatType) { | ||||
12335 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | ||||
12336 | if (!RHS.isInvalid()) | ||||
12337 | return LHSType; | ||||
12338 | |||||
12339 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
12340 | } | ||||
12341 | |||||
12342 | if (!LHSMatType && RHSMatType) { | ||||
12343 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | ||||
12344 | if (!LHS.isInvalid()) | ||||
12345 | return RHSType; | ||||
12346 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
12347 | } | ||||
12348 | |||||
12349 | return InvalidOperands(Loc, LHS, RHS); | ||||
12350 | } | ||||
12351 | |||||
12352 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12353 | SourceLocation Loc, | ||||
12354 | bool IsCompAssign) { | ||||
12355 | if (!IsCompAssign) { | ||||
12356 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12357 | if (LHS.isInvalid()) | ||||
12358 | return QualType(); | ||||
12359 | } | ||||
12360 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12361 | if (RHS.isInvalid()) | ||||
12362 | return QualType(); | ||||
12363 | |||||
12364 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
12365 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
12366 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12366, __PRETTY_FUNCTION__)); | ||||
12367 | |||||
12368 | if (LHSMatType && RHSMatType) { | ||||
12369 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | ||||
12370 | return InvalidOperands(Loc, LHS, RHS); | ||||
12371 | |||||
12372 | if (!Context.hasSameType(LHSMatType->getElementType(), | ||||
12373 | RHSMatType->getElementType())) | ||||
12374 | return InvalidOperands(Loc, LHS, RHS); | ||||
12375 | |||||
12376 | return Context.getConstantMatrixType(LHSMatType->getElementType(), | ||||
12377 | LHSMatType->getNumRows(), | ||||
12378 | RHSMatType->getNumColumns()); | ||||
12379 | } | ||||
12380 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
12381 | } | ||||
12382 | |||||
12383 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12384 | SourceLocation Loc, | ||||
12385 | BinaryOperatorKind Opc) { | ||||
12386 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
12387 | |||||
12388 | bool IsCompAssign = | ||||
12389 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | ||||
12390 | |||||
12391 | if (LHS.get()->getType()->isVectorType() || | ||||
12392 | RHS.get()->getType()->isVectorType()) { | ||||
12393 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
12394 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
12395 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
12396 | /*AllowBothBool*/true, | ||||
12397 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
12398 | return InvalidOperands(Loc, LHS, RHS); | ||||
12399 | } | ||||
12400 | |||||
12401 | if (Opc == BO_And) | ||||
12402 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
12403 | |||||
12404 | if (LHS.get()->getType()->hasFloatingRepresentation() || | ||||
12405 | RHS.get()->getType()->hasFloatingRepresentation()) | ||||
12406 | return InvalidOperands(Loc, LHS, RHS); | ||||
12407 | |||||
12408 | ExprResult LHSResult = LHS, RHSResult = RHS; | ||||
12409 | QualType compType = UsualArithmeticConversions( | ||||
12410 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | ||||
12411 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | ||||
12412 | return QualType(); | ||||
12413 | LHS = LHSResult.get(); | ||||
12414 | RHS = RHSResult.get(); | ||||
12415 | |||||
12416 | if (Opc == BO_Xor) | ||||
12417 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | ||||
12418 | |||||
12419 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | ||||
12420 | return compType; | ||||
12421 | return InvalidOperands(Loc, LHS, RHS); | ||||
12422 | } | ||||
12423 | |||||
12424 | // C99 6.5.[13,14] | ||||
12425 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12426 | SourceLocation Loc, | ||||
12427 | BinaryOperatorKind Opc) { | ||||
12428 | // Check vector operands differently. | ||||
12429 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | ||||
12430 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | ||||
12431 | |||||
12432 | bool EnumConstantInBoolContext = false; | ||||
12433 | for (const ExprResult &HS : {LHS, RHS}) { | ||||
12434 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | ||||
12435 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | ||||
12436 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | ||||
12437 | EnumConstantInBoolContext = true; | ||||
12438 | } | ||||
12439 | } | ||||
12440 | |||||
12441 | if (EnumConstantInBoolContext) | ||||
12442 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | ||||
12443 | |||||
12444 | // Diagnose cases where the user write a logical and/or but probably meant a | ||||
12445 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | ||||
12446 | // is a constant. | ||||
12447 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | ||||
12448 | !LHS.get()->getType()->isBooleanType() && | ||||
12449 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | ||||
12450 | // Don't warn in macros or template instantiations. | ||||
12451 | !Loc.isMacroID() && !inTemplateInstantiation()) { | ||||
12452 | // If the RHS can be constant folded, and if it constant folds to something | ||||
12453 | // that isn't 0 or 1 (which indicate a potential logical operation that | ||||
12454 | // happened to fold to true/false) then warn. | ||||
12455 | // Parens on the RHS are ignored. | ||||
12456 | Expr::EvalResult EVResult; | ||||
12457 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | ||||
12458 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
12459 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | ||||
12460 | !RHS.get()->getExprLoc().isMacroID()) || | ||||
12461 | (Result != 0 && Result != 1)) { | ||||
12462 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | ||||
12463 | << RHS.get()->getSourceRange() | ||||
12464 | << (Opc == BO_LAnd ? "&&" : "||"); | ||||
12465 | // Suggest replacing the logical operator with the bitwise version | ||||
12466 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | ||||
12467 | << (Opc == BO_LAnd ? "&" : "|") | ||||
12468 | << FixItHint::CreateReplacement(SourceRange( | ||||
12469 | Loc, getLocForEndOfToken(Loc)), | ||||
12470 | Opc == BO_LAnd ? "&" : "|"); | ||||
12471 | if (Opc == BO_LAnd) | ||||
12472 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | ||||
12473 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | ||||
12474 | << FixItHint::CreateRemoval( | ||||
12475 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | ||||
12476 | RHS.get()->getEndLoc())); | ||||
12477 | } | ||||
12478 | } | ||||
12479 | } | ||||
12480 | |||||
12481 | if (!Context.getLangOpts().CPlusPlus) { | ||||
12482 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | ||||
12483 | // not operate on the built-in scalar and vector float types. | ||||
12484 | if (Context.getLangOpts().OpenCL && | ||||
12485 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
12486 | if (LHS.get()->getType()->isFloatingType() || | ||||
12487 | RHS.get()->getType()->isFloatingType()) | ||||
12488 | return InvalidOperands(Loc, LHS, RHS); | ||||
12489 | } | ||||
12490 | |||||
12491 | LHS = UsualUnaryConversions(LHS.get()); | ||||
12492 | if (LHS.isInvalid()) | ||||
12493 | return QualType(); | ||||
12494 | |||||
12495 | RHS = UsualUnaryConversions(RHS.get()); | ||||
12496 | if (RHS.isInvalid()) | ||||
12497 | return QualType(); | ||||
12498 | |||||
12499 | if (!LHS.get()->getType()->isScalarType() || | ||||
12500 | !RHS.get()->getType()->isScalarType()) | ||||
12501 | return InvalidOperands(Loc, LHS, RHS); | ||||
12502 | |||||
12503 | return Context.IntTy; | ||||
12504 | } | ||||
12505 | |||||
12506 | // The following is safe because we only use this method for | ||||
12507 | // non-overloadable operands. | ||||
12508 | |||||
12509 | // C++ [expr.log.and]p1 | ||||
12510 | // C++ [expr.log.or]p1 | ||||
12511 | // The operands are both contextually converted to type bool. | ||||
12512 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | ||||
12513 | if (LHSRes.isInvalid()) | ||||
12514 | return InvalidOperands(Loc, LHS, RHS); | ||||
12515 | LHS = LHSRes; | ||||
12516 | |||||
12517 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | ||||
12518 | if (RHSRes.isInvalid()) | ||||
12519 | return InvalidOperands(Loc, LHS, RHS); | ||||
12520 | RHS = RHSRes; | ||||
12521 | |||||
12522 | // C++ [expr.log.and]p2 | ||||
12523 | // C++ [expr.log.or]p2 | ||||
12524 | // The result is a bool. | ||||
12525 | return Context.BoolTy; | ||||
12526 | } | ||||
12527 | |||||
12528 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | ||||
12529 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
12530 | if (!ME) return false; | ||||
12531 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | ||||
12532 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | ||||
12533 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | ||||
12534 | if (!Base) return false; | ||||
12535 | return Base->getMethodDecl() != nullptr; | ||||
12536 | } | ||||
12537 | |||||
12538 | /// Is the given expression (which must be 'const') a reference to a | ||||
12539 | /// variable which was originally non-const, but which has become | ||||
12540 | /// 'const' due to being captured within a block? | ||||
12541 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | ||||
12542 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | ||||
12543 | assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified ()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12543, __PRETTY_FUNCTION__)); | ||||
12544 | E = E->IgnoreParens(); | ||||
12545 | |||||
12546 | // Must be a reference to a declaration from an enclosing scope. | ||||
12547 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
12548 | if (!DRE) return NCCK_None; | ||||
12549 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | ||||
12550 | |||||
12551 | // The declaration must be a variable which is not declared 'const'. | ||||
12552 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
12553 | if (!var) return NCCK_None; | ||||
12554 | if (var->getType().isConstQualified()) return NCCK_None; | ||||
12555 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?" ) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12555, __PRETTY_FUNCTION__)); | ||||
12556 | |||||
12557 | // Decide whether the first capture was for a block or a lambda. | ||||
12558 | DeclContext *DC = S.CurContext, *Prev = nullptr; | ||||
12559 | // Decide whether the first capture was for a block or a lambda. | ||||
12560 | while (DC) { | ||||
12561 | // For init-capture, it is possible that the variable belongs to the | ||||
12562 | // template pattern of the current context. | ||||
12563 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | ||||
12564 | if (var->isInitCapture() && | ||||
12565 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | ||||
12566 | break; | ||||
12567 | if (DC == var->getDeclContext()) | ||||
12568 | break; | ||||
12569 | Prev = DC; | ||||
12570 | DC = DC->getParent(); | ||||
12571 | } | ||||
12572 | // Unless we have an init-capture, we've gone one step too far. | ||||
12573 | if (!var->isInitCapture()) | ||||
12574 | DC = Prev; | ||||
12575 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | ||||
12576 | } | ||||
12577 | |||||
12578 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | ||||
12579 | Ty = Ty.getNonReferenceType(); | ||||
12580 | if (IsDereference && Ty->isPointerType()) | ||||
12581 | Ty = Ty->getPointeeType(); | ||||
12582 | return !Ty.isConstQualified(); | ||||
12583 | } | ||||
12584 | |||||
12585 | // Update err_typecheck_assign_const and note_typecheck_assign_const | ||||
12586 | // when this enum is changed. | ||||
12587 | enum { | ||||
12588 | ConstFunction, | ||||
12589 | ConstVariable, | ||||
12590 | ConstMember, | ||||
12591 | ConstMethod, | ||||
12592 | NestedConstMember, | ||||
12593 | ConstUnknown, // Keep as last element | ||||
12594 | }; | ||||
12595 | |||||
12596 | /// Emit the "read-only variable not assignable" error and print notes to give | ||||
12597 | /// more information about why the variable is not assignable, such as pointing | ||||
12598 | /// to the declaration of a const variable, showing that a method is const, or | ||||
12599 | /// that the function is returning a const reference. | ||||
12600 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | ||||
12601 | SourceLocation Loc) { | ||||
12602 | SourceRange ExprRange = E->getSourceRange(); | ||||
12603 | |||||
12604 | // Only emit one error on the first const found. All other consts will emit | ||||
12605 | // a note to the error. | ||||
12606 | bool DiagnosticEmitted = false; | ||||
12607 | |||||
12608 | // Track if the current expression is the result of a dereference, and if the | ||||
12609 | // next checked expression is the result of a dereference. | ||||
12610 | bool IsDereference = false; | ||||
12611 | bool NextIsDereference = false; | ||||
12612 | |||||
12613 | // Loop to process MemberExpr chains. | ||||
12614 | while (true) { | ||||
12615 | IsDereference = NextIsDereference; | ||||
12616 | |||||
12617 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | ||||
12618 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
12619 | NextIsDereference = ME->isArrow(); | ||||
12620 | const ValueDecl *VD = ME->getMemberDecl(); | ||||
12621 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | ||||
12622 | // Mutable fields can be modified even if the class is const. | ||||
12623 | if (Field->isMutable()) { | ||||
12624 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted." ) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12624, __PRETTY_FUNCTION__)); | ||||
12625 | break; | ||||
12626 | } | ||||
12627 | |||||
12628 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | ||||
12629 | if (!DiagnosticEmitted) { | ||||
12630 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12631 | << ExprRange << ConstMember << false /*static*/ << Field | ||||
12632 | << Field->getType(); | ||||
12633 | DiagnosticEmitted = true; | ||||
12634 | } | ||||
12635 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12636 | << ConstMember << false /*static*/ << Field << Field->getType() | ||||
12637 | << Field->getSourceRange(); | ||||
12638 | } | ||||
12639 | E = ME->getBase(); | ||||
12640 | continue; | ||||
12641 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | ||||
12642 | if (VDecl->getType().isConstQualified()) { | ||||
12643 | if (!DiagnosticEmitted) { | ||||
12644 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12645 | << ExprRange << ConstMember << true /*static*/ << VDecl | ||||
12646 | << VDecl->getType(); | ||||
12647 | DiagnosticEmitted = true; | ||||
12648 | } | ||||
12649 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12650 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | ||||
12651 | << VDecl->getSourceRange(); | ||||
12652 | } | ||||
12653 | // Static fields do not inherit constness from parents. | ||||
12654 | break; | ||||
12655 | } | ||||
12656 | break; // End MemberExpr | ||||
12657 | } else if (const ArraySubscriptExpr *ASE = | ||||
12658 | dyn_cast<ArraySubscriptExpr>(E)) { | ||||
12659 | E = ASE->getBase()->IgnoreParenImpCasts(); | ||||
12660 | continue; | ||||
12661 | } else if (const ExtVectorElementExpr *EVE = | ||||
12662 | dyn_cast<ExtVectorElementExpr>(E)) { | ||||
12663 | E = EVE->getBase()->IgnoreParenImpCasts(); | ||||
12664 | continue; | ||||
12665 | } | ||||
12666 | break; | ||||
12667 | } | ||||
12668 | |||||
12669 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
12670 | // Function calls | ||||
12671 | const FunctionDecl *FD = CE->getDirectCallee(); | ||||
12672 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | ||||
12673 | if (!DiagnosticEmitted) { | ||||
12674 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
12675 | << ConstFunction << FD; | ||||
12676 | DiagnosticEmitted = true; | ||||
12677 | } | ||||
12678 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | ||||
12679 | diag::note_typecheck_assign_const) | ||||
12680 | << ConstFunction << FD << FD->getReturnType() | ||||
12681 | << FD->getReturnTypeSourceRange(); | ||||
12682 | } | ||||
12683 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
12684 | // Point to variable declaration. | ||||
12685 | if (const ValueDecl *VD = DRE->getDecl()) { | ||||
12686 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | ||||
12687 | if (!DiagnosticEmitted) { | ||||
12688 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12689 | << ExprRange << ConstVariable << VD << VD->getType(); | ||||
12690 | DiagnosticEmitted = true; | ||||
12691 | } | ||||
12692 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12693 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | ||||
12694 | } | ||||
12695 | } | ||||
12696 | } else if (isa<CXXThisExpr>(E)) { | ||||
12697 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | ||||
12698 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | ||||
12699 | if (MD->isConst()) { | ||||
12700 | if (!DiagnosticEmitted) { | ||||
12701 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
12702 | << ConstMethod << MD; | ||||
12703 | DiagnosticEmitted = true; | ||||
12704 | } | ||||
12705 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | ||||
12706 | << ConstMethod << MD << MD->getSourceRange(); | ||||
12707 | } | ||||
12708 | } | ||||
12709 | } | ||||
12710 | } | ||||
12711 | |||||
12712 | if (DiagnosticEmitted) | ||||
12713 | return; | ||||
12714 | |||||
12715 | // Can't determine a more specific message, so display the generic error. | ||||
12716 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | ||||
12717 | } | ||||
12718 | |||||
12719 | enum OriginalExprKind { | ||||
12720 | OEK_Variable, | ||||
12721 | OEK_Member, | ||||
12722 | OEK_LValue | ||||
12723 | }; | ||||
12724 | |||||
12725 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | ||||
12726 | const RecordType *Ty, | ||||
12727 | SourceLocation Loc, SourceRange Range, | ||||
12728 | OriginalExprKind OEK, | ||||
12729 | bool &DiagnosticEmitted) { | ||||
12730 | std::vector<const RecordType *> RecordTypeList; | ||||
12731 | RecordTypeList.push_back(Ty); | ||||
12732 | unsigned NextToCheckIndex = 0; | ||||
12733 | // We walk the record hierarchy breadth-first to ensure that we print | ||||
12734 | // diagnostics in field nesting order. | ||||
12735 | while (RecordTypeList.size() > NextToCheckIndex) { | ||||
12736 | bool IsNested = NextToCheckIndex > 0; | ||||
12737 | for (const FieldDecl *Field : | ||||
12738 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | ||||
12739 | // First, check every field for constness. | ||||
12740 | QualType FieldTy = Field->getType(); | ||||
12741 | if (FieldTy.isConstQualified()) { | ||||
12742 | if (!DiagnosticEmitted) { | ||||
12743 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12744 | << Range << NestedConstMember << OEK << VD | ||||
12745 | << IsNested << Field; | ||||
12746 | DiagnosticEmitted = true; | ||||
12747 | } | ||||
12748 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | ||||
12749 | << NestedConstMember << IsNested << Field | ||||
12750 | << FieldTy << Field->getSourceRange(); | ||||
12751 | } | ||||
12752 | |||||
12753 | // Then we append it to the list to check next in order. | ||||
12754 | FieldTy = FieldTy.getCanonicalType(); | ||||
12755 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | ||||
12756 | if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) | ||||
12757 | RecordTypeList.push_back(FieldRecTy); | ||||
12758 | } | ||||
12759 | } | ||||
12760 | ++NextToCheckIndex; | ||||
12761 | } | ||||
12762 | } | ||||
12763 | |||||
12764 | /// Emit an error for the case where a record we are trying to assign to has a | ||||
12765 | /// const-qualified field somewhere in its hierarchy. | ||||
12766 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | ||||
12767 | SourceLocation Loc) { | ||||
12768 | QualType Ty = E->getType(); | ||||
12769 | assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ? static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12769, __PRETTY_FUNCTION__)); | ||||
12770 | SourceRange Range = E->getSourceRange(); | ||||
12771 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | ||||
12772 | bool DiagEmitted = false; | ||||
12773 | |||||
12774 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
12775 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | ||||
12776 | Range, OEK_Member, DiagEmitted); | ||||
12777 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
12778 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | ||||
12779 | Range, OEK_Variable, DiagEmitted); | ||||
12780 | else | ||||
12781 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | ||||
12782 | Range, OEK_LValue, DiagEmitted); | ||||
12783 | if (!DiagEmitted) | ||||
12784 | DiagnoseConstAssignment(S, E, Loc); | ||||
12785 | } | ||||
12786 | |||||
12787 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | ||||
12788 | /// emit an error and return true. If so, return false. | ||||
12789 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | ||||
12790 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast <void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12790, __PRETTY_FUNCTION__)); | ||||
12791 | |||||
12792 | S.CheckShadowingDeclModification(E, Loc); | ||||
12793 | |||||
12794 | SourceLocation OrigLoc = Loc; | ||||
12795 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | ||||
12796 | &Loc); | ||||
12797 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | ||||
12798 | IsLV = Expr::MLV_InvalidMessageExpression; | ||||
12799 | if (IsLV == Expr::MLV_Valid) | ||||
12800 | return false; | ||||
12801 | |||||
12802 | unsigned DiagID = 0; | ||||
12803 | bool NeedType = false; | ||||
12804 | switch (IsLV) { // C99 6.5.16p2 | ||||
12805 | case Expr::MLV_ConstQualified: | ||||
12806 | // Use a specialized diagnostic when we're assigning to an object | ||||
12807 | // from an enclosing function or block. | ||||
12808 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | ||||
12809 | if (NCCK == NCCK_Block) | ||||
12810 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | ||||
12811 | else | ||||
12812 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | ||||
12813 | break; | ||||
12814 | } | ||||
12815 | |||||
12816 | // In ARC, use some specialized diagnostics for occasions where we | ||||
12817 | // infer 'const'. These are always pseudo-strong variables. | ||||
12818 | if (S.getLangOpts().ObjCAutoRefCount) { | ||||
12819 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | ||||
12820 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | ||||
12821 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | ||||
12822 | |||||
12823 | // Use the normal diagnostic if it's pseudo-__strong but the | ||||
12824 | // user actually wrote 'const'. | ||||
12825 | if (var->isARCPseudoStrong() && | ||||
12826 | (!var->getTypeSourceInfo() || | ||||
12827 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | ||||
12828 | // There are three pseudo-strong cases: | ||||
12829 | // - self | ||||
12830 | ObjCMethodDecl *method = S.getCurMethodDecl(); | ||||
12831 | if (method && var == method->getSelfDecl()) { | ||||
12832 | DiagID = method->isClassMethod() | ||||
12833 | ? diag::err_typecheck_arc_assign_self_class_method | ||||
12834 | : diag::err_typecheck_arc_assign_self; | ||||
12835 | |||||
12836 | // - Objective-C externally_retained attribute. | ||||
12837 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | ||||
12838 | isa<ParmVarDecl>(var)) { | ||||
12839 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | ||||
12840 | |||||
12841 | // - fast enumeration variables | ||||
12842 | } else { | ||||
12843 | DiagID = diag::err_typecheck_arr_assign_enumeration; | ||||
12844 | } | ||||
12845 | |||||
12846 | SourceRange Assign; | ||||
12847 | if (Loc != OrigLoc) | ||||
12848 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
12849 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
12850 | // We need to preserve the AST regardless, so migration tool | ||||
12851 | // can do its job. | ||||
12852 | return false; | ||||
12853 | } | ||||
12854 | } | ||||
12855 | } | ||||
12856 | |||||
12857 | // If none of the special cases above are triggered, then this is a | ||||
12858 | // simple const assignment. | ||||
12859 | if (DiagID == 0) { | ||||
12860 | DiagnoseConstAssignment(S, E, Loc); | ||||
12861 | return true; | ||||
12862 | } | ||||
12863 | |||||
12864 | break; | ||||
12865 | case Expr::MLV_ConstAddrSpace: | ||||
12866 | DiagnoseConstAssignment(S, E, Loc); | ||||
12867 | return true; | ||||
12868 | case Expr::MLV_ConstQualifiedField: | ||||
12869 | DiagnoseRecursiveConstFields(S, E, Loc); | ||||
12870 | return true; | ||||
12871 | case Expr::MLV_ArrayType: | ||||
12872 | case Expr::MLV_ArrayTemporary: | ||||
12873 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | ||||
12874 | NeedType = true; | ||||
12875 | break; | ||||
12876 | case Expr::MLV_NotObjectType: | ||||
12877 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | ||||
12878 | NeedType = true; | ||||
12879 | break; | ||||
12880 | case Expr::MLV_LValueCast: | ||||
12881 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | ||||
12882 | break; | ||||
12883 | case Expr::MLV_Valid: | ||||
12884 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12884); | ||||
12885 | case Expr::MLV_InvalidExpression: | ||||
12886 | case Expr::MLV_MemberFunction: | ||||
12887 | case Expr::MLV_ClassTemporary: | ||||
12888 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | ||||
12889 | break; | ||||
12890 | case Expr::MLV_IncompleteType: | ||||
12891 | case Expr::MLV_IncompleteVoidType: | ||||
12892 | return S.RequireCompleteType(Loc, E->getType(), | ||||
12893 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | ||||
12894 | case Expr::MLV_DuplicateVectorComponents: | ||||
12895 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | ||||
12896 | break; | ||||
12897 | case Expr::MLV_NoSetterProperty: | ||||
12898 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12898); | ||||
12899 | case Expr::MLV_InvalidMessageExpression: | ||||
12900 | DiagID = diag::err_readonly_message_assignment; | ||||
12901 | break; | ||||
12902 | case Expr::MLV_SubObjCPropertySetting: | ||||
12903 | DiagID = diag::err_no_subobject_property_setting; | ||||
12904 | break; | ||||
12905 | } | ||||
12906 | |||||
12907 | SourceRange Assign; | ||||
12908 | if (Loc != OrigLoc) | ||||
12909 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
12910 | if (NeedType) | ||||
12911 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | ||||
12912 | else | ||||
12913 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
12914 | return true; | ||||
12915 | } | ||||
12916 | |||||
12917 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | ||||
12918 | SourceLocation Loc, | ||||
12919 | Sema &Sema) { | ||||
12920 | if (Sema.inTemplateInstantiation()) | ||||
12921 | return; | ||||
12922 | if (Sema.isUnevaluatedContext()) | ||||
12923 | return; | ||||
12924 | if (Loc.isInvalid() || Loc.isMacroID()) | ||||
12925 | return; | ||||
12926 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | ||||
12927 | return; | ||||
12928 | |||||
12929 | // C / C++ fields | ||||
12930 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | ||||
12931 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | ||||
12932 | if (ML && MR) { | ||||
12933 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | ||||
12934 | return; | ||||
12935 | const ValueDecl *LHSDecl = | ||||
12936 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | ||||
12937 | const ValueDecl *RHSDecl = | ||||
12938 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | ||||
12939 | if (LHSDecl != RHSDecl) | ||||
12940 | return; | ||||
12941 | if (LHSDecl->getType().isVolatileQualified()) | ||||
12942 | return; | ||||
12943 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
12944 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
12945 | return; | ||||
12946 | |||||
12947 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | ||||
12948 | } | ||||
12949 | |||||
12950 | // Objective-C instance variables | ||||
12951 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | ||||
12952 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | ||||
12953 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | ||||
12954 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | ||||
12955 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | ||||
12956 | if (RL && RR && RL->getDecl() == RR->getDecl()) | ||||
12957 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | ||||
12958 | } | ||||
12959 | } | ||||
12960 | |||||
12961 | // C99 6.5.16.1 | ||||
12962 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | ||||
12963 | SourceLocation Loc, | ||||
12964 | QualType CompoundType) { | ||||
12965 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 12965, __PRETTY_FUNCTION__)); | ||||
12966 | |||||
12967 | // Verify that LHS is a modifiable lvalue, and emit error if not. | ||||
12968 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | ||||
12969 | return QualType(); | ||||
12970 | |||||
12971 | QualType LHSType = LHSExpr->getType(); | ||||
12972 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | ||||
12973 | CompoundType; | ||||
12974 | // OpenCL v1.2 s6.1.1.1 p2: | ||||
12975 | // The half data type can only be used to declare a pointer to a buffer that | ||||
12976 | // contains half values | ||||
12977 | if (getLangOpts().OpenCL && | ||||
12978 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
12979 | LHSType->isHalfType()) { | ||||
12980 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | ||||
12981 | << LHSType.getUnqualifiedType(); | ||||
12982 | return QualType(); | ||||
12983 | } | ||||
12984 | |||||
12985 | AssignConvertType ConvTy; | ||||
12986 | if (CompoundType.isNull()) { | ||||
12987 | Expr *RHSCheck = RHS.get(); | ||||
12988 | |||||
12989 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | ||||
12990 | |||||
12991 | QualType LHSTy(LHSType); | ||||
12992 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | ||||
12993 | if (RHS.isInvalid()) | ||||
12994 | return QualType(); | ||||
12995 | // Special case of NSObject attributes on c-style pointer types. | ||||
12996 | if (ConvTy == IncompatiblePointer && | ||||
12997 | ((Context.isObjCNSObjectType(LHSType) && | ||||
12998 | RHSType->isObjCObjectPointerType()) || | ||||
12999 | (Context.isObjCNSObjectType(RHSType) && | ||||
13000 | LHSType->isObjCObjectPointerType()))) | ||||
13001 | ConvTy = Compatible; | ||||
13002 | |||||
13003 | if (ConvTy == Compatible && | ||||
13004 | LHSType->isObjCObjectType()) | ||||
13005 | Diag(Loc, diag::err_objc_object_assignment) | ||||
13006 | << LHSType; | ||||
13007 | |||||
13008 | // If the RHS is a unary plus or minus, check to see if they = and + are | ||||
13009 | // right next to each other. If so, the user may have typo'd "x =+ 4" | ||||
13010 | // instead of "x += 4". | ||||
13011 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | ||||
13012 | RHSCheck = ICE->getSubExpr(); | ||||
13013 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | ||||
13014 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | ||||
13015 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | ||||
13016 | // Only if the two operators are exactly adjacent. | ||||
13017 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | ||||
13018 | // And there is a space or other character before the subexpr of the | ||||
13019 | // unary +/-. We don't want to warn on "x=-1". | ||||
13020 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | ||||
13021 | UO->getSubExpr()->getBeginLoc().isFileID()) { | ||||
13022 | Diag(Loc, diag::warn_not_compound_assign) | ||||
13023 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | ||||
13024 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | ||||
13025 | } | ||||
13026 | } | ||||
13027 | |||||
13028 | if (ConvTy == Compatible) { | ||||
13029 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | ||||
13030 | // Warn about retain cycles where a block captures the LHS, but | ||||
13031 | // not if the LHS is a simple variable into which the block is | ||||
13032 | // being stored...unless that variable can be captured by reference! | ||||
13033 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | ||||
13034 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | ||||
13035 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | ||||
13036 | checkRetainCycles(LHSExpr, RHS.get()); | ||||
13037 | } | ||||
13038 | |||||
13039 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | ||||
13040 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | ||||
13041 | // It is safe to assign a weak reference into a strong variable. | ||||
13042 | // Although this code can still have problems: | ||||
13043 | // id x = self.weakProp; | ||||
13044 | // id y = self.weakProp; | ||||
13045 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||
13046 | // paths through the function. This should be revisited if | ||||
13047 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||
13048 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | ||||
13049 | // variable, which will be valid for the current autorelease scope. | ||||
13050 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||
13051 | RHS.get()->getBeginLoc())) | ||||
13052 | getCurFunction()->markSafeWeakUse(RHS.get()); | ||||
13053 | |||||
13054 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | ||||
13055 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | ||||
13056 | } | ||||
13057 | } | ||||
13058 | } else { | ||||
13059 | // Compound assignment "x += y" | ||||
13060 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | ||||
13061 | } | ||||
13062 | |||||
13063 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | ||||
13064 | RHS.get(), AA_Assigning)) | ||||
13065 | return QualType(); | ||||
13066 | |||||
13067 | CheckForNullPointerDereference(*this, LHSExpr); | ||||
13068 | |||||
13069 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | ||||
13070 | if (CompoundType.isNull()) { | ||||
13071 | // C++2a [expr.ass]p5: | ||||
13072 | // A simple-assignment whose left operand is of a volatile-qualified | ||||
13073 | // type is deprecated unless the assignment is either a discarded-value | ||||
13074 | // expression or an unevaluated operand | ||||
13075 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | ||||
13076 | } else { | ||||
13077 | // C++2a [expr.ass]p6: | ||||
13078 | // [Compound-assignment] expressions are deprecated if E1 has | ||||
13079 | // volatile-qualified type | ||||
13080 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | ||||
13081 | } | ||||
13082 | } | ||||
13083 | |||||
13084 | // C99 6.5.16p3: The type of an assignment expression is the type of the | ||||
13085 | // left operand unless the left operand has qualified type, in which case | ||||
13086 | // it is the unqualified version of the type of the left operand. | ||||
13087 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | ||||
13088 | // is converted to the type of the assignment expression (above). | ||||
13089 | // C++ 5.17p1: the type of the assignment expression is that of its left | ||||
13090 | // operand. | ||||
13091 | return (getLangOpts().CPlusPlus | ||||
13092 | ? LHSType : LHSType.getUnqualifiedType()); | ||||
13093 | } | ||||
13094 | |||||
13095 | // Only ignore explicit casts to void. | ||||
13096 | static bool IgnoreCommaOperand(const Expr *E) { | ||||
13097 | E = E->IgnoreParens(); | ||||
13098 | |||||
13099 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | ||||
13100 | if (CE->getCastKind() == CK_ToVoid) { | ||||
13101 | return true; | ||||
13102 | } | ||||
13103 | |||||
13104 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | ||||
13105 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | ||||
13106 | CE->getSubExpr()->getType()->isDependentType()) { | ||||
13107 | return true; | ||||
13108 | } | ||||
13109 | } | ||||
13110 | |||||
13111 | return false; | ||||
13112 | } | ||||
13113 | |||||
13114 | // Look for instances where it is likely the comma operator is confused with | ||||
13115 | // another operator. There is an explicit list of acceptable expressions for | ||||
13116 | // the left hand side of the comma operator, otherwise emit a warning. | ||||
13117 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | ||||
13118 | // No warnings in macros | ||||
13119 | if (Loc.isMacroID()) | ||||
13120 | return; | ||||
13121 | |||||
13122 | // Don't warn in template instantiations. | ||||
13123 | if (inTemplateInstantiation()) | ||||
13124 | return; | ||||
13125 | |||||
13126 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | ||||
13127 | // instead, skip more than needed, then call back into here with the | ||||
13128 | // CommaVisitor in SemaStmt.cpp. | ||||
13129 | // The listed locations are the initialization and increment portions | ||||
13130 | // of a for loop. The additional checks are on the condition of | ||||
13131 | // if statements, do/while loops, and for loops. | ||||
13132 | // Differences in scope flags for C89 mode requires the extra logic. | ||||
13133 | const unsigned ForIncrementFlags = | ||||
13134 | getLangOpts().C99 || getLangOpts().CPlusPlus | ||||
13135 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | ||||
13136 | : Scope::ContinueScope | Scope::BreakScope; | ||||
13137 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | ||||
13138 | const unsigned ScopeFlags = getCurScope()->getFlags(); | ||||
13139 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | ||||
13140 | (ScopeFlags & ForInitFlags) == ForInitFlags) | ||||
13141 | return; | ||||
13142 | |||||
13143 | // If there are multiple comma operators used together, get the RHS of the | ||||
13144 | // of the comma operator as the LHS. | ||||
13145 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | ||||
13146 | if (BO->getOpcode() != BO_Comma) | ||||
13147 | break; | ||||
13148 | LHS = BO->getRHS(); | ||||
13149 | } | ||||
13150 | |||||
13151 | // Only allow some expressions on LHS to not warn. | ||||
13152 | if (IgnoreCommaOperand(LHS)) | ||||
13153 | return; | ||||
13154 | |||||
13155 | Diag(Loc, diag::warn_comma_operator); | ||||
13156 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | ||||
13157 | << LHS->getSourceRange() | ||||
13158 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | ||||
13159 | LangOpts.CPlusPlus ? "static_cast<void>(" | ||||
13160 | : "(void)(") | ||||
13161 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | ||||
13162 | ")"); | ||||
13163 | } | ||||
13164 | |||||
13165 | // C99 6.5.17 | ||||
13166 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
13167 | SourceLocation Loc) { | ||||
13168 | LHS = S.CheckPlaceholderExpr(LHS.get()); | ||||
13169 | RHS = S.CheckPlaceholderExpr(RHS.get()); | ||||
13170 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
13171 | return QualType(); | ||||
13172 | |||||
13173 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | ||||
13174 | // operands, but not unary promotions. | ||||
13175 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | ||||
13176 | |||||
13177 | // So we treat the LHS as a ignored value, and in C++ we allow the | ||||
13178 | // containing site to determine what should be done with the RHS. | ||||
13179 | LHS = S.IgnoredValueConversions(LHS.get()); | ||||
13180 | if (LHS.isInvalid()) | ||||
13181 | return QualType(); | ||||
13182 | |||||
13183 | S.DiagnoseUnusedExprResult(LHS.get()); | ||||
13184 | |||||
13185 | if (!S.getLangOpts().CPlusPlus) { | ||||
13186 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13187 | if (RHS.isInvalid()) | ||||
13188 | return QualType(); | ||||
13189 | if (!RHS.get()->getType()->isVoidType()) | ||||
13190 | S.RequireCompleteType(Loc, RHS.get()->getType(), | ||||
13191 | diag::err_incomplete_type); | ||||
13192 | } | ||||
13193 | |||||
13194 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | ||||
13195 | S.DiagnoseCommaOperator(LHS.get(), Loc); | ||||
13196 | |||||
13197 | return RHS.get()->getType(); | ||||
13198 | } | ||||
13199 | |||||
13200 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | ||||
13201 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | ||||
13202 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | ||||
13203 | ExprValueKind &VK, | ||||
13204 | ExprObjectKind &OK, | ||||
13205 | SourceLocation OpLoc, | ||||
13206 | bool IsInc, bool IsPrefix) { | ||||
13207 | if (Op->isTypeDependent()) | ||||
13208 | return S.Context.DependentTy; | ||||
13209 | |||||
13210 | QualType ResType = Op->getType(); | ||||
13211 | // Atomic types can be used for increment / decrement where the non-atomic | ||||
13212 | // versions can, so ignore the _Atomic() specifier for the purpose of | ||||
13213 | // checking. | ||||
13214 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
13215 | ResType = ResAtomicType->getValueType(); | ||||
13216 | |||||
13217 | assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression" ) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13217, __PRETTY_FUNCTION__)); | ||||
13218 | |||||
13219 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | ||||
13220 | // Decrement of bool is not allowed. | ||||
13221 | if (!IsInc) { | ||||
13222 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | ||||
13223 | return QualType(); | ||||
13224 | } | ||||
13225 | // Increment of bool sets it to true, but is deprecated. | ||||
13226 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | ||||
13227 | : diag::warn_increment_bool) | ||||
13228 | << Op->getSourceRange(); | ||||
13229 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | ||||
13230 | // Error on enum increments and decrements in C++ mode | ||||
13231 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | ||||
13232 | return QualType(); | ||||
13233 | } else if (ResType->isRealType()) { | ||||
13234 | // OK! | ||||
13235 | } else if (ResType->isPointerType()) { | ||||
13236 | // C99 6.5.2.4p2, 6.5.6p2 | ||||
13237 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | ||||
13238 | return QualType(); | ||||
13239 | } else if (ResType->isObjCObjectPointerType()) { | ||||
13240 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | ||||
13241 | // Otherwise, we just need a complete type. | ||||
13242 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | ||||
13243 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | ||||
13244 | return QualType(); | ||||
13245 | } else if (ResType->isAnyComplexType()) { | ||||
13246 | // C99 does not support ++/-- on complex types, we allow as an extension. | ||||
13247 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | ||||
13248 | << ResType << Op->getSourceRange(); | ||||
13249 | } else if (ResType->isPlaceholderType()) { | ||||
13250 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
13251 | if (PR.isInvalid()) return QualType(); | ||||
13252 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | ||||
13253 | IsInc, IsPrefix); | ||||
13254 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | ||||
13255 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | ||||
13256 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | ||||
13257 | (ResType->castAs<VectorType>()->getVectorKind() != | ||||
13258 | VectorType::AltiVecBool)) { | ||||
13259 | // The z vector extensions allow ++ and -- for non-bool vectors. | ||||
13260 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | ||||
13261 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | ||||
13262 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | ||||
13263 | } else { | ||||
13264 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | ||||
13265 | << ResType << int(IsInc) << Op->getSourceRange(); | ||||
13266 | return QualType(); | ||||
13267 | } | ||||
13268 | // At this point, we know we have a real, complex or pointer type. | ||||
13269 | // Now make sure the operand is a modifiable lvalue. | ||||
13270 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | ||||
13271 | return QualType(); | ||||
13272 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | ||||
13273 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | ||||
13274 | // An operand with volatile-qualified type is deprecated | ||||
13275 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | ||||
13276 | << IsInc << ResType; | ||||
13277 | } | ||||
13278 | // In C++, a prefix increment is the same type as the operand. Otherwise | ||||
13279 | // (in C or with postfix), the increment is the unqualified type of the | ||||
13280 | // operand. | ||||
13281 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | ||||
13282 | VK = VK_LValue; | ||||
13283 | OK = Op->getObjectKind(); | ||||
13284 | return ResType; | ||||
13285 | } else { | ||||
13286 | VK = VK_RValue; | ||||
13287 | return ResType.getUnqualifiedType(); | ||||
13288 | } | ||||
13289 | } | ||||
13290 | |||||
13291 | |||||
13292 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | ||||
13293 | /// This routine allows us to typecheck complex/recursive expressions | ||||
13294 | /// where the declaration is needed for type checking. We only need to | ||||
13295 | /// handle cases when the expression references a function designator | ||||
13296 | /// or is an lvalue. Here are some examples: | ||||
13297 | /// - &(x) => x | ||||
13298 | /// - &*****f => f for f a function designator. | ||||
13299 | /// - &s.xx => s | ||||
13300 | /// - &s.zz[1].yy -> s, if zz is an array | ||||
13301 | /// - *(x + 1) -> x, if x is an array | ||||
13302 | /// - &"123"[2] -> 0 | ||||
13303 | /// - & __real__ x -> x | ||||
13304 | /// | ||||
13305 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | ||||
13306 | /// members. | ||||
13307 | static ValueDecl *getPrimaryDecl(Expr *E) { | ||||
13308 | switch (E->getStmtClass()) { | ||||
13309 | case Stmt::DeclRefExprClass: | ||||
13310 | return cast<DeclRefExpr>(E)->getDecl(); | ||||
13311 | case Stmt::MemberExprClass: | ||||
13312 | // If this is an arrow operator, the address is an offset from | ||||
13313 | // the base's value, so the object the base refers to is | ||||
13314 | // irrelevant. | ||||
13315 | if (cast<MemberExpr>(E)->isArrow()) | ||||
13316 | return nullptr; | ||||
13317 | // Otherwise, the expression refers to a part of the base | ||||
13318 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | ||||
13319 | case Stmt::ArraySubscriptExprClass: { | ||||
13320 | // FIXME: This code shouldn't be necessary! We should catch the implicit | ||||
13321 | // promotion of register arrays earlier. | ||||
13322 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | ||||
13323 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | ||||
13324 | if (ICE->getSubExpr()->getType()->isArrayType()) | ||||
13325 | return getPrimaryDecl(ICE->getSubExpr()); | ||||
13326 | } | ||||
13327 | return nullptr; | ||||
13328 | } | ||||
13329 | case Stmt::UnaryOperatorClass: { | ||||
13330 | UnaryOperator *UO = cast<UnaryOperator>(E); | ||||
13331 | |||||
13332 | switch(UO->getOpcode()) { | ||||
13333 | case UO_Real: | ||||
13334 | case UO_Imag: | ||||
13335 | case UO_Extension: | ||||
13336 | return getPrimaryDecl(UO->getSubExpr()); | ||||
13337 | default: | ||||
13338 | return nullptr; | ||||
13339 | } | ||||
13340 | } | ||||
13341 | case Stmt::ParenExprClass: | ||||
13342 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | ||||
13343 | case Stmt::ImplicitCastExprClass: | ||||
13344 | // If the result of an implicit cast is an l-value, we care about | ||||
13345 | // the sub-expression; otherwise, the result here doesn't matter. | ||||
13346 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | ||||
13347 | case Stmt::CXXUuidofExprClass: | ||||
13348 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | ||||
13349 | default: | ||||
13350 | return nullptr; | ||||
13351 | } | ||||
13352 | } | ||||
13353 | |||||
13354 | namespace { | ||||
13355 | enum { | ||||
13356 | AO_Bit_Field = 0, | ||||
13357 | AO_Vector_Element = 1, | ||||
13358 | AO_Property_Expansion = 2, | ||||
13359 | AO_Register_Variable = 3, | ||||
13360 | AO_Matrix_Element = 4, | ||||
13361 | AO_No_Error = 5 | ||||
13362 | }; | ||||
13363 | } | ||||
13364 | /// Diagnose invalid operand for address of operations. | ||||
13365 | /// | ||||
13366 | /// \param Type The type of operand which cannot have its address taken. | ||||
13367 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | ||||
13368 | Expr *E, unsigned Type) { | ||||
13369 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | ||||
13370 | } | ||||
13371 | |||||
13372 | /// CheckAddressOfOperand - The operand of & must be either a function | ||||
13373 | /// designator or an lvalue designating an object. If it is an lvalue, the | ||||
13374 | /// object cannot be declared with storage class register or be a bit field. | ||||
13375 | /// Note: The usual conversions are *not* applied to the operand of the & | ||||
13376 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | ||||
13377 | /// In C++, the operand might be an overloaded function name, in which case | ||||
13378 | /// we allow the '&' but retain the overloaded-function type. | ||||
13379 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | ||||
13380 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | ||||
13381 | if (PTy->getKind() == BuiltinType::Overload) { | ||||
13382 | Expr *E = OrigOp.get()->IgnoreParens(); | ||||
13383 | if (!isa<OverloadExpr>(E)) { | ||||
13384 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13384, __PRETTY_FUNCTION__)); | ||||
13385 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | ||||
13386 | << OrigOp.get()->getSourceRange(); | ||||
13387 | return QualType(); | ||||
13388 | } | ||||
13389 | |||||
13390 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | ||||
13391 | if (isa<UnresolvedMemberExpr>(Ovl)) | ||||
13392 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | ||||
13393 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13394 | << OrigOp.get()->getSourceRange(); | ||||
13395 | return QualType(); | ||||
13396 | } | ||||
13397 | |||||
13398 | return Context.OverloadTy; | ||||
13399 | } | ||||
13400 | |||||
13401 | if (PTy->getKind() == BuiltinType::UnknownAny) | ||||
13402 | return Context.UnknownAnyTy; | ||||
13403 | |||||
13404 | if (PTy->getKind() == BuiltinType::BoundMember) { | ||||
13405 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13406 | << OrigOp.get()->getSourceRange(); | ||||
13407 | return QualType(); | ||||
13408 | } | ||||
13409 | |||||
13410 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | ||||
13411 | if (OrigOp.isInvalid()) return QualType(); | ||||
13412 | } | ||||
13413 | |||||
13414 | if (OrigOp.get()->isTypeDependent()) | ||||
13415 | return Context.DependentTy; | ||||
13416 | |||||
13417 | assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast <void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13417, __PRETTY_FUNCTION__)); | ||||
13418 | |||||
13419 | // Make sure to ignore parentheses in subsequent checks | ||||
13420 | Expr *op = OrigOp.get()->IgnoreParens(); | ||||
13421 | |||||
13422 | // In OpenCL captures for blocks called as lambda functions | ||||
13423 | // are located in the private address space. Blocks used in | ||||
13424 | // enqueue_kernel can be located in a different address space | ||||
13425 | // depending on a vendor implementation. Thus preventing | ||||
13426 | // taking an address of the capture to avoid invalid AS casts. | ||||
13427 | if (LangOpts.OpenCL) { | ||||
13428 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | ||||
13429 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | ||||
13430 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | ||||
13431 | return QualType(); | ||||
13432 | } | ||||
13433 | } | ||||
13434 | |||||
13435 | if (getLangOpts().C99) { | ||||
13436 | // Implement C99-only parts of addressof rules. | ||||
13437 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | ||||
13438 | if (uOp->getOpcode() == UO_Deref) | ||||
13439 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | ||||
13440 | // (assuming the deref expression is valid). | ||||
13441 | return uOp->getSubExpr()->getType(); | ||||
13442 | } | ||||
13443 | // Technically, there should be a check for array subscript | ||||
13444 | // expressions here, but the result of one is always an lvalue anyway. | ||||
13445 | } | ||||
13446 | ValueDecl *dcl = getPrimaryDecl(op); | ||||
13447 | |||||
13448 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | ||||
13449 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
13450 | op->getBeginLoc())) | ||||
13451 | return QualType(); | ||||
13452 | |||||
13453 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | ||||
13454 | unsigned AddressOfError = AO_No_Error; | ||||
13455 | |||||
13456 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | ||||
13457 | bool sfinae = (bool)isSFINAEContext(); | ||||
13458 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | ||||
13459 | : diag::ext_typecheck_addrof_temporary) | ||||
13460 | << op->getType() << op->getSourceRange(); | ||||
13461 | if (sfinae) | ||||
13462 | return QualType(); | ||||
13463 | // Materialize the temporary as an lvalue so that we can take its address. | ||||
13464 | OrigOp = op = | ||||
13465 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | ||||
13466 | } else if (isa<ObjCSelectorExpr>(op)) { | ||||
13467 | return Context.getPointerType(op->getType()); | ||||
13468 | } else if (lval == Expr::LV_MemberFunction) { | ||||
13469 | // If it's an instance method, make a member pointer. | ||||
13470 | // The expression must have exactly the form &A::foo. | ||||
13471 | |||||
13472 | // If the underlying expression isn't a decl ref, give up. | ||||
13473 | if (!isa<DeclRefExpr>(op)) { | ||||
13474 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13475 | << OrigOp.get()->getSourceRange(); | ||||
13476 | return QualType(); | ||||
13477 | } | ||||
13478 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | ||||
13479 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | ||||
13480 | |||||
13481 | // The id-expression was parenthesized. | ||||
13482 | if (OrigOp.get() != DRE) { | ||||
13483 | Diag(OpLoc, diag::err_parens_pointer_member_function) | ||||
13484 | << OrigOp.get()->getSourceRange(); | ||||
13485 | |||||
13486 | // The method was named without a qualifier. | ||||
13487 | } else if (!DRE->getQualifier()) { | ||||
13488 | if (MD->getParent()->getName().empty()) | ||||
13489 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
13490 | << op->getSourceRange(); | ||||
13491 | else { | ||||
13492 | SmallString<32> Str; | ||||
13493 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | ||||
13494 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
13495 | << op->getSourceRange() | ||||
13496 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | ||||
13497 | } | ||||
13498 | } | ||||
13499 | |||||
13500 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | ||||
13501 | if (isa<CXXDestructorDecl>(MD)) | ||||
13502 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | ||||
13503 | |||||
13504 | QualType MPTy = Context.getMemberPointerType( | ||||
13505 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | ||||
13506 | // Under the MS ABI, lock down the inheritance model now. | ||||
13507 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
13508 | (void)isCompleteType(OpLoc, MPTy); | ||||
13509 | return MPTy; | ||||
13510 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | ||||
13511 | // C99 6.5.3.2p1 | ||||
13512 | // The operand must be either an l-value or a function designator | ||||
13513 | if (!op->getType()->isFunctionType()) { | ||||
13514 | // Use a special diagnostic for loads from property references. | ||||
13515 | if (isa<PseudoObjectExpr>(op)) { | ||||
13516 | AddressOfError = AO_Property_Expansion; | ||||
13517 | } else { | ||||
13518 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | ||||
13519 | << op->getType() << op->getSourceRange(); | ||||
13520 | return QualType(); | ||||
13521 | } | ||||
13522 | } | ||||
13523 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | ||||
13524 | // The operand cannot be a bit-field | ||||
13525 | AddressOfError = AO_Bit_Field; | ||||
13526 | } else if (op->getObjectKind() == OK_VectorComponent) { | ||||
13527 | // The operand cannot be an element of a vector | ||||
13528 | AddressOfError = AO_Vector_Element; | ||||
13529 | } else if (op->getObjectKind() == OK_MatrixComponent) { | ||||
13530 | // The operand cannot be an element of a matrix. | ||||
13531 | AddressOfError = AO_Matrix_Element; | ||||
13532 | } else if (dcl) { // C99 6.5.3.2p1 | ||||
13533 | // We have an lvalue with a decl. Make sure the decl is not declared | ||||
13534 | // with the register storage-class specifier. | ||||
13535 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | ||||
13536 | // in C++ it is not error to take address of a register | ||||
13537 | // variable (c++03 7.1.1P3) | ||||
13538 | if (vd->getStorageClass() == SC_Register && | ||||
13539 | !getLangOpts().CPlusPlus) { | ||||
13540 | AddressOfError = AO_Register_Variable; | ||||
13541 | } | ||||
13542 | } else if (isa<MSPropertyDecl>(dcl)) { | ||||
13543 | AddressOfError = AO_Property_Expansion; | ||||
13544 | } else if (isa<FunctionTemplateDecl>(dcl)) { | ||||
13545 | return Context.OverloadTy; | ||||
13546 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | ||||
13547 | // Okay: we can take the address of a field. | ||||
13548 | // Could be a pointer to member, though, if there is an explicit | ||||
13549 | // scope qualifier for the class. | ||||
13550 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | ||||
13551 | DeclContext *Ctx = dcl->getDeclContext(); | ||||
13552 | if (Ctx && Ctx->isRecord()) { | ||||
13553 | if (dcl->getType()->isReferenceType()) { | ||||
13554 | Diag(OpLoc, | ||||
13555 | diag::err_cannot_form_pointer_to_member_of_reference_type) | ||||
13556 | << dcl->getDeclName() << dcl->getType(); | ||||
13557 | return QualType(); | ||||
13558 | } | ||||
13559 | |||||
13560 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | ||||
13561 | Ctx = Ctx->getParent(); | ||||
13562 | |||||
13563 | QualType MPTy = Context.getMemberPointerType( | ||||
13564 | op->getType(), | ||||
13565 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | ||||
13566 | // Under the MS ABI, lock down the inheritance model now. | ||||
13567 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
13568 | (void)isCompleteType(OpLoc, MPTy); | ||||
13569 | return MPTy; | ||||
13570 | } | ||||
13571 | } | ||||
13572 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | ||||
13573 | !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) | ||||
13574 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13574); | ||||
13575 | } | ||||
13576 | |||||
13577 | if (AddressOfError != AO_No_Error) { | ||||
13578 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | ||||
13579 | return QualType(); | ||||
13580 | } | ||||
13581 | |||||
13582 | if (lval == Expr::LV_IncompleteVoidType) { | ||||
13583 | // Taking the address of a void variable is technically illegal, but we | ||||
13584 | // allow it in cases which are otherwise valid. | ||||
13585 | // Example: "extern void x; void* y = &x;". | ||||
13586 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | ||||
13587 | } | ||||
13588 | |||||
13589 | // If the operand has type "type", the result has type "pointer to type". | ||||
13590 | if (op->getType()->isObjCObjectType()) | ||||
13591 | return Context.getObjCObjectPointerType(op->getType()); | ||||
13592 | |||||
13593 | CheckAddressOfPackedMember(op); | ||||
13594 | |||||
13595 | return Context.getPointerType(op->getType()); | ||||
13596 | } | ||||
13597 | |||||
13598 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | ||||
13599 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | ||||
13600 | if (!DRE) | ||||
13601 | return; | ||||
13602 | const Decl *D = DRE->getDecl(); | ||||
13603 | if (!D) | ||||
13604 | return; | ||||
13605 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | ||||
13606 | if (!Param) | ||||
13607 | return; | ||||
13608 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | ||||
13609 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | ||||
13610 | return; | ||||
13611 | if (FunctionScopeInfo *FD = S.getCurFunction()) | ||||
13612 | if (!FD->ModifiedNonNullParams.count(Param)) | ||||
13613 | FD->ModifiedNonNullParams.insert(Param); | ||||
13614 | } | ||||
13615 | |||||
13616 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | ||||
13617 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | ||||
13618 | SourceLocation OpLoc) { | ||||
13619 | if (Op->isTypeDependent()) | ||||
13620 | return S.Context.DependentTy; | ||||
13621 | |||||
13622 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | ||||
13623 | if (ConvResult.isInvalid()) | ||||
13624 | return QualType(); | ||||
13625 | Op = ConvResult.get(); | ||||
13626 | QualType OpTy = Op->getType(); | ||||
13627 | QualType Result; | ||||
13628 | |||||
13629 | if (isa<CXXReinterpretCastExpr>(Op)) { | ||||
13630 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | ||||
13631 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | ||||
13632 | Op->getSourceRange()); | ||||
13633 | } | ||||
13634 | |||||
13635 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | ||||
13636 | { | ||||
13637 | Result = PT->getPointeeType(); | ||||
13638 | } | ||||
13639 | else if (const ObjCObjectPointerType *OPT = | ||||
13640 | OpTy->getAs<ObjCObjectPointerType>()) | ||||
13641 | Result = OPT->getPointeeType(); | ||||
13642 | else { | ||||
13643 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
13644 | if (PR.isInvalid()) return QualType(); | ||||
13645 | if (PR.get() != Op) | ||||
13646 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | ||||
13647 | } | ||||
13648 | |||||
13649 | if (Result.isNull()) { | ||||
13650 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | ||||
13651 | << OpTy << Op->getSourceRange(); | ||||
13652 | return QualType(); | ||||
13653 | } | ||||
13654 | |||||
13655 | // Note that per both C89 and C99, indirection is always legal, even if Result | ||||
13656 | // is an incomplete type or void. It would be possible to warn about | ||||
13657 | // dereferencing a void pointer, but it's completely well-defined, and such a | ||||
13658 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | ||||
13659 | // for pointers to 'void' but is fine for any other pointer type: | ||||
13660 | // | ||||
13661 | // C++ [expr.unary.op]p1: | ||||
13662 | // [...] the expression to which [the unary * operator] is applied shall | ||||
13663 | // be a pointer to an object type, or a pointer to a function type | ||||
13664 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | ||||
13665 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | ||||
13666 | << OpTy << Op->getSourceRange(); | ||||
13667 | |||||
13668 | // Dereferences are usually l-values... | ||||
13669 | VK = VK_LValue; | ||||
13670 | |||||
13671 | // ...except that certain expressions are never l-values in C. | ||||
13672 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | ||||
13673 | VK = VK_RValue; | ||||
13674 | |||||
13675 | return Result; | ||||
13676 | } | ||||
13677 | |||||
13678 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | ||||
13679 | BinaryOperatorKind Opc; | ||||
13680 | switch (Kind) { | ||||
13681 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13681); | ||||
13682 | case tok::periodstar: Opc = BO_PtrMemD; break; | ||||
13683 | case tok::arrowstar: Opc = BO_PtrMemI; break; | ||||
13684 | case tok::star: Opc = BO_Mul; break; | ||||
13685 | case tok::slash: Opc = BO_Div; break; | ||||
13686 | case tok::percent: Opc = BO_Rem; break; | ||||
13687 | case tok::plus: Opc = BO_Add; break; | ||||
13688 | case tok::minus: Opc = BO_Sub; break; | ||||
13689 | case tok::lessless: Opc = BO_Shl; break; | ||||
13690 | case tok::greatergreater: Opc = BO_Shr; break; | ||||
13691 | case tok::lessequal: Opc = BO_LE; break; | ||||
13692 | case tok::less: Opc = BO_LT; break; | ||||
13693 | case tok::greaterequal: Opc = BO_GE; break; | ||||
13694 | case tok::greater: Opc = BO_GT; break; | ||||
13695 | case tok::exclaimequal: Opc = BO_NE; break; | ||||
13696 | case tok::equalequal: Opc = BO_EQ; break; | ||||
13697 | case tok::spaceship: Opc = BO_Cmp; break; | ||||
13698 | case tok::amp: Opc = BO_And; break; | ||||
13699 | case tok::caret: Opc = BO_Xor; break; | ||||
13700 | case tok::pipe: Opc = BO_Or; break; | ||||
13701 | case tok::ampamp: Opc = BO_LAnd; break; | ||||
13702 | case tok::pipepipe: Opc = BO_LOr; break; | ||||
13703 | case tok::equal: Opc = BO_Assign; break; | ||||
13704 | case tok::starequal: Opc = BO_MulAssign; break; | ||||
13705 | case tok::slashequal: Opc = BO_DivAssign; break; | ||||
13706 | case tok::percentequal: Opc = BO_RemAssign; break; | ||||
13707 | case tok::plusequal: Opc = BO_AddAssign; break; | ||||
13708 | case tok::minusequal: Opc = BO_SubAssign; break; | ||||
13709 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | ||||
13710 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | ||||
13711 | case tok::ampequal: Opc = BO_AndAssign; break; | ||||
13712 | case tok::caretequal: Opc = BO_XorAssign; break; | ||||
13713 | case tok::pipeequal: Opc = BO_OrAssign; break; | ||||
13714 | case tok::comma: Opc = BO_Comma; break; | ||||
13715 | } | ||||
13716 | return Opc; | ||||
13717 | } | ||||
13718 | |||||
13719 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | ||||
13720 | tok::TokenKind Kind) { | ||||
13721 | UnaryOperatorKind Opc; | ||||
13722 | switch (Kind) { | ||||
13723 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13723); | ||||
13724 | case tok::plusplus: Opc = UO_PreInc; break; | ||||
13725 | case tok::minusminus: Opc = UO_PreDec; break; | ||||
13726 | case tok::amp: Opc = UO_AddrOf; break; | ||||
13727 | case tok::star: Opc = UO_Deref; break; | ||||
13728 | case tok::plus: Opc = UO_Plus; break; | ||||
13729 | case tok::minus: Opc = UO_Minus; break; | ||||
13730 | case tok::tilde: Opc = UO_Not; break; | ||||
13731 | case tok::exclaim: Opc = UO_LNot; break; | ||||
13732 | case tok::kw___real: Opc = UO_Real; break; | ||||
13733 | case tok::kw___imag: Opc = UO_Imag; break; | ||||
13734 | case tok::kw___extension__: Opc = UO_Extension; break; | ||||
13735 | } | ||||
13736 | return Opc; | ||||
13737 | } | ||||
13738 | |||||
13739 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | ||||
13740 | /// This warning suppressed in the event of macro expansions. | ||||
13741 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | ||||
13742 | SourceLocation OpLoc, bool IsBuiltin) { | ||||
13743 | if (S.inTemplateInstantiation()) | ||||
13744 | return; | ||||
13745 | if (S.isUnevaluatedContext()) | ||||
13746 | return; | ||||
13747 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | ||||
13748 | return; | ||||
13749 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | ||||
13750 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | ||||
13751 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | ||||
13752 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | ||||
13753 | if (!LHSDeclRef || !RHSDeclRef || | ||||
13754 | LHSDeclRef->getLocation().isMacroID() || | ||||
13755 | RHSDeclRef->getLocation().isMacroID()) | ||||
13756 | return; | ||||
13757 | const ValueDecl *LHSDecl = | ||||
13758 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
13759 | const ValueDecl *RHSDecl = | ||||
13760 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
13761 | if (LHSDecl != RHSDecl) | ||||
13762 | return; | ||||
13763 | if (LHSDecl->getType().isVolatileQualified()) | ||||
13764 | return; | ||||
13765 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
13766 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
13767 | return; | ||||
13768 | |||||
13769 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | ||||
13770 | : diag::warn_self_assignment_overloaded) | ||||
13771 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | ||||
13772 | << RHSExpr->getSourceRange(); | ||||
13773 | } | ||||
13774 | |||||
13775 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | ||||
13776 | /// is usually indicative of introspection within the Objective-C pointer. | ||||
13777 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | ||||
13778 | SourceLocation OpLoc) { | ||||
13779 | if (!S.getLangOpts().ObjC) | ||||
13780 | return; | ||||
13781 | |||||
13782 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | ||||
13783 | const Expr *LHS = L.get(); | ||||
13784 | const Expr *RHS = R.get(); | ||||
13785 | |||||
13786 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
13787 | ObjCPointerExpr = LHS; | ||||
13788 | OtherExpr = RHS; | ||||
13789 | } | ||||
13790 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
13791 | ObjCPointerExpr = RHS; | ||||
13792 | OtherExpr = LHS; | ||||
13793 | } | ||||
13794 | |||||
13795 | // This warning is deliberately made very specific to reduce false | ||||
13796 | // positives with logic that uses '&' for hashing. This logic mainly | ||||
13797 | // looks for code trying to introspect into tagged pointers, which | ||||
13798 | // code should generally never do. | ||||
13799 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | ||||
13800 | unsigned Diag = diag::warn_objc_pointer_masking; | ||||
13801 | // Determine if we are introspecting the result of performSelectorXXX. | ||||
13802 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | ||||
13803 | // Special case messages to -performSelector and friends, which | ||||
13804 | // can return non-pointer values boxed in a pointer value. | ||||
13805 | // Some clients may wish to silence warnings in this subcase. | ||||
13806 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | ||||
13807 | Selector S = ME->getSelector(); | ||||
13808 | StringRef SelArg0 = S.getNameForSlot(0); | ||||
13809 | if (SelArg0.startswith("performSelector")) | ||||
13810 | Diag = diag::warn_objc_pointer_masking_performSelector; | ||||
13811 | } | ||||
13812 | |||||
13813 | S.Diag(OpLoc, Diag) | ||||
13814 | << ObjCPointerExpr->getSourceRange(); | ||||
13815 | } | ||||
13816 | } | ||||
13817 | |||||
13818 | static NamedDecl *getDeclFromExpr(Expr *E) { | ||||
13819 | if (!E) | ||||
13820 | return nullptr; | ||||
13821 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
13822 | return DRE->getDecl(); | ||||
13823 | if (auto *ME = dyn_cast<MemberExpr>(E)) | ||||
13824 | return ME->getMemberDecl(); | ||||
13825 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | ||||
13826 | return IRE->getDecl(); | ||||
13827 | return nullptr; | ||||
13828 | } | ||||
13829 | |||||
13830 | // This helper function promotes a binary operator's operands (which are of a | ||||
13831 | // half vector type) to a vector of floats and then truncates the result to | ||||
13832 | // a vector of either half or short. | ||||
13833 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | ||||
13834 | BinaryOperatorKind Opc, QualType ResultTy, | ||||
13835 | ExprValueKind VK, ExprObjectKind OK, | ||||
13836 | bool IsCompAssign, SourceLocation OpLoc, | ||||
13837 | FPOptionsOverride FPFeatures) { | ||||
13838 | auto &Context = S.getASTContext(); | ||||
13839 | assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13841, __PRETTY_FUNCTION__)) | ||||
13840 | isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13841, __PRETTY_FUNCTION__)) | ||||
13841 | "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13841, __PRETTY_FUNCTION__)); | ||||
13842 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13844, __PRETTY_FUNCTION__)) | ||||
13843 | isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13844, __PRETTY_FUNCTION__)) | ||||
13844 | "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 13844, __PRETTY_FUNCTION__)); | ||||
13845 | |||||
13846 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | ||||
13847 | QualType BinOpResTy = RHS.get()->getType(); | ||||
13848 | |||||
13849 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | ||||
13850 | // change BinOpResTy to a vector of ints. | ||||
13851 | if (isVector(ResultTy, Context.ShortTy)) | ||||
13852 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | ||||
13853 | |||||
13854 | if (IsCompAssign) | ||||
13855 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
13856 | ResultTy, VK, OK, OpLoc, FPFeatures, | ||||
13857 | BinOpResTy, BinOpResTy); | ||||
13858 | |||||
13859 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | ||||
13860 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
13861 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | ||||
13862 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | ||||
13863 | } | ||||
13864 | |||||
13865 | static std::pair<ExprResult, ExprResult> | ||||
13866 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | ||||
13867 | Expr *RHSExpr) { | ||||
13868 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
13869 | if (!S.Context.isDependenceAllowed()) { | ||||
13870 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
13871 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
13872 | // been dealt with before checking the operands. | ||||
13873 | LHS = S.CorrectDelayedTyposInExpr(LHS); | ||||
13874 | RHS = S.CorrectDelayedTyposInExpr( | ||||
13875 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | ||||
13876 | [Opc, LHS](Expr *E) { | ||||
13877 | if (Opc != BO_Assign) | ||||
13878 | return ExprResult(E); | ||||
13879 | // Avoid correcting the RHS to the same Expr as the LHS. | ||||
13880 | Decl *D = getDeclFromExpr(E); | ||||
13881 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | ||||
13882 | }); | ||||
13883 | } | ||||
13884 | return std::make_pair(LHS, RHS); | ||||
13885 | } | ||||
13886 | |||||
13887 | /// Returns true if conversion between vectors of halfs and vectors of floats | ||||
13888 | /// is needed. | ||||
13889 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | ||||
13890 | Expr *E0, Expr *E1 = nullptr) { | ||||
13891 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | ||||
13892 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | ||||
13893 | return false; | ||||
13894 | |||||
13895 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | ||||
13896 | QualType Ty = E->IgnoreImplicit()->getType(); | ||||
13897 | |||||
13898 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | ||||
13899 | // to vectors of floats. Although the element type of the vectors is __fp16, | ||||
13900 | // the vectors shouldn't be treated as storage-only types. See the | ||||
13901 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | ||||
13902 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | ||||
13903 | if (VT->getVectorKind() == VectorType::NeonVector) | ||||
13904 | return false; | ||||
13905 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | ||||
13906 | } | ||||
13907 | return false; | ||||
13908 | }; | ||||
13909 | |||||
13910 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | ||||
13911 | } | ||||
13912 | |||||
13913 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | ||||
13914 | /// operator @p Opc at location @c TokLoc. This routine only supports | ||||
13915 | /// built-in operations; ActOnBinOp handles overloaded operators. | ||||
13916 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | ||||
13917 | BinaryOperatorKind Opc, | ||||
13918 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
13919 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | ||||
13920 | // The syntax only allows initializer lists on the RHS of assignment, | ||||
13921 | // so we don't need to worry about accepting invalid code for | ||||
13922 | // non-assignment operators. | ||||
13923 | // C++11 5.17p9: | ||||
13924 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | ||||
13925 | // of x = {} is x = T(). | ||||
13926 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
13927 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
13928 | InitializedEntity Entity = | ||||
13929 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | ||||
13930 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | ||||
13931 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | ||||
13932 | if (Init.isInvalid()) | ||||
13933 | return Init; | ||||
13934 | RHSExpr = Init.get(); | ||||
13935 | } | ||||
13936 | |||||
13937 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
13938 | QualType ResultTy; // Result type of the binary operator. | ||||
13939 | // The following two variables are used for compound assignment operators | ||||
13940 | QualType CompLHSTy; // Type of LHS after promotions for computation | ||||
13941 | QualType CompResultTy; // Type of computation result | ||||
13942 | ExprValueKind VK = VK_RValue; | ||||
13943 | ExprObjectKind OK = OK_Ordinary; | ||||
13944 | bool ConvertHalfVec = false; | ||||
13945 | |||||
13946 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
13947 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
13948 | return ExprError(); | ||||
13949 | |||||
13950 | if (getLangOpts().OpenCL) { | ||||
13951 | QualType LHSTy = LHSExpr->getType(); | ||||
13952 | QualType RHSTy = RHSExpr->getType(); | ||||
13953 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | ||||
13954 | // the ATOMIC_VAR_INIT macro. | ||||
13955 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | ||||
13956 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
13957 | if (BO_Assign == Opc) | ||||
13958 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | ||||
13959 | else | ||||
13960 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
13961 | return ExprError(); | ||||
13962 | } | ||||
13963 | |||||
13964 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
13965 | // only with a builtin functions and therefore should be disallowed here. | ||||
13966 | if (LHSTy->isImageType() || RHSTy->isImageType() || | ||||
13967 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | ||||
13968 | LHSTy->isPipeType() || RHSTy->isPipeType() || | ||||
13969 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | ||||
13970 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
13971 | return ExprError(); | ||||
13972 | } | ||||
13973 | } | ||||
13974 | |||||
13975 | switch (Opc) { | ||||
13976 | case BO_Assign: | ||||
13977 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | ||||
13978 | if (getLangOpts().CPlusPlus && | ||||
13979 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | ||||
13980 | VK = LHS.get()->getValueKind(); | ||||
13981 | OK = LHS.get()->getObjectKind(); | ||||
13982 | } | ||||
13983 | if (!ResultTy.isNull()) { | ||||
13984 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
13985 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | ||||
13986 | |||||
13987 | // Avoid copying a block to the heap if the block is assigned to a local | ||||
13988 | // auto variable that is declared in the same scope as the block. This | ||||
13989 | // optimization is unsafe if the local variable is declared in an outer | ||||
13990 | // scope. For example: | ||||
13991 | // | ||||
13992 | // BlockTy b; | ||||
13993 | // { | ||||
13994 | // b = ^{...}; | ||||
13995 | // } | ||||
13996 | // // It is unsafe to invoke the block here if it wasn't copied to the | ||||
13997 | // // heap. | ||||
13998 | // b(); | ||||
13999 | |||||
14000 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | ||||
14001 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | ||||
14002 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | ||||
14003 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | ||||
14004 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||
14005 | |||||
14006 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
14007 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | ||||
14008 | NTCUC_Assignment, NTCUK_Copy); | ||||
14009 | } | ||||
14010 | RecordModifiableNonNullParam(*this, LHS.get()); | ||||
14011 | break; | ||||
14012 | case BO_PtrMemD: | ||||
14013 | case BO_PtrMemI: | ||||
14014 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | ||||
14015 | Opc == BO_PtrMemI); | ||||
14016 | break; | ||||
14017 | case BO_Mul: | ||||
14018 | case BO_Div: | ||||
14019 | ConvertHalfVec = true; | ||||
14020 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | ||||
14021 | Opc == BO_Div); | ||||
14022 | break; | ||||
14023 | case BO_Rem: | ||||
14024 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | ||||
14025 | break; | ||||
14026 | case BO_Add: | ||||
14027 | ConvertHalfVec = true; | ||||
14028 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | ||||
14029 | break; | ||||
14030 | case BO_Sub: | ||||
14031 | ConvertHalfVec = true; | ||||
14032 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | ||||
14033 | break; | ||||
14034 | case BO_Shl: | ||||
14035 | case BO_Shr: | ||||
14036 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | ||||
14037 | break; | ||||
14038 | case BO_LE: | ||||
14039 | case BO_LT: | ||||
14040 | case BO_GE: | ||||
14041 | case BO_GT: | ||||
14042 | ConvertHalfVec = true; | ||||
14043 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14044 | break; | ||||
14045 | case BO_EQ: | ||||
14046 | case BO_NE: | ||||
14047 | ConvertHalfVec = true; | ||||
14048 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14049 | break; | ||||
14050 | case BO_Cmp: | ||||
14051 | ConvertHalfVec = true; | ||||
14052 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14053 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast <void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14053, __PRETTY_FUNCTION__)); | ||||
14054 | break; | ||||
14055 | case BO_And: | ||||
14056 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | ||||
14057 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
14058 | case BO_Xor: | ||||
14059 | case BO_Or: | ||||
14060 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
14061 | break; | ||||
14062 | case BO_LAnd: | ||||
14063 | case BO_LOr: | ||||
14064 | ConvertHalfVec = true; | ||||
14065 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | ||||
14066 | break; | ||||
14067 | case BO_MulAssign: | ||||
14068 | case BO_DivAssign: | ||||
14069 | ConvertHalfVec = true; | ||||
14070 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | ||||
14071 | Opc == BO_DivAssign); | ||||
14072 | CompLHSTy = CompResultTy; | ||||
14073 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14074 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14075 | break; | ||||
14076 | case BO_RemAssign: | ||||
14077 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | ||||
14078 | CompLHSTy = CompResultTy; | ||||
14079 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14080 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14081 | break; | ||||
14082 | case BO_AddAssign: | ||||
14083 | ConvertHalfVec = true; | ||||
14084 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | ||||
14085 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14086 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14087 | break; | ||||
14088 | case BO_SubAssign: | ||||
14089 | ConvertHalfVec = true; | ||||
14090 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | ||||
14091 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14092 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14093 | break; | ||||
14094 | case BO_ShlAssign: | ||||
14095 | case BO_ShrAssign: | ||||
14096 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | ||||
14097 | CompLHSTy = CompResultTy; | ||||
14098 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14099 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14100 | break; | ||||
14101 | case BO_AndAssign: | ||||
14102 | case BO_OrAssign: // fallthrough | ||||
14103 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
14104 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
14105 | case BO_XorAssign: | ||||
14106 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
14107 | CompLHSTy = CompResultTy; | ||||
14108 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14109 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14110 | break; | ||||
14111 | case BO_Comma: | ||||
14112 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | ||||
14113 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | ||||
14114 | VK = RHS.get()->getValueKind(); | ||||
14115 | OK = RHS.get()->getObjectKind(); | ||||
14116 | } | ||||
14117 | break; | ||||
14118 | } | ||||
14119 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | ||||
14120 | return ExprError(); | ||||
14121 | |||||
14122 | // Some of the binary operations require promoting operands of half vector to | ||||
14123 | // float vectors and truncating the result back to half vector. For now, we do | ||||
14124 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | ||||
14125 | // arm64). | ||||
14126 | assert((((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14129, __PRETTY_FUNCTION__)) | ||||
14127 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14129, __PRETTY_FUNCTION__)) | ||||
14128 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14129, __PRETTY_FUNCTION__)) | ||||
14129 | "both sides are half vectors or neither sides are")(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14129, __PRETTY_FUNCTION__)); | ||||
14130 | ConvertHalfVec = | ||||
14131 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | ||||
14132 | |||||
14133 | // Check for array bounds violations for both sides of the BinaryOperator | ||||
14134 | CheckArrayAccess(LHS.get()); | ||||
14135 | CheckArrayAccess(RHS.get()); | ||||
14136 | |||||
14137 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | ||||
14138 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | ||||
14139 | &Context.Idents.get("object_setClass"), | ||||
14140 | SourceLocation(), LookupOrdinaryName); | ||||
14141 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | ||||
14142 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
14143 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | ||||
14144 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | ||||
14145 | "object_setClass(") | ||||
14146 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | ||||
14147 | ",") | ||||
14148 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
14149 | } | ||||
14150 | else | ||||
14151 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | ||||
14152 | } | ||||
14153 | else if (const ObjCIvarRefExpr *OIRE = | ||||
14154 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | ||||
14155 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | ||||
14156 | |||||
14157 | // Opc is not a compound assignment if CompResultTy is null. | ||||
14158 | if (CompResultTy.isNull()) { | ||||
14159 | if (ConvertHalfVec) | ||||
14160 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | ||||
14161 | OpLoc, CurFPFeatureOverrides()); | ||||
14162 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | ||||
14163 | VK, OK, OpLoc, CurFPFeatureOverrides()); | ||||
14164 | } | ||||
14165 | |||||
14166 | // Handle compound assignments. | ||||
14167 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | ||||
14168 | OK_ObjCProperty) { | ||||
14169 | VK = VK_LValue; | ||||
14170 | OK = LHS.get()->getObjectKind(); | ||||
14171 | } | ||||
14172 | |||||
14173 | // The LHS is not converted to the result type for fixed-point compound | ||||
14174 | // assignment as the common type is computed on demand. Reset the CompLHSTy | ||||
14175 | // to the LHS type we would have gotten after unary conversions. | ||||
14176 | if (CompResultTy->isFixedPointType()) | ||||
14177 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | ||||
14178 | |||||
14179 | if (ConvertHalfVec) | ||||
14180 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | ||||
14181 | OpLoc, CurFPFeatureOverrides()); | ||||
14182 | |||||
14183 | return CompoundAssignOperator::Create( | ||||
14184 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | ||||
14185 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | ||||
14186 | } | ||||
14187 | |||||
14188 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | ||||
14189 | /// operators are mixed in a way that suggests that the programmer forgot that | ||||
14190 | /// comparison operators have higher precedence. The most typical example of | ||||
14191 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | ||||
14192 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
14193 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
14194 | Expr *RHSExpr) { | ||||
14195 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | ||||
14196 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | ||||
14197 | |||||
14198 | // Check that one of the sides is a comparison operator and the other isn't. | ||||
14199 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | ||||
14200 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | ||||
14201 | if (isLeftComp == isRightComp) | ||||
14202 | return; | ||||
14203 | |||||
14204 | // Bitwise operations are sometimes used as eager logical ops. | ||||
14205 | // Don't diagnose this. | ||||
14206 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | ||||
14207 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | ||||
14208 | if (isLeftBitwise || isRightBitwise) | ||||
14209 | return; | ||||
14210 | |||||
14211 | SourceRange DiagRange = isLeftComp | ||||
14212 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | ||||
14213 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | ||||
14214 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | ||||
14215 | SourceRange ParensRange = | ||||
14216 | isLeftComp | ||||
14217 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | ||||
14218 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | ||||
14219 | |||||
14220 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | ||||
14221 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | ||||
14222 | SuggestParentheses(Self, OpLoc, | ||||
14223 | Self.PDiag(diag::note_precedence_silence) << OpStr, | ||||
14224 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | ||||
14225 | SuggestParentheses(Self, OpLoc, | ||||
14226 | Self.PDiag(diag::note_precedence_bitwise_first) | ||||
14227 | << BinaryOperator::getOpcodeStr(Opc), | ||||
14228 | ParensRange); | ||||
14229 | } | ||||
14230 | |||||
14231 | /// It accepts a '&&' expr that is inside a '||' one. | ||||
14232 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | ||||
14233 | /// in parentheses. | ||||
14234 | static void | ||||
14235 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | ||||
14236 | BinaryOperator *Bop) { | ||||
14237 | assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> ( 0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14237, __PRETTY_FUNCTION__)); | ||||
14238 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | ||||
14239 | << Bop->getSourceRange() << OpLoc; | ||||
14240 | SuggestParentheses(Self, Bop->getOperatorLoc(), | ||||
14241 | Self.PDiag(diag::note_precedence_silence) | ||||
14242 | << Bop->getOpcodeStr(), | ||||
14243 | Bop->getSourceRange()); | ||||
14244 | } | ||||
14245 | |||||
14246 | /// Returns true if the given expression can be evaluated as a constant | ||||
14247 | /// 'true'. | ||||
14248 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | ||||
14249 | bool Res; | ||||
14250 | return !E->isValueDependent() && | ||||
14251 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | ||||
14252 | } | ||||
14253 | |||||
14254 | /// Returns true if the given expression can be evaluated as a constant | ||||
14255 | /// 'false'. | ||||
14256 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | ||||
14257 | bool Res; | ||||
14258 | return !E->isValueDependent() && | ||||
14259 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | ||||
14260 | } | ||||
14261 | |||||
14262 | /// Look for '&&' in the left hand of a '||' expr. | ||||
14263 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | ||||
14264 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14265 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | ||||
14266 | if (Bop->getOpcode() == BO_LAnd) { | ||||
14267 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | ||||
14268 | if (EvaluatesAsFalse(S, RHSExpr)) | ||||
14269 | return; | ||||
14270 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | ||||
14271 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | ||||
14272 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
14273 | } else if (Bop->getOpcode() == BO_LOr) { | ||||
14274 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | ||||
14275 | // If it's "a || b && 1 || c" we didn't warn earlier for | ||||
14276 | // "a || b && 1", but warn now. | ||||
14277 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | ||||
14278 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | ||||
14279 | } | ||||
14280 | } | ||||
14281 | } | ||||
14282 | } | ||||
14283 | |||||
14284 | /// Look for '&&' in the right hand of a '||' expr. | ||||
14285 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | ||||
14286 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14287 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | ||||
14288 | if (Bop->getOpcode() == BO_LAnd) { | ||||
14289 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | ||||
14290 | if (EvaluatesAsFalse(S, LHSExpr)) | ||||
14291 | return; | ||||
14292 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | ||||
14293 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | ||||
14294 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
14295 | } | ||||
14296 | } | ||||
14297 | } | ||||
14298 | |||||
14299 | /// Look for bitwise op in the left or right hand of a bitwise op with | ||||
14300 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | ||||
14301 | /// the '&' expression in parentheses. | ||||
14302 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | ||||
14303 | SourceLocation OpLoc, Expr *SubExpr) { | ||||
14304 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
14305 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | ||||
14306 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | ||||
14307 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | ||||
14308 | << Bop->getSourceRange() << OpLoc; | ||||
14309 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
14310 | S.PDiag(diag::note_precedence_silence) | ||||
14311 | << Bop->getOpcodeStr(), | ||||
14312 | Bop->getSourceRange()); | ||||
14313 | } | ||||
14314 | } | ||||
14315 | } | ||||
14316 | |||||
14317 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | ||||
14318 | Expr *SubExpr, StringRef Shift) { | ||||
14319 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
14320 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | ||||
14321 | StringRef Op = Bop->getOpcodeStr(); | ||||
14322 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | ||||
14323 | << Bop->getSourceRange() << OpLoc << Shift << Op; | ||||
14324 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
14325 | S.PDiag(diag::note_precedence_silence) << Op, | ||||
14326 | Bop->getSourceRange()); | ||||
14327 | } | ||||
14328 | } | ||||
14329 | } | ||||
14330 | |||||
14331 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | ||||
14332 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14333 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | ||||
14334 | if (!OCE) | ||||
14335 | return; | ||||
14336 | |||||
14337 | FunctionDecl *FD = OCE->getDirectCallee(); | ||||
14338 | if (!FD || !FD->isOverloadedOperator()) | ||||
14339 | return; | ||||
14340 | |||||
14341 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | ||||
14342 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | ||||
14343 | return; | ||||
14344 | |||||
14345 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | ||||
14346 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | ||||
14347 | << (Kind == OO_LessLess); | ||||
14348 | SuggestParentheses(S, OCE->getOperatorLoc(), | ||||
14349 | S.PDiag(diag::note_precedence_silence) | ||||
14350 | << (Kind == OO_LessLess ? "<<" : ">>"), | ||||
14351 | OCE->getSourceRange()); | ||||
14352 | SuggestParentheses( | ||||
14353 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | ||||
14354 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
14355 | } | ||||
14356 | |||||
14357 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | ||||
14358 | /// precedence. | ||||
14359 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
14360 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
14361 | Expr *RHSExpr){ | ||||
14362 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | ||||
14363 | if (BinaryOperator::isBitwiseOp(Opc)) | ||||
14364 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | ||||
14365 | |||||
14366 | // Diagnose "arg1 & arg2 | arg3" | ||||
14367 | if ((Opc == BO_Or || Opc == BO_Xor) && | ||||
14368 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
14369 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | ||||
14370 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | ||||
14371 | } | ||||
14372 | |||||
14373 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | ||||
14374 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | ||||
14375 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
14376 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14377 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14378 | } | ||||
14379 | |||||
14380 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | ||||
14381 | || Opc == BO_Shr) { | ||||
14382 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | ||||
14383 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | ||||
14384 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | ||||
14385 | } | ||||
14386 | |||||
14387 | // Warn on overloaded shift operators and comparisons, such as: | ||||
14388 | // cout << 5 == 4; | ||||
14389 | if (BinaryOperator::isComparisonOp(Opc)) | ||||
14390 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14391 | } | ||||
14392 | |||||
14393 | // Binary Operators. 'Tok' is the token for the operator. | ||||
14394 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | ||||
14395 | tok::TokenKind Kind, | ||||
14396 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14397 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | ||||
14398 | assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression") ? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14398, __PRETTY_FUNCTION__)); | ||||
14399 | assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression" ) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14399, __PRETTY_FUNCTION__)); | ||||
14400 | |||||
14401 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | ||||
14402 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | ||||
14403 | |||||
14404 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | ||||
14405 | } | ||||
14406 | |||||
14407 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | ||||
14408 | UnresolvedSetImpl &Functions) { | ||||
14409 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | ||||
14410 | if (OverOp != OO_None && OverOp != OO_Equal) | ||||
14411 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
14412 | |||||
14413 | // In C++20 onwards, we may have a second operator to look up. | ||||
14414 | if (getLangOpts().CPlusPlus20) { | ||||
14415 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | ||||
14416 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | ||||
14417 | } | ||||
14418 | } | ||||
14419 | |||||
14420 | /// Build an overloaded binary operator expression in the given scope. | ||||
14421 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | ||||
14422 | BinaryOperatorKind Opc, | ||||
14423 | Expr *LHS, Expr *RHS) { | ||||
14424 | switch (Opc) { | ||||
14425 | case BO_Assign: | ||||
14426 | case BO_DivAssign: | ||||
14427 | case BO_RemAssign: | ||||
14428 | case BO_SubAssign: | ||||
14429 | case BO_AndAssign: | ||||
14430 | case BO_OrAssign: | ||||
14431 | case BO_XorAssign: | ||||
14432 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | ||||
14433 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | ||||
14434 | break; | ||||
14435 | default: | ||||
14436 | break; | ||||
14437 | } | ||||
14438 | |||||
14439 | // Find all of the overloaded operators visible from this point. | ||||
14440 | UnresolvedSet<16> Functions; | ||||
14441 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | ||||
14442 | |||||
14443 | // Build the (potentially-overloaded, potentially-dependent) | ||||
14444 | // binary operation. | ||||
14445 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | ||||
14446 | } | ||||
14447 | |||||
14448 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | ||||
14449 | BinaryOperatorKind Opc, | ||||
14450 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14451 | ExprResult LHS, RHS; | ||||
14452 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
14453 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
14454 | return ExprError(); | ||||
14455 | LHSExpr = LHS.get(); | ||||
14456 | RHSExpr = RHS.get(); | ||||
14457 | |||||
14458 | // We want to end up calling one of checkPseudoObjectAssignment | ||||
14459 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | ||||
14460 | // both expressions are overloadable or either is type-dependent), | ||||
14461 | // or CreateBuiltinBinOp (in any other case). We also want to get | ||||
14462 | // any placeholder types out of the way. | ||||
14463 | |||||
14464 | // Handle pseudo-objects in the LHS. | ||||
14465 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | ||||
14466 | // Assignments with a pseudo-object l-value need special analysis. | ||||
14467 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
14468 | BinaryOperator::isAssignmentOp(Opc)) | ||||
14469 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14470 | |||||
14471 | // Don't resolve overloads if the other type is overloadable. | ||||
14472 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | ||||
14473 | // We can't actually test that if we still have a placeholder, | ||||
14474 | // though. Fortunately, none of the exceptions we see in that | ||||
14475 | // code below are valid when the LHS is an overload set. Note | ||||
14476 | // that an overload set can be dependently-typed, but it never | ||||
14477 | // instantiates to having an overloadable type. | ||||
14478 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
14479 | if (resolvedRHS.isInvalid()) return ExprError(); | ||||
14480 | RHSExpr = resolvedRHS.get(); | ||||
14481 | |||||
14482 | if (RHSExpr->isTypeDependent() || | ||||
14483 | RHSExpr->getType()->isOverloadableType()) | ||||
14484 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14485 | } | ||||
14486 | |||||
14487 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | ||||
14488 | // template, diagnose the missing 'template' keyword instead of diagnosing | ||||
14489 | // an invalid use of a bound member function. | ||||
14490 | // | ||||
14491 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | ||||
14492 | // to C++1z [over.over]/1.4, but we already checked for that case above. | ||||
14493 | if (Opc == BO_LT && inTemplateInstantiation() && | ||||
14494 | (pty->getKind() == BuiltinType::BoundMember || | ||||
14495 | pty->getKind() == BuiltinType::Overload)) { | ||||
14496 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | ||||
14497 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | ||||
14498 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | ||||
14499 | return isa<FunctionTemplateDecl>(ND); | ||||
14500 | })) { | ||||
14501 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | ||||
14502 | : OE->getNameLoc(), | ||||
14503 | diag::err_template_kw_missing) | ||||
14504 | << OE->getName().getAsString() << ""; | ||||
14505 | return ExprError(); | ||||
14506 | } | ||||
14507 | } | ||||
14508 | |||||
14509 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | ||||
14510 | if (LHS.isInvalid()) return ExprError(); | ||||
14511 | LHSExpr = LHS.get(); | ||||
14512 | } | ||||
14513 | |||||
14514 | // Handle pseudo-objects in the RHS. | ||||
14515 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | ||||
14516 | // An overload in the RHS can potentially be resolved by the type | ||||
14517 | // being assigned to. | ||||
14518 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | ||||
14519 | if (getLangOpts().CPlusPlus && | ||||
14520 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | ||||
14521 | LHSExpr->getType()->isOverloadableType())) | ||||
14522 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14523 | |||||
14524 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14525 | } | ||||
14526 | |||||
14527 | // Don't resolve overloads if the other type is overloadable. | ||||
14528 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | ||||
14529 | LHSExpr->getType()->isOverloadableType()) | ||||
14530 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14531 | |||||
14532 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
14533 | if (!resolvedRHS.isUsable()) return ExprError(); | ||||
14534 | RHSExpr = resolvedRHS.get(); | ||||
14535 | } | ||||
14536 | |||||
14537 | if (getLangOpts().CPlusPlus) { | ||||
14538 | // If either expression is type-dependent, always build an | ||||
14539 | // overloaded op. | ||||
14540 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | ||||
14541 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14542 | |||||
14543 | // Otherwise, build an overloaded op if either expression has an | ||||
14544 | // overloadable type. | ||||
14545 | if (LHSExpr->getType()->isOverloadableType() || | ||||
14546 | RHSExpr->getType()->isOverloadableType()) | ||||
14547 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14548 | } | ||||
14549 | |||||
14550 | if (getLangOpts().RecoveryAST && | ||||
14551 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | ||||
14552 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14552, __PRETTY_FUNCTION__)); | ||||
14553 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14554, __PRETTY_FUNCTION__)) | ||||
14554 | "Should only occur in error-recovery path.")(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14554, __PRETTY_FUNCTION__)); | ||||
14555 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | ||||
14556 | // C [6.15.16] p3: | ||||
14557 | // An assignment expression has the value of the left operand after the | ||||
14558 | // assignment, but is not an lvalue. | ||||
14559 | return CompoundAssignOperator::Create( | ||||
14560 | Context, LHSExpr, RHSExpr, Opc, | ||||
14561 | LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, | ||||
14562 | OpLoc, CurFPFeatureOverrides()); | ||||
14563 | QualType ResultType; | ||||
14564 | switch (Opc) { | ||||
14565 | case BO_Assign: | ||||
14566 | ResultType = LHSExpr->getType().getUnqualifiedType(); | ||||
14567 | break; | ||||
14568 | case BO_LT: | ||||
14569 | case BO_GT: | ||||
14570 | case BO_LE: | ||||
14571 | case BO_GE: | ||||
14572 | case BO_EQ: | ||||
14573 | case BO_NE: | ||||
14574 | case BO_LAnd: | ||||
14575 | case BO_LOr: | ||||
14576 | // These operators have a fixed result type regardless of operands. | ||||
14577 | ResultType = Context.IntTy; | ||||
14578 | break; | ||||
14579 | case BO_Comma: | ||||
14580 | ResultType = RHSExpr->getType(); | ||||
14581 | break; | ||||
14582 | default: | ||||
14583 | ResultType = Context.DependentTy; | ||||
14584 | break; | ||||
14585 | } | ||||
14586 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | ||||
14587 | VK_RValue, OK_Ordinary, OpLoc, | ||||
14588 | CurFPFeatureOverrides()); | ||||
14589 | } | ||||
14590 | |||||
14591 | // Build a built-in binary operation. | ||||
14592 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14593 | } | ||||
14594 | |||||
14595 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | ||||
14596 | if (T.isNull() || T->isDependentType()) | ||||
14597 | return false; | ||||
14598 | |||||
14599 | if (!T->isPromotableIntegerType()) | ||||
14600 | return true; | ||||
14601 | |||||
14602 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | ||||
14603 | } | ||||
14604 | |||||
14605 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | ||||
14606 | UnaryOperatorKind Opc, | ||||
14607 | Expr *InputExpr) { | ||||
14608 | ExprResult Input = InputExpr; | ||||
14609 | ExprValueKind VK = VK_RValue; | ||||
14610 | ExprObjectKind OK = OK_Ordinary; | ||||
14611 | QualType resultType; | ||||
14612 | bool CanOverflow = false; | ||||
14613 | |||||
14614 | bool ConvertHalfVec = false; | ||||
14615 | if (getLangOpts().OpenCL) { | ||||
14616 | QualType Ty = InputExpr->getType(); | ||||
14617 | // The only legal unary operation for atomics is '&'. | ||||
14618 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | ||||
14619 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
14620 | // only with a builtin functions and therefore should be disallowed here. | ||||
14621 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | ||||
14622 | || Ty->isBlockPointerType())) { | ||||
14623 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14624 | << InputExpr->getType() | ||||
14625 | << Input.get()->getSourceRange()); | ||||
14626 | } | ||||
14627 | } | ||||
14628 | |||||
14629 | switch (Opc) { | ||||
14630 | case UO_PreInc: | ||||
14631 | case UO_PreDec: | ||||
14632 | case UO_PostInc: | ||||
14633 | case UO_PostDec: | ||||
14634 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | ||||
14635 | OpLoc, | ||||
14636 | Opc == UO_PreInc || | ||||
14637 | Opc == UO_PostInc, | ||||
14638 | Opc == UO_PreInc || | ||||
14639 | Opc == UO_PreDec); | ||||
14640 | CanOverflow = isOverflowingIntegerType(Context, resultType); | ||||
14641 | break; | ||||
14642 | case UO_AddrOf: | ||||
14643 | resultType = CheckAddressOfOperand(Input, OpLoc); | ||||
14644 | CheckAddressOfNoDeref(InputExpr); | ||||
14645 | RecordModifiableNonNullParam(*this, InputExpr); | ||||
14646 | break; | ||||
14647 | case UO_Deref: { | ||||
14648 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
14649 | if (Input.isInvalid()) return ExprError(); | ||||
14650 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | ||||
14651 | break; | ||||
14652 | } | ||||
14653 | case UO_Plus: | ||||
14654 | case UO_Minus: | ||||
14655 | CanOverflow = Opc == UO_Minus && | ||||
14656 | isOverflowingIntegerType(Context, Input.get()->getType()); | ||||
14657 | Input = UsualUnaryConversions(Input.get()); | ||||
14658 | if (Input.isInvalid()) return ExprError(); | ||||
14659 | // Unary plus and minus require promoting an operand of half vector to a | ||||
14660 | // float vector and truncating the result back to a half vector. For now, we | ||||
14661 | // do this only when HalfArgsAndReturns is set (that is, when the target is | ||||
14662 | // arm or arm64). | ||||
14663 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | ||||
14664 | |||||
14665 | // If the operand is a half vector, promote it to a float vector. | ||||
14666 | if (ConvertHalfVec) | ||||
14667 | Input = convertVector(Input.get(), Context.FloatTy, *this); | ||||
14668 | resultType = Input.get()->getType(); | ||||
14669 | if (resultType->isDependentType()) | ||||
14670 | break; | ||||
14671 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | ||||
14672 | break; | ||||
14673 | else if (resultType->isVectorType() && | ||||
14674 | // The z vector extensions don't allow + or - with bool vectors. | ||||
14675 | (!Context.getLangOpts().ZVector || | ||||
14676 | resultType->castAs<VectorType>()->getVectorKind() != | ||||
14677 | VectorType::AltiVecBool)) | ||||
14678 | break; | ||||
14679 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | ||||
14680 | Opc == UO_Plus && | ||||
14681 | resultType->isPointerType()) | ||||
14682 | break; | ||||
14683 | |||||
14684 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14685 | << resultType << Input.get()->getSourceRange()); | ||||
14686 | |||||
14687 | case UO_Not: // bitwise complement | ||||
14688 | Input = UsualUnaryConversions(Input.get()); | ||||
14689 | if (Input.isInvalid()) | ||||
14690 | return ExprError(); | ||||
14691 | resultType = Input.get()->getType(); | ||||
14692 | if (resultType->isDependentType()) | ||||
14693 | break; | ||||
14694 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | ||||
14695 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | ||||
14696 | // C99 does not support '~' for complex conjugation. | ||||
14697 | Diag(OpLoc, diag::ext_integer_complement_complex) | ||||
14698 | << resultType << Input.get()->getSourceRange(); | ||||
14699 | else if (resultType->hasIntegerRepresentation()) | ||||
14700 | break; | ||||
14701 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | ||||
14702 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | ||||
14703 | // on vector float types. | ||||
14704 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
14705 | if (!T->isIntegerType()) | ||||
14706 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14707 | << resultType << Input.get()->getSourceRange()); | ||||
14708 | } else { | ||||
14709 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14710 | << resultType << Input.get()->getSourceRange()); | ||||
14711 | } | ||||
14712 | break; | ||||
14713 | |||||
14714 | case UO_LNot: // logical negation | ||||
14715 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | ||||
14716 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
14717 | if (Input.isInvalid()) return ExprError(); | ||||
14718 | resultType = Input.get()->getType(); | ||||
14719 | |||||
14720 | // Though we still have to promote half FP to float... | ||||
14721 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | ||||
14722 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | ||||
14723 | resultType = Context.FloatTy; | ||||
14724 | } | ||||
14725 | |||||
14726 | if (resultType->isDependentType()) | ||||
14727 | break; | ||||
14728 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | ||||
14729 | // C99 6.5.3.3p1: ok, fallthrough; | ||||
14730 | if (Context.getLangOpts().CPlusPlus) { | ||||
14731 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | ||||
14732 | // operand contextually converted to bool. | ||||
14733 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | ||||
14734 | ScalarTypeToBooleanCastKind(resultType)); | ||||
14735 | } else if (Context.getLangOpts().OpenCL && | ||||
14736 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
14737 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
14738 | // operate on scalar float types. | ||||
14739 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | ||||
14740 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14741 | << resultType << Input.get()->getSourceRange()); | ||||
14742 | } | ||||
14743 | } else if (resultType->isExtVectorType()) { | ||||
14744 | if (Context.getLangOpts().OpenCL && | ||||
14745 | Context.getLangOpts().OpenCLVersion < 120 && | ||||
14746 | !Context.getLangOpts().OpenCLCPlusPlus) { | ||||
14747 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
14748 | // operate on vector float types. | ||||
14749 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
14750 | if (!T->isIntegerType()) | ||||
14751 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14752 | << resultType << Input.get()->getSourceRange()); | ||||
14753 | } | ||||
14754 | // Vector logical not returns the signed variant of the operand type. | ||||
14755 | resultType = GetSignedVectorType(resultType); | ||||
14756 | break; | ||||
14757 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | ||||
14758 | const VectorType *VTy = resultType->castAs<VectorType>(); | ||||
14759 | if (VTy->getVectorKind() != VectorType::GenericVector) | ||||
14760 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14761 | << resultType << Input.get()->getSourceRange()); | ||||
14762 | |||||
14763 | // Vector logical not returns the signed variant of the operand type. | ||||
14764 | resultType = GetSignedVectorType(resultType); | ||||
14765 | break; | ||||
14766 | } else { | ||||
14767 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14768 | << resultType << Input.get()->getSourceRange()); | ||||
14769 | } | ||||
14770 | |||||
14771 | // LNot always has type int. C99 6.5.3.3p5. | ||||
14772 | // In C++, it's bool. C++ 5.3.1p8 | ||||
14773 | resultType = Context.getLogicalOperationType(); | ||||
14774 | break; | ||||
14775 | case UO_Real: | ||||
14776 | case UO_Imag: | ||||
14777 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | ||||
14778 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | ||||
14779 | // complex l-values to ordinary l-values and all other values to r-values. | ||||
14780 | if (Input.isInvalid()) return ExprError(); | ||||
14781 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | ||||
14782 | if (Input.get()->getValueKind() != VK_RValue && | ||||
14783 | Input.get()->getObjectKind() == OK_Ordinary) | ||||
14784 | VK = Input.get()->getValueKind(); | ||||
14785 | } else if (!getLangOpts().CPlusPlus) { | ||||
14786 | // In C, a volatile scalar is read by __imag. In C++, it is not. | ||||
14787 | Input = DefaultLvalueConversion(Input.get()); | ||||
14788 | } | ||||
14789 | break; | ||||
14790 | case UO_Extension: | ||||
14791 | resultType = Input.get()->getType(); | ||||
14792 | VK = Input.get()->getValueKind(); | ||||
14793 | OK = Input.get()->getObjectKind(); | ||||
14794 | break; | ||||
14795 | case UO_Coawait: | ||||
14796 | // It's unnecessary to represent the pass-through operator co_await in the | ||||
14797 | // AST; just return the input expression instead. | ||||
14798 | assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14800, __PRETTY_FUNCTION__)) | ||||
14799 | "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14800, __PRETTY_FUNCTION__)) | ||||
14800 | "building operator co_await")((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14800, __PRETTY_FUNCTION__)); | ||||
14801 | return Input; | ||||
14802 | } | ||||
14803 | if (resultType.isNull() || Input.isInvalid()) | ||||
14804 | return ExprError(); | ||||
14805 | |||||
14806 | // Check for array bounds violations in the operand of the UnaryOperator, | ||||
14807 | // except for the '*' and '&' operators that have to be handled specially | ||||
14808 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | ||||
14809 | // that are explicitly defined as valid by the standard). | ||||
14810 | if (Opc != UO_AddrOf && Opc != UO_Deref) | ||||
14811 | CheckArrayAccess(Input.get()); | ||||
14812 | |||||
14813 | auto *UO = | ||||
14814 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | ||||
14815 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | ||||
14816 | |||||
14817 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | ||||
14818 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | ||||
14819 | !isUnevaluatedContext()) | ||||
14820 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | ||||
14821 | |||||
14822 | // Convert the result back to a half vector. | ||||
14823 | if (ConvertHalfVec) | ||||
14824 | return convertVector(UO, Context.HalfTy, *this); | ||||
14825 | return UO; | ||||
14826 | } | ||||
14827 | |||||
14828 | /// Determine whether the given expression is a qualified member | ||||
14829 | /// access expression, of a form that could be turned into a pointer to member | ||||
14830 | /// with the address-of operator. | ||||
14831 | bool Sema::isQualifiedMemberAccess(Expr *E) { | ||||
14832 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
14833 | if (!DRE->getQualifier()) | ||||
14834 | return false; | ||||
14835 | |||||
14836 | ValueDecl *VD = DRE->getDecl(); | ||||
14837 | if (!VD->isCXXClassMember()) | ||||
14838 | return false; | ||||
14839 | |||||
14840 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | ||||
14841 | return true; | ||||
14842 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | ||||
14843 | return Method->isInstance(); | ||||
14844 | |||||
14845 | return false; | ||||
14846 | } | ||||
14847 | |||||
14848 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | ||||
14849 | if (!ULE->getQualifier()) | ||||
14850 | return false; | ||||
14851 | |||||
14852 | for (NamedDecl *D : ULE->decls()) { | ||||
14853 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | ||||
14854 | if (Method->isInstance()) | ||||
14855 | return true; | ||||
14856 | } else { | ||||
14857 | // Overload set does not contain methods. | ||||
14858 | break; | ||||
14859 | } | ||||
14860 | } | ||||
14861 | |||||
14862 | return false; | ||||
14863 | } | ||||
14864 | |||||
14865 | return false; | ||||
14866 | } | ||||
14867 | |||||
14868 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
14869 | UnaryOperatorKind Opc, Expr *Input) { | ||||
14870 | // First things first: handle placeholders so that the | ||||
14871 | // overloaded-operator check considers the right type. | ||||
14872 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | ||||
14873 | // Increment and decrement of pseudo-object references. | ||||
14874 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
14875 | UnaryOperator::isIncrementDecrementOp(Opc)) | ||||
14876 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | ||||
14877 | |||||
14878 | // extension is always a builtin operator. | ||||
14879 | if (Opc == UO_Extension) | ||||
14880 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
14881 | |||||
14882 | // & gets special logic for several kinds of placeholder. | ||||
14883 | // The builtin code knows what to do. | ||||
14884 | if (Opc == UO_AddrOf && | ||||
14885 | (pty->getKind() == BuiltinType::Overload || | ||||
14886 | pty->getKind() == BuiltinType::UnknownAny || | ||||
14887 | pty->getKind() == BuiltinType::BoundMember)) | ||||
14888 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
14889 | |||||
14890 | // Anything else needs to be handled now. | ||||
14891 | ExprResult Result = CheckPlaceholderExpr(Input); | ||||
14892 | if (Result.isInvalid()) return ExprError(); | ||||
14893 | Input = Result.get(); | ||||
14894 | } | ||||
14895 | |||||
14896 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | ||||
14897 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | ||||
14898 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | ||||
14899 | // Find all of the overloaded operators visible from this point. | ||||
14900 | UnresolvedSet<16> Functions; | ||||
14901 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | ||||
14902 | if (S && OverOp != OO_None) | ||||
14903 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
14904 | |||||
14905 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | ||||
14906 | } | ||||
14907 | |||||
14908 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
14909 | } | ||||
14910 | |||||
14911 | // Unary Operators. 'Tok' is the token for the operator. | ||||
14912 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
14913 | tok::TokenKind Op, Expr *Input) { | ||||
14914 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | ||||
14915 | } | ||||
14916 | |||||
14917 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | ||||
14918 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | ||||
14919 | LabelDecl *TheDecl) { | ||||
14920 | TheDecl->markUsed(Context); | ||||
14921 | // Create the AST node. The address of a label always has type 'void*'. | ||||
14922 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | ||||
14923 | Context.getPointerType(Context.VoidTy)); | ||||
14924 | } | ||||
14925 | |||||
14926 | void Sema::ActOnStartStmtExpr() { | ||||
14927 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
14928 | } | ||||
14929 | |||||
14930 | void Sema::ActOnStmtExprError() { | ||||
14931 | // Note that function is also called by TreeTransform when leaving a | ||||
14932 | // StmtExpr scope without rebuilding anything. | ||||
14933 | |||||
14934 | DiscardCleanupsInEvaluationContext(); | ||||
14935 | PopExpressionEvaluationContext(); | ||||
14936 | } | ||||
14937 | |||||
14938 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | ||||
14939 | SourceLocation RPLoc) { | ||||
14940 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | ||||
14941 | } | ||||
14942 | |||||
14943 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | ||||
14944 | SourceLocation RPLoc, unsigned TemplateDepth) { | ||||
14945 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!") ? static_cast<void> (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14945, __PRETTY_FUNCTION__)); | ||||
14946 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | ||||
14947 | |||||
14948 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
14949 | DiscardCleanupsInEvaluationContext(); | ||||
14950 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14951, __PRETTY_FUNCTION__)) | ||||
14951 | "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 14951, __PRETTY_FUNCTION__)); | ||||
14952 | PopExpressionEvaluationContext(); | ||||
14953 | |||||
14954 | // FIXME: there are a variety of strange constraints to enforce here, for | ||||
14955 | // example, it is not possible to goto into a stmt expression apparently. | ||||
14956 | // More semantic analysis is needed. | ||||
14957 | |||||
14958 | // If there are sub-stmts in the compound stmt, take the type of the last one | ||||
14959 | // as the type of the stmtexpr. | ||||
14960 | QualType Ty = Context.VoidTy; | ||||
14961 | bool StmtExprMayBindToTemp = false; | ||||
14962 | if (!Compound->body_empty()) { | ||||
14963 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | ||||
14964 | if (const auto *LastStmt = | ||||
14965 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | ||||
14966 | if (const Expr *Value = LastStmt->getExprStmt()) { | ||||
14967 | StmtExprMayBindToTemp = true; | ||||
14968 | Ty = Value->getType(); | ||||
14969 | } | ||||
14970 | } | ||||
14971 | } | ||||
14972 | |||||
14973 | // FIXME: Check that expression type is complete/non-abstract; statement | ||||
14974 | // expressions are not lvalues. | ||||
14975 | Expr *ResStmtExpr = | ||||
14976 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | ||||
14977 | if (StmtExprMayBindToTemp) | ||||
14978 | return MaybeBindToTemporary(ResStmtExpr); | ||||
14979 | return ResStmtExpr; | ||||
14980 | } | ||||
14981 | |||||
14982 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | ||||
14983 | if (ER.isInvalid()) | ||||
14984 | return ExprError(); | ||||
14985 | |||||
14986 | // Do function/array conversion on the last expression, but not | ||||
14987 | // lvalue-to-rvalue. However, initialize an unqualified type. | ||||
14988 | ER = DefaultFunctionArrayConversion(ER.get()); | ||||
14989 | if (ER.isInvalid()) | ||||
14990 | return ExprError(); | ||||
14991 | Expr *E = ER.get(); | ||||
14992 | |||||
14993 | if (E->isTypeDependent()) | ||||
14994 | return E; | ||||
14995 | |||||
14996 | // In ARC, if the final expression ends in a consume, splice | ||||
14997 | // the consume out and bind it later. In the alternate case | ||||
14998 | // (when dealing with a retainable type), the result | ||||
14999 | // initialization will create a produce. In both cases the | ||||
15000 | // result will be +1, and we'll need to balance that out with | ||||
15001 | // a bind. | ||||
15002 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | ||||
15003 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | ||||
15004 | return Cast->getSubExpr(); | ||||
15005 | |||||
15006 | // FIXME: Provide a better location for the initialization. | ||||
15007 | return PerformCopyInitialization( | ||||
15008 | InitializedEntity::InitializeStmtExprResult( | ||||
15009 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | ||||
15010 | SourceLocation(), E); | ||||
15011 | } | ||||
15012 | |||||
15013 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | ||||
15014 | TypeSourceInfo *TInfo, | ||||
15015 | ArrayRef<OffsetOfComponent> Components, | ||||
15016 | SourceLocation RParenLoc) { | ||||
15017 | QualType ArgTy = TInfo->getType(); | ||||
15018 | bool Dependent = ArgTy->isDependentType(); | ||||
15019 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | ||||
15020 | |||||
15021 | // We must have at least one component that refers to the type, and the first | ||||
15022 | // one is known to be a field designator. Verify that the ArgTy represents | ||||
15023 | // a struct/union/class. | ||||
15024 | if (!Dependent && !ArgTy->isRecordType()) | ||||
15025 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | ||||
15026 | << ArgTy << TypeRange); | ||||
15027 | |||||
15028 | // Type must be complete per C99 7.17p3 because a declaring a variable | ||||
15029 | // with an incomplete type would be ill-formed. | ||||
15030 | if (!Dependent | ||||
15031 | && RequireCompleteType(BuiltinLoc, ArgTy, | ||||
15032 | diag::err_offsetof_incomplete_type, TypeRange)) | ||||
15033 | return ExprError(); | ||||
15034 | |||||
15035 | bool DidWarnAboutNonPOD = false; | ||||
15036 | QualType CurrentType = ArgTy; | ||||
15037 | SmallVector<OffsetOfNode, 4> Comps; | ||||
15038 | SmallVector<Expr*, 4> Exprs; | ||||
15039 | for (const OffsetOfComponent &OC : Components) { | ||||
15040 | if (OC.isBrackets) { | ||||
15041 | // Offset of an array sub-field. TODO: Should we allow vector elements? | ||||
15042 | if (!CurrentType->isDependentType()) { | ||||
15043 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | ||||
15044 | if(!AT) | ||||
15045 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | ||||
15046 | << CurrentType); | ||||
15047 | CurrentType = AT->getElementType(); | ||||
15048 | } else | ||||
15049 | CurrentType = Context.DependentTy; | ||||
15050 | |||||
15051 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | ||||
15052 | if (IdxRval.isInvalid()) | ||||
15053 | return ExprError(); | ||||
15054 | Expr *Idx = IdxRval.get(); | ||||
15055 | |||||
15056 | // The expression must be an integral expression. | ||||
15057 | // FIXME: An integral constant expression? | ||||
15058 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | ||||
15059 | !Idx->getType()->isIntegerType()) | ||||
15060 | return ExprError( | ||||
15061 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | ||||
15062 | << Idx->getSourceRange()); | ||||
15063 | |||||
15064 | // Record this array index. | ||||
15065 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | ||||
15066 | Exprs.push_back(Idx); | ||||
15067 | continue; | ||||
15068 | } | ||||
15069 | |||||
15070 | // Offset of a field. | ||||
15071 | if (CurrentType->isDependentType()) { | ||||
15072 | // We have the offset of a field, but we can't look into the dependent | ||||
15073 | // type. Just record the identifier of the field. | ||||
15074 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | ||||
15075 | CurrentType = Context.DependentTy; | ||||
15076 | continue; | ||||
15077 | } | ||||
15078 | |||||
15079 | // We need to have a complete type to look into. | ||||
15080 | if (RequireCompleteType(OC.LocStart, CurrentType, | ||||
15081 | diag::err_offsetof_incomplete_type)) | ||||
15082 | return ExprError(); | ||||
15083 | |||||
15084 | // Look for the designated field. | ||||
15085 | const RecordType *RC = CurrentType->getAs<RecordType>(); | ||||
15086 | if (!RC) | ||||
15087 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | ||||
15088 | << CurrentType); | ||||
15089 | RecordDecl *RD = RC->getDecl(); | ||||
15090 | |||||
15091 | // C++ [lib.support.types]p5: | ||||
15092 | // The macro offsetof accepts a restricted set of type arguments in this | ||||
15093 | // International Standard. type shall be a POD structure or a POD union | ||||
15094 | // (clause 9). | ||||
15095 | // C++11 [support.types]p4: | ||||
15096 | // If type is not a standard-layout class (Clause 9), the results are | ||||
15097 | // undefined. | ||||
15098 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
15099 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | ||||
15100 | unsigned DiagID = | ||||
15101 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | ||||
15102 | : diag::ext_offsetof_non_pod_type; | ||||
15103 | |||||
15104 | if (!IsSafe && !DidWarnAboutNonPOD && | ||||
15105 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | ||||
15106 | PDiag(DiagID) | ||||
15107 | << SourceRange(Components[0].LocStart, OC.LocEnd) | ||||
15108 | << CurrentType)) | ||||
15109 | DidWarnAboutNonPOD = true; | ||||
15110 | } | ||||
15111 | |||||
15112 | // Look for the field. | ||||
15113 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | ||||
15114 | LookupQualifiedName(R, RD); | ||||
15115 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | ||||
15116 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | ||||
15117 | if (!MemberDecl) { | ||||
15118 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | ||||
15119 | MemberDecl = IndirectMemberDecl->getAnonField(); | ||||
15120 | } | ||||
15121 | |||||
15122 | if (!MemberDecl) | ||||
15123 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | ||||
15124 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | ||||
15125 | OC.LocEnd)); | ||||
15126 | |||||
15127 | // C99 7.17p3: | ||||
15128 | // (If the specified member is a bit-field, the behavior is undefined.) | ||||
15129 | // | ||||
15130 | // We diagnose this as an error. | ||||
15131 | if (MemberDecl->isBitField()) { | ||||
15132 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | ||||
15133 | << MemberDecl->getDeclName() | ||||
15134 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
15135 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | ||||
15136 | return ExprError(); | ||||
15137 | } | ||||
15138 | |||||
15139 | RecordDecl *Parent = MemberDecl->getParent(); | ||||
15140 | if (IndirectMemberDecl) | ||||
15141 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | ||||
15142 | |||||
15143 | // If the member was found in a base class, introduce OffsetOfNodes for | ||||
15144 | // the base class indirections. | ||||
15145 | CXXBasePaths Paths; | ||||
15146 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | ||||
15147 | Paths)) { | ||||
15148 | if (Paths.getDetectedVirtual()) { | ||||
15149 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | ||||
15150 | << MemberDecl->getDeclName() | ||||
15151 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
15152 | return ExprError(); | ||||
15153 | } | ||||
15154 | |||||
15155 | CXXBasePath &Path = Paths.front(); | ||||
15156 | for (const CXXBasePathElement &B : Path) | ||||
15157 | Comps.push_back(OffsetOfNode(B.Base)); | ||||
15158 | } | ||||
15159 | |||||
15160 | if (IndirectMemberDecl) { | ||||
15161 | for (auto *FI : IndirectMemberDecl->chain()) { | ||||
15162 | assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15162, __PRETTY_FUNCTION__)); | ||||
15163 | Comps.push_back(OffsetOfNode(OC.LocStart, | ||||
15164 | cast<FieldDecl>(FI), OC.LocEnd)); | ||||
15165 | } | ||||
15166 | } else | ||||
15167 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | ||||
15168 | |||||
15169 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
15170 | } | ||||
15171 | |||||
15172 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | ||||
15173 | Comps, Exprs, RParenLoc); | ||||
15174 | } | ||||
15175 | |||||
15176 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | ||||
15177 | SourceLocation BuiltinLoc, | ||||
15178 | SourceLocation TypeLoc, | ||||
15179 | ParsedType ParsedArgTy, | ||||
15180 | ArrayRef<OffsetOfComponent> Components, | ||||
15181 | SourceLocation RParenLoc) { | ||||
15182 | |||||
15183 | TypeSourceInfo *ArgTInfo; | ||||
15184 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | ||||
15185 | if (ArgTy.isNull()) | ||||
15186 | return ExprError(); | ||||
15187 | |||||
15188 | if (!ArgTInfo) | ||||
15189 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | ||||
15190 | |||||
15191 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | ||||
15192 | } | ||||
15193 | |||||
15194 | |||||
15195 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | ||||
15196 | Expr *CondExpr, | ||||
15197 | Expr *LHSExpr, Expr *RHSExpr, | ||||
15198 | SourceLocation RPLoc) { | ||||
15199 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? static_cast<void> (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15199, __PRETTY_FUNCTION__)); | ||||
15200 | |||||
15201 | ExprValueKind VK = VK_RValue; | ||||
15202 | ExprObjectKind OK = OK_Ordinary; | ||||
15203 | QualType resType; | ||||
15204 | bool CondIsTrue = false; | ||||
15205 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | ||||
15206 | resType = Context.DependentTy; | ||||
15207 | } else { | ||||
15208 | // The conditional expression is required to be a constant expression. | ||||
15209 | llvm::APSInt condEval(32); | ||||
15210 | ExprResult CondICE = VerifyIntegerConstantExpression( | ||||
15211 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | ||||
15212 | if (CondICE.isInvalid()) | ||||
15213 | return ExprError(); | ||||
15214 | CondExpr = CondICE.get(); | ||||
15215 | CondIsTrue = condEval.getZExtValue(); | ||||
15216 | |||||
15217 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | ||||
15218 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | ||||
15219 | |||||
15220 | resType = ActiveExpr->getType(); | ||||
15221 | VK = ActiveExpr->getValueKind(); | ||||
15222 | OK = ActiveExpr->getObjectKind(); | ||||
15223 | } | ||||
15224 | |||||
15225 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | ||||
15226 | resType, VK, OK, RPLoc, CondIsTrue); | ||||
15227 | } | ||||
15228 | |||||
15229 | //===----------------------------------------------------------------------===// | ||||
15230 | // Clang Extensions. | ||||
15231 | //===----------------------------------------------------------------------===// | ||||
15232 | |||||
15233 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | ||||
15234 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | ||||
15235 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | ||||
15236 | |||||
15237 | if (LangOpts.CPlusPlus) { | ||||
15238 | MangleNumberingContext *MCtx; | ||||
15239 | Decl *ManglingContextDecl; | ||||
15240 | std::tie(MCtx, ManglingContextDecl) = | ||||
15241 | getCurrentMangleNumberContext(Block->getDeclContext()); | ||||
15242 | if (MCtx) { | ||||
15243 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | ||||
15244 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | ||||
15245 | } | ||||
15246 | } | ||||
15247 | |||||
15248 | PushBlockScope(CurScope, Block); | ||||
15249 | CurContext->addDecl(Block); | ||||
15250 | if (CurScope) | ||||
15251 | PushDeclContext(CurScope, Block); | ||||
15252 | else | ||||
15253 | CurContext = Block; | ||||
15254 | |||||
15255 | getCurBlock()->HasImplicitReturnType = true; | ||||
15256 | |||||
15257 | // Enter a new evaluation context to insulate the block from any | ||||
15258 | // cleanups from the enclosing full-expression. | ||||
15259 | PushExpressionEvaluationContext( | ||||
15260 | ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15261 | } | ||||
15262 | |||||
15263 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | ||||
15264 | Scope *CurScope) { | ||||
15265 | assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15266, __PRETTY_FUNCTION__)) | ||||
15266 | "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15266, __PRETTY_FUNCTION__)); | ||||
15267 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)((ParamInfo.getContext() == DeclaratorContext::BlockLiteral) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15267, __PRETTY_FUNCTION__)); | ||||
15268 | BlockScopeInfo *CurBlock = getCurBlock(); | ||||
15269 | |||||
15270 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | ||||
15271 | QualType T = Sig->getType(); | ||||
15272 | |||||
15273 | // FIXME: We should allow unexpanded parameter packs here, but that would, | ||||
15274 | // in turn, make the block expression contain unexpanded parameter packs. | ||||
15275 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | ||||
15276 | // Drop the parameters. | ||||
15277 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15278 | EPI.HasTrailingReturn = false; | ||||
15279 | EPI.TypeQuals.addConst(); | ||||
15280 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | ||||
15281 | Sig = Context.getTrivialTypeSourceInfo(T); | ||||
15282 | } | ||||
15283 | |||||
15284 | // GetTypeForDeclarator always produces a function type for a block | ||||
15285 | // literal signature. Furthermore, it is always a FunctionProtoType | ||||
15286 | // unless the function was written with a typedef. | ||||
15287 | assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15288, __PRETTY_FUNCTION__)) | ||||
15288 | "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15288, __PRETTY_FUNCTION__)); | ||||
15289 | |||||
15290 | // Look for an explicit signature in that function type. | ||||
15291 | FunctionProtoTypeLoc ExplicitSignature; | ||||
15292 | |||||
15293 | if ((ExplicitSignature = Sig->getTypeLoc() | ||||
15294 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | ||||
15295 | |||||
15296 | // Check whether that explicit signature was synthesized by | ||||
15297 | // GetTypeForDeclarator. If so, don't save that as part of the | ||||
15298 | // written signature. | ||||
15299 | if (ExplicitSignature.getLocalRangeBegin() == | ||||
15300 | ExplicitSignature.getLocalRangeEnd()) { | ||||
15301 | // This would be much cheaper if we stored TypeLocs instead of | ||||
15302 | // TypeSourceInfos. | ||||
15303 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | ||||
15304 | unsigned Size = Result.getFullDataSize(); | ||||
15305 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | ||||
15306 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | ||||
15307 | |||||
15308 | ExplicitSignature = FunctionProtoTypeLoc(); | ||||
15309 | } | ||||
15310 | } | ||||
15311 | |||||
15312 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | ||||
15313 | CurBlock->FunctionType = T; | ||||
15314 | |||||
15315 | const auto *Fn = T->castAs<FunctionType>(); | ||||
15316 | QualType RetTy = Fn->getReturnType(); | ||||
15317 | bool isVariadic = | ||||
15318 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | ||||
15319 | |||||
15320 | CurBlock->TheDecl->setIsVariadic(isVariadic); | ||||
15321 | |||||
15322 | // Context.DependentTy is used as a placeholder for a missing block | ||||
15323 | // return type. TODO: what should we do with declarators like: | ||||
15324 | // ^ * { ... } | ||||
15325 | // If the answer is "apply template argument deduction".... | ||||
15326 | if (RetTy != Context.DependentTy) { | ||||
15327 | CurBlock->ReturnType = RetTy; | ||||
15328 | CurBlock->TheDecl->setBlockMissingReturnType(false); | ||||
15329 | CurBlock->HasImplicitReturnType = false; | ||||
15330 | } | ||||
15331 | |||||
15332 | // Push block parameters from the declarator if we had them. | ||||
15333 | SmallVector<ParmVarDecl*, 8> Params; | ||||
15334 | if (ExplicitSignature) { | ||||
15335 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | ||||
15336 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | ||||
15337 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | ||||
15338 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | ||||
15339 | // Diagnose this as an extension in C17 and earlier. | ||||
15340 | if (!getLangOpts().C2x) | ||||
15341 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | ||||
15342 | } | ||||
15343 | Params.push_back(Param); | ||||
15344 | } | ||||
15345 | |||||
15346 | // Fake up parameter variables if we have a typedef, like | ||||
15347 | // ^ fntype { ... } | ||||
15348 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | ||||
15349 | for (const auto &I : Fn->param_types()) { | ||||
15350 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | ||||
15351 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | ||||
15352 | Params.push_back(Param); | ||||
15353 | } | ||||
15354 | } | ||||
15355 | |||||
15356 | // Set the parameters on the block decl. | ||||
15357 | if (!Params.empty()) { | ||||
15358 | CurBlock->TheDecl->setParams(Params); | ||||
15359 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | ||||
15360 | /*CheckParameterNames=*/false); | ||||
15361 | } | ||||
15362 | |||||
15363 | // Finally we can process decl attributes. | ||||
15364 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | ||||
15365 | |||||
15366 | // Put the parameter variables in scope. | ||||
15367 | for (auto AI : CurBlock->TheDecl->parameters()) { | ||||
15368 | AI->setOwningFunction(CurBlock->TheDecl); | ||||
15369 | |||||
15370 | // If this has an identifier, add it to the scope stack. | ||||
15371 | if (AI->getIdentifier()) { | ||||
15372 | CheckShadow(CurBlock->TheScope, AI); | ||||
15373 | |||||
15374 | PushOnScopeChains(AI, CurBlock->TheScope); | ||||
15375 | } | ||||
15376 | } | ||||
15377 | } | ||||
15378 | |||||
15379 | /// ActOnBlockError - If there is an error parsing a block, this callback | ||||
15380 | /// is invoked to pop the information about the block from the action impl. | ||||
15381 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | ||||
15382 | // Leave the expression-evaluation context. | ||||
15383 | DiscardCleanupsInEvaluationContext(); | ||||
15384 | PopExpressionEvaluationContext(); | ||||
15385 | |||||
15386 | // Pop off CurBlock, handle nested blocks. | ||||
15387 | PopDeclContext(); | ||||
15388 | PopFunctionScopeInfo(); | ||||
15389 | } | ||||
15390 | |||||
15391 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | ||||
15392 | /// literal was successfully completed. ^(int x){...} | ||||
15393 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | ||||
15394 | Stmt *Body, Scope *CurScope) { | ||||
15395 | // If blocks are disabled, emit an error. | ||||
15396 | if (!LangOpts.Blocks) | ||||
15397 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||
15398 | |||||
15399 | // Leave the expression-evaluation context. | ||||
15400 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
15401 | DiscardCleanupsInEvaluationContext(); | ||||
15402 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15403, __PRETTY_FUNCTION__)) | ||||
15403 | "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15403, __PRETTY_FUNCTION__)); | ||||
15404 | PopExpressionEvaluationContext(); | ||||
15405 | |||||
15406 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | ||||
15407 | BlockDecl *BD = BSI->TheDecl; | ||||
15408 | |||||
15409 | if (BSI->HasImplicitReturnType) | ||||
15410 | deduceClosureReturnType(*BSI); | ||||
15411 | |||||
15412 | QualType RetTy = Context.VoidTy; | ||||
15413 | if (!BSI->ReturnType.isNull()) | ||||
15414 | RetTy = BSI->ReturnType; | ||||
15415 | |||||
15416 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | ||||
15417 | QualType BlockTy; | ||||
15418 | |||||
15419 | // If the user wrote a function type in some form, try to use that. | ||||
15420 | if (!BSI->FunctionType.isNull()) { | ||||
15421 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | ||||
15422 | |||||
15423 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | ||||
15424 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | ||||
15425 | |||||
15426 | // Turn protoless block types into nullary block types. | ||||
15427 | if (isa<FunctionNoProtoType>(FTy)) { | ||||
15428 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15429 | EPI.ExtInfo = Ext; | ||||
15430 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
15431 | |||||
15432 | // Otherwise, if we don't need to change anything about the function type, | ||||
15433 | // preserve its sugar structure. | ||||
15434 | } else if (FTy->getReturnType() == RetTy && | ||||
15435 | (!NoReturn || FTy->getNoReturnAttr())) { | ||||
15436 | BlockTy = BSI->FunctionType; | ||||
15437 | |||||
15438 | // Otherwise, make the minimal modifications to the function type. | ||||
15439 | } else { | ||||
15440 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | ||||
15441 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
15442 | EPI.TypeQuals = Qualifiers(); | ||||
15443 | EPI.ExtInfo = Ext; | ||||
15444 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | ||||
15445 | } | ||||
15446 | |||||
15447 | // If we don't have a function type, just build one from nothing. | ||||
15448 | } else { | ||||
15449 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15450 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | ||||
15451 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
15452 | } | ||||
15453 | |||||
15454 | DiagnoseUnusedParameters(BD->parameters()); | ||||
15455 | BlockTy = Context.getBlockPointerType(BlockTy); | ||||
15456 | |||||
15457 | // If needed, diagnose invalid gotos and switches in the block. | ||||
15458 | if (getCurFunction()->NeedsScopeChecking() && | ||||
15459 | !PP.isCodeCompletionEnabled()) | ||||
15460 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | ||||
15461 | |||||
15462 | BD->setBody(cast<CompoundStmt>(Body)); | ||||
15463 | |||||
15464 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||
15465 | DiagnoseUnguardedAvailabilityViolations(BD); | ||||
15466 | |||||
15467 | // Try to apply the named return value optimization. We have to check again | ||||
15468 | // if we can do this, though, because blocks keep return statements around | ||||
15469 | // to deduce an implicit return type. | ||||
15470 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | ||||
15471 | !BD->isDependentContext()) | ||||
15472 | computeNRVO(Body, BSI); | ||||
15473 | |||||
15474 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | ||||
15475 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
15476 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | ||||
15477 | NTCUK_Destruct|NTCUK_Copy); | ||||
15478 | |||||
15479 | PopDeclContext(); | ||||
15480 | |||||
15481 | // Set the captured variables on the block. | ||||
15482 | SmallVector<BlockDecl::Capture, 4> Captures; | ||||
15483 | for (Capture &Cap : BSI->Captures) { | ||||
15484 | if (Cap.isInvalid() || Cap.isThisCapture()) | ||||
15485 | continue; | ||||
15486 | |||||
15487 | VarDecl *Var = Cap.getVariable(); | ||||
15488 | Expr *CopyExpr = nullptr; | ||||
15489 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | ||||
15490 | if (const RecordType *Record = | ||||
15491 | Cap.getCaptureType()->getAs<RecordType>()) { | ||||
15492 | // The capture logic needs the destructor, so make sure we mark it. | ||||
15493 | // Usually this is unnecessary because most local variables have | ||||
15494 | // their destructors marked at declaration time, but parameters are | ||||
15495 | // an exception because it's technically only the call site that | ||||
15496 | // actually requires the destructor. | ||||
15497 | if (isa<ParmVarDecl>(Var)) | ||||
15498 | FinalizeVarWithDestructor(Var, Record); | ||||
15499 | |||||
15500 | // Enter a separate potentially-evaluated context while building block | ||||
15501 | // initializers to isolate their cleanups from those of the block | ||||
15502 | // itself. | ||||
15503 | // FIXME: Is this appropriate even when the block itself occurs in an | ||||
15504 | // unevaluated operand? | ||||
15505 | EnterExpressionEvaluationContext EvalContext( | ||||
15506 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15507 | |||||
15508 | SourceLocation Loc = Cap.getLocation(); | ||||
15509 | |||||
15510 | ExprResult Result = BuildDeclarationNameExpr( | ||||
15511 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | ||||
15512 | |||||
15513 | // According to the blocks spec, the capture of a variable from | ||||
15514 | // the stack requires a const copy constructor. This is not true | ||||
15515 | // of the copy/move done to move a __block variable to the heap. | ||||
15516 | if (!Result.isInvalid() && | ||||
15517 | !Result.get()->getType().isConstQualified()) { | ||||
15518 | Result = ImpCastExprToType(Result.get(), | ||||
15519 | Result.get()->getType().withConst(), | ||||
15520 | CK_NoOp, VK_LValue); | ||||
15521 | } | ||||
15522 | |||||
15523 | if (!Result.isInvalid()) { | ||||
15524 | Result = PerformCopyInitialization( | ||||
15525 | InitializedEntity::InitializeBlock(Var->getLocation(), | ||||
15526 | Cap.getCaptureType(), false), | ||||
15527 | Loc, Result.get()); | ||||
15528 | } | ||||
15529 | |||||
15530 | // Build a full-expression copy expression if initialization | ||||
15531 | // succeeded and used a non-trivial constructor. Recover from | ||||
15532 | // errors by pretending that the copy isn't necessary. | ||||
15533 | if (!Result.isInvalid() && | ||||
15534 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | ||||
15535 | ->isTrivial()) { | ||||
15536 | Result = MaybeCreateExprWithCleanups(Result); | ||||
15537 | CopyExpr = Result.get(); | ||||
15538 | } | ||||
15539 | } | ||||
15540 | } | ||||
15541 | |||||
15542 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | ||||
15543 | CopyExpr); | ||||
15544 | Captures.push_back(NewCap); | ||||
15545 | } | ||||
15546 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | ||||
15547 | |||||
15548 | // Pop the block scope now but keep it alive to the end of this function. | ||||
15549 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||
15550 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | ||||
15551 | |||||
15552 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | ||||
15553 | |||||
15554 | // If the block isn't obviously global, i.e. it captures anything at | ||||
15555 | // all, then we need to do a few things in the surrounding context: | ||||
15556 | if (Result->getBlockDecl()->hasCaptures()) { | ||||
15557 | // First, this expression has a new cleanup object. | ||||
15558 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | ||||
15559 | Cleanup.setExprNeedsCleanups(true); | ||||
15560 | |||||
15561 | // It also gets a branch-protected scope if any of the captured | ||||
15562 | // variables needs destruction. | ||||
15563 | for (const auto &CI : Result->getBlockDecl()->captures()) { | ||||
15564 | const VarDecl *var = CI.getVariable(); | ||||
15565 | if (var->getType().isDestructedType() != QualType::DK_none) { | ||||
15566 | setFunctionHasBranchProtectedScope(); | ||||
15567 | break; | ||||
15568 | } | ||||
15569 | } | ||||
15570 | } | ||||
15571 | |||||
15572 | if (getCurFunction()) | ||||
15573 | getCurFunction()->addBlock(BD); | ||||
15574 | |||||
15575 | return Result; | ||||
15576 | } | ||||
15577 | |||||
15578 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | ||||
15579 | SourceLocation RPLoc) { | ||||
15580 | TypeSourceInfo *TInfo; | ||||
15581 | GetTypeFromParser(Ty, &TInfo); | ||||
15582 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | ||||
15583 | } | ||||
15584 | |||||
15585 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | ||||
15586 | Expr *E, TypeSourceInfo *TInfo, | ||||
15587 | SourceLocation RPLoc) { | ||||
15588 | Expr *OrigExpr = E; | ||||
15589 | bool IsMS = false; | ||||
15590 | |||||
15591 | // CUDA device code does not support varargs. | ||||
15592 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | ||||
15593 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | ||||
15594 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | ||||
15595 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | ||||
15596 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | ||||
15597 | } | ||||
15598 | } | ||||
15599 | |||||
15600 | // NVPTX does not support va_arg expression. | ||||
15601 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | ||||
15602 | Context.getTargetInfo().getTriple().isNVPTX()) | ||||
15603 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | ||||
15604 | |||||
15605 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | ||||
15606 | // as Microsoft ABI on an actual Microsoft platform, where | ||||
15607 | // __builtin_ms_va_list and __builtin_va_list are the same.) | ||||
15608 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | ||||
15609 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | ||||
15610 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | ||||
15611 | if (Context.hasSameType(MSVaListType, E->getType())) { | ||||
15612 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
15613 | return ExprError(); | ||||
15614 | IsMS = true; | ||||
15615 | } | ||||
15616 | } | ||||
15617 | |||||
15618 | // Get the va_list type | ||||
15619 | QualType VaListType = Context.getBuiltinVaListType(); | ||||
15620 | if (!IsMS) { | ||||
15621 | if (VaListType->isArrayType()) { | ||||
15622 | // Deal with implicit array decay; for example, on x86-64, | ||||
15623 | // va_list is an array, but it's supposed to decay to | ||||
15624 | // a pointer for va_arg. | ||||
15625 | VaListType = Context.getArrayDecayedType(VaListType); | ||||
15626 | // Make sure the input expression also decays appropriately. | ||||
15627 | ExprResult Result = UsualUnaryConversions(E); | ||||
15628 | if (Result.isInvalid()) | ||||
15629 | return ExprError(); | ||||
15630 | E = Result.get(); | ||||
15631 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | ||||
15632 | // If va_list is a record type and we are compiling in C++ mode, | ||||
15633 | // check the argument using reference binding. | ||||
15634 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
15635 | Context, Context.getLValueReferenceType(VaListType), false); | ||||
15636 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | ||||
15637 | if (Init.isInvalid()) | ||||
15638 | return ExprError(); | ||||
15639 | E = Init.getAs<Expr>(); | ||||
15640 | } else { | ||||
15641 | // Otherwise, the va_list argument must be an l-value because | ||||
15642 | // it is modified by va_arg. | ||||
15643 | if (!E->isTypeDependent() && | ||||
15644 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
15645 | return ExprError(); | ||||
15646 | } | ||||
15647 | } | ||||
15648 | |||||
15649 | if (!IsMS && !E->isTypeDependent() && | ||||
15650 | !Context.hasSameType(VaListType, E->getType())) | ||||
15651 | return ExprError( | ||||
15652 | Diag(E->getBeginLoc(), | ||||
15653 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | ||||
15654 | << OrigExpr->getType() << E->getSourceRange()); | ||||
15655 | |||||
15656 | if (!TInfo->getType()->isDependentType()) { | ||||
15657 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | ||||
15658 | diag::err_second_parameter_to_va_arg_incomplete, | ||||
15659 | TInfo->getTypeLoc())) | ||||
15660 | return ExprError(); | ||||
15661 | |||||
15662 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | ||||
15663 | TInfo->getType(), | ||||
15664 | diag::err_second_parameter_to_va_arg_abstract, | ||||
15665 | TInfo->getTypeLoc())) | ||||
15666 | return ExprError(); | ||||
15667 | |||||
15668 | if (!TInfo->getType().isPODType(Context)) { | ||||
15669 | Diag(TInfo->getTypeLoc().getBeginLoc(), | ||||
15670 | TInfo->getType()->isObjCLifetimeType() | ||||
15671 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | ||||
15672 | : diag::warn_second_parameter_to_va_arg_not_pod) | ||||
15673 | << TInfo->getType() | ||||
15674 | << TInfo->getTypeLoc().getSourceRange(); | ||||
15675 | } | ||||
15676 | |||||
15677 | // Check for va_arg where arguments of the given type will be promoted | ||||
15678 | // (i.e. this va_arg is guaranteed to have undefined behavior). | ||||
15679 | QualType PromoteType; | ||||
15680 | if (TInfo->getType()->isPromotableIntegerType()) { | ||||
15681 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | ||||
15682 | if (Context.typesAreCompatible(PromoteType, TInfo->getType())) | ||||
15683 | PromoteType = QualType(); | ||||
15684 | } | ||||
15685 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | ||||
15686 | PromoteType = Context.DoubleTy; | ||||
15687 | if (!PromoteType.isNull()) | ||||
15688 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | ||||
15689 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | ||||
15690 | << TInfo->getType() | ||||
15691 | << PromoteType | ||||
15692 | << TInfo->getTypeLoc().getSourceRange()); | ||||
15693 | } | ||||
15694 | |||||
15695 | QualType T = TInfo->getType().getNonLValueExprType(Context); | ||||
15696 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | ||||
15697 | } | ||||
15698 | |||||
15699 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | ||||
15700 | // The type of __null will be int or long, depending on the size of | ||||
15701 | // pointers on the target. | ||||
15702 | QualType Ty; | ||||
15703 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | ||||
15704 | if (pw == Context.getTargetInfo().getIntWidth()) | ||||
15705 | Ty = Context.IntTy; | ||||
15706 | else if (pw == Context.getTargetInfo().getLongWidth()) | ||||
15707 | Ty = Context.LongTy; | ||||
15708 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | ||||
15709 | Ty = Context.LongLongTy; | ||||
15710 | else { | ||||
15711 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15711); | ||||
15712 | } | ||||
15713 | |||||
15714 | return new (Context) GNUNullExpr(Ty, TokenLoc); | ||||
15715 | } | ||||
15716 | |||||
15717 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
15718 | SourceLocation BuiltinLoc, | ||||
15719 | SourceLocation RPLoc) { | ||||
15720 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); | ||||
15721 | } | ||||
15722 | |||||
15723 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
15724 | SourceLocation BuiltinLoc, | ||||
15725 | SourceLocation RPLoc, | ||||
15726 | DeclContext *ParentContext) { | ||||
15727 | return new (Context) | ||||
15728 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); | ||||
15729 | } | ||||
15730 | |||||
15731 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | ||||
15732 | bool Diagnose) { | ||||
15733 | if (!getLangOpts().ObjC) | ||||
15734 | return false; | ||||
15735 | |||||
15736 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | ||||
15737 | if (!PT) | ||||
15738 | return false; | ||||
15739 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | ||||
15740 | |||||
15741 | // Ignore any parens, implicit casts (should only be | ||||
15742 | // array-to-pointer decays), and not-so-opaque values. The last is | ||||
15743 | // important for making this trigger for property assignments. | ||||
15744 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | ||||
15745 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | ||||
15746 | if (OV->getSourceExpr()) | ||||
15747 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | ||||
15748 | |||||
15749 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | ||||
15750 | if (!PT->isObjCIdType() && | ||||
15751 | !(ID && ID->getIdentifier()->isStr("NSString"))) | ||||
15752 | return false; | ||||
15753 | if (!SL->isAscii()) | ||||
15754 | return false; | ||||
15755 | |||||
15756 | if (Diagnose) { | ||||
15757 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
15758 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | ||||
15759 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | ||||
15760 | } | ||||
15761 | return true; | ||||
15762 | } | ||||
15763 | |||||
15764 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | ||||
15765 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | ||||
15766 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | ||||
15767 | !SrcExpr->isNullPointerConstant( | ||||
15768 | getASTContext(), Expr::NPC_NeverValueDependent)) { | ||||
15769 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | ||||
15770 | return false; | ||||
15771 | if (Diagnose) { | ||||
15772 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
15773 | << /*number*/1 | ||||
15774 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | ||||
15775 | Expr *NumLit = | ||||
15776 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | ||||
15777 | if (NumLit) | ||||
15778 | Exp = NumLit; | ||||
15779 | } | ||||
15780 | return true; | ||||
15781 | } | ||||
15782 | |||||
15783 | return false; | ||||
15784 | } | ||||
15785 | |||||
15786 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | ||||
15787 | const Expr *SrcExpr) { | ||||
15788 | if (!DstType->isFunctionPointerType() || | ||||
15789 | !SrcExpr->getType()->isFunctionType()) | ||||
15790 | return false; | ||||
15791 | |||||
15792 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | ||||
15793 | if (!DRE) | ||||
15794 | return false; | ||||
15795 | |||||
15796 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||
15797 | if (!FD) | ||||
15798 | return false; | ||||
15799 | |||||
15800 | return !S.checkAddressOfFunctionIsAvailable(FD, | ||||
15801 | /*Complain=*/true, | ||||
15802 | SrcExpr->getBeginLoc()); | ||||
15803 | } | ||||
15804 | |||||
15805 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | ||||
15806 | SourceLocation Loc, | ||||
15807 | QualType DstType, QualType SrcType, | ||||
15808 | Expr *SrcExpr, AssignmentAction Action, | ||||
15809 | bool *Complained) { | ||||
15810 | if (Complained) | ||||
15811 | *Complained = false; | ||||
15812 | |||||
15813 | // Decode the result (notice that AST's are still created for extensions). | ||||
15814 | bool CheckInferredResultType = false; | ||||
15815 | bool isInvalid = false; | ||||
15816 | unsigned DiagKind = 0; | ||||
15817 | ConversionFixItGenerator ConvHints; | ||||
15818 | bool MayHaveConvFixit = false; | ||||
15819 | bool MayHaveFunctionDiff = false; | ||||
15820 | const ObjCInterfaceDecl *IFace = nullptr; | ||||
15821 | const ObjCProtocolDecl *PDecl = nullptr; | ||||
15822 | |||||
15823 | switch (ConvTy) { | ||||
15824 | case Compatible: | ||||
15825 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | ||||
15826 | return false; | ||||
15827 | |||||
15828 | case PointerToInt: | ||||
15829 | if (getLangOpts().CPlusPlus) { | ||||
15830 | DiagKind = diag::err_typecheck_convert_pointer_int; | ||||
15831 | isInvalid = true; | ||||
15832 | } else { | ||||
15833 | DiagKind = diag::ext_typecheck_convert_pointer_int; | ||||
15834 | } | ||||
15835 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15836 | MayHaveConvFixit = true; | ||||
15837 | break; | ||||
15838 | case IntToPointer: | ||||
15839 | if (getLangOpts().CPlusPlus) { | ||||
15840 | DiagKind = diag::err_typecheck_convert_int_pointer; | ||||
15841 | isInvalid = true; | ||||
15842 | } else { | ||||
15843 | DiagKind = diag::ext_typecheck_convert_int_pointer; | ||||
15844 | } | ||||
15845 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15846 | MayHaveConvFixit = true; | ||||
15847 | break; | ||||
15848 | case IncompatibleFunctionPointer: | ||||
15849 | if (getLangOpts().CPlusPlus) { | ||||
15850 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | ||||
15851 | isInvalid = true; | ||||
15852 | } else { | ||||
15853 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | ||||
15854 | } | ||||
15855 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15856 | MayHaveConvFixit = true; | ||||
15857 | break; | ||||
15858 | case IncompatiblePointer: | ||||
15859 | if (Action == AA_Passing_CFAudited) { | ||||
15860 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | ||||
15861 | } else if (getLangOpts().CPlusPlus) { | ||||
15862 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | ||||
15863 | isInvalid = true; | ||||
15864 | } else { | ||||
15865 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | ||||
15866 | } | ||||
15867 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | ||||
15868 | SrcType->isObjCObjectPointerType(); | ||||
15869 | if (!CheckInferredResultType) { | ||||
15870 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15871 | } else if (CheckInferredResultType) { | ||||
15872 | SrcType = SrcType.getUnqualifiedType(); | ||||
15873 | DstType = DstType.getUnqualifiedType(); | ||||
15874 | } | ||||
15875 | MayHaveConvFixit = true; | ||||
15876 | break; | ||||
15877 | case IncompatiblePointerSign: | ||||
15878 | if (getLangOpts().CPlusPlus) { | ||||
15879 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | ||||
15880 | isInvalid = true; | ||||
15881 | } else { | ||||
15882 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | ||||
15883 | } | ||||
15884 | break; | ||||
15885 | case FunctionVoidPointer: | ||||
15886 | if (getLangOpts().CPlusPlus) { | ||||
15887 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | ||||
15888 | isInvalid = true; | ||||
15889 | } else { | ||||
15890 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | ||||
15891 | } | ||||
15892 | break; | ||||
15893 | case IncompatiblePointerDiscardsQualifiers: { | ||||
15894 | // Perform array-to-pointer decay if necessary. | ||||
15895 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | ||||
15896 | |||||
15897 | isInvalid = true; | ||||
15898 | |||||
15899 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | ||||
15900 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | ||||
15901 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | ||||
15902 | DiagKind = diag::err_typecheck_incompatible_address_space; | ||||
15903 | break; | ||||
15904 | |||||
15905 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | ||||
15906 | DiagKind = diag::err_typecheck_incompatible_ownership; | ||||
15907 | break; | ||||
15908 | } | ||||
15909 | |||||
15910 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 15910); | ||||
15911 | // fallthrough | ||||
15912 | } | ||||
15913 | case CompatiblePointerDiscardsQualifiers: | ||||
15914 | // If the qualifiers lost were because we were applying the | ||||
15915 | // (deprecated) C++ conversion from a string literal to a char* | ||||
15916 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | ||||
15917 | // Ideally, this check would be performed in | ||||
15918 | // checkPointerTypesForAssignment. However, that would require a | ||||
15919 | // bit of refactoring (so that the second argument is an | ||||
15920 | // expression, rather than a type), which should be done as part | ||||
15921 | // of a larger effort to fix checkPointerTypesForAssignment for | ||||
15922 | // C++ semantics. | ||||
15923 | if (getLangOpts().CPlusPlus && | ||||
15924 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | ||||
15925 | return false; | ||||
15926 | if (getLangOpts().CPlusPlus) { | ||||
15927 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | ||||
15928 | isInvalid = true; | ||||
15929 | } else { | ||||
15930 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | ||||
15931 | } | ||||
15932 | |||||
15933 | break; | ||||
15934 | case IncompatibleNestedPointerQualifiers: | ||||
15935 | if (getLangOpts().CPlusPlus) { | ||||
15936 | isInvalid = true; | ||||
15937 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | ||||
15938 | } else { | ||||
15939 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | ||||
15940 | } | ||||
15941 | break; | ||||
15942 | case IncompatibleNestedPointerAddressSpaceMismatch: | ||||
15943 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | ||||
15944 | isInvalid = true; | ||||
15945 | break; | ||||
15946 | case IntToBlockPointer: | ||||
15947 | DiagKind = diag::err_int_to_block_pointer; | ||||
15948 | isInvalid = true; | ||||
15949 | break; | ||||
15950 | case IncompatibleBlockPointer: | ||||
15951 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | ||||
15952 | isInvalid = true; | ||||
15953 | break; | ||||
15954 | case IncompatibleObjCQualifiedId: { | ||||
15955 | if (SrcType->isObjCQualifiedIdType()) { | ||||
15956 | const ObjCObjectPointerType *srcOPT = | ||||
15957 | SrcType->castAs<ObjCObjectPointerType>(); | ||||
15958 | for (auto *srcProto : srcOPT->quals()) { | ||||
15959 | PDecl = srcProto; | ||||
15960 | break; | ||||
15961 | } | ||||
15962 | if (const ObjCInterfaceType *IFaceT = | ||||
15963 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
15964 | IFace = IFaceT->getDecl(); | ||||
15965 | } | ||||
15966 | else if (DstType->isObjCQualifiedIdType()) { | ||||
15967 | const ObjCObjectPointerType *dstOPT = | ||||
15968 | DstType->castAs<ObjCObjectPointerType>(); | ||||
15969 | for (auto *dstProto : dstOPT->quals()) { | ||||
15970 | PDecl = dstProto; | ||||
15971 | break; | ||||
15972 | } | ||||
15973 | if (const ObjCInterfaceType *IFaceT = | ||||
15974 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
15975 | IFace = IFaceT->getDecl(); | ||||
15976 | } | ||||
15977 | if (getLangOpts().CPlusPlus) { | ||||
15978 | DiagKind = diag::err_incompatible_qualified_id; | ||||
15979 | isInvalid = true; | ||||
15980 | } else { | ||||
15981 | DiagKind = diag::warn_incompatible_qualified_id; | ||||
15982 | } | ||||
15983 | break; | ||||
15984 | } | ||||
15985 | case IncompatibleVectors: | ||||
15986 | if (getLangOpts().CPlusPlus) { | ||||
15987 | DiagKind = diag::err_incompatible_vectors; | ||||
15988 | isInvalid = true; | ||||
15989 | } else { | ||||
15990 | DiagKind = diag::warn_incompatible_vectors; | ||||
15991 | } | ||||
15992 | break; | ||||
15993 | case IncompatibleObjCWeakRef: | ||||
15994 | DiagKind = diag::err_arc_weak_unavailable_assign; | ||||
15995 | isInvalid = true; | ||||
15996 | break; | ||||
15997 | case Incompatible: | ||||
15998 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | ||||
15999 | if (Complained) | ||||
16000 | *Complained = true; | ||||
16001 | return true; | ||||
16002 | } | ||||
16003 | |||||
16004 | DiagKind = diag::err_typecheck_convert_incompatible; | ||||
16005 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16006 | MayHaveConvFixit = true; | ||||
16007 | isInvalid = true; | ||||
16008 | MayHaveFunctionDiff = true; | ||||
16009 | break; | ||||
16010 | } | ||||
16011 | |||||
16012 | QualType FirstType, SecondType; | ||||
16013 | switch (Action) { | ||||
16014 | case AA_Assigning: | ||||
16015 | case AA_Initializing: | ||||
16016 | // The destination type comes first. | ||||
16017 | FirstType = DstType; | ||||
16018 | SecondType = SrcType; | ||||
16019 | break; | ||||
16020 | |||||
16021 | case AA_Returning: | ||||
16022 | case AA_Passing: | ||||
16023 | case AA_Passing_CFAudited: | ||||
16024 | case AA_Converting: | ||||
16025 | case AA_Sending: | ||||
16026 | case AA_Casting: | ||||
16027 | // The source type comes first. | ||||
16028 | FirstType = SrcType; | ||||
16029 | SecondType = DstType; | ||||
16030 | break; | ||||
16031 | } | ||||
16032 | |||||
16033 | PartialDiagnostic FDiag = PDiag(DiagKind); | ||||
16034 | if (Action == AA_Passing_CFAudited) | ||||
16035 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | ||||
16036 | else | ||||
16037 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | ||||
16038 | |||||
16039 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || | ||||
16040 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { | ||||
16041 | auto isPlainChar = [](const clang::Type *Type) { | ||||
16042 | return Type->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
16043 | Type->isSpecificBuiltinType(BuiltinType::Char_U); | ||||
16044 | }; | ||||
16045 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || | ||||
16046 | isPlainChar(SecondType->getPointeeOrArrayElementType())); | ||||
16047 | } | ||||
16048 | |||||
16049 | // If we can fix the conversion, suggest the FixIts. | ||||
16050 | if (!ConvHints.isNull()) { | ||||
16051 | for (FixItHint &H : ConvHints.Hints) | ||||
16052 | FDiag << H; | ||||
16053 | } | ||||
16054 | |||||
16055 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | ||||
16056 | |||||
16057 | if (MayHaveFunctionDiff) | ||||
16058 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | ||||
16059 | |||||
16060 | Diag(Loc, FDiag); | ||||
16061 | if ((DiagKind == diag::warn_incompatible_qualified_id || | ||||
16062 | DiagKind == diag::err_incompatible_qualified_id) && | ||||
16063 | PDecl && IFace && !IFace->hasDefinition()) | ||||
16064 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | ||||
16065 | << IFace << PDecl; | ||||
16066 | |||||
16067 | if (SecondType == Context.OverloadTy) | ||||
16068 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | ||||
16069 | FirstType, /*TakingAddress=*/true); | ||||
16070 | |||||
16071 | if (CheckInferredResultType) | ||||
16072 | EmitRelatedResultTypeNote(SrcExpr); | ||||
16073 | |||||
16074 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | ||||
16075 | EmitRelatedResultTypeNoteForReturn(DstType); | ||||
16076 | |||||
16077 | if (Complained) | ||||
16078 | *Complained = true; | ||||
16079 | return isInvalid; | ||||
16080 | } | ||||
16081 | |||||
16082 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
16083 | llvm::APSInt *Result, | ||||
16084 | AllowFoldKind CanFold) { | ||||
16085 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | ||||
16086 | public: | ||||
16087 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
16088 | QualType T) override { | ||||
16089 | return S.Diag(Loc, diag::err_ice_not_integral) | ||||
16090 | << T << S.LangOpts.CPlusPlus; | ||||
16091 | } | ||||
16092 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
16093 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
16094 | } | ||||
16095 | } Diagnoser; | ||||
16096 | |||||
16097 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
16098 | } | ||||
16099 | |||||
16100 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
16101 | llvm::APSInt *Result, | ||||
16102 | unsigned DiagID, | ||||
16103 | AllowFoldKind CanFold) { | ||||
16104 | class IDDiagnoser : public VerifyICEDiagnoser { | ||||
16105 | unsigned DiagID; | ||||
16106 | |||||
16107 | public: | ||||
16108 | IDDiagnoser(unsigned DiagID) | ||||
16109 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | ||||
16110 | |||||
16111 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
16112 | return S.Diag(Loc, DiagID); | ||||
16113 | } | ||||
16114 | } Diagnoser(DiagID); | ||||
16115 | |||||
16116 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
16117 | } | ||||
16118 | |||||
16119 | Sema::SemaDiagnosticBuilder | ||||
16120 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
16121 | QualType T) { | ||||
16122 | return diagnoseNotICE(S, Loc); | ||||
16123 | } | ||||
16124 | |||||
16125 | Sema::SemaDiagnosticBuilder | ||||
16126 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | ||||
16127 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
16128 | } | ||||
16129 | |||||
16130 | ExprResult | ||||
16131 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | ||||
16132 | VerifyICEDiagnoser &Diagnoser, | ||||
16133 | AllowFoldKind CanFold) { | ||||
16134 | SourceLocation DiagLoc = E->getBeginLoc(); | ||||
16135 | |||||
16136 | if (getLangOpts().CPlusPlus11) { | ||||
16137 | // C++11 [expr.const]p5: | ||||
16138 | // If an expression of literal class type is used in a context where an | ||||
16139 | // integral constant expression is required, then that class type shall | ||||
16140 | // have a single non-explicit conversion function to an integral or | ||||
16141 | // unscoped enumeration type | ||||
16142 | ExprResult Converted; | ||||
16143 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | ||||
16144 | VerifyICEDiagnoser &BaseDiagnoser; | ||||
16145 | public: | ||||
16146 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | ||||
16147 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | ||||
16148 | BaseDiagnoser.Suppress, true), | ||||
16149 | BaseDiagnoser(BaseDiagnoser) {} | ||||
16150 | |||||
16151 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | ||||
16152 | QualType T) override { | ||||
16153 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | ||||
16154 | } | ||||
16155 | |||||
16156 | SemaDiagnosticBuilder diagnoseIncomplete( | ||||
16157 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
16158 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | ||||
16159 | } | ||||
16160 | |||||
16161 | SemaDiagnosticBuilder diagnoseExplicitConv( | ||||
16162 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
16163 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | ||||
16164 | } | ||||
16165 | |||||
16166 | SemaDiagnosticBuilder noteExplicitConv( | ||||
16167 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
16168 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
16169 | << ConvTy->isEnumeralType() << ConvTy; | ||||
16170 | } | ||||
16171 | |||||
16172 | SemaDiagnosticBuilder diagnoseAmbiguous( | ||||
16173 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
16174 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | ||||
16175 | } | ||||
16176 | |||||
16177 | SemaDiagnosticBuilder noteAmbiguous( | ||||
16178 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
16179 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
16180 | << ConvTy->isEnumeralType() << ConvTy; | ||||
16181 | } | ||||
16182 | |||||
16183 | SemaDiagnosticBuilder diagnoseConversion( | ||||
16184 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
16185 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16185); | ||||
16186 | } | ||||
16187 | } ConvertDiagnoser(Diagnoser); | ||||
16188 | |||||
16189 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | ||||
16190 | ConvertDiagnoser); | ||||
16191 | if (Converted.isInvalid()) | ||||
16192 | return Converted; | ||||
16193 | E = Converted.get(); | ||||
16194 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | ||||
16195 | return ExprError(); | ||||
16196 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
16197 | // An ICE must be of integral or unscoped enumeration type. | ||||
16198 | if (!Diagnoser.Suppress) | ||||
16199 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | ||||
16200 | << E->getSourceRange(); | ||||
16201 | return ExprError(); | ||||
16202 | } | ||||
16203 | |||||
16204 | ExprResult RValueExpr = DefaultLvalueConversion(E); | ||||
16205 | if (RValueExpr.isInvalid()) | ||||
16206 | return ExprError(); | ||||
16207 | |||||
16208 | E = RValueExpr.get(); | ||||
16209 | |||||
16210 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | ||||
16211 | // in the non-ICE case. | ||||
16212 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | ||||
16213 | if (Result) | ||||
16214 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | ||||
16215 | if (!isa<ConstantExpr>(E)) | ||||
16216 | E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) | ||||
16217 | : ConstantExpr::Create(Context, E); | ||||
16218 | return E; | ||||
16219 | } | ||||
16220 | |||||
16221 | Expr::EvalResult EvalResult; | ||||
16222 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
16223 | EvalResult.Diag = &Notes; | ||||
16224 | |||||
16225 | // Try to evaluate the expression, and produce diagnostics explaining why it's | ||||
16226 | // not a constant expression as a side-effect. | ||||
16227 | bool Folded = | ||||
16228 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | ||||
16229 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | ||||
16230 | |||||
16231 | if (!isa<ConstantExpr>(E)) | ||||
16232 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | ||||
16233 | |||||
16234 | // In C++11, we can rely on diagnostics being produced for any expression | ||||
16235 | // which is not a constant expression. If no diagnostics were produced, then | ||||
16236 | // this is a constant expression. | ||||
16237 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | ||||
16238 | if (Result) | ||||
16239 | *Result = EvalResult.Val.getInt(); | ||||
16240 | return E; | ||||
16241 | } | ||||
16242 | |||||
16243 | // If our only note is the usual "invalid subexpression" note, just point | ||||
16244 | // the caret at its location rather than producing an essentially | ||||
16245 | // redundant note. | ||||
16246 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||
16247 | diag::note_invalid_subexpr_in_const_expr) { | ||||
16248 | DiagLoc = Notes[0].first; | ||||
16249 | Notes.clear(); | ||||
16250 | } | ||||
16251 | |||||
16252 | if (!Folded || !CanFold) { | ||||
16253 | if (!Diagnoser.Suppress) { | ||||
16254 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | ||||
16255 | for (const PartialDiagnosticAt &Note : Notes) | ||||
16256 | Diag(Note.first, Note.second); | ||||
16257 | } | ||||
16258 | |||||
16259 | return ExprError(); | ||||
16260 | } | ||||
16261 | |||||
16262 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | ||||
16263 | for (const PartialDiagnosticAt &Note : Notes) | ||||
16264 | Diag(Note.first, Note.second); | ||||
16265 | |||||
16266 | if (Result) | ||||
16267 | *Result = EvalResult.Val.getInt(); | ||||
16268 | return E; | ||||
16269 | } | ||||
16270 | |||||
16271 | namespace { | ||||
16272 | // Handle the case where we conclude a expression which we speculatively | ||||
16273 | // considered to be unevaluated is actually evaluated. | ||||
16274 | class TransformToPE : public TreeTransform<TransformToPE> { | ||||
16275 | typedef TreeTransform<TransformToPE> BaseTransform; | ||||
16276 | |||||
16277 | public: | ||||
16278 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | ||||
16279 | |||||
16280 | // Make sure we redo semantic analysis | ||||
16281 | bool AlwaysRebuild() { return true; } | ||||
16282 | bool ReplacingOriginal() { return true; } | ||||
16283 | |||||
16284 | // We need to special-case DeclRefExprs referring to FieldDecls which | ||||
16285 | // are not part of a member pointer formation; normal TreeTransforming | ||||
16286 | // doesn't catch this case because of the way we represent them in the AST. | ||||
16287 | // FIXME: This is a bit ugly; is it really the best way to handle this | ||||
16288 | // case? | ||||
16289 | // | ||||
16290 | // Error on DeclRefExprs referring to FieldDecls. | ||||
16291 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
16292 | if (isa<FieldDecl>(E->getDecl()) && | ||||
16293 | !SemaRef.isUnevaluatedContext()) | ||||
16294 | return SemaRef.Diag(E->getLocation(), | ||||
16295 | diag::err_invalid_non_static_member_use) | ||||
16296 | << E->getDecl() << E->getSourceRange(); | ||||
16297 | |||||
16298 | return BaseTransform::TransformDeclRefExpr(E); | ||||
16299 | } | ||||
16300 | |||||
16301 | // Exception: filter out member pointer formation | ||||
16302 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | ||||
16303 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | ||||
16304 | return E; | ||||
16305 | |||||
16306 | return BaseTransform::TransformUnaryOperator(E); | ||||
16307 | } | ||||
16308 | |||||
16309 | // The body of a lambda-expression is in a separate expression evaluation | ||||
16310 | // context so never needs to be transformed. | ||||
16311 | // FIXME: Ideally we wouldn't transform the closure type either, and would | ||||
16312 | // just recreate the capture expressions and lambda expression. | ||||
16313 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | ||||
16314 | return SkipLambdaBody(E, Body); | ||||
16315 | } | ||||
16316 | }; | ||||
16317 | } | ||||
16318 | |||||
16319 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | ||||
16320 | assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16321, __PRETTY_FUNCTION__)) | ||||
16321 | "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16321, __PRETTY_FUNCTION__)); | ||||
16322 | ExprEvalContexts.back().Context = | ||||
16323 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | ||||
16324 | if (isUnevaluatedContext()) | ||||
16325 | return E; | ||||
16326 | return TransformToPE(*this).TransformExpr(E); | ||||
16327 | } | ||||
16328 | |||||
16329 | void | ||||
16330 | Sema::PushExpressionEvaluationContext( | ||||
16331 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | ||||
16332 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
16333 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | ||||
16334 | LambdaContextDecl, ExprContext); | ||||
16335 | Cleanup.reset(); | ||||
16336 | if (!MaybeODRUseExprs.empty()) | ||||
16337 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | ||||
16338 | } | ||||
16339 | |||||
16340 | void | ||||
16341 | Sema::PushExpressionEvaluationContext( | ||||
16342 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | ||||
16343 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
16344 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | ||||
16345 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | ||||
16346 | } | ||||
16347 | |||||
16348 | namespace { | ||||
16349 | |||||
16350 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | ||||
16351 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | ||||
16352 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | ||||
16353 | if (E->getOpcode() == UO_Deref) | ||||
16354 | return CheckPossibleDeref(S, E->getSubExpr()); | ||||
16355 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | ||||
16356 | return CheckPossibleDeref(S, E->getBase()); | ||||
16357 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | ||||
16358 | return CheckPossibleDeref(S, E->getBase()); | ||||
16359 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | ||||
16360 | QualType Inner; | ||||
16361 | QualType Ty = E->getType(); | ||||
16362 | if (const auto *Ptr = Ty->getAs<PointerType>()) | ||||
16363 | Inner = Ptr->getPointeeType(); | ||||
16364 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | ||||
16365 | Inner = Arr->getElementType(); | ||||
16366 | else | ||||
16367 | return nullptr; | ||||
16368 | |||||
16369 | if (Inner->hasAttr(attr::NoDeref)) | ||||
16370 | return E; | ||||
16371 | } | ||||
16372 | return nullptr; | ||||
16373 | } | ||||
16374 | |||||
16375 | } // namespace | ||||
16376 | |||||
16377 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | ||||
16378 | for (const Expr *E : Rec.PossibleDerefs) { | ||||
16379 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | ||||
16380 | if (DeclRef) { | ||||
16381 | const ValueDecl *Decl = DeclRef->getDecl(); | ||||
16382 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | ||||
16383 | << Decl->getName() << E->getSourceRange(); | ||||
16384 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | ||||
16385 | } else { | ||||
16386 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | ||||
16387 | << E->getSourceRange(); | ||||
16388 | } | ||||
16389 | } | ||||
16390 | Rec.PossibleDerefs.clear(); | ||||
16391 | } | ||||
16392 | |||||
16393 | /// Check whether E, which is either a discarded-value expression or an | ||||
16394 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | ||||
16395 | /// and if so, remove it from the list of volatile-qualified assignments that | ||||
16396 | /// we are going to warn are deprecated. | ||||
16397 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | ||||
16398 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | ||||
16399 | return; | ||||
16400 | |||||
16401 | // Note: ignoring parens here is not justified by the standard rules, but | ||||
16402 | // ignoring parentheses seems like a more reasonable approach, and this only | ||||
16403 | // drives a deprecation warning so doesn't affect conformance. | ||||
16404 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | ||||
16405 | if (BO->getOpcode() == BO_Assign) { | ||||
16406 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | ||||
16407 | LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), | ||||
16408 | LHSs.end()); | ||||
16409 | } | ||||
16410 | } | ||||
16411 | } | ||||
16412 | |||||
16413 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | ||||
16414 | if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || | ||||
16415 | RebuildingImmediateInvocation) | ||||
16416 | return E; | ||||
16417 | |||||
16418 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | ||||
16419 | /// It's OK if this fails; we'll also remove this in | ||||
16420 | /// HandleImmediateInvocations, but catching it here allows us to avoid | ||||
16421 | /// walking the AST looking for it in simple cases. | ||||
16422 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | ||||
16423 | if (auto *DeclRef = | ||||
16424 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | ||||
16425 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | ||||
16426 | |||||
16427 | E = MaybeCreateExprWithCleanups(E); | ||||
16428 | |||||
16429 | ConstantExpr *Res = ConstantExpr::Create( | ||||
16430 | getASTContext(), E.get(), | ||||
16431 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | ||||
16432 | getASTContext()), | ||||
16433 | /*IsImmediateInvocation*/ true); | ||||
16434 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | ||||
16435 | return Res; | ||||
16436 | } | ||||
16437 | |||||
16438 | static void EvaluateAndDiagnoseImmediateInvocation( | ||||
16439 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | ||||
16440 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
16441 | Expr::EvalResult Eval; | ||||
16442 | Eval.Diag = &Notes; | ||||
16443 | ConstantExpr *CE = Candidate.getPointer(); | ||||
16444 | bool Result = CE->EvaluateAsConstantExpr( | ||||
16445 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | ||||
16446 | if (!Result || !Notes.empty()) { | ||||
16447 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | ||||
16448 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | ||||
16449 | InnerExpr = FunctionalCast->getSubExpr(); | ||||
16450 | FunctionDecl *FD = nullptr; | ||||
16451 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | ||||
16452 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | ||||
16453 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | ||||
16454 | FD = Call->getConstructor(); | ||||
16455 | else | ||||
16456 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16456); | ||||
16457 | assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail ("FD->isConsteval()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16457, __PRETTY_FUNCTION__)); | ||||
16458 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | ||||
16459 | for (auto &Note : Notes) | ||||
16460 | SemaRef.Diag(Note.first, Note.second); | ||||
16461 | return; | ||||
16462 | } | ||||
16463 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | ||||
16464 | } | ||||
16465 | |||||
16466 | static void RemoveNestedImmediateInvocation( | ||||
16467 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | ||||
16468 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | ||||
16469 | struct ComplexRemove : TreeTransform<ComplexRemove> { | ||||
16470 | using Base = TreeTransform<ComplexRemove>; | ||||
16471 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
16472 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | ||||
16473 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | ||||
16474 | CurrentII; | ||||
16475 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | ||||
16476 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | ||||
16477 | SmallVector<Sema::ImmediateInvocationCandidate, | ||||
16478 | 4>::reverse_iterator Current) | ||||
16479 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | ||||
16480 | void RemoveImmediateInvocation(ConstantExpr* E) { | ||||
16481 | auto It = std::find_if(CurrentII, IISet.rend(), | ||||
16482 | [E](Sema::ImmediateInvocationCandidate Elem) { | ||||
16483 | return Elem.getPointer() == E; | ||||
16484 | }); | ||||
16485 | assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16487, __PRETTY_FUNCTION__)) | ||||
16486 | "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16487, __PRETTY_FUNCTION__)) | ||||
16487 | "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16487, __PRETTY_FUNCTION__)); | ||||
16488 | It->setInt(1); // Mark as deleted | ||||
16489 | } | ||||
16490 | ExprResult TransformConstantExpr(ConstantExpr *E) { | ||||
16491 | if (!E->isImmediateInvocation()) | ||||
16492 | return Base::TransformConstantExpr(E); | ||||
16493 | RemoveImmediateInvocation(E); | ||||
16494 | return Base::TransformExpr(E->getSubExpr()); | ||||
16495 | } | ||||
16496 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | ||||
16497 | /// we need to remove its DeclRefExpr from the DRSet. | ||||
16498 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
16499 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | ||||
16500 | return Base::TransformCXXOperatorCallExpr(E); | ||||
16501 | } | ||||
16502 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | ||||
16503 | /// here. | ||||
16504 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | ||||
16505 | if (!Init) | ||||
16506 | return Init; | ||||
16507 | /// ConstantExpr are the first layer of implicit node to be removed so if | ||||
16508 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | ||||
16509 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||
16510 | if (CE->isImmediateInvocation()) | ||||
16511 | RemoveImmediateInvocation(CE); | ||||
16512 | return Base::TransformInitializer(Init, NotCopyInit); | ||||
16513 | } | ||||
16514 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
16515 | DRSet.erase(E); | ||||
16516 | return E; | ||||
16517 | } | ||||
16518 | bool AlwaysRebuild() { return false; } | ||||
16519 | bool ReplacingOriginal() { return true; } | ||||
16520 | bool AllowSkippingCXXConstructExpr() { | ||||
16521 | bool Res = AllowSkippingFirstCXXConstructExpr; | ||||
16522 | AllowSkippingFirstCXXConstructExpr = true; | ||||
16523 | return Res; | ||||
16524 | } | ||||
16525 | bool AllowSkippingFirstCXXConstructExpr = true; | ||||
16526 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | ||||
16527 | Rec.ImmediateInvocationCandidates, It); | ||||
16528 | |||||
16529 | /// CXXConstructExpr with a single argument are getting skipped by | ||||
16530 | /// TreeTransform in some situtation because they could be implicit. This | ||||
16531 | /// can only occur for the top-level CXXConstructExpr because it is used | ||||
16532 | /// nowhere in the expression being transformed therefore will not be rebuilt. | ||||
16533 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | ||||
16534 | /// skipping the first CXXConstructExpr. | ||||
16535 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | ||||
16536 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | ||||
16537 | |||||
16538 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | ||||
16539 | assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail ("Res.isUsable()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16539, __PRETTY_FUNCTION__)); | ||||
16540 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | ||||
16541 | It->getPointer()->setSubExpr(Res.get()); | ||||
16542 | } | ||||
16543 | |||||
16544 | static void | ||||
16545 | HandleImmediateInvocations(Sema &SemaRef, | ||||
16546 | Sema::ExpressionEvaluationContextRecord &Rec) { | ||||
16547 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | ||||
16548 | Rec.ReferenceToConsteval.size() == 0) || | ||||
16549 | SemaRef.RebuildingImmediateInvocation) | ||||
16550 | return; | ||||
16551 | |||||
16552 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | ||||
16553 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | ||||
16554 | /// need to remove ReferenceToConsteval in the immediate invocation. | ||||
16555 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | ||||
16556 | |||||
16557 | /// Prevent sema calls during the tree transform from adding pointers that | ||||
16558 | /// are already in the sets. | ||||
16559 | llvm::SaveAndRestore<bool> DisableIITracking( | ||||
16560 | SemaRef.RebuildingImmediateInvocation, true); | ||||
16561 | |||||
16562 | /// Prevent diagnostic during tree transfrom as they are duplicates | ||||
16563 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | ||||
16564 | |||||
16565 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | ||||
16566 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | ||||
16567 | if (!It->getInt()) | ||||
16568 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | ||||
16569 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | ||||
16570 | Rec.ReferenceToConsteval.size()) { | ||||
16571 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | ||||
16572 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
16573 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | ||||
16574 | bool VisitDeclRefExpr(DeclRefExpr *E) { | ||||
16575 | DRSet.erase(E); | ||||
16576 | return DRSet.size(); | ||||
16577 | } | ||||
16578 | } Visitor(Rec.ReferenceToConsteval); | ||||
16579 | Visitor.TraverseStmt( | ||||
16580 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | ||||
16581 | } | ||||
16582 | for (auto CE : Rec.ImmediateInvocationCandidates) | ||||
16583 | if (!CE.getInt()) | ||||
16584 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | ||||
16585 | for (auto DR : Rec.ReferenceToConsteval) { | ||||
16586 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | ||||
16587 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | ||||
16588 | << FD; | ||||
16589 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | ||||
16590 | } | ||||
16591 | } | ||||
16592 | |||||
16593 | void Sema::PopExpressionEvaluationContext() { | ||||
16594 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | ||||
16595 | unsigned NumTypos = Rec.NumTypos; | ||||
16596 | |||||
16597 | if (!Rec.Lambdas.empty()) { | ||||
16598 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | ||||
16599 | if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || | ||||
16600 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { | ||||
16601 | unsigned D; | ||||
16602 | if (Rec.isUnevaluated()) { | ||||
16603 | // C++11 [expr.prim.lambda]p2: | ||||
16604 | // A lambda-expression shall not appear in an unevaluated operand | ||||
16605 | // (Clause 5). | ||||
16606 | D = diag::err_lambda_unevaluated_operand; | ||||
16607 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | ||||
16608 | // C++1y [expr.const]p2: | ||||
16609 | // A conditional-expression e is a core constant expression unless the | ||||
16610 | // evaluation of e, following the rules of the abstract machine, would | ||||
16611 | // evaluate [...] a lambda-expression. | ||||
16612 | D = diag::err_lambda_in_constant_expression; | ||||
16613 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | ||||
16614 | // C++17 [expr.prim.lamda]p2: | ||||
16615 | // A lambda-expression shall not appear [...] in a template-argument. | ||||
16616 | D = diag::err_lambda_in_invalid_context; | ||||
16617 | } else | ||||
16618 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16618); | ||||
16619 | |||||
16620 | for (const auto *L : Rec.Lambdas) | ||||
16621 | Diag(L->getBeginLoc(), D); | ||||
16622 | } | ||||
16623 | } | ||||
16624 | |||||
16625 | WarnOnPendingNoDerefs(Rec); | ||||
16626 | HandleImmediateInvocations(*this, Rec); | ||||
16627 | |||||
16628 | // Warn on any volatile-qualified simple-assignments that are not discarded- | ||||
16629 | // value expressions nor unevaluated operands (those cases get removed from | ||||
16630 | // this list by CheckUnusedVolatileAssignment). | ||||
16631 | for (auto *BO : Rec.VolatileAssignmentLHSs) | ||||
16632 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | ||||
16633 | << BO->getType(); | ||||
16634 | |||||
16635 | // When are coming out of an unevaluated context, clear out any | ||||
16636 | // temporaries that we may have created as part of the evaluation of | ||||
16637 | // the expression in that context: they aren't relevant because they | ||||
16638 | // will never be constructed. | ||||
16639 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | ||||
16640 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | ||||
16641 | ExprCleanupObjects.end()); | ||||
16642 | Cleanup = Rec.ParentCleanup; | ||||
16643 | CleanupVarDeclMarking(); | ||||
16644 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | ||||
16645 | // Otherwise, merge the contexts together. | ||||
16646 | } else { | ||||
16647 | Cleanup.mergeFrom(Rec.ParentCleanup); | ||||
16648 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | ||||
16649 | Rec.SavedMaybeODRUseExprs.end()); | ||||
16650 | } | ||||
16651 | |||||
16652 | // Pop the current expression evaluation context off the stack. | ||||
16653 | ExprEvalContexts.pop_back(); | ||||
16654 | |||||
16655 | // The global expression evaluation context record is never popped. | ||||
16656 | ExprEvalContexts.back().NumTypos += NumTypos; | ||||
16657 | } | ||||
16658 | |||||
16659 | void Sema::DiscardCleanupsInEvaluationContext() { | ||||
16660 | ExprCleanupObjects.erase( | ||||
16661 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | ||||
16662 | ExprCleanupObjects.end()); | ||||
16663 | Cleanup.reset(); | ||||
16664 | MaybeODRUseExprs.clear(); | ||||
16665 | } | ||||
16666 | |||||
16667 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | ||||
16668 | ExprResult Result = CheckPlaceholderExpr(E); | ||||
16669 | if (Result.isInvalid()) | ||||
16670 | return ExprError(); | ||||
16671 | E = Result.get(); | ||||
16672 | if (!E->getType()->isVariablyModifiedType()) | ||||
16673 | return E; | ||||
16674 | return TransformToPotentiallyEvaluated(E); | ||||
16675 | } | ||||
16676 | |||||
16677 | /// Are we in a context that is potentially constant evaluated per C++20 | ||||
16678 | /// [expr.const]p12? | ||||
16679 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | ||||
16680 | /// C++2a [expr.const]p12: | ||||
16681 | // An expression or conversion is potentially constant evaluated if it is | ||||
16682 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
16683 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
16684 | // -- a manifestly constant-evaluated expression, | ||||
16685 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
16686 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
16687 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
16688 | // -- a potentially-evaluated expression, | ||||
16689 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
16690 | // -- an immediate subexpression of a braced-init-list, | ||||
16691 | |||||
16692 | // -- [FIXME] an expression of the form & cast-expression that occurs | ||||
16693 | // within a templated entity | ||||
16694 | // -- a subexpression of one of the above that is not a subexpression of | ||||
16695 | // a nested unevaluated operand. | ||||
16696 | return true; | ||||
16697 | |||||
16698 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
16699 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
16700 | // Expressions in this context are never evaluated. | ||||
16701 | return false; | ||||
16702 | } | ||||
16703 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16703); | ||||
16704 | } | ||||
16705 | |||||
16706 | /// Return true if this function has a calling convention that requires mangling | ||||
16707 | /// in the size of the parameter pack. | ||||
16708 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | ||||
16709 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | ||||
16710 | // we don't need parameter type sizes. | ||||
16711 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | ||||
16712 | if (!TT.isOSWindows() || !TT.isX86()) | ||||
16713 | return false; | ||||
16714 | |||||
16715 | // If this is C++ and this isn't an extern "C" function, parameters do not | ||||
16716 | // need to be complete. In this case, C++ mangling will apply, which doesn't | ||||
16717 | // use the size of the parameters. | ||||
16718 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | ||||
16719 | return false; | ||||
16720 | |||||
16721 | // Stdcall, fastcall, and vectorcall need this special treatment. | ||||
16722 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
16723 | switch (CC) { | ||||
16724 | case CC_X86StdCall: | ||||
16725 | case CC_X86FastCall: | ||||
16726 | case CC_X86VectorCall: | ||||
16727 | return true; | ||||
16728 | default: | ||||
16729 | break; | ||||
16730 | } | ||||
16731 | return false; | ||||
16732 | } | ||||
16733 | |||||
16734 | /// Require that all of the parameter types of function be complete. Normally, | ||||
16735 | /// parameter types are only required to be complete when a function is called | ||||
16736 | /// or defined, but to mangle functions with certain calling conventions, the | ||||
16737 | /// mangler needs to know the size of the parameter list. In this situation, | ||||
16738 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | ||||
16739 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | ||||
16740 | /// result in a linker error. Clang doesn't implement this behavior, and instead | ||||
16741 | /// attempts to error at compile time. | ||||
16742 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | ||||
16743 | SourceLocation Loc) { | ||||
16744 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | ||||
16745 | FunctionDecl *FD; | ||||
16746 | ParmVarDecl *Param; | ||||
16747 | |||||
16748 | public: | ||||
16749 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | ||||
16750 | : FD(FD), Param(Param) {} | ||||
16751 | |||||
16752 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
16753 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
16754 | StringRef CCName; | ||||
16755 | switch (CC) { | ||||
16756 | case CC_X86StdCall: | ||||
16757 | CCName = "stdcall"; | ||||
16758 | break; | ||||
16759 | case CC_X86FastCall: | ||||
16760 | CCName = "fastcall"; | ||||
16761 | break; | ||||
16762 | case CC_X86VectorCall: | ||||
16763 | CCName = "vectorcall"; | ||||
16764 | break; | ||||
16765 | default: | ||||
16766 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16766); | ||||
16767 | } | ||||
16768 | |||||
16769 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | ||||
16770 | << Param->getDeclName() << FD->getDeclName() << CCName; | ||||
16771 | } | ||||
16772 | }; | ||||
16773 | |||||
16774 | for (ParmVarDecl *Param : FD->parameters()) { | ||||
16775 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | ||||
16776 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | ||||
16777 | } | ||||
16778 | } | ||||
16779 | |||||
16780 | namespace { | ||||
16781 | enum class OdrUseContext { | ||||
16782 | /// Declarations in this context are not odr-used. | ||||
16783 | None, | ||||
16784 | /// Declarations in this context are formally odr-used, but this is a | ||||
16785 | /// dependent context. | ||||
16786 | Dependent, | ||||
16787 | /// Declarations in this context are odr-used but not actually used (yet). | ||||
16788 | FormallyOdrUsed, | ||||
16789 | /// Declarations in this context are used. | ||||
16790 | Used | ||||
16791 | }; | ||||
16792 | } | ||||
16793 | |||||
16794 | /// Are we within a context in which references to resolved functions or to | ||||
16795 | /// variables result in odr-use? | ||||
16796 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | ||||
16797 | OdrUseContext Result; | ||||
16798 | |||||
16799 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
16800 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
16801 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
16802 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
16803 | return OdrUseContext::None; | ||||
16804 | |||||
16805 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
16806 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
16807 | Result = OdrUseContext::Used; | ||||
16808 | break; | ||||
16809 | |||||
16810 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
16811 | Result = OdrUseContext::FormallyOdrUsed; | ||||
16812 | break; | ||||
16813 | |||||
16814 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
16815 | // A default argument formally results in odr-use, but doesn't actually | ||||
16816 | // result in a use in any real sense until it itself is used. | ||||
16817 | Result = OdrUseContext::FormallyOdrUsed; | ||||
16818 | break; | ||||
16819 | } | ||||
16820 | |||||
16821 | if (SemaRef.CurContext->isDependentContext()) | ||||
16822 | return OdrUseContext::Dependent; | ||||
16823 | |||||
16824 | return Result; | ||||
16825 | } | ||||
16826 | |||||
16827 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | ||||
16828 | if (!Func->isConstexpr()) | ||||
16829 | return false; | ||||
16830 | |||||
16831 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | ||||
16832 | return true; | ||||
16833 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | ||||
16834 | return CCD && CCD->getInheritedConstructor(); | ||||
16835 | } | ||||
16836 | |||||
16837 | /// Mark a function referenced, and check whether it is odr-used | ||||
16838 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | ||||
16839 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | ||||
16840 | bool MightBeOdrUse) { | ||||
16841 | assert(Func && "No function?")((Func && "No function?") ? static_cast<void> ( 0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 16841, __PRETTY_FUNCTION__)); | ||||
16842 | |||||
16843 | Func->setReferenced(); | ||||
16844 | |||||
16845 | // Recursive functions aren't really used until they're used from some other | ||||
16846 | // context. | ||||
16847 | bool IsRecursiveCall = CurContext == Func; | ||||
16848 | |||||
16849 | // C++11 [basic.def.odr]p3: | ||||
16850 | // A function whose name appears as a potentially-evaluated expression is | ||||
16851 | // odr-used if it is the unique lookup result or the selected member of a | ||||
16852 | // set of overloaded functions [...]. | ||||
16853 | // | ||||
16854 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | ||||
16855 | // can just check that here. | ||||
16856 | OdrUseContext OdrUse = | ||||
16857 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | ||||
16858 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | ||||
16859 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
16860 | |||||
16861 | // Trivial default constructors and destructors are never actually used. | ||||
16862 | // FIXME: What about other special members? | ||||
16863 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | ||||
16864 | OdrUse == OdrUseContext::Used) { | ||||
16865 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | ||||
16866 | if (Constructor->isDefaultConstructor()) | ||||
16867 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
16868 | if (isa<CXXDestructorDecl>(Func)) | ||||
16869 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
16870 | } | ||||
16871 | |||||
16872 | // C++20 [expr.const]p12: | ||||
16873 | // A function [...] is needed for constant evaluation if it is [...] a | ||||
16874 | // constexpr function that is named by an expression that is potentially | ||||
16875 | // constant evaluated | ||||
16876 | bool NeededForConstantEvaluation = | ||||
16877 | isPotentiallyConstantEvaluatedContext(*this) && | ||||
16878 | isImplicitlyDefinableConstexprFunction(Func); | ||||
16879 | |||||
16880 | // Determine whether we require a function definition to exist, per | ||||
16881 | // C++11 [temp.inst]p3: | ||||
16882 | // Unless a function template specialization has been explicitly | ||||
16883 | // instantiated or explicitly specialized, the function template | ||||
16884 | // specialization is implicitly instantiated when the specialization is | ||||
16885 | // referenced in a context that requires a function definition to exist. | ||||
16886 | // C++20 [temp.inst]p7: | ||||
16887 | // The existence of a definition of a [...] function is considered to | ||||
16888 | // affect the semantics of the program if the [...] function is needed for | ||||
16889 | // constant evaluation by an expression | ||||
16890 | // C++20 [basic.def.odr]p10: | ||||
16891 | // Every program shall contain exactly one definition of every non-inline | ||||
16892 | // function or variable that is odr-used in that program outside of a | ||||
16893 | // discarded statement | ||||
16894 | // C++20 [special]p1: | ||||
16895 | // The implementation will implicitly define [defaulted special members] | ||||
16896 | // if they are odr-used or needed for constant evaluation. | ||||
16897 | // | ||||
16898 | // Note that we skip the implicit instantiation of templates that are only | ||||
16899 | // used in unused default arguments or by recursive calls to themselves. | ||||
16900 | // This is formally non-conforming, but seems reasonable in practice. | ||||
16901 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | ||||
16902 | NeededForConstantEvaluation); | ||||
16903 | |||||
16904 | // C++14 [temp.expl.spec]p6: | ||||
16905 | // If a template [...] is explicitly specialized then that specialization | ||||
16906 | // shall be declared before the first use of that specialization that would | ||||
16907 | // cause an implicit instantiation to take place, in every translation unit | ||||
16908 | // in which such a use occurs | ||||
16909 | if (NeedDefinition && | ||||
16910 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | ||||
16911 | Func->getMemberSpecializationInfo())) | ||||
16912 | checkSpecializationVisibility(Loc, Func); | ||||
16913 | |||||
16914 | if (getLangOpts().CUDA) | ||||
16915 | CheckCUDACall(Loc, Func); | ||||
16916 | |||||
16917 | if (getLangOpts().SYCLIsDevice) | ||||
16918 | checkSYCLDeviceFunction(Loc, Func); | ||||
16919 | |||||
16920 | // If we need a definition, try to create one. | ||||
16921 | if (NeedDefinition && !Func->getBody()) { | ||||
16922 | runWithSufficientStackSpace(Loc, [&] { | ||||
16923 | if (CXXConstructorDecl *Constructor = | ||||
16924 | dyn_cast<CXXConstructorDecl>(Func)) { | ||||
16925 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | ||||
16926 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | ||||
16927 | if (Constructor->isDefaultConstructor()) { | ||||
16928 | if (Constructor->isTrivial() && | ||||
16929 | !Constructor->hasAttr<DLLExportAttr>()) | ||||
16930 | return; | ||||
16931 | DefineImplicitDefaultConstructor(Loc, Constructor); | ||||
16932 | } else if (Constructor->isCopyConstructor()) { | ||||
16933 | DefineImplicitCopyConstructor(Loc, Constructor); | ||||
16934 | } else if (Constructor->isMoveConstructor()) { | ||||
16935 | DefineImplicitMoveConstructor(Loc, Constructor); | ||||
16936 | } | ||||
16937 | } else if (Constructor->getInheritedConstructor()) { | ||||
16938 | DefineInheritingConstructor(Loc, Constructor); | ||||
16939 | } | ||||
16940 | } else if (CXXDestructorDecl *Destructor = | ||||
16941 | dyn_cast<CXXDestructorDecl>(Func)) { | ||||
16942 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | ||||
16943 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | ||||
16944 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | ||||
16945 | return; | ||||
16946 | DefineImplicitDestructor(Loc, Destructor); | ||||
16947 | } | ||||
16948 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | ||||
16949 | MarkVTableUsed(Loc, Destructor->getParent()); | ||||
16950 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | ||||
16951 | if (MethodDecl->isOverloadedOperator() && | ||||
16952 | MethodDecl->getOverloadedOperator() == OO_Equal) { | ||||
16953 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | ||||
16954 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | ||||
16955 | if (MethodDecl->isCopyAssignmentOperator()) | ||||
16956 | DefineImplicitCopyAssignment(Loc, MethodDecl); | ||||
16957 | else if (MethodDecl->isMoveAssignmentOperator()) | ||||
16958 | DefineImplicitMoveAssignment(Loc, MethodDecl); | ||||
16959 | } | ||||
16960 | } else if (isa<CXXConversionDecl>(MethodDecl) && | ||||
16961 | MethodDecl->getParent()->isLambda()) { | ||||
16962 | CXXConversionDecl *Conversion = | ||||
16963 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | ||||
16964 | if (Conversion->isLambdaToBlockPointerConversion()) | ||||
16965 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | ||||
16966 | else | ||||
16967 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | ||||
16968 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | ||||
16969 | MarkVTableUsed(Loc, MethodDecl->getParent()); | ||||
16970 | } | ||||
16971 | |||||
16972 | if (Func->isDefaulted() && !Func->isDeleted()) { | ||||
16973 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | ||||
16974 | if (DCK != DefaultedComparisonKind::None) | ||||
16975 | DefineDefaultedComparison(Loc, Func, DCK); | ||||
16976 | } | ||||
16977 | |||||
16978 | // Implicit instantiation of function templates and member functions of | ||||
16979 | // class templates. | ||||
16980 | if (Func->isImplicitlyInstantiable()) { | ||||
16981 | TemplateSpecializationKind TSK = | ||||
16982 | Func->getTemplateSpecializationKindForInstantiation(); | ||||
16983 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | ||||
16984 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
16985 | if (FirstInstantiation) { | ||||
16986 | PointOfInstantiation = Loc; | ||||
16987 | if (auto *MSI = Func->getMemberSpecializationInfo()) | ||||
16988 | MSI->setPointOfInstantiation(Loc); | ||||
16989 | // FIXME: Notify listener. | ||||
16990 | else | ||||
16991 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
16992 | } else if (TSK != TSK_ImplicitInstantiation) { | ||||
16993 | // Use the point of use as the point of instantiation, instead of the | ||||
16994 | // point of explicit instantiation (which we track as the actual point | ||||
16995 | // of instantiation). This gives better backtraces in diagnostics. | ||||
16996 | PointOfInstantiation = Loc; | ||||
16997 | } | ||||
16998 | |||||
16999 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | ||||
17000 | Func->isConstexpr()) { | ||||
17001 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | ||||
17002 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | ||||
17003 | CodeSynthesisContexts.size()) | ||||
17004 | PendingLocalImplicitInstantiations.push_back( | ||||
17005 | std::make_pair(Func, PointOfInstantiation)); | ||||
17006 | else if (Func->isConstexpr()) | ||||
17007 | // Do not defer instantiations of constexpr functions, to avoid the | ||||
17008 | // expression evaluator needing to call back into Sema if it sees a | ||||
17009 | // call to such a function. | ||||
17010 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | ||||
17011 | else { | ||||
17012 | Func->setInstantiationIsPending(true); | ||||
17013 | PendingInstantiations.push_back( | ||||
17014 | std::make_pair(Func, PointOfInstantiation)); | ||||
17015 | // Notify the consumer that a function was implicitly instantiated. | ||||
17016 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | ||||
17017 | } | ||||
17018 | } | ||||
17019 | } else { | ||||
17020 | // Walk redefinitions, as some of them may be instantiable. | ||||
17021 | for (auto i : Func->redecls()) { | ||||
17022 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | ||||
17023 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | ||||
17024 | } | ||||
17025 | } | ||||
17026 | }); | ||||
17027 | } | ||||
17028 | |||||
17029 | // C++14 [except.spec]p17: | ||||
17030 | // An exception-specification is considered to be needed when: | ||||
17031 | // - the function is odr-used or, if it appears in an unevaluated operand, | ||||
17032 | // would be odr-used if the expression were potentially-evaluated; | ||||
17033 | // | ||||
17034 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | ||||
17035 | // function is a pure virtual function we're calling, and in that case the | ||||
17036 | // function was selected by overload resolution and we need to resolve its | ||||
17037 | // exception specification for a different reason. | ||||
17038 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | ||||
17039 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | ||||
17040 | ResolveExceptionSpec(Loc, FPT); | ||||
17041 | |||||
17042 | // If this is the first "real" use, act on that. | ||||
17043 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | ||||
17044 | // Keep track of used but undefined functions. | ||||
17045 | if (!Func->isDefined()) { | ||||
17046 | if (mightHaveNonExternalLinkage(Func)) | ||||
17047 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
17048 | else if (Func->getMostRecentDecl()->isInlined() && | ||||
17049 | !LangOpts.GNUInline && | ||||
17050 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | ||||
17051 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
17052 | else if (isExternalWithNoLinkageType(Func)) | ||||
17053 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
17054 | } | ||||
17055 | |||||
17056 | // Some x86 Windows calling conventions mangle the size of the parameter | ||||
17057 | // pack into the name. Computing the size of the parameters requires the | ||||
17058 | // parameter types to be complete. Check that now. | ||||
17059 | if (funcHasParameterSizeMangling(*this, Func)) | ||||
17060 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | ||||
17061 | |||||
17062 | // In the MS C++ ABI, the compiler emits destructor variants where they are | ||||
17063 | // used. If the destructor is used here but defined elsewhere, mark the | ||||
17064 | // virtual base destructors referenced. If those virtual base destructors | ||||
17065 | // are inline, this will ensure they are defined when emitting the complete | ||||
17066 | // destructor variant. This checking may be redundant if the destructor is | ||||
17067 | // provided later in this TU. | ||||
17068 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
17069 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | ||||
17070 | CXXRecordDecl *Parent = Dtor->getParent(); | ||||
17071 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | ||||
17072 | CheckCompleteDestructorVariant(Loc, Dtor); | ||||
17073 | } | ||||
17074 | } | ||||
17075 | |||||
17076 | Func->markUsed(Context); | ||||
17077 | } | ||||
17078 | } | ||||
17079 | |||||
17080 | /// Directly mark a variable odr-used. Given a choice, prefer to use | ||||
17081 | /// MarkVariableReferenced since it does additional checks and then | ||||
17082 | /// calls MarkVarDeclODRUsed. | ||||
17083 | /// If the variable must be captured: | ||||
17084 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | ||||
17085 | /// - else capture it in the DeclContext that maps to the | ||||
17086 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | ||||
17087 | static void | ||||
17088 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | ||||
17089 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | ||||
17090 | // Keep track of used but undefined variables. | ||||
17091 | // FIXME: We shouldn't suppress this warning for static data members. | ||||
17092 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | ||||
17093 | (!Var->isExternallyVisible() || Var->isInline() || | ||||
17094 | SemaRef.isExternalWithNoLinkageType(Var)) && | ||||
17095 | !(Var->isStaticDataMember() && Var->hasInit())) { | ||||
17096 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | ||||
17097 | if (old.isInvalid()) | ||||
17098 | old = Loc; | ||||
17099 | } | ||||
17100 | QualType CaptureType, DeclRefType; | ||||
17101 | if (SemaRef.LangOpts.OpenMP) | ||||
17102 | SemaRef.tryCaptureOpenMPLambdas(Var); | ||||
17103 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | ||||
17104 | /*EllipsisLoc*/ SourceLocation(), | ||||
17105 | /*BuildAndDiagnose*/ true, | ||||
17106 | CaptureType, DeclRefType, | ||||
17107 | FunctionScopeIndexToStopAt); | ||||
17108 | |||||
17109 | Var->markUsed(SemaRef.Context); | ||||
17110 | } | ||||
17111 | |||||
17112 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | ||||
17113 | SourceLocation Loc, | ||||
17114 | unsigned CapturingScopeIndex) { | ||||
17115 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | ||||
17116 | } | ||||
17117 | |||||
17118 | static void | ||||
17119 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||
17120 | ValueDecl *var, DeclContext *DC) { | ||||
17121 | DeclContext *VarDC = var->getDeclContext(); | ||||
17122 | |||||
17123 | // If the parameter still belongs to the translation unit, then | ||||
17124 | // we're actually just using one parameter in the declaration of | ||||
17125 | // the next. | ||||
17126 | if (isa<ParmVarDecl>(var) && | ||||
17127 | isa<TranslationUnitDecl>(VarDC)) | ||||
17128 | return; | ||||
17129 | |||||
17130 | // For C code, don't diagnose about capture if we're not actually in code | ||||
17131 | // right now; it's impossible to write a non-constant expression outside of | ||||
17132 | // function context, so we'll get other (more useful) diagnostics later. | ||||
17133 | // | ||||
17134 | // For C++, things get a bit more nasty... it would be nice to suppress this | ||||
17135 | // diagnostic for certain cases like using a local variable in an array bound | ||||
17136 | // for a member of a local class, but the correct predicate is not obvious. | ||||
17137 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | ||||
17138 | return; | ||||
17139 | |||||
17140 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | ||||
17141 | unsigned ContextKind = 3; // unknown | ||||
17142 | if (isa<CXXMethodDecl>(VarDC) && | ||||
17143 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | ||||
17144 | ContextKind = 2; | ||||
17145 | } else if (isa<FunctionDecl>(VarDC)) { | ||||
17146 | ContextKind = 0; | ||||
17147 | } else if (isa<BlockDecl>(VarDC)) { | ||||
17148 | ContextKind = 1; | ||||
17149 | } | ||||
17150 | |||||
17151 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | ||||
17152 | << var << ValueKind << ContextKind << VarDC; | ||||
17153 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | ||||
17154 | << var; | ||||
17155 | |||||
17156 | // FIXME: Add additional diagnostic info about class etc. which prevents | ||||
17157 | // capture. | ||||
17158 | } | ||||
17159 | |||||
17160 | |||||
17161 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | ||||
17162 | bool &SubCapturesAreNested, | ||||
17163 | QualType &CaptureType, | ||||
17164 | QualType &DeclRefType) { | ||||
17165 | // Check whether we've already captured it. | ||||
17166 | if (CSI->CaptureMap.count(Var)) { | ||||
17167 | // If we found a capture, any subcaptures are nested. | ||||
17168 | SubCapturesAreNested = true; | ||||
17169 | |||||
17170 | // Retrieve the capture type for this variable. | ||||
17171 | CaptureType = CSI->getCapture(Var).getCaptureType(); | ||||
17172 | |||||
17173 | // Compute the type of an expression that refers to this variable. | ||||
17174 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17175 | |||||
17176 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | ||||
17177 | // are mutable in the sense that user can change their value - they are | ||||
17178 | // private instances of the captured declarations. | ||||
17179 | const Capture &Cap = CSI->getCapture(Var); | ||||
17180 | if (Cap.isCopyCapture() && | ||||
17181 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | ||||
17182 | !(isa<CapturedRegionScopeInfo>(CSI) && | ||||
17183 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | ||||
17184 | DeclRefType.addConst(); | ||||
17185 | return true; | ||||
17186 | } | ||||
17187 | return false; | ||||
17188 | } | ||||
17189 | |||||
17190 | // Only block literals, captured statements, and lambda expressions can | ||||
17191 | // capture; other scopes don't work. | ||||
17192 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | ||||
17193 | SourceLocation Loc, | ||||
17194 | const bool Diagnose, Sema &S) { | ||||
17195 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | ||||
17196 | return getLambdaAwareParentOfDeclContext(DC); | ||||
17197 | else if (Var->hasLocalStorage()) { | ||||
17198 | if (Diagnose) | ||||
17199 | diagnoseUncapturableValueReference(S, Loc, Var, DC); | ||||
17200 | } | ||||
17201 | return nullptr; | ||||
17202 | } | ||||
17203 | |||||
17204 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
17205 | // certain types of variables (unnamed, variably modified types etc.) | ||||
17206 | // so check for eligibility. | ||||
17207 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | ||||
17208 | SourceLocation Loc, | ||||
17209 | const bool Diagnose, Sema &S) { | ||||
17210 | |||||
17211 | bool IsBlock = isa<BlockScopeInfo>(CSI); | ||||
17212 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | ||||
17213 | |||||
17214 | // Lambdas are not allowed to capture unnamed variables | ||||
17215 | // (e.g. anonymous unions). | ||||
17216 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | ||||
17217 | // assuming that's the intent. | ||||
17218 | if (IsLambda && !Var->getDeclName()) { | ||||
17219 | if (Diagnose) { | ||||
17220 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | ||||
17221 | S.Diag(Var->getLocation(), diag::note_declared_at); | ||||
17222 | } | ||||
17223 | return false; | ||||
17224 | } | ||||
17225 | |||||
17226 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | ||||
17227 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | ||||
17228 | if (Diagnose) { | ||||
17229 | S.Diag(Loc, diag::err_ref_vm_type); | ||||
17230 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17231 | } | ||||
17232 | return false; | ||||
17233 | } | ||||
17234 | // Prohibit structs with flexible array members too. | ||||
17235 | // We cannot capture what is in the tail end of the struct. | ||||
17236 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | ||||
17237 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | ||||
17238 | if (Diagnose) { | ||||
17239 | if (IsBlock) | ||||
17240 | S.Diag(Loc, diag::err_ref_flexarray_type); | ||||
17241 | else | ||||
17242 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | ||||
17243 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17244 | } | ||||
17245 | return false; | ||||
17246 | } | ||||
17247 | } | ||||
17248 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
17249 | // Lambdas and captured statements are not allowed to capture __block | ||||
17250 | // variables; they don't support the expected semantics. | ||||
17251 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | ||||
17252 | if (Diagnose) { | ||||
17253 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | ||||
17254 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17255 | } | ||||
17256 | return false; | ||||
17257 | } | ||||
17258 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | ||||
17259 | if (S.getLangOpts().OpenCL && IsBlock && | ||||
17260 | Var->getType()->isBlockPointerType()) { | ||||
17261 | if (Diagnose) | ||||
17262 | S.Diag(Loc, diag::err_opencl_block_ref_block); | ||||
17263 | return false; | ||||
17264 | } | ||||
17265 | |||||
17266 | return true; | ||||
17267 | } | ||||
17268 | |||||
17269 | // Returns true if the capture by block was successful. | ||||
17270 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | ||||
17271 | SourceLocation Loc, | ||||
17272 | const bool BuildAndDiagnose, | ||||
17273 | QualType &CaptureType, | ||||
17274 | QualType &DeclRefType, | ||||
17275 | const bool Nested, | ||||
17276 | Sema &S, bool Invalid) { | ||||
17277 | bool ByRef = false; | ||||
17278 | |||||
17279 | // Blocks are not allowed to capture arrays, excepting OpenCL. | ||||
17280 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | ||||
17281 | // (decayed to pointers). | ||||
17282 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | ||||
17283 | if (BuildAndDiagnose) { | ||||
17284 | S.Diag(Loc, diag::err_ref_array_type); | ||||
17285 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17286 | Invalid = true; | ||||
17287 | } else { | ||||
17288 | return false; | ||||
17289 | } | ||||
17290 | } | ||||
17291 | |||||
17292 | // Forbid the block-capture of autoreleasing variables. | ||||
17293 | if (!Invalid && | ||||
17294 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
17295 | if (BuildAndDiagnose) { | ||||
17296 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | ||||
17297 | << /*block*/ 0; | ||||
17298 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17299 | Invalid = true; | ||||
17300 | } else { | ||||
17301 | return false; | ||||
17302 | } | ||||
17303 | } | ||||
17304 | |||||
17305 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | ||||
17306 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | ||||
17307 | QualType PointeeTy = PT->getPointeeType(); | ||||
17308 | |||||
17309 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | ||||
17310 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | ||||
17311 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | ||||
17312 | if (BuildAndDiagnose) { | ||||
17313 | SourceLocation VarLoc = Var->getLocation(); | ||||
17314 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | ||||
17315 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | ||||
17316 | } | ||||
17317 | } | ||||
17318 | } | ||||
17319 | |||||
17320 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
17321 | if (HasBlocksAttr || CaptureType->isReferenceType() || | ||||
17322 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | ||||
17323 | // Block capture by reference does not change the capture or | ||||
17324 | // declaration reference types. | ||||
17325 | ByRef = true; | ||||
17326 | } else { | ||||
17327 | // Block capture by copy introduces 'const'. | ||||
17328 | CaptureType = CaptureType.getNonReferenceType().withConst(); | ||||
17329 | DeclRefType = CaptureType; | ||||
17330 | } | ||||
17331 | |||||
17332 | // Actually capture the variable. | ||||
17333 | if (BuildAndDiagnose) | ||||
17334 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | ||||
17335 | CaptureType, Invalid); | ||||
17336 | |||||
17337 | return !Invalid; | ||||
17338 | } | ||||
17339 | |||||
17340 | |||||
17341 | /// Capture the given variable in the captured region. | ||||
17342 | static bool captureInCapturedRegion( | ||||
17343 | CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, | ||||
17344 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, | ||||
17345 | const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, | ||||
17346 | bool IsTopScope, Sema &S, bool Invalid) { | ||||
17347 | // By default, capture variables by reference. | ||||
17348 | bool ByRef = true; | ||||
17349 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
17350 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
17351 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | ||||
17352 | // Using an LValue reference type is consistent with Lambdas (see below). | ||||
17353 | if (S.isOpenMPCapturedDecl(Var)) { | ||||
17354 | bool HasConst = DeclRefType.isConstQualified(); | ||||
17355 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
17356 | // Don't lose diagnostics about assignments to const. | ||||
17357 | if (HasConst) | ||||
17358 | DeclRefType.addConst(); | ||||
17359 | } | ||||
17360 | // Do not capture firstprivates in tasks. | ||||
17361 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | ||||
17362 | OMPC_unknown) | ||||
17363 | return true; | ||||
17364 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | ||||
17365 | RSI->OpenMPCaptureLevel); | ||||
17366 | } | ||||
17367 | |||||
17368 | if (ByRef) | ||||
17369 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
17370 | else | ||||
17371 | CaptureType = DeclRefType; | ||||
17372 | |||||
17373 | // Actually capture the variable. | ||||
17374 | if (BuildAndDiagnose) | ||||
17375 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | ||||
17376 | Loc, SourceLocation(), CaptureType, Invalid); | ||||
17377 | |||||
17378 | return !Invalid; | ||||
17379 | } | ||||
17380 | |||||
17381 | /// Capture the given variable in the lambda. | ||||
17382 | static bool captureInLambda(LambdaScopeInfo *LSI, | ||||
17383 | VarDecl *Var, | ||||
17384 | SourceLocation Loc, | ||||
17385 | const bool BuildAndDiagnose, | ||||
17386 | QualType &CaptureType, | ||||
17387 | QualType &DeclRefType, | ||||
17388 | const bool RefersToCapturedVariable, | ||||
17389 | const Sema::TryCaptureKind Kind, | ||||
17390 | SourceLocation EllipsisLoc, | ||||
17391 | const bool IsTopScope, | ||||
17392 | Sema &S, bool Invalid) { | ||||
17393 | // Determine whether we are capturing by reference or by value. | ||||
17394 | bool ByRef = false; | ||||
17395 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
17396 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
17397 | } else { | ||||
17398 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | ||||
17399 | } | ||||
17400 | |||||
17401 | // Compute the type of the field that will capture this variable. | ||||
17402 | if (ByRef) { | ||||
17403 | // C++11 [expr.prim.lambda]p15: | ||||
17404 | // An entity is captured by reference if it is implicitly or | ||||
17405 | // explicitly captured but not captured by copy. It is | ||||
17406 | // unspecified whether additional unnamed non-static data | ||||
17407 | // members are declared in the closure type for entities | ||||
17408 | // captured by reference. | ||||
17409 | // | ||||
17410 | // FIXME: It is not clear whether we want to build an lvalue reference | ||||
17411 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | ||||
17412 | // to do the former, while EDG does the latter. Core issue 1249 will | ||||
17413 | // clarify, but for now we follow GCC because it's a more permissive and | ||||
17414 | // easily defensible position. | ||||
17415 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
17416 | } else { | ||||
17417 | // C++11 [expr.prim.lambda]p14: | ||||
17418 | // For each entity captured by copy, an unnamed non-static | ||||
17419 | // data member is declared in the closure type. The | ||||
17420 | // declaration order of these members is unspecified. The type | ||||
17421 | // of such a data member is the type of the corresponding | ||||
17422 | // captured entity if the entity is not a reference to an | ||||
17423 | // object, or the referenced type otherwise. [Note: If the | ||||
17424 | // captured entity is a reference to a function, the | ||||
17425 | // corresponding data member is also a reference to a | ||||
17426 | // function. - end note ] | ||||
17427 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | ||||
17428 | if (!RefType->getPointeeType()->isFunctionType()) | ||||
17429 | CaptureType = RefType->getPointeeType(); | ||||
17430 | } | ||||
17431 | |||||
17432 | // Forbid the lambda copy-capture of autoreleasing variables. | ||||
17433 | if (!Invalid && | ||||
17434 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
17435 | if (BuildAndDiagnose) { | ||||
17436 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | ||||
17437 | S.Diag(Var->getLocation(), diag::note_previous_decl) | ||||
17438 | << Var->getDeclName(); | ||||
17439 | Invalid = true; | ||||
17440 | } else { | ||||
17441 | return false; | ||||
17442 | } | ||||
17443 | } | ||||
17444 | |||||
17445 | // Make sure that by-copy captures are of a complete and non-abstract type. | ||||
17446 | if (!Invalid && BuildAndDiagnose) { | ||||
17447 | if (!CaptureType->isDependentType() && | ||||
17448 | S.RequireCompleteSizedType( | ||||
17449 | Loc, CaptureType, | ||||
17450 | diag::err_capture_of_incomplete_or_sizeless_type, | ||||
17451 | Var->getDeclName())) | ||||
17452 | Invalid = true; | ||||
17453 | else if (S.RequireNonAbstractType(Loc, CaptureType, | ||||
17454 | diag::err_capture_of_abstract_type)) | ||||
17455 | Invalid = true; | ||||
17456 | } | ||||
17457 | } | ||||
17458 | |||||
17459 | // Compute the type of a reference to this captured variable. | ||||
17460 | if (ByRef) | ||||
17461 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17462 | else { | ||||
17463 | // C++ [expr.prim.lambda]p5: | ||||
17464 | // The closure type for a lambda-expression has a public inline | ||||
17465 | // function call operator [...]. This function call operator is | ||||
17466 | // declared const (9.3.1) if and only if the lambda-expression's | ||||
17467 | // parameter-declaration-clause is not followed by mutable. | ||||
17468 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17469 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | ||||
17470 | DeclRefType.addConst(); | ||||
17471 | } | ||||
17472 | |||||
17473 | // Add the capture. | ||||
17474 | if (BuildAndDiagnose) | ||||
17475 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | ||||
17476 | Loc, EllipsisLoc, CaptureType, Invalid); | ||||
17477 | |||||
17478 | return !Invalid; | ||||
17479 | } | ||||
17480 | |||||
17481 | static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { | ||||
17482 | // Offer a Copy fix even if the type is dependent. | ||||
17483 | if (Var->getType()->isDependentType()) | ||||
17484 | return true; | ||||
17485 | QualType T = Var->getType().getNonReferenceType(); | ||||
17486 | if (T.isTriviallyCopyableType(Context)) | ||||
17487 | return true; | ||||
17488 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | ||||
17489 | |||||
17490 | if (!(RD = RD->getDefinition())) | ||||
17491 | return false; | ||||
17492 | if (RD->hasSimpleCopyConstructor()) | ||||
17493 | return true; | ||||
17494 | if (RD->hasUserDeclaredCopyConstructor()) | ||||
17495 | for (CXXConstructorDecl *Ctor : RD->ctors()) | ||||
17496 | if (Ctor->isCopyConstructor()) | ||||
17497 | return !Ctor->isDeleted(); | ||||
17498 | } | ||||
17499 | return false; | ||||
17500 | } | ||||
17501 | |||||
17502 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or | ||||
17503 | /// default capture. Fixes may be omitted if they aren't allowed by the | ||||
17504 | /// standard, for example we can't emit a default copy capture fix-it if we | ||||
17505 | /// already explicitly copy capture capture another variable. | ||||
17506 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, | ||||
17507 | VarDecl *Var) { | ||||
17508 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)((LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) ? static_cast<void> (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 17508, __PRETTY_FUNCTION__)); | ||||
17509 | // Don't offer Capture by copy of default capture by copy fixes if Var is | ||||
17510 | // known not to be copy constructible. | ||||
17511 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); | ||||
17512 | |||||
17513 | SmallString<32> FixBuffer; | ||||
17514 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; | ||||
17515 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { | ||||
17516 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); | ||||
17517 | if (ShouldOfferCopyFix) { | ||||
17518 | // Offer fixes to insert an explicit capture for the variable. | ||||
17519 | // [] -> [VarName] | ||||
17520 | // [OtherCapture] -> [OtherCapture, VarName] | ||||
17521 | FixBuffer.assign({Separator, Var->getName()}); | ||||
17522 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
17523 | << Var << /*value*/ 0 | ||||
17524 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
17525 | } | ||||
17526 | // As above but capture by reference. | ||||
17527 | FixBuffer.assign({Separator, "&", Var->getName()}); | ||||
17528 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
17529 | << Var << /*reference*/ 1 | ||||
17530 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
17531 | } | ||||
17532 | |||||
17533 | // Only try to offer default capture if there are no captures excluding this | ||||
17534 | // and init captures. | ||||
17535 | // [this]: OK. | ||||
17536 | // [X = Y]: OK. | ||||
17537 | // [&A, &B]: Don't offer. | ||||
17538 | // [A, B]: Don't offer. | ||||
17539 | if (llvm::any_of(LSI->Captures, [](Capture &C) { | ||||
17540 | return !C.isThisCapture() && !C.isInitCapture(); | ||||
17541 | })) | ||||
17542 | return; | ||||
17543 | |||||
17544 | // The default capture specifiers, '=' or '&', must appear first in the | ||||
17545 | // capture body. | ||||
17546 | SourceLocation DefaultInsertLoc = | ||||
17547 | LSI->IntroducerRange.getBegin().getLocWithOffset(1); | ||||
17548 | |||||
17549 | if (ShouldOfferCopyFix) { | ||||
17550 | bool CanDefaultCopyCapture = true; | ||||
17551 | // [=, *this] OK since c++17 | ||||
17552 | // [=, this] OK since c++20 | ||||
17553 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) | ||||
17554 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 | ||||
17555 | ? LSI->getCXXThisCapture().isCopyCapture() | ||||
17556 | : false; | ||||
17557 | // We can't use default capture by copy if any captures already specified | ||||
17558 | // capture by copy. | ||||
17559 | if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
17560 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); | ||||
17561 | })) { | ||||
17562 | FixBuffer.assign({"=", Separator}); | ||||
17563 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
17564 | << /*value*/ 0 | ||||
17565 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
17566 | } | ||||
17567 | } | ||||
17568 | |||||
17569 | // We can't use default capture by reference if any captures already specified | ||||
17570 | // capture by reference. | ||||
17571 | if (llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
17572 | return !C.isInitCapture() && C.isReferenceCapture() && | ||||
17573 | !C.isThisCapture(); | ||||
17574 | })) { | ||||
17575 | FixBuffer.assign({"&", Separator}); | ||||
17576 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
17577 | << /*reference*/ 1 | ||||
17578 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
17579 | } | ||||
17580 | } | ||||
17581 | |||||
17582 | bool Sema::tryCaptureVariable( | ||||
17583 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | ||||
17584 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | ||||
17585 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | ||||
17586 | // An init-capture is notionally from the context surrounding its | ||||
17587 | // declaration, but its parent DC is the lambda class. | ||||
17588 | DeclContext *VarDC = Var->getDeclContext(); | ||||
17589 | if (Var->isInitCapture()) | ||||
17590 | VarDC = VarDC->getParent(); | ||||
17591 | |||||
17592 | DeclContext *DC = CurContext; | ||||
17593 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | ||||
17594 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | ||||
17595 | // We need to sync up the Declaration Context with the | ||||
17596 | // FunctionScopeIndexToStopAt | ||||
17597 | if (FunctionScopeIndexToStopAt) { | ||||
17598 | unsigned FSIndex = FunctionScopes.size() - 1; | ||||
17599 | while (FSIndex != MaxFunctionScopesIndex) { | ||||
17600 | DC = getLambdaAwareParentOfDeclContext(DC); | ||||
17601 | --FSIndex; | ||||
17602 | } | ||||
17603 | } | ||||
17604 | |||||
17605 | |||||
17606 | // If the variable is declared in the current context, there is no need to | ||||
17607 | // capture it. | ||||
17608 | if (VarDC == DC) return true; | ||||
17609 | |||||
17610 | // Capture global variables if it is required to use private copy of this | ||||
17611 | // variable. | ||||
17612 | bool IsGlobal = !Var->hasLocalStorage(); | ||||
17613 | if (IsGlobal && | ||||
17614 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | ||||
17615 | MaxFunctionScopesIndex))) | ||||
17616 | return true; | ||||
17617 | Var = Var->getCanonicalDecl(); | ||||
17618 | |||||
17619 | // Walk up the stack to determine whether we can capture the variable, | ||||
17620 | // performing the "simple" checks that don't depend on type. We stop when | ||||
17621 | // we've either hit the declared scope of the variable or find an existing | ||||
17622 | // capture of that variable. We start from the innermost capturing-entity | ||||
17623 | // (the DC) and ensure that all intervening capturing-entities | ||||
17624 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | ||||
17625 | // declcontext can either capture the variable or have already captured | ||||
17626 | // the variable. | ||||
17627 | CaptureType = Var->getType(); | ||||
17628 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17629 | bool Nested = false; | ||||
17630 | bool Explicit = (Kind != TryCapture_Implicit); | ||||
17631 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | ||||
17632 | do { | ||||
17633 | // Only block literals, captured statements, and lambda expressions can | ||||
17634 | // capture; other scopes don't work. | ||||
17635 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | ||||
17636 | ExprLoc, | ||||
17637 | BuildAndDiagnose, | ||||
17638 | *this); | ||||
17639 | // We need to check for the parent *first* because, if we *have* | ||||
17640 | // private-captured a global variable, we need to recursively capture it in | ||||
17641 | // intermediate blocks, lambdas, etc. | ||||
17642 | if (!ParentDC) { | ||||
17643 | if (IsGlobal) { | ||||
17644 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | ||||
17645 | break; | ||||
17646 | } | ||||
17647 | return true; | ||||
17648 | } | ||||
17649 | |||||
17650 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | ||||
17651 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | ||||
17652 | |||||
17653 | |||||
17654 | // Check whether we've already captured it. | ||||
17655 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | ||||
17656 | DeclRefType)) { | ||||
17657 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | ||||
17658 | break; | ||||
17659 | } | ||||
17660 | // If we are instantiating a generic lambda call operator body, | ||||
17661 | // we do not want to capture new variables. What was captured | ||||
17662 | // during either a lambdas transformation or initial parsing | ||||
17663 | // should be used. | ||||
17664 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | ||||
17665 | if (BuildAndDiagnose) { | ||||
17666 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
17667 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | ||||
17668 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
17669 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17670 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
17671 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
17672 | } else | ||||
17673 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); | ||||
17674 | } | ||||
17675 | return true; | ||||
17676 | } | ||||
17677 | |||||
17678 | // Try to capture variable-length arrays types. | ||||
17679 | if (Var->getType()->isVariablyModifiedType()) { | ||||
17680 | // We're going to walk down into the type and look for VLA | ||||
17681 | // expressions. | ||||
17682 | QualType QTy = Var->getType(); | ||||
17683 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
17684 | QTy = PVD->getOriginalType(); | ||||
17685 | captureVariablyModifiedType(Context, QTy, CSI); | ||||
17686 | } | ||||
17687 | |||||
17688 | if (getLangOpts().OpenMP) { | ||||
17689 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
17690 | // OpenMP private variables should not be captured in outer scope, so | ||||
17691 | // just break here. Similarly, global variables that are captured in a | ||||
17692 | // target region should not be captured outside the scope of the region. | ||||
17693 | if (RSI->CapRegionKind == CR_OpenMP) { | ||||
17694 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | ||||
17695 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | ||||
17696 | // If the variable is private (i.e. not captured) and has variably | ||||
17697 | // modified type, we still need to capture the type for correct | ||||
17698 | // codegen in all regions, associated with the construct. Currently, | ||||
17699 | // it is captured in the innermost captured region only. | ||||
17700 | if (IsOpenMPPrivateDecl != OMPC_unknown && | ||||
17701 | Var->getType()->isVariablyModifiedType()) { | ||||
17702 | QualType QTy = Var->getType(); | ||||
17703 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
17704 | QTy = PVD->getOriginalType(); | ||||
17705 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | ||||
17706 | I < E; ++I) { | ||||
17707 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | ||||
17708 | FunctionScopes[FunctionScopesIndex - I]); | ||||
17709 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 17711, __PRETTY_FUNCTION__)) | ||||
17710 | "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 17711, __PRETTY_FUNCTION__)) | ||||
17711 | "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 17711, __PRETTY_FUNCTION__)); | ||||
17712 | captureVariablyModifiedType(Context, QTy, OuterRSI); | ||||
17713 | } | ||||
17714 | } | ||||
17715 | bool IsTargetCap = | ||||
17716 | IsOpenMPPrivateDecl != OMPC_private && | ||||
17717 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | ||||
17718 | RSI->OpenMPCaptureLevel); | ||||
17719 | // Do not capture global if it is not privatized in outer regions. | ||||
17720 | bool IsGlobalCap = | ||||
17721 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | ||||
17722 | RSI->OpenMPCaptureLevel); | ||||
17723 | |||||
17724 | // When we detect target captures we are looking from inside the | ||||
17725 | // target region, therefore we need to propagate the capture from the | ||||
17726 | // enclosing region. Therefore, the capture is not initially nested. | ||||
17727 | if (IsTargetCap) | ||||
17728 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | ||||
17729 | |||||
17730 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | ||||
17731 | (IsGlobal && !IsGlobalCap)) { | ||||
17732 | Nested = !IsTargetCap; | ||||
17733 | bool HasConst = DeclRefType.isConstQualified(); | ||||
17734 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
17735 | // Don't lose diagnostics about assignments to const. | ||||
17736 | if (HasConst) | ||||
17737 | DeclRefType.addConst(); | ||||
17738 | CaptureType = Context.getLValueReferenceType(DeclRefType); | ||||
17739 | break; | ||||
17740 | } | ||||
17741 | } | ||||
17742 | } | ||||
17743 | } | ||||
17744 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | ||||
17745 | // No capture-default, and this is not an explicit capture | ||||
17746 | // so cannot capture this variable. | ||||
17747 | if (BuildAndDiagnose) { | ||||
17748 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
17749 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17750 | auto *LSI = cast<LambdaScopeInfo>(CSI); | ||||
17751 | if (LSI->Lambda) { | ||||
17752 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
17753 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
17754 | } | ||||
17755 | // FIXME: If we error out because an outer lambda can not implicitly | ||||
17756 | // capture a variable that an inner lambda explicitly captures, we | ||||
17757 | // should have the inner lambda do the explicit capture - because | ||||
17758 | // it makes for cleaner diagnostics later. This would purely be done | ||||
17759 | // so that the diagnostic does not misleadingly claim that a variable | ||||
17760 | // can not be captured by a lambda implicitly even though it is captured | ||||
17761 | // explicitly. Suggestion: | ||||
17762 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | ||||
17763 | // at the function head | ||||
17764 | // - cache the StartingDeclContext - this must be a lambda | ||||
17765 | // - captureInLambda in the innermost lambda the variable. | ||||
17766 | } | ||||
17767 | return true; | ||||
17768 | } | ||||
17769 | |||||
17770 | FunctionScopesIndex--; | ||||
17771 | DC = ParentDC; | ||||
17772 | Explicit = false; | ||||
17773 | } while (!VarDC->Equals(DC)); | ||||
17774 | |||||
17775 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | ||||
17776 | // computing the type of the capture at each step, checking type-specific | ||||
17777 | // requirements, and adding captures if requested. | ||||
17778 | // If the variable had already been captured previously, we start capturing | ||||
17779 | // at the lambda nested within that one. | ||||
17780 | bool Invalid = false; | ||||
17781 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | ||||
17782 | ++I) { | ||||
17783 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | ||||
17784 | |||||
17785 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
17786 | // certain types of variables (unnamed, variably modified types etc.) | ||||
17787 | // so check for eligibility. | ||||
17788 | if (!Invalid) | ||||
17789 | Invalid = | ||||
17790 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | ||||
17791 | |||||
17792 | // After encountering an error, if we're actually supposed to capture, keep | ||||
17793 | // capturing in nested contexts to suppress any follow-on diagnostics. | ||||
17794 | if (Invalid && !BuildAndDiagnose) | ||||
17795 | return true; | ||||
17796 | |||||
17797 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | ||||
17798 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
17799 | DeclRefType, Nested, *this, Invalid); | ||||
17800 | Nested = true; | ||||
17801 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
17802 | Invalid = !captureInCapturedRegion( | ||||
17803 | RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, | ||||
17804 | Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
17805 | Nested = true; | ||||
17806 | } else { | ||||
17807 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
17808 | Invalid = | ||||
17809 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
17810 | DeclRefType, Nested, Kind, EllipsisLoc, | ||||
17811 | /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
17812 | Nested = true; | ||||
17813 | } | ||||
17814 | |||||
17815 | if (Invalid && !BuildAndDiagnose) | ||||
17816 | return true; | ||||
17817 | } | ||||
17818 | return Invalid; | ||||
17819 | } | ||||
17820 | |||||
17821 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | ||||
17822 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | ||||
17823 | QualType CaptureType; | ||||
17824 | QualType DeclRefType; | ||||
17825 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | ||||
17826 | /*BuildAndDiagnose=*/true, CaptureType, | ||||
17827 | DeclRefType, nullptr); | ||||
17828 | } | ||||
17829 | |||||
17830 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | ||||
17831 | QualType CaptureType; | ||||
17832 | QualType DeclRefType; | ||||
17833 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
17834 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
17835 | DeclRefType, nullptr); | ||||
17836 | } | ||||
17837 | |||||
17838 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | ||||
17839 | QualType CaptureType; | ||||
17840 | QualType DeclRefType; | ||||
17841 | |||||
17842 | // Determine whether we can capture this variable. | ||||
17843 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
17844 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
17845 | DeclRefType, nullptr)) | ||||
17846 | return QualType(); | ||||
17847 | |||||
17848 | return DeclRefType; | ||||
17849 | } | ||||
17850 | |||||
17851 | namespace { | ||||
17852 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | ||||
17853 | // The produced TemplateArgumentListInfo* points to data stored within this | ||||
17854 | // object, so should only be used in contexts where the pointer will not be | ||||
17855 | // used after the CopiedTemplateArgs object is destroyed. | ||||
17856 | class CopiedTemplateArgs { | ||||
17857 | bool HasArgs; | ||||
17858 | TemplateArgumentListInfo TemplateArgStorage; | ||||
17859 | public: | ||||
17860 | template<typename RefExpr> | ||||
17861 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | ||||
17862 | if (HasArgs) | ||||
17863 | E->copyTemplateArgumentsInto(TemplateArgStorage); | ||||
17864 | } | ||||
17865 | operator TemplateArgumentListInfo*() | ||||
17866 | #ifdef __has_cpp_attribute | ||||
17867 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | ||||
17868 | [[clang::lifetimebound]] | ||||
17869 | #endif | ||||
17870 | #endif | ||||
17871 | { | ||||
17872 | return HasArgs ? &TemplateArgStorage : nullptr; | ||||
17873 | } | ||||
17874 | }; | ||||
17875 | } | ||||
17876 | |||||
17877 | /// Walk the set of potential results of an expression and mark them all as | ||||
17878 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | ||||
17879 | /// | ||||
17880 | /// \return A new expression if we found any potential results, ExprEmpty() if | ||||
17881 | /// not, and ExprError() if we diagnosed an error. | ||||
17882 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | ||||
17883 | NonOdrUseReason NOUR) { | ||||
17884 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | ||||
17885 | // an object that satisfies the requirements for appearing in a | ||||
17886 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | ||||
17887 | // is immediately applied." This function handles the lvalue-to-rvalue | ||||
17888 | // conversion part. | ||||
17889 | // | ||||
17890 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | ||||
17891 | // transform it into the relevant kind of non-odr-use node and rebuild the | ||||
17892 | // tree of nodes leading to it. | ||||
17893 | // | ||||
17894 | // This is a mini-TreeTransform that only transforms a restricted subset of | ||||
17895 | // nodes (and only certain operands of them). | ||||
17896 | |||||
17897 | // Rebuild a subexpression. | ||||
17898 | auto Rebuild = [&](Expr *Sub) { | ||||
17899 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | ||||
17900 | }; | ||||
17901 | |||||
17902 | // Check whether a potential result satisfies the requirements of NOUR. | ||||
17903 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | ||||
17904 | // Any entity other than a VarDecl is always odr-used whenever it's named | ||||
17905 | // in a potentially-evaluated expression. | ||||
17906 | auto *VD = dyn_cast<VarDecl>(D); | ||||
17907 | if (!VD) | ||||
17908 | return true; | ||||
17909 | |||||
17910 | // C++2a [basic.def.odr]p4: | ||||
17911 | // A variable x whose name appears as a potentially-evalauted expression | ||||
17912 | // e is odr-used by e unless | ||||
17913 | // -- x is a reference that is usable in constant expressions, or | ||||
17914 | // -- x is a variable of non-reference type that is usable in constant | ||||
17915 | // expressions and has no mutable subobjects, and e is an element of | ||||
17916 | // the set of potential results of an expression of | ||||
17917 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
17918 | // conversion is applied, or | ||||
17919 | // -- x is a variable of non-reference type, and e is an element of the | ||||
17920 | // set of potential results of a discarded-value expression to which | ||||
17921 | // the lvalue-to-rvalue conversion is not applied | ||||
17922 | // | ||||
17923 | // We check the first bullet and the "potentially-evaluated" condition in | ||||
17924 | // BuildDeclRefExpr. We check the type requirements in the second bullet | ||||
17925 | // in CheckLValueToRValueConversionOperand below. | ||||
17926 | switch (NOUR) { | ||||
17927 | case NOUR_None: | ||||
17928 | case NOUR_Unevaluated: | ||||
17929 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 17929); | ||||
17930 | |||||
17931 | case NOUR_Constant: | ||||
17932 | // Constant references were handled when they were built. | ||||
17933 | if (VD->getType()->isReferenceType()) | ||||
17934 | return true; | ||||
17935 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | ||||
17936 | if (RD->hasMutableFields()) | ||||
17937 | return true; | ||||
17938 | if (!VD->isUsableInConstantExpressions(S.Context)) | ||||
17939 | return true; | ||||
17940 | break; | ||||
17941 | |||||
17942 | case NOUR_Discarded: | ||||
17943 | if (VD->getType()->isReferenceType()) | ||||
17944 | return true; | ||||
17945 | break; | ||||
17946 | } | ||||
17947 | return false; | ||||
17948 | }; | ||||
17949 | |||||
17950 | // Mark that this expression does not constitute an odr-use. | ||||
17951 | auto MarkNotOdrUsed = [&] { | ||||
17952 | S.MaybeODRUseExprs.remove(E); | ||||
17953 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | ||||
17954 | LSI->markVariableExprAsNonODRUsed(E); | ||||
17955 | }; | ||||
17956 | |||||
17957 | // C++2a [basic.def.odr]p2: | ||||
17958 | // The set of potential results of an expression e is defined as follows: | ||||
17959 | switch (E->getStmtClass()) { | ||||
| |||||
17960 | // -- If e is an id-expression, ... | ||||
17961 | case Expr::DeclRefExprClass: { | ||||
17962 | auto *DRE = cast<DeclRefExpr>(E); | ||||
17963 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | ||||
17964 | break; | ||||
17965 | |||||
17966 | // Rebuild as a non-odr-use DeclRefExpr. | ||||
17967 | MarkNotOdrUsed(); | ||||
17968 | return DeclRefExpr::Create( | ||||
17969 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | ||||
17970 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | ||||
17971 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | ||||
17972 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | ||||
17973 | } | ||||
17974 | |||||
17975 | case Expr::FunctionParmPackExprClass: { | ||||
17976 | auto *FPPE = cast<FunctionParmPackExpr>(E); | ||||
17977 | // If any of the declarations in the pack is odr-used, then the expression | ||||
17978 | // as a whole constitutes an odr-use. | ||||
17979 | for (VarDecl *D : *FPPE) | ||||
17980 | if (IsPotentialResultOdrUsed(D)) | ||||
17981 | return ExprEmpty(); | ||||
17982 | |||||
17983 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | ||||
17984 | // nothing cares about whether we marked this as an odr-use, but it might | ||||
17985 | // be useful for non-compiler tools. | ||||
17986 | MarkNotOdrUsed(); | ||||
17987 | break; | ||||
17988 | } | ||||
17989 | |||||
17990 | // -- If e is a subscripting operation with an array operand... | ||||
17991 | case Expr::ArraySubscriptExprClass: { | ||||
17992 | auto *ASE = cast<ArraySubscriptExpr>(E); | ||||
17993 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | ||||
17994 | if (!OldBase->getType()->isArrayType()) | ||||
17995 | break; | ||||
17996 | ExprResult Base = Rebuild(OldBase); | ||||
17997 | if (!Base.isUsable()) | ||||
17998 | return Base; | ||||
17999 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | ||||
18000 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | ||||
18001 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | ||||
18002 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | ||||
18003 | ASE->getRBracketLoc()); | ||||
18004 | } | ||||
18005 | |||||
18006 | case Expr::MemberExprClass: { | ||||
18007 | auto *ME = cast<MemberExpr>(E); | ||||
18008 | // -- If e is a class member access expression [...] naming a non-static | ||||
18009 | // data member... | ||||
18010 | if (isa<FieldDecl>(ME->getMemberDecl())) { | ||||
18011 | ExprResult Base = Rebuild(ME->getBase()); | ||||
18012 | if (!Base.isUsable()) | ||||
18013 | return Base; | ||||
18014 | return MemberExpr::Create( | ||||
18015 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | ||||
18016 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | ||||
18017 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | ||||
18018 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | ||||
18019 | ME->getObjectKind(), ME->isNonOdrUse()); | ||||
18020 | } | ||||
18021 | |||||
18022 | if (ME->getMemberDecl()->isCXXInstanceMember()) | ||||
18023 | break; | ||||
18024 | |||||
18025 | // -- If e is a class member access expression naming a static data member, | ||||
18026 | // ... | ||||
18027 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | ||||
18028 | break; | ||||
18029 | |||||
18030 | // Rebuild as a non-odr-use MemberExpr. | ||||
18031 | MarkNotOdrUsed(); | ||||
18032 | return MemberExpr::Create( | ||||
18033 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | ||||
18034 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | ||||
18035 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | ||||
18036 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | ||||
18037 | return ExprEmpty(); | ||||
18038 | } | ||||
18039 | |||||
18040 | case Expr::BinaryOperatorClass: { | ||||
18041 | auto *BO = cast<BinaryOperator>(E); | ||||
18042 | Expr *LHS = BO->getLHS(); | ||||
18043 | Expr *RHS = BO->getRHS(); | ||||
18044 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | ||||
18045 | if (BO->getOpcode() == BO_PtrMemD) { | ||||
18046 | ExprResult Sub = Rebuild(LHS); | ||||
18047 | if (!Sub.isUsable()) | ||||
18048 | return Sub; | ||||
18049 | LHS = Sub.get(); | ||||
18050 | // -- If e is a comma expression, ... | ||||
18051 | } else if (BO->getOpcode() == BO_Comma) { | ||||
18052 | ExprResult Sub = Rebuild(RHS); | ||||
18053 | if (!Sub.isUsable()) | ||||
18054 | return Sub; | ||||
18055 | RHS = Sub.get(); | ||||
18056 | } else { | ||||
18057 | break; | ||||
18058 | } | ||||
18059 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | ||||
18060 | LHS, RHS); | ||||
18061 | } | ||||
18062 | |||||
18063 | // -- If e has the form (e1)... | ||||
18064 | case Expr::ParenExprClass: { | ||||
18065 | auto *PE = cast<ParenExpr>(E); | ||||
18066 | ExprResult Sub = Rebuild(PE->getSubExpr()); | ||||
18067 | if (!Sub.isUsable()) | ||||
18068 | return Sub; | ||||
18069 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | ||||
18070 | } | ||||
18071 | |||||
18072 | // -- If e is a glvalue conditional expression, ... | ||||
18073 | // We don't apply this to a binary conditional operator. FIXME: Should we? | ||||
18074 | case Expr::ConditionalOperatorClass: { | ||||
18075 | auto *CO = cast<ConditionalOperator>(E); | ||||
18076 | ExprResult LHS = Rebuild(CO->getLHS()); | ||||
18077 | if (LHS.isInvalid()) | ||||
18078 | return ExprError(); | ||||
18079 | ExprResult RHS = Rebuild(CO->getRHS()); | ||||
18080 | if (RHS.isInvalid()) | ||||
18081 | return ExprError(); | ||||
18082 | if (!LHS.isUsable() && !RHS.isUsable()) | ||||
18083 | return ExprEmpty(); | ||||
18084 | if (!LHS.isUsable()) | ||||
18085 | LHS = CO->getLHS(); | ||||
18086 | if (!RHS.isUsable()) | ||||
18087 | RHS = CO->getRHS(); | ||||
18088 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | ||||
18089 | CO->getCond(), LHS.get(), RHS.get()); | ||||
18090 | } | ||||
18091 | |||||
18092 | // [Clang extension] | ||||
18093 | // -- If e has the form __extension__ e1... | ||||
18094 | case Expr::UnaryOperatorClass: { | ||||
18095 | auto *UO = cast<UnaryOperator>(E); | ||||
18096 | if (UO->getOpcode() != UO_Extension) | ||||
18097 | break; | ||||
18098 | ExprResult Sub = Rebuild(UO->getSubExpr()); | ||||
18099 | if (!Sub.isUsable()) | ||||
18100 | return Sub; | ||||
18101 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | ||||
18102 | Sub.get()); | ||||
18103 | } | ||||
18104 | |||||
18105 | // [Clang extension] | ||||
18106 | // -- If e has the form _Generic(...), the set of potential results is the | ||||
18107 | // union of the sets of potential results of the associated expressions. | ||||
18108 | case Expr::GenericSelectionExprClass: { | ||||
18109 | auto *GSE = cast<GenericSelectionExpr>(E); | ||||
18110 | |||||
18111 | SmallVector<Expr *, 4> AssocExprs; | ||||
18112 | bool AnyChanged = false; | ||||
18113 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | ||||
18114 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | ||||
18115 | if (AssocExpr.isInvalid()) | ||||
18116 | return ExprError(); | ||||
18117 | if (AssocExpr.isUsable()) { | ||||
18118 | AssocExprs.push_back(AssocExpr.get()); | ||||
18119 | AnyChanged = true; | ||||
18120 | } else { | ||||
18121 | AssocExprs.push_back(OrigAssocExpr); | ||||
18122 | } | ||||
18123 | } | ||||
18124 | |||||
18125 | return AnyChanged ? S.CreateGenericSelectionExpr( | ||||
18126 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | ||||
18127 | GSE->getRParenLoc(), GSE->getControllingExpr(), | ||||
18128 | GSE->getAssocTypeSourceInfos(), AssocExprs) | ||||
18129 | : ExprEmpty(); | ||||
18130 | } | ||||
18131 | |||||
18132 | // [Clang extension] | ||||
18133 | // -- If e has the form __builtin_choose_expr(...), the set of potential | ||||
18134 | // results is the union of the sets of potential results of the | ||||
18135 | // second and third subexpressions. | ||||
18136 | case Expr::ChooseExprClass: { | ||||
18137 | auto *CE = cast<ChooseExpr>(E); | ||||
18138 | |||||
18139 | ExprResult LHS = Rebuild(CE->getLHS()); | ||||
18140 | if (LHS.isInvalid()) | ||||
18141 | return ExprError(); | ||||
18142 | |||||
18143 | ExprResult RHS = Rebuild(CE->getLHS()); | ||||
18144 | if (RHS.isInvalid()) | ||||
18145 | return ExprError(); | ||||
18146 | |||||
18147 | if (!LHS.get() && !RHS.get()) | ||||
18148 | return ExprEmpty(); | ||||
18149 | if (!LHS.isUsable()) | ||||
18150 | LHS = CE->getLHS(); | ||||
18151 | if (!RHS.isUsable()) | ||||
18152 | RHS = CE->getRHS(); | ||||
18153 | |||||
18154 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | ||||
18155 | RHS.get(), CE->getRParenLoc()); | ||||
18156 | } | ||||
18157 | |||||
18158 | // Step through non-syntactic nodes. | ||||
18159 | case Expr::ConstantExprClass: { | ||||
18160 | auto *CE = cast<ConstantExpr>(E); | ||||
18161 | ExprResult Sub = Rebuild(CE->getSubExpr()); | ||||
18162 | if (!Sub.isUsable()) | ||||
18163 | return Sub; | ||||
18164 | return ConstantExpr::Create(S.Context, Sub.get()); | ||||
18165 | } | ||||
18166 | |||||
18167 | // We could mostly rely on the recursive rebuilding to rebuild implicit | ||||
18168 | // casts, but not at the top level, so rebuild them here. | ||||
18169 | case Expr::ImplicitCastExprClass: { | ||||
18170 | auto *ICE = cast<ImplicitCastExpr>(E); | ||||
18171 | // Only step through the narrow set of cast kinds we expect to encounter. | ||||
18172 | // Anything else suggests we've left the region in which potential results | ||||
18173 | // can be found. | ||||
18174 | switch (ICE->getCastKind()) { | ||||
18175 | case CK_NoOp: | ||||
18176 | case CK_DerivedToBase: | ||||
18177 | case CK_UncheckedDerivedToBase: { | ||||
18178 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | ||||
18179 | if (!Sub.isUsable()) | ||||
18180 | return Sub; | ||||
18181 | CXXCastPath Path(ICE->path()); | ||||
18182 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | ||||
18183 | ICE->getValueKind(), &Path); | ||||
18184 | } | ||||
18185 | |||||
18186 | default: | ||||
18187 | break; | ||||
18188 | } | ||||
18189 | break; | ||||
18190 | } | ||||
18191 | |||||
18192 | default: | ||||
18193 | break; | ||||
18194 | } | ||||
18195 | |||||
18196 | // Can't traverse through this node. Nothing to do. | ||||
18197 | return ExprEmpty(); | ||||
18198 | } | ||||
18199 | |||||
18200 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | ||||
18201 | // Check whether the operand is or contains an object of non-trivial C union | ||||
18202 | // type. | ||||
18203 | if (E->getType().isVolatileQualified() && | ||||
18204 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
18205 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | ||||
18206 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
18207 | Sema::NTCUC_LValueToRValueVolatile, | ||||
18208 | NTCUK_Destruct|NTCUK_Copy); | ||||
18209 | |||||
18210 | // C++2a [basic.def.odr]p4: | ||||
18211 | // [...] an expression of non-volatile-qualified non-class type to which | ||||
18212 | // the lvalue-to-rvalue conversion is applied [...] | ||||
18213 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | ||||
18214 | return E; | ||||
18215 | |||||
18216 | ExprResult Result = | ||||
18217 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | ||||
18218 | if (Result.isInvalid()) | ||||
18219 | return ExprError(); | ||||
18220 | return Result.get() ? Result : E; | ||||
18221 | } | ||||
18222 | |||||
18223 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | ||||
18224 | Res = CorrectDelayedTyposInExpr(Res); | ||||
18225 | |||||
18226 | if (!Res.isUsable()) | ||||
18227 | return Res; | ||||
18228 | |||||
18229 | // If a constant-expression is a reference to a variable where we delay | ||||
18230 | // deciding whether it is an odr-use, just assume we will apply the | ||||
18231 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | ||||
18232 | // (a non-type template argument), we have special handling anyway. | ||||
18233 | return CheckLValueToRValueConversionOperand(Res.get()); | ||||
18234 | } | ||||
18235 | |||||
18236 | void Sema::CleanupVarDeclMarking() { | ||||
18237 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | ||||
18238 | // call. | ||||
18239 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | ||||
18240 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | ||||
18241 | |||||
18242 | for (Expr *E : LocalMaybeODRUseExprs) { | ||||
18243 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
18244 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | ||||
18245 | DRE->getLocation(), *this); | ||||
18246 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
18247 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | ||||
18248 | *this); | ||||
18249 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | ||||
18250 | for (VarDecl *VD : *FP) | ||||
18251 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | ||||
18252 | } else { | ||||
18253 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18253); | ||||
18254 | } | ||||
18255 | } | ||||
18256 | |||||
18257 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18258, __PRETTY_FUNCTION__)) | ||||
18258 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18258, __PRETTY_FUNCTION__)); | ||||
18259 | } | ||||
18260 | |||||
18261 | static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, | ||||
18262 | VarDecl *Var, Expr *E) { | ||||
18263 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18265, __PRETTY_FUNCTION__)) | ||||
18264 | isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18265, __PRETTY_FUNCTION__)) | ||||
18265 | "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18265, __PRETTY_FUNCTION__)); | ||||
18266 | Var->setReferenced(); | ||||
18267 | |||||
18268 | if (Var->isInvalidDecl()) | ||||
18269 | return; | ||||
18270 | |||||
18271 | // Record a CUDA/HIP static device/constant variable if it is referenced | ||||
18272 | // by host code. This is done conservatively, when the variable is referenced | ||||
18273 | // in any of the following contexts: | ||||
18274 | // - a non-function context | ||||
18275 | // - a host function | ||||
18276 | // - a host device function | ||||
18277 | // This also requires the reference of the static device/constant variable by | ||||
18278 | // host code to be visible in the device compilation for the compiler to be | ||||
18279 | // able to externalize the static device/constant variable. | ||||
18280 | if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { | ||||
18281 | auto *CurContext = SemaRef.CurContext; | ||||
18282 | if (!CurContext || !isa<FunctionDecl>(CurContext) || | ||||
18283 | cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || | ||||
18284 | (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && | ||||
18285 | !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) | ||||
18286 | SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); | ||||
18287 | } | ||||
18288 | |||||
18289 | auto *MSI = Var->getMemberSpecializationInfo(); | ||||
18290 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | ||||
18291 | : Var->getTemplateSpecializationKind(); | ||||
18292 | |||||
18293 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
18294 | bool UsableInConstantExpr = | ||||
18295 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | ||||
18296 | |||||
18297 | // C++20 [expr.const]p12: | ||||
18298 | // A variable [...] is needed for constant evaluation if it is [...] a | ||||
18299 | // variable whose name appears as a potentially constant evaluated | ||||
18300 | // expression that is either a contexpr variable or is of non-volatile | ||||
18301 | // const-qualified integral type or of reference type | ||||
18302 | bool NeededForConstantEvaluation = | ||||
18303 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | ||||
18304 | |||||
18305 | bool NeedDefinition = | ||||
18306 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | ||||
18307 | |||||
18308 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18309, __PRETTY_FUNCTION__)) | ||||
18309 | "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18309, __PRETTY_FUNCTION__)); | ||||
18310 | |||||
18311 | // If this might be a member specialization of a static data member, check | ||||
18312 | // the specialization is visible. We already did the checks for variable | ||||
18313 | // template specializations when we created them. | ||||
18314 | if (NeedDefinition && TSK != TSK_Undeclared && | ||||
18315 | !isa<VarTemplateSpecializationDecl>(Var)) | ||||
18316 | SemaRef.checkSpecializationVisibility(Loc, Var); | ||||
18317 | |||||
18318 | // Perform implicit instantiation of static data members, static data member | ||||
18319 | // templates of class templates, and variable template specializations. Delay | ||||
18320 | // instantiations of variable templates, except for those that could be used | ||||
18321 | // in a constant expression. | ||||
18322 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | ||||
18323 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | ||||
18324 | // instantiation declaration if a variable is usable in a constant | ||||
18325 | // expression (among other cases). | ||||
18326 | bool TryInstantiating = | ||||
18327 | TSK == TSK_ImplicitInstantiation || | ||||
18328 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | ||||
18329 | |||||
18330 | if (TryInstantiating) { | ||||
18331 | SourceLocation PointOfInstantiation = | ||||
18332 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | ||||
18333 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
18334 | if (FirstInstantiation) { | ||||
18335 | PointOfInstantiation = Loc; | ||||
18336 | if (MSI) | ||||
18337 | MSI->setPointOfInstantiation(PointOfInstantiation); | ||||
18338 | // FIXME: Notify listener. | ||||
18339 | else | ||||
18340 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
18341 | } | ||||
18342 | |||||
18343 | if (UsableInConstantExpr) { | ||||
18344 | // Do not defer instantiations of variables that could be used in a | ||||
18345 | // constant expression. | ||||
18346 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||
18347 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||
18348 | }); | ||||
18349 | |||||
18350 | // Re-set the member to trigger a recomputation of the dependence bits | ||||
18351 | // for the expression. | ||||
18352 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
18353 | DRE->setDecl(DRE->getDecl()); | ||||
18354 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
18355 | ME->setMemberDecl(ME->getMemberDecl()); | ||||
18356 | } else if (FirstInstantiation || | ||||
18357 | isa<VarTemplateSpecializationDecl>(Var)) { | ||||
18358 | // FIXME: For a specialization of a variable template, we don't | ||||
18359 | // distinguish between "declaration and type implicitly instantiated" | ||||
18360 | // and "implicit instantiation of definition requested", so we have | ||||
18361 | // no direct way to avoid enqueueing the pending instantiation | ||||
18362 | // multiple times. | ||||
18363 | SemaRef.PendingInstantiations | ||||
18364 | .push_back(std::make_pair(Var, PointOfInstantiation)); | ||||
18365 | } | ||||
18366 | } | ||||
18367 | } | ||||
18368 | |||||
18369 | // C++2a [basic.def.odr]p4: | ||||
18370 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
18371 | // is odr-used by e unless | ||||
18372 | // -- x is a reference that is usable in constant expressions | ||||
18373 | // -- x is a variable of non-reference type that is usable in constant | ||||
18374 | // expressions and has no mutable subobjects [FIXME], and e is an | ||||
18375 | // element of the set of potential results of an expression of | ||||
18376 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
18377 | // conversion is applied | ||||
18378 | // -- x is a variable of non-reference type, and e is an element of the set | ||||
18379 | // of potential results of a discarded-value expression to which the | ||||
18380 | // lvalue-to-rvalue conversion is not applied [FIXME] | ||||
18381 | // | ||||
18382 | // We check the first part of the second bullet here, and | ||||
18383 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | ||||
18384 | // FIXME: To get the third bullet right, we need to delay this even for | ||||
18385 | // variables that are not usable in constant expressions. | ||||
18386 | |||||
18387 | // If we already know this isn't an odr-use, there's nothing more to do. | ||||
18388 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
18389 | if (DRE->isNonOdrUse()) | ||||
18390 | return; | ||||
18391 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
18392 | if (ME->isNonOdrUse()) | ||||
18393 | return; | ||||
18394 | |||||
18395 | switch (OdrUse) { | ||||
18396 | case OdrUseContext::None: | ||||
18397 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18398, __PRETTY_FUNCTION__)) | ||||
18398 | "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18398, __PRETTY_FUNCTION__)); | ||||
18399 | break; | ||||
18400 | |||||
18401 | case OdrUseContext::FormallyOdrUsed: | ||||
18402 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | ||||
18403 | // behavior. | ||||
18404 | break; | ||||
18405 | |||||
18406 | case OdrUseContext::Used: | ||||
18407 | // If we might later find that this expression isn't actually an odr-use, | ||||
18408 | // delay the marking. | ||||
18409 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
18410 | SemaRef.MaybeODRUseExprs.insert(E); | ||||
18411 | else | ||||
18412 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | ||||
18413 | break; | ||||
18414 | |||||
18415 | case OdrUseContext::Dependent: | ||||
18416 | // If this is a dependent context, we don't need to mark variables as | ||||
18417 | // odr-used, but we may still need to track them for lambda capture. | ||||
18418 | // FIXME: Do we also need to do this inside dependent typeid expressions | ||||
18419 | // (which are modeled as unevaluated at this point)? | ||||
18420 | const bool RefersToEnclosingScope = | ||||
18421 | (SemaRef.CurContext != Var->getDeclContext() && | ||||
18422 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | ||||
18423 | if (RefersToEnclosingScope) { | ||||
18424 | LambdaScopeInfo *const LSI = | ||||
18425 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | ||||
18426 | if (LSI && (!LSI->CallOperator || | ||||
18427 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | ||||
18428 | // If a variable could potentially be odr-used, defer marking it so | ||||
18429 | // until we finish analyzing the full expression for any | ||||
18430 | // lvalue-to-rvalue | ||||
18431 | // or discarded value conversions that would obviate odr-use. | ||||
18432 | // Add it to the list of potential captures that will be analyzed | ||||
18433 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | ||||
18434 | // unless the variable is a reference that was initialized by a constant | ||||
18435 | // expression (this will never need to be captured or odr-used). | ||||
18436 | // | ||||
18437 | // FIXME: We can simplify this a lot after implementing P0588R1. | ||||
18438 | assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression." ) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18438, __PRETTY_FUNCTION__)); | ||||
18439 | if (!Var->getType()->isReferenceType() || | ||||
18440 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
18441 | LSI->addPotentialCapture(E->IgnoreParens()); | ||||
18442 | } | ||||
18443 | } | ||||
18444 | break; | ||||
18445 | } | ||||
18446 | } | ||||
18447 | |||||
18448 | /// Mark a variable referenced, and check whether it is odr-used | ||||
18449 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | ||||
18450 | /// used directly for normal expressions referring to VarDecl. | ||||
18451 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | ||||
18452 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); | ||||
18453 | } | ||||
18454 | |||||
18455 | static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, | ||||
18456 | Decl *D, Expr *E, bool MightBeOdrUse) { | ||||
18457 | if (SemaRef.isInOpenMPDeclareTargetContext()) | ||||
18458 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | ||||
18459 | |||||
18460 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | ||||
18461 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); | ||||
18462 | return; | ||||
18463 | } | ||||
18464 | |||||
18465 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | ||||
18466 | |||||
18467 | // If this is a call to a method via a cast, also mark the method in the | ||||
18468 | // derived class used in case codegen can devirtualize the call. | ||||
18469 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
18470 | if (!ME) | ||||
18471 | return; | ||||
18472 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
18473 | if (!MD) | ||||
18474 | return; | ||||
18475 | // Only attempt to devirtualize if this is truly a virtual call. | ||||
18476 | bool IsVirtualCall = MD->isVirtual() && | ||||
18477 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | ||||
18478 | if (!IsVirtualCall) | ||||
18479 | return; | ||||
18480 | |||||
18481 | // If it's possible to devirtualize the call, mark the called function | ||||
18482 | // referenced. | ||||
18483 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | ||||
18484 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | ||||
18485 | if (DM) | ||||
18486 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | ||||
18487 | } | ||||
18488 | |||||
18489 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | ||||
18490 | /// | ||||
18491 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to be | ||||
18492 | /// handled with care if the DeclRefExpr is not newly-created. | ||||
18493 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | ||||
18494 | // TODO: update this with DR# once a defect report is filed. | ||||
18495 | // C++11 defect. The address of a pure member should not be an ODR use, even | ||||
18496 | // if it's a qualified reference. | ||||
18497 | bool OdrUse = true; | ||||
18498 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | ||||
18499 | if (Method->isVirtual() && | ||||
18500 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | ||||
18501 | OdrUse = false; | ||||
18502 | |||||
18503 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||
18504 | if (!isConstantEvaluated() && FD->isConsteval() && | ||||
18505 | !RebuildingImmediateInvocation) | ||||
18506 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | ||||
18507 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); | ||||
18508 | } | ||||
18509 | |||||
18510 | /// Perform reference-marking and odr-use handling for a MemberExpr. | ||||
18511 | void Sema::MarkMemberReferenced(MemberExpr *E) { | ||||
18512 | // C++11 [basic.def.odr]p2: | ||||
18513 | // A non-overloaded function whose name appears as a potentially-evaluated | ||||
18514 | // expression or a member of a set of candidate functions, if selected by | ||||
18515 | // overload resolution when referred to from a potentially-evaluated | ||||
18516 | // expression, is odr-used, unless it is a pure virtual function and its | ||||
18517 | // name is not explicitly qualified. | ||||
18518 | bool MightBeOdrUse = true; | ||||
18519 | if (E->performsVirtualDispatch(getLangOpts())) { | ||||
18520 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | ||||
18521 | if (Method->isPure()) | ||||
18522 | MightBeOdrUse = false; | ||||
18523 | } | ||||
18524 | SourceLocation Loc = | ||||
18525 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | ||||
18526 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); | ||||
18527 | } | ||||
18528 | |||||
18529 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | ||||
18530 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | ||||
18531 | for (VarDecl *VD : *E) | ||||
18532 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); | ||||
18533 | } | ||||
18534 | |||||
18535 | /// Perform marking for a reference to an arbitrary declaration. It | ||||
18536 | /// marks the declaration referenced, and performs odr-use checking for | ||||
18537 | /// functions and variables. This method should not be used when building a | ||||
18538 | /// normal expression which refers to a variable. | ||||
18539 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | ||||
18540 | bool MightBeOdrUse) { | ||||
18541 | if (MightBeOdrUse) { | ||||
18542 | if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||
18543 | MarkVariableReferenced(Loc, VD); | ||||
18544 | return; | ||||
18545 | } | ||||
18546 | } | ||||
18547 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||
18548 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | ||||
18549 | return; | ||||
18550 | } | ||||
18551 | D->setReferenced(); | ||||
18552 | } | ||||
18553 | |||||
18554 | namespace { | ||||
18555 | // Mark all of the declarations used by a type as referenced. | ||||
18556 | // FIXME: Not fully implemented yet! We need to have a better understanding | ||||
18557 | // of when we're entering a context we should not recurse into. | ||||
18558 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | ||||
18559 | // TreeTransforms rebuilding the type in a new context. Rather than | ||||
18560 | // duplicating the TreeTransform logic, we should consider reusing it here. | ||||
18561 | // Currently that causes problems when rebuilding LambdaExprs. | ||||
18562 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | ||||
18563 | Sema &S; | ||||
18564 | SourceLocation Loc; | ||||
18565 | |||||
18566 | public: | ||||
18567 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | ||||
18568 | |||||
18569 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | ||||
18570 | |||||
18571 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | ||||
18572 | }; | ||||
18573 | } | ||||
18574 | |||||
18575 | bool MarkReferencedDecls::TraverseTemplateArgument( | ||||
18576 | const TemplateArgument &Arg) { | ||||
18577 | { | ||||
18578 | // A non-type template argument is a constant-evaluated context. | ||||
18579 | EnterExpressionEvaluationContext Evaluated( | ||||
18580 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
18581 | if (Arg.getKind() == TemplateArgument::Declaration) { | ||||
18582 | if (Decl *D = Arg.getAsDecl()) | ||||
18583 | S.MarkAnyDeclReferenced(Loc, D, true); | ||||
18584 | } else if (Arg.getKind() == TemplateArgument::Expression) { | ||||
18585 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | ||||
18586 | } | ||||
18587 | } | ||||
18588 | |||||
18589 | return Inherited::TraverseTemplateArgument(Arg); | ||||
18590 | } | ||||
18591 | |||||
18592 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | ||||
18593 | MarkReferencedDecls Marker(*this, Loc); | ||||
18594 | Marker.TraverseType(T); | ||||
18595 | } | ||||
18596 | |||||
18597 | namespace { | ||||
18598 | /// Helper class that marks all of the declarations referenced by | ||||
18599 | /// potentially-evaluated subexpressions as "referenced". | ||||
18600 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | ||||
18601 | public: | ||||
18602 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | ||||
18603 | bool SkipLocalVariables; | ||||
18604 | |||||
18605 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) | ||||
18606 | : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} | ||||
18607 | |||||
18608 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | ||||
18609 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | ||||
18610 | } | ||||
18611 | |||||
18612 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||
18613 | // If we were asked not to visit local variables, don't. | ||||
18614 | if (SkipLocalVariables) { | ||||
18615 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||
18616 | if (VD->hasLocalStorage()) | ||||
18617 | return; | ||||
18618 | } | ||||
18619 | |||||
18620 | // FIXME: This can trigger the instantiation of the initializer of a | ||||
18621 | // variable, which can cause the expression to become value-dependent | ||||
18622 | // or error-dependent. Do we need to propagate the new dependence bits? | ||||
18623 | S.MarkDeclRefReferenced(E); | ||||
18624 | } | ||||
18625 | |||||
18626 | void VisitMemberExpr(MemberExpr *E) { | ||||
18627 | S.MarkMemberReferenced(E); | ||||
18628 | Visit(E->getBase()); | ||||
18629 | } | ||||
18630 | }; | ||||
18631 | } // namespace | ||||
18632 | |||||
18633 | /// Mark any declarations that appear within this expression or any | ||||
18634 | /// potentially-evaluated subexpressions as "referenced". | ||||
18635 | /// | ||||
18636 | /// \param SkipLocalVariables If true, don't mark local variables as | ||||
18637 | /// 'referenced'. | ||||
18638 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | ||||
18639 | bool SkipLocalVariables) { | ||||
18640 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); | ||||
18641 | } | ||||
18642 | |||||
18643 | /// Emit a diagnostic that describes an effect on the run-time behavior | ||||
18644 | /// of the program being compiled. | ||||
18645 | /// | ||||
18646 | /// This routine emits the given diagnostic when the code currently being | ||||
18647 | /// type-checked is "potentially evaluated", meaning that there is a | ||||
18648 | /// possibility that the code will actually be executable. Code in sizeof() | ||||
18649 | /// expressions, code used only during overload resolution, etc., are not | ||||
18650 | /// potentially evaluated. This routine will suppress such diagnostics or, | ||||
18651 | /// in the absolutely nutty case of potentially potentially evaluated | ||||
18652 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | ||||
18653 | /// later. | ||||
18654 | /// | ||||
18655 | /// This routine should be used for all diagnostics that describe the run-time | ||||
18656 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | ||||
18657 | /// Failure to do so will likely result in spurious diagnostics or failures | ||||
18658 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | ||||
18659 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | ||||
18660 | const PartialDiagnostic &PD) { | ||||
18661 | switch (ExprEvalContexts.back().Context) { | ||||
18662 | case ExpressionEvaluationContext::Unevaluated: | ||||
18663 | case ExpressionEvaluationContext::UnevaluatedList: | ||||
18664 | case ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
18665 | case ExpressionEvaluationContext::DiscardedStatement: | ||||
18666 | // The argument will never be evaluated, so don't complain. | ||||
18667 | break; | ||||
18668 | |||||
18669 | case ExpressionEvaluationContext::ConstantEvaluated: | ||||
18670 | // Relevant diagnostics should be produced by constant evaluation. | ||||
18671 | break; | ||||
18672 | |||||
18673 | case ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
18674 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
18675 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | ||||
18676 | FunctionScopes.back()->PossiblyUnreachableDiags. | ||||
18677 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | ||||
18678 | return true; | ||||
18679 | } | ||||
18680 | |||||
18681 | // The initializer of a constexpr variable or of the first declaration of a | ||||
18682 | // static data member is not syntactically a constant evaluated constant, | ||||
18683 | // but nonetheless is always required to be a constant expression, so we | ||||
18684 | // can skip diagnosing. | ||||
18685 | // FIXME: Using the mangling context here is a hack. | ||||
18686 | if (auto *VD = dyn_cast_or_null<VarDecl>( | ||||
18687 | ExprEvalContexts.back().ManglingContextDecl)) { | ||||
18688 | if (VD->isConstexpr() || | ||||
18689 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | ||||
18690 | break; | ||||
18691 | // FIXME: For any other kind of variable, we should build a CFG for its | ||||
18692 | // initializer and check whether the context in question is reachable. | ||||
18693 | } | ||||
18694 | |||||
18695 | Diag(Loc, PD); | ||||
18696 | return true; | ||||
18697 | } | ||||
18698 | |||||
18699 | return false; | ||||
18700 | } | ||||
18701 | |||||
18702 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | ||||
18703 | const PartialDiagnostic &PD) { | ||||
18704 | return DiagRuntimeBehavior( | ||||
18705 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | ||||
18706 | } | ||||
18707 | |||||
18708 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | ||||
18709 | CallExpr *CE, FunctionDecl *FD) { | ||||
18710 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | ||||
18711 | return false; | ||||
18712 | |||||
18713 | // If we're inside a decltype's expression, don't check for a valid return | ||||
18714 | // type or construct temporaries until we know whether this is the last call. | ||||
18715 | if (ExprEvalContexts.back().ExprContext == | ||||
18716 | ExpressionEvaluationContextRecord::EK_Decltype) { | ||||
18717 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | ||||
18718 | return false; | ||||
18719 | } | ||||
18720 | |||||
18721 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | ||||
18722 | FunctionDecl *FD; | ||||
18723 | CallExpr *CE; | ||||
18724 | |||||
18725 | public: | ||||
18726 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | ||||
18727 | : FD(FD), CE(CE) { } | ||||
18728 | |||||
18729 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
18730 | if (!FD) { | ||||
18731 | S.Diag(Loc, diag::err_call_incomplete_return) | ||||
18732 | << T << CE->getSourceRange(); | ||||
18733 | return; | ||||
18734 | } | ||||
18735 | |||||
18736 | S.Diag(Loc, diag::err_call_function_incomplete_return) | ||||
18737 | << CE->getSourceRange() << FD << T; | ||||
18738 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | ||||
18739 | << FD->getDeclName(); | ||||
18740 | } | ||||
18741 | } Diagnoser(FD, CE); | ||||
18742 | |||||
18743 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | ||||
18744 | return true; | ||||
18745 | |||||
18746 | return false; | ||||
18747 | } | ||||
18748 | |||||
18749 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | ||||
18750 | // will prevent this condition from triggering, which is what we want. | ||||
18751 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | ||||
18752 | SourceLocation Loc; | ||||
18753 | |||||
18754 | unsigned diagnostic = diag::warn_condition_is_assignment; | ||||
18755 | bool IsOrAssign = false; | ||||
18756 | |||||
18757 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | ||||
18758 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | ||||
18759 | return; | ||||
18760 | |||||
18761 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | ||||
18762 | |||||
18763 | // Greylist some idioms by putting them into a warning subcategory. | ||||
18764 | if (ObjCMessageExpr *ME | ||||
18765 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | ||||
18766 | Selector Sel = ME->getSelector(); | ||||
18767 | |||||
18768 | // self = [<foo> init...] | ||||
18769 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | ||||
18770 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
18771 | |||||
18772 | // <foo> = [<bar> nextObject] | ||||
18773 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | ||||
18774 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
18775 | } | ||||
18776 | |||||
18777 | Loc = Op->getOperatorLoc(); | ||||
18778 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
18779 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | ||||
18780 | return; | ||||
18781 | |||||
18782 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | ||||
18783 | Loc = Op->getOperatorLoc(); | ||||
18784 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | ||||
18785 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | ||||
18786 | else { | ||||
18787 | // Not an assignment. | ||||
18788 | return; | ||||
18789 | } | ||||
18790 | |||||
18791 | Diag(Loc, diagnostic) << E->getSourceRange(); | ||||
18792 | |||||
18793 | SourceLocation Open = E->getBeginLoc(); | ||||
18794 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | ||||
18795 | Diag(Loc, diag::note_condition_assign_silence) | ||||
18796 | << FixItHint::CreateInsertion(Open, "(") | ||||
18797 | << FixItHint::CreateInsertion(Close, ")"); | ||||
18798 | |||||
18799 | if (IsOrAssign) | ||||
18800 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | ||||
18801 | << FixItHint::CreateReplacement(Loc, "!="); | ||||
18802 | else | ||||
18803 | Diag(Loc, diag::note_condition_assign_to_comparison) | ||||
18804 | << FixItHint::CreateReplacement(Loc, "=="); | ||||
18805 | } | ||||
18806 | |||||
18807 | /// Redundant parentheses over an equality comparison can indicate | ||||
18808 | /// that the user intended an assignment used as condition. | ||||
18809 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | ||||
18810 | // Don't warn if the parens came from a macro. | ||||
18811 | SourceLocation parenLoc = ParenE->getBeginLoc(); | ||||
18812 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | ||||
18813 | return; | ||||
18814 | // Don't warn for dependent expressions. | ||||
18815 | if (ParenE->isTypeDependent()) | ||||
18816 | return; | ||||
18817 | |||||
18818 | Expr *E = ParenE->IgnoreParens(); | ||||
18819 | |||||
18820 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | ||||
18821 | if (opE->getOpcode() == BO_EQ && | ||||
18822 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | ||||
18823 | == Expr::MLV_Valid) { | ||||
18824 | SourceLocation Loc = opE->getOperatorLoc(); | ||||
18825 | |||||
18826 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | ||||
18827 | SourceRange ParenERange = ParenE->getSourceRange(); | ||||
18828 | Diag(Loc, diag::note_equality_comparison_silence) | ||||
18829 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | ||||
18830 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | ||||
18831 | Diag(Loc, diag::note_equality_comparison_to_assign) | ||||
18832 | << FixItHint::CreateReplacement(Loc, "="); | ||||
18833 | } | ||||
18834 | } | ||||
18835 | |||||
18836 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | ||||
18837 | bool IsConstexpr) { | ||||
18838 | DiagnoseAssignmentAsCondition(E); | ||||
18839 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | ||||
18840 | DiagnoseEqualityWithExtraParens(parenE); | ||||
18841 | |||||
18842 | ExprResult result = CheckPlaceholderExpr(E); | ||||
18843 | if (result.isInvalid()) return ExprError(); | ||||
18844 | E = result.get(); | ||||
18845 | |||||
18846 | if (!E->isTypeDependent()) { | ||||
18847 | if (getLangOpts().CPlusPlus) | ||||
18848 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | ||||
18849 | |||||
18850 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | ||||
18851 | if (ERes.isInvalid()) | ||||
18852 | return ExprError(); | ||||
18853 | E = ERes.get(); | ||||
18854 | |||||
18855 | QualType T = E->getType(); | ||||
18856 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | ||||
18857 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | ||||
18858 | << T << E->getSourceRange(); | ||||
18859 | return ExprError(); | ||||
18860 | } | ||||
18861 | CheckBoolLikeConversion(E, Loc); | ||||
18862 | } | ||||
18863 | |||||
18864 | return E; | ||||
18865 | } | ||||
18866 | |||||
18867 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | ||||
18868 | Expr *SubExpr, ConditionKind CK) { | ||||
18869 | // Empty conditions are valid in for-statements. | ||||
18870 | if (!SubExpr) | ||||
18871 | return ConditionResult(); | ||||
18872 | |||||
18873 | ExprResult Cond; | ||||
18874 | switch (CK) { | ||||
18875 | case ConditionKind::Boolean: | ||||
18876 | Cond = CheckBooleanCondition(Loc, SubExpr); | ||||
18877 | break; | ||||
18878 | |||||
18879 | case ConditionKind::ConstexprIf: | ||||
18880 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | ||||
18881 | break; | ||||
18882 | |||||
18883 | case ConditionKind::Switch: | ||||
18884 | Cond = CheckSwitchCondition(Loc, SubExpr); | ||||
18885 | break; | ||||
18886 | } | ||||
18887 | if (Cond.isInvalid()) { | ||||
18888 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | ||||
18889 | {SubExpr}); | ||||
18890 | if (!Cond.get()) | ||||
18891 | return ConditionError(); | ||||
18892 | } | ||||
18893 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | ||||
18894 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | ||||
18895 | if (!FullExpr.get()) | ||||
18896 | return ConditionError(); | ||||
18897 | |||||
18898 | return ConditionResult(*this, nullptr, FullExpr, | ||||
18899 | CK == ConditionKind::ConstexprIf); | ||||
18900 | } | ||||
18901 | |||||
18902 | namespace { | ||||
18903 | /// A visitor for rebuilding a call to an __unknown_any expression | ||||
18904 | /// to have an appropriate type. | ||||
18905 | struct RebuildUnknownAnyFunction | ||||
18906 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | ||||
18907 | |||||
18908 | Sema &S; | ||||
18909 | |||||
18910 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | ||||
18911 | |||||
18912 | ExprResult VisitStmt(Stmt *S) { | ||||
18913 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18913); | ||||
18914 | } | ||||
18915 | |||||
18916 | ExprResult VisitExpr(Expr *E) { | ||||
18917 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | ||||
18918 | << E->getSourceRange(); | ||||
18919 | return ExprError(); | ||||
18920 | } | ||||
18921 | |||||
18922 | /// Rebuild an expression which simply semantically wraps another | ||||
18923 | /// expression which it shares the type and value kind of. | ||||
18924 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
18925 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
18926 | if (SubResult.isInvalid()) return ExprError(); | ||||
18927 | |||||
18928 | Expr *SubExpr = SubResult.get(); | ||||
18929 | E->setSubExpr(SubExpr); | ||||
18930 | E->setType(SubExpr->getType()); | ||||
18931 | E->setValueKind(SubExpr->getValueKind()); | ||||
18932 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18932, __PRETTY_FUNCTION__)); | ||||
18933 | return E; | ||||
18934 | } | ||||
18935 | |||||
18936 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
18937 | return rebuildSugarExpr(E); | ||||
18938 | } | ||||
18939 | |||||
18940 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
18941 | return rebuildSugarExpr(E); | ||||
18942 | } | ||||
18943 | |||||
18944 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
18945 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
18946 | if (SubResult.isInvalid()) return ExprError(); | ||||
18947 | |||||
18948 | Expr *SubExpr = SubResult.get(); | ||||
18949 | E->setSubExpr(SubExpr); | ||||
18950 | E->setType(S.Context.getPointerType(SubExpr->getType())); | ||||
18951 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18951, __PRETTY_FUNCTION__)); | ||||
18952 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18952, __PRETTY_FUNCTION__)); | ||||
18953 | return E; | ||||
18954 | } | ||||
18955 | |||||
18956 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | ||||
18957 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | ||||
18958 | |||||
18959 | E->setType(VD->getType()); | ||||
18960 | |||||
18961 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 18961, __PRETTY_FUNCTION__)); | ||||
18962 | if (S.getLangOpts().CPlusPlus && | ||||
18963 | !(isa<CXXMethodDecl>(VD) && | ||||
18964 | cast<CXXMethodDecl>(VD)->isInstance())) | ||||
18965 | E->setValueKind(VK_LValue); | ||||
18966 | |||||
18967 | return E; | ||||
18968 | } | ||||
18969 | |||||
18970 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
18971 | return resolveDecl(E, E->getMemberDecl()); | ||||
18972 | } | ||||
18973 | |||||
18974 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
18975 | return resolveDecl(E, E->getDecl()); | ||||
18976 | } | ||||
18977 | }; | ||||
18978 | } | ||||
18979 | |||||
18980 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
18981 | /// to have a function type. | ||||
18982 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | ||||
18983 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | ||||
18984 | if (Result.isInvalid()) return ExprError(); | ||||
18985 | return S.DefaultFunctionArrayConversion(Result.get()); | ||||
18986 | } | ||||
18987 | |||||
18988 | namespace { | ||||
18989 | /// A visitor for rebuilding an expression of type __unknown_anytype | ||||
18990 | /// into one which resolves the type directly on the referring | ||||
18991 | /// expression. Strict preservation of the original source | ||||
18992 | /// structure is not a goal. | ||||
18993 | struct RebuildUnknownAnyExpr | ||||
18994 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | ||||
18995 | |||||
18996 | Sema &S; | ||||
18997 | |||||
18998 | /// The current destination type. | ||||
18999 | QualType DestType; | ||||
19000 | |||||
19001 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | ||||
19002 | : S(S), DestType(CastType) {} | ||||
19003 | |||||
19004 | ExprResult VisitStmt(Stmt *S) { | ||||
19005 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19005); | ||||
19006 | } | ||||
19007 | |||||
19008 | ExprResult VisitExpr(Expr *E) { | ||||
19009 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
19010 | << E->getSourceRange(); | ||||
19011 | return ExprError(); | ||||
19012 | } | ||||
19013 | |||||
19014 | ExprResult VisitCallExpr(CallExpr *E); | ||||
19015 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | ||||
19016 | |||||
19017 | /// Rebuild an expression which simply semantically wraps another | ||||
19018 | /// expression which it shares the type and value kind of. | ||||
19019 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
19020 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
19021 | if (SubResult.isInvalid()) return ExprError(); | ||||
19022 | Expr *SubExpr = SubResult.get(); | ||||
19023 | E->setSubExpr(SubExpr); | ||||
19024 | E->setType(SubExpr->getType()); | ||||
19025 | E->setValueKind(SubExpr->getValueKind()); | ||||
19026 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19026, __PRETTY_FUNCTION__)); | ||||
19027 | return E; | ||||
19028 | } | ||||
19029 | |||||
19030 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
19031 | return rebuildSugarExpr(E); | ||||
19032 | } | ||||
19033 | |||||
19034 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
19035 | return rebuildSugarExpr(E); | ||||
19036 | } | ||||
19037 | |||||
19038 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
19039 | const PointerType *Ptr = DestType->getAs<PointerType>(); | ||||
19040 | if (!Ptr) { | ||||
19041 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | ||||
19042 | << E->getSourceRange(); | ||||
19043 | return ExprError(); | ||||
19044 | } | ||||
19045 | |||||
19046 | if (isa<CallExpr>(E->getSubExpr())) { | ||||
19047 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | ||||
19048 | << E->getSourceRange(); | ||||
19049 | return ExprError(); | ||||
19050 | } | ||||
19051 | |||||
19052 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19052, __PRETTY_FUNCTION__)); | ||||
19053 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19053, __PRETTY_FUNCTION__)); | ||||
19054 | E->setType(DestType); | ||||
19055 | |||||
19056 | // Build the sub-expression as if it were an object of the pointee type. | ||||
19057 | DestType = Ptr->getPointeeType(); | ||||
19058 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
19059 | if (SubResult.isInvalid()) return ExprError(); | ||||
19060 | E->setSubExpr(SubResult.get()); | ||||
19061 | return E; | ||||
19062 | } | ||||
19063 | |||||
19064 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | ||||
19065 | |||||
19066 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | ||||
19067 | |||||
19068 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
19069 | return resolveDecl(E, E->getMemberDecl()); | ||||
19070 | } | ||||
19071 | |||||
19072 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
19073 | return resolveDecl(E, E->getDecl()); | ||||
19074 | } | ||||
19075 | }; | ||||
19076 | } | ||||
19077 | |||||
19078 | /// Rebuilds a call expression which yielded __unknown_anytype. | ||||
19079 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | ||||
19080 | Expr *CalleeExpr = E->getCallee(); | ||||
19081 | |||||
19082 | enum FnKind { | ||||
19083 | FK_MemberFunction, | ||||
19084 | FK_FunctionPointer, | ||||
19085 | FK_BlockPointer | ||||
19086 | }; | ||||
19087 | |||||
19088 | FnKind Kind; | ||||
19089 | QualType CalleeType = CalleeExpr->getType(); | ||||
19090 | if (CalleeType == S.Context.BoundMemberTy) { | ||||
19091 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr >(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19091, __PRETTY_FUNCTION__)); | ||||
19092 | Kind = FK_MemberFunction; | ||||
19093 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | ||||
19094 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | ||||
19095 | CalleeType = Ptr->getPointeeType(); | ||||
19096 | Kind = FK_FunctionPointer; | ||||
19097 | } else { | ||||
19098 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | ||||
19099 | Kind = FK_BlockPointer; | ||||
19100 | } | ||||
19101 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | ||||
19102 | |||||
19103 | // Verify that this is a legal result type of a function. | ||||
19104 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
19105 | unsigned diagID = diag::err_func_returning_array_function; | ||||
19106 | if (Kind == FK_BlockPointer) | ||||
19107 | diagID = diag::err_block_returning_array_function; | ||||
19108 | |||||
19109 | S.Diag(E->getExprLoc(), diagID) | ||||
19110 | << DestType->isFunctionType() << DestType; | ||||
19111 | return ExprError(); | ||||
19112 | } | ||||
19113 | |||||
19114 | // Otherwise, go ahead and set DestType as the call's result. | ||||
19115 | E->setType(DestType.getNonLValueExprType(S.Context)); | ||||
19116 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
19117 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19117, __PRETTY_FUNCTION__)); | ||||
19118 | |||||
19119 | // Rebuild the function type, replacing the result type with DestType. | ||||
19120 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | ||||
19121 | if (Proto) { | ||||
19122 | // __unknown_anytype(...) is a special case used by the debugger when | ||||
19123 | // it has no idea what a function's signature is. | ||||
19124 | // | ||||
19125 | // We want to build this call essentially under the K&R | ||||
19126 | // unprototyped rules, but making a FunctionNoProtoType in C++ | ||||
19127 | // would foul up all sorts of assumptions. However, we cannot | ||||
19128 | // simply pass all arguments as variadic arguments, nor can we | ||||
19129 | // portably just call the function under a non-variadic type; see | ||||
19130 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | ||||
19131 | // However, it turns out that in practice it is generally safe to | ||||
19132 | // call a function declared as "A foo(B,C,D);" under the prototype | ||||
19133 | // "A foo(B,C,D,...);". The only known exception is with the | ||||
19134 | // Windows ABI, where any variadic function is implicitly cdecl | ||||
19135 | // regardless of its normal CC. Therefore we change the parameter | ||||
19136 | // types to match the types of the arguments. | ||||
19137 | // | ||||
19138 | // This is a hack, but it is far superior to moving the | ||||
19139 | // corresponding target-specific code from IR-gen to Sema/AST. | ||||
19140 | |||||
19141 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | ||||
19142 | SmallVector<QualType, 8> ArgTypes; | ||||
19143 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | ||||
19144 | ArgTypes.reserve(E->getNumArgs()); | ||||
19145 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | ||||
19146 | Expr *Arg = E->getArg(i); | ||||
19147 | QualType ArgType = Arg->getType(); | ||||
19148 | if (E->isLValue()) { | ||||
19149 | ArgType = S.Context.getLValueReferenceType(ArgType); | ||||
19150 | } else if (E->isXValue()) { | ||||
19151 | ArgType = S.Context.getRValueReferenceType(ArgType); | ||||
19152 | } | ||||
19153 | ArgTypes.push_back(ArgType); | ||||
19154 | } | ||||
19155 | ParamTypes = ArgTypes; | ||||
19156 | } | ||||
19157 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | ||||
19158 | Proto->getExtProtoInfo()); | ||||
19159 | } else { | ||||
19160 | DestType = S.Context.getFunctionNoProtoType(DestType, | ||||
19161 | FnType->getExtInfo()); | ||||
19162 | } | ||||
19163 | |||||
19164 | // Rebuild the appropriate pointer-to-function type. | ||||
19165 | switch (Kind) { | ||||
19166 | case FK_MemberFunction: | ||||
19167 | // Nothing to do. | ||||
19168 | break; | ||||
19169 | |||||
19170 | case FK_FunctionPointer: | ||||
19171 | DestType = S.Context.getPointerType(DestType); | ||||
19172 | break; | ||||
19173 | |||||
19174 | case FK_BlockPointer: | ||||
19175 | DestType = S.Context.getBlockPointerType(DestType); | ||||
19176 | break; | ||||
19177 | } | ||||
19178 | |||||
19179 | // Finally, we can recurse. | ||||
19180 | ExprResult CalleeResult = Visit(CalleeExpr); | ||||
19181 | if (!CalleeResult.isUsable()) return ExprError(); | ||||
19182 | E->setCallee(CalleeResult.get()); | ||||
19183 | |||||
19184 | // Bind a temporary if necessary. | ||||
19185 | return S.MaybeBindToTemporary(E); | ||||
19186 | } | ||||
19187 | |||||
19188 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | ||||
19189 | // Verify that this is a legal result type of a call. | ||||
19190 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
19191 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | ||||
19192 | << DestType->isFunctionType() << DestType; | ||||
19193 | return ExprError(); | ||||
19194 | } | ||||
19195 | |||||
19196 | // Rewrite the method result type if available. | ||||
19197 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | ||||
19198 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast <void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19198, __PRETTY_FUNCTION__)); | ||||
19199 | Method->setReturnType(DestType); | ||||
19200 | } | ||||
19201 | |||||
19202 | // Change the type of the message. | ||||
19203 | E->setType(DestType.getNonReferenceType()); | ||||
19204 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
19205 | |||||
19206 | return S.MaybeBindToTemporary(E); | ||||
19207 | } | ||||
19208 | |||||
19209 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
19210 | // The only case we should ever see here is a function-to-pointer decay. | ||||
19211 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | ||||
19212 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19212, __PRETTY_FUNCTION__)); | ||||
19213 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19213, __PRETTY_FUNCTION__)); | ||||
19214 | |||||
19215 | E->setType(DestType); | ||||
19216 | |||||
19217 | // Rebuild the sub-expression as the pointee (function) type. | ||||
19218 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | ||||
19219 | |||||
19220 | ExprResult Result = Visit(E->getSubExpr()); | ||||
19221 | if (!Result.isUsable()) return ExprError(); | ||||
19222 | |||||
19223 | E->setSubExpr(Result.get()); | ||||
19224 | return E; | ||||
19225 | } else if (E->getCastKind() == CK_LValueToRValue) { | ||||
19226 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19226, __PRETTY_FUNCTION__)); | ||||
19227 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19227, __PRETTY_FUNCTION__)); | ||||
19228 | |||||
19229 | assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast <void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19229, __PRETTY_FUNCTION__)); | ||||
19230 | |||||
19231 | E->setType(DestType); | ||||
19232 | |||||
19233 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | ||||
19234 | DestType = S.Context.getLValueReferenceType(DestType); | ||||
19235 | |||||
19236 | ExprResult Result = Visit(E->getSubExpr()); | ||||
19237 | if (!Result.isUsable()) return ExprError(); | ||||
19238 | |||||
19239 | E->setSubExpr(Result.get()); | ||||
19240 | return E; | ||||
19241 | } else { | ||||
19242 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19242); | ||||
19243 | } | ||||
19244 | } | ||||
19245 | |||||
19246 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | ||||
19247 | ExprValueKind ValueKind = VK_LValue; | ||||
19248 | QualType Type = DestType; | ||||
19249 | |||||
19250 | // We know how to make this work for certain kinds of decls: | ||||
19251 | |||||
19252 | // - functions | ||||
19253 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | ||||
19254 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | ||||
19255 | DestType = Ptr->getPointeeType(); | ||||
19256 | ExprResult Result = resolveDecl(E, VD); | ||||
19257 | if (Result.isInvalid()) return ExprError(); | ||||
19258 | return S.ImpCastExprToType(Result.get(), Type, | ||||
19259 | CK_FunctionToPointerDecay, VK_RValue); | ||||
19260 | } | ||||
19261 | |||||
19262 | if (!Type->isFunctionType()) { | ||||
19263 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | ||||
19264 | << VD << E->getSourceRange(); | ||||
19265 | return ExprError(); | ||||
19266 | } | ||||
19267 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | ||||
19268 | // We must match the FunctionDecl's type to the hack introduced in | ||||
19269 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | ||||
19270 | // type. See the lengthy commentary in that routine. | ||||
19271 | QualType FDT = FD->getType(); | ||||
19272 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | ||||
19273 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | ||||
19274 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
19275 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | ||||
19276 | SourceLocation Loc = FD->getLocation(); | ||||
19277 | FunctionDecl *NewFD = FunctionDecl::Create( | ||||
19278 | S.Context, FD->getDeclContext(), Loc, Loc, | ||||
19279 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | ||||
19280 | SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), | ||||
19281 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | ||||
19282 | |||||
19283 | if (FD->getQualifier()) | ||||
19284 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | ||||
19285 | |||||
19286 | SmallVector<ParmVarDecl*, 16> Params; | ||||
19287 | for (const auto &AI : FT->param_types()) { | ||||
19288 | ParmVarDecl *Param = | ||||
19289 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | ||||
19290 | Param->setScopeInfo(0, Params.size()); | ||||
19291 | Params.push_back(Param); | ||||
19292 | } | ||||
19293 | NewFD->setParams(Params); | ||||
19294 | DRE->setDecl(NewFD); | ||||
19295 | VD = DRE->getDecl(); | ||||
19296 | } | ||||
19297 | } | ||||
19298 | |||||
19299 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | ||||
19300 | if (MD->isInstance()) { | ||||
19301 | ValueKind = VK_RValue; | ||||
19302 | Type = S.Context.BoundMemberTy; | ||||
19303 | } | ||||
19304 | |||||
19305 | // Function references aren't l-values in C. | ||||
19306 | if (!S.getLangOpts().CPlusPlus) | ||||
19307 | ValueKind = VK_RValue; | ||||
19308 | |||||
19309 | // - variables | ||||
19310 | } else if (isa<VarDecl>(VD)) { | ||||
19311 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | ||||
19312 | Type = RefTy->getPointeeType(); | ||||
19313 | } else if (Type->isFunctionType()) { | ||||
19314 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | ||||
19315 | << VD << E->getSourceRange(); | ||||
19316 | return ExprError(); | ||||
19317 | } | ||||
19318 | |||||
19319 | // - nothing else | ||||
19320 | } else { | ||||
19321 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | ||||
19322 | << VD << E->getSourceRange(); | ||||
19323 | return ExprError(); | ||||
19324 | } | ||||
19325 | |||||
19326 | // Modifying the declaration like this is friendly to IR-gen but | ||||
19327 | // also really dangerous. | ||||
19328 | VD->setType(DestType); | ||||
19329 | E->setType(Type); | ||||
19330 | E->setValueKind(ValueKind); | ||||
19331 | return E; | ||||
19332 | } | ||||
19333 | |||||
19334 | /// Check a cast of an unknown-any type. We intentionally only | ||||
19335 | /// trigger this for C-style casts. | ||||
19336 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | ||||
19337 | Expr *CastExpr, CastKind &CastKind, | ||||
19338 | ExprValueKind &VK, CXXCastPath &Path) { | ||||
19339 | // The type we're casting to must be either void or complete. | ||||
19340 | if (!CastType->isVoidType() && | ||||
19341 | RequireCompleteType(TypeRange.getBegin(), CastType, | ||||
19342 | diag::err_typecheck_cast_to_incomplete)) | ||||
19343 | return ExprError(); | ||||
19344 | |||||
19345 | // Rewrite the casted expression from scratch. | ||||
19346 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | ||||
19347 | if (!result.isUsable()) return ExprError(); | ||||
19348 | |||||
19349 | CastExpr = result.get(); | ||||
19350 | VK = CastExpr->getValueKind(); | ||||
19351 | CastKind = CK_NoOp; | ||||
19352 | |||||
19353 | return CastExpr; | ||||
19354 | } | ||||
19355 | |||||
19356 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | ||||
19357 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | ||||
19358 | } | ||||
19359 | |||||
19360 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | ||||
19361 | Expr *arg, QualType ¶mType) { | ||||
19362 | // If the syntactic form of the argument is not an explicit cast of | ||||
19363 | // any sort, just do default argument promotion. | ||||
19364 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | ||||
19365 | if (!castArg) { | ||||
19366 | ExprResult result = DefaultArgumentPromotion(arg); | ||||
19367 | if (result.isInvalid()) return ExprError(); | ||||
19368 | paramType = result.get()->getType(); | ||||
19369 | return result; | ||||
19370 | } | ||||
19371 | |||||
19372 | // Otherwise, use the type that was written in the explicit cast. | ||||
19373 | assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0 ) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19373, __PRETTY_FUNCTION__)); | ||||
19374 | paramType = castArg->getTypeAsWritten(); | ||||
19375 | |||||
19376 | // Copy-initialize a parameter of that type. | ||||
19377 | InitializedEntity entity = | ||||
19378 | InitializedEntity::InitializeParameter(Context, paramType, | ||||
19379 | /*consumed*/ false); | ||||
19380 | return PerformCopyInitialization(entity, callLoc, arg); | ||||
19381 | } | ||||
19382 | |||||
19383 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | ||||
19384 | Expr *orig = E; | ||||
19385 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | ||||
19386 | while (true) { | ||||
19387 | E = E->IgnoreParenImpCasts(); | ||||
19388 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | ||||
19389 | E = call->getCallee(); | ||||
19390 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
19391 | } else { | ||||
19392 | break; | ||||
19393 | } | ||||
19394 | } | ||||
19395 | |||||
19396 | SourceLocation loc; | ||||
19397 | NamedDecl *d; | ||||
19398 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | ||||
19399 | loc = ref->getLocation(); | ||||
19400 | d = ref->getDecl(); | ||||
19401 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | ||||
19402 | loc = mem->getMemberLoc(); | ||||
19403 | d = mem->getMemberDecl(); | ||||
19404 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | ||||
19405 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
19406 | loc = msg->getSelectorStartLoc(); | ||||
19407 | d = msg->getMethodDecl(); | ||||
19408 | if (!d) { | ||||
19409 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | ||||
19410 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | ||||
19411 | << orig->getSourceRange(); | ||||
19412 | return ExprError(); | ||||
19413 | } | ||||
19414 | } else { | ||||
19415 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
19416 | << E->getSourceRange(); | ||||
19417 | return ExprError(); | ||||
19418 | } | ||||
19419 | |||||
19420 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | ||||
19421 | |||||
19422 | // Never recoverable. | ||||
19423 | return ExprError(); | ||||
19424 | } | ||||
19425 | |||||
19426 | /// Check for operands with placeholder types and complain if found. | ||||
19427 | /// Returns ExprError() if there was an error and no recovery was possible. | ||||
19428 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | ||||
19429 | if (!Context.isDependenceAllowed()) { | ||||
19430 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
19431 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
19432 | // been dealt with before checking the operands. | ||||
19433 | ExprResult Result = CorrectDelayedTyposInExpr(E); | ||||
19434 | if (!Result.isUsable()) return ExprError(); | ||||
19435 | E = Result.get(); | ||||
19436 | } | ||||
19437 | |||||
19438 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | ||||
19439 | if (!placeholderType) return E; | ||||
19440 | |||||
19441 | switch (placeholderType->getKind()) { | ||||
19442 | |||||
19443 | // Overloaded expressions. | ||||
19444 | case BuiltinType::Overload: { | ||||
19445 | // Try to resolve a single function template specialization. | ||||
19446 | // This is obligatory. | ||||
19447 | ExprResult Result = E; | ||||
19448 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | ||||
19449 | return Result; | ||||
19450 | |||||
19451 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||
19452 | // leaves Result unchanged on failure. | ||||
19453 | Result = E; | ||||
19454 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | ||||
19455 | return Result; | ||||
19456 | |||||
19457 | // If that failed, try to recover with a call. | ||||
19458 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | ||||
19459 | /*complain*/ true); | ||||
19460 | return Result; | ||||
19461 | } | ||||
19462 | |||||
19463 | // Bound member functions. | ||||
19464 | case BuiltinType::BoundMember: { | ||||
19465 | ExprResult result = E; | ||||
19466 | const Expr *BME = E->IgnoreParens(); | ||||
19467 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | ||||
19468 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | ||||
19469 | if (isa<CXXPseudoDestructorExpr>(BME)) { | ||||
19470 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | ||||
19471 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | ||||
19472 | if (ME->getMemberNameInfo().getName().getNameKind() == | ||||
19473 | DeclarationName::CXXDestructorName) | ||||
19474 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | ||||
19475 | } | ||||
19476 | tryToRecoverWithCall(result, PD, | ||||
19477 | /*complain*/ true); | ||||
19478 | return result; | ||||
19479 | } | ||||
19480 | |||||
19481 | // ARC unbridged casts. | ||||
19482 | case BuiltinType::ARCUnbridgedCast: { | ||||
19483 | Expr *realCast = stripARCUnbridgedCast(E); | ||||
19484 | diagnoseARCUnbridgedCast(realCast); | ||||
19485 | return realCast; | ||||
19486 | } | ||||
19487 | |||||
19488 | // Expressions of unknown type. | ||||
19489 | case BuiltinType::UnknownAny: | ||||
19490 | return diagnoseUnknownAnyExpr(*this, E); | ||||
19491 | |||||
19492 | // Pseudo-objects. | ||||
19493 | case BuiltinType::PseudoObject: | ||||
19494 | return checkPseudoObjectRValue(E); | ||||
19495 | |||||
19496 | case BuiltinType::BuiltinFn: { | ||||
19497 | // Accept __noop without parens by implicitly converting it to a call expr. | ||||
19498 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | ||||
19499 | if (DRE) { | ||||
19500 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | ||||
19501 | if (FD->getBuiltinID() == Builtin::BI__noop) { | ||||
19502 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | ||||
19503 | CK_BuiltinFnToFnPtr) | ||||
19504 | .get(); | ||||
19505 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | ||||
19506 | VK_RValue, SourceLocation(), | ||||
19507 | FPOptionsOverride()); | ||||
19508 | } | ||||
19509 | } | ||||
19510 | |||||
19511 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | ||||
19512 | return ExprError(); | ||||
19513 | } | ||||
19514 | |||||
19515 | case BuiltinType::IncompleteMatrixIdx: | ||||
19516 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | ||||
19517 | ->getRowIdx() | ||||
19518 | ->getBeginLoc(), | ||||
19519 | diag::err_matrix_incomplete_index); | ||||
19520 | return ExprError(); | ||||
19521 | |||||
19522 | // Expressions of unknown type. | ||||
19523 | case BuiltinType::OMPArraySection: | ||||
19524 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | ||||
19525 | return ExprError(); | ||||
19526 | |||||
19527 | // Expressions of unknown type. | ||||
19528 | case BuiltinType::OMPArrayShaping: | ||||
19529 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | ||||
19530 | |||||
19531 | case BuiltinType::OMPIterator: | ||||
19532 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | ||||
19533 | |||||
19534 | // Everything else should be impossible. | ||||
19535 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
19536 | case BuiltinType::Id: | ||||
19537 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
19538 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
19539 | case BuiltinType::Id: | ||||
19540 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
19541 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
19542 | case BuiltinType::Id: | ||||
19543 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
19544 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
19545 | case BuiltinType::Id: | ||||
19546 | #include "clang/Basic/PPCTypes.def" | ||||
19547 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
19548 | #include "clang/Basic/RISCVVTypes.def" | ||||
19549 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | ||||
19550 | #define PLACEHOLDER_TYPE(Id, SingletonId) | ||||
19551 | #include "clang/AST/BuiltinTypes.def" | ||||
19552 | break; | ||||
19553 | } | ||||
19554 | |||||
19555 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19555); | ||||
19556 | } | ||||
19557 | |||||
19558 | bool Sema::CheckCaseExpression(Expr *E) { | ||||
19559 | if (E->isTypeDependent()) | ||||
19560 | return true; | ||||
19561 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | ||||
19562 | return E->getType()->isIntegralOrEnumerationType(); | ||||
19563 | return false; | ||||
19564 | } | ||||
19565 | |||||
19566 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | ||||
19567 | ExprResult | ||||
19568 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | ||||
19569 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19570, __PRETTY_FUNCTION__)) | ||||
19570 | "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExpr.cpp" , 19570, __PRETTY_FUNCTION__)); | ||||
19571 | QualType BoolT = Context.ObjCBuiltinBoolTy; | ||||
19572 | if (!Context.getBOOLDecl()) { | ||||
19573 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | ||||
19574 | Sema::LookupOrdinaryName); | ||||
19575 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | ||||
19576 | NamedDecl *ND = Result.getFoundDecl(); | ||||
19577 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | ||||
19578 | Context.setBOOLDecl(TD); | ||||
19579 | } | ||||
19580 | } | ||||
19581 | if (Context.getBOOLDecl()) | ||||
19582 | BoolT = Context.getBOOLType(); | ||||
19583 | return new (Context) | ||||
19584 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | ||||
19585 | } | ||||
19586 | |||||
19587 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | ||||
19588 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | ||||
19589 | SourceLocation RParen) { | ||||
19590 | |||||
19591 | StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); | ||||
19592 | |||||
19593 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
19594 | return Spec.getPlatform() == Platform; | ||||
19595 | }); | ||||
19596 | |||||
19597 | VersionTuple Version; | ||||
19598 | if (Spec != AvailSpecs.end()) | ||||
19599 | Version = Spec->getVersion(); | ||||
19600 | |||||
19601 | // The use of `@available` in the enclosing function should be analyzed to | ||||
19602 | // warn when it's used inappropriately (i.e. not if(@available)). | ||||
19603 | if (getCurFunctionOrMethodDecl()) | ||||
19604 | getEnclosingFunction()->HasPotentialAvailabilityViolations = true; | ||||
19605 | else if (getCurBlock() || getCurLambda()) | ||||
19606 | getCurFunction()->HasPotentialAvailabilityViolations = true; | ||||
19607 | |||||
19608 | return new (Context) | ||||
19609 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | ||||
19610 | } | ||||
19611 | |||||
19612 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | ||||
19613 | ArrayRef<Expr *> SubExprs, QualType T) { | ||||
19614 | if (!Context.getLangOpts().RecoveryAST) | ||||
19615 | return ExprError(); | ||||
19616 | |||||
19617 | if (isSFINAEContext()) | ||||
19618 | return ExprError(); | ||||
19619 | |||||
19620 | if (T.isNull() || !Context.getLangOpts().RecoveryASTType) | ||||
19621 | // We don't know the concrete type, fallback to dependent type. | ||||
19622 | T = Context.DependentTy; | ||||
19623 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | ||||
19624 | } |
1 | //===- Type.h - C Language Family Type Representation -----------*- 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 | /// \file |
10 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/DependenceFlags.h" |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/TemplateName.h" |
23 | #include "clang/Basic/AddressSpaces.h" |
24 | #include "clang/Basic/AttrKinds.h" |
25 | #include "clang/Basic/Diagnostic.h" |
26 | #include "clang/Basic/ExceptionSpecificationType.h" |
27 | #include "clang/Basic/LLVM.h" |
28 | #include "clang/Basic/Linkage.h" |
29 | #include "clang/Basic/PartialDiagnostic.h" |
30 | #include "clang/Basic/SourceLocation.h" |
31 | #include "clang/Basic/Specifiers.h" |
32 | #include "clang/Basic/Visibility.h" |
33 | #include "llvm/ADT/APInt.h" |
34 | #include "llvm/ADT/APSInt.h" |
35 | #include "llvm/ADT/ArrayRef.h" |
36 | #include "llvm/ADT/FoldingSet.h" |
37 | #include "llvm/ADT/None.h" |
38 | #include "llvm/ADT/Optional.h" |
39 | #include "llvm/ADT/PointerIntPair.h" |
40 | #include "llvm/ADT/PointerUnion.h" |
41 | #include "llvm/ADT/StringRef.h" |
42 | #include "llvm/ADT/Twine.h" |
43 | #include "llvm/ADT/iterator_range.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/Compiler.h" |
46 | #include "llvm/Support/ErrorHandling.h" |
47 | #include "llvm/Support/PointerLikeTypeTraits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include "llvm/Support/type_traits.h" |
50 | #include <cassert> |
51 | #include <cstddef> |
52 | #include <cstdint> |
53 | #include <cstring> |
54 | #include <string> |
55 | #include <type_traits> |
56 | #include <utility> |
57 | |
58 | namespace clang { |
59 | |
60 | class ExtQuals; |
61 | class QualType; |
62 | class ConceptDecl; |
63 | class TagDecl; |
64 | class TemplateParameterList; |
65 | class Type; |
66 | |
67 | enum { |
68 | TypeAlignmentInBits = 4, |
69 | TypeAlignment = 1 << TypeAlignmentInBits |
70 | }; |
71 | |
72 | namespace serialization { |
73 | template <class T> class AbstractTypeReader; |
74 | template <class T> class AbstractTypeWriter; |
75 | } |
76 | |
77 | } // namespace clang |
78 | |
79 | namespace llvm { |
80 | |
81 | template <typename T> |
82 | struct PointerLikeTypeTraits; |
83 | template<> |
84 | struct PointerLikeTypeTraits< ::clang::Type*> { |
85 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
86 | |
87 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
88 | return static_cast< ::clang::Type*>(P); |
89 | } |
90 | |
91 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
92 | }; |
93 | |
94 | template<> |
95 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
96 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
97 | |
98 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
99 | return static_cast< ::clang::ExtQuals*>(P); |
100 | } |
101 | |
102 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
103 | }; |
104 | |
105 | } // namespace llvm |
106 | |
107 | namespace clang { |
108 | |
109 | class ASTContext; |
110 | template <typename> class CanQual; |
111 | class CXXRecordDecl; |
112 | class DeclContext; |
113 | class EnumDecl; |
114 | class Expr; |
115 | class ExtQualsTypeCommonBase; |
116 | class FunctionDecl; |
117 | class IdentifierInfo; |
118 | class NamedDecl; |
119 | class ObjCInterfaceDecl; |
120 | class ObjCProtocolDecl; |
121 | class ObjCTypeParamDecl; |
122 | struct PrintingPolicy; |
123 | class RecordDecl; |
124 | class Stmt; |
125 | class TagDecl; |
126 | class TemplateArgument; |
127 | class TemplateArgumentListInfo; |
128 | class TemplateArgumentLoc; |
129 | class TemplateTypeParmDecl; |
130 | class TypedefNameDecl; |
131 | class UnresolvedUsingTypenameDecl; |
132 | |
133 | using CanQualType = CanQual<Type>; |
134 | |
135 | // Provide forward declarations for all of the *Type classes. |
136 | #define TYPE(Class, Base) class Class##Type; |
137 | #include "clang/AST/TypeNodes.inc" |
138 | |
139 | /// The collection of all-type qualifiers we support. |
140 | /// Clang supports five independent qualifiers: |
141 | /// * C99: const, volatile, and restrict |
142 | /// * MS: __unaligned |
143 | /// * Embedded C (TR18037): address spaces |
144 | /// * Objective C: the GC attributes (none, weak, or strong) |
145 | class Qualifiers { |
146 | public: |
147 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
148 | Const = 0x1, |
149 | Restrict = 0x2, |
150 | Volatile = 0x4, |
151 | CVRMask = Const | Volatile | Restrict |
152 | }; |
153 | |
154 | enum GC { |
155 | GCNone = 0, |
156 | Weak, |
157 | Strong |
158 | }; |
159 | |
160 | enum ObjCLifetime { |
161 | /// There is no lifetime qualification on this type. |
162 | OCL_None, |
163 | |
164 | /// This object can be modified without requiring retains or |
165 | /// releases. |
166 | OCL_ExplicitNone, |
167 | |
168 | /// Assigning into this object requires the old value to be |
169 | /// released and the new value to be retained. The timing of the |
170 | /// release of the old value is inexact: it may be moved to |
171 | /// immediately after the last known point where the value is |
172 | /// live. |
173 | OCL_Strong, |
174 | |
175 | /// Reading or writing from this object requires a barrier call. |
176 | OCL_Weak, |
177 | |
178 | /// Assigning into this object requires a lifetime extension. |
179 | OCL_Autoreleasing |
180 | }; |
181 | |
182 | enum { |
183 | /// The maximum supported address space number. |
184 | /// 23 bits should be enough for anyone. |
185 | MaxAddressSpace = 0x7fffffu, |
186 | |
187 | /// The width of the "fast" qualifier mask. |
188 | FastWidth = 3, |
189 | |
190 | /// The fast qualifier mask. |
191 | FastMask = (1 << FastWidth) - 1 |
192 | }; |
193 | |
194 | /// Returns the common set of qualifiers while removing them from |
195 | /// the given sets. |
196 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
197 | // If both are only CVR-qualified, bit operations are sufficient. |
198 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
199 | Qualifiers Q; |
200 | Q.Mask = L.Mask & R.Mask; |
201 | L.Mask &= ~Q.Mask; |
202 | R.Mask &= ~Q.Mask; |
203 | return Q; |
204 | } |
205 | |
206 | Qualifiers Q; |
207 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
208 | Q.addCVRQualifiers(CommonCRV); |
209 | L.removeCVRQualifiers(CommonCRV); |
210 | R.removeCVRQualifiers(CommonCRV); |
211 | |
212 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
213 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
214 | L.removeObjCGCAttr(); |
215 | R.removeObjCGCAttr(); |
216 | } |
217 | |
218 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
219 | Q.setObjCLifetime(L.getObjCLifetime()); |
220 | L.removeObjCLifetime(); |
221 | R.removeObjCLifetime(); |
222 | } |
223 | |
224 | if (L.getAddressSpace() == R.getAddressSpace()) { |
225 | Q.setAddressSpace(L.getAddressSpace()); |
226 | L.removeAddressSpace(); |
227 | R.removeAddressSpace(); |
228 | } |
229 | return Q; |
230 | } |
231 | |
232 | static Qualifiers fromFastMask(unsigned Mask) { |
233 | Qualifiers Qs; |
234 | Qs.addFastQualifiers(Mask); |
235 | return Qs; |
236 | } |
237 | |
238 | static Qualifiers fromCVRMask(unsigned CVR) { |
239 | Qualifiers Qs; |
240 | Qs.addCVRQualifiers(CVR); |
241 | return Qs; |
242 | } |
243 | |
244 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
245 | Qualifiers Qs; |
246 | Qs.addCVRUQualifiers(CVRU); |
247 | return Qs; |
248 | } |
249 | |
250 | // Deserialize qualifiers from an opaque representation. |
251 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
252 | Qualifiers Qs; |
253 | Qs.Mask = opaque; |
254 | return Qs; |
255 | } |
256 | |
257 | // Serialize these qualifiers into an opaque representation. |
258 | unsigned getAsOpaqueValue() const { |
259 | return Mask; |
260 | } |
261 | |
262 | bool hasConst() const { return Mask & Const; } |
263 | bool hasOnlyConst() const { return Mask == Const; } |
264 | void removeConst() { Mask &= ~Const; } |
265 | void addConst() { Mask |= Const; } |
266 | |
267 | bool hasVolatile() const { return Mask & Volatile; } |
268 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
269 | void removeVolatile() { Mask &= ~Volatile; } |
270 | void addVolatile() { Mask |= Volatile; } |
271 | |
272 | bool hasRestrict() const { return Mask & Restrict; } |
273 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
274 | void removeRestrict() { Mask &= ~Restrict; } |
275 | void addRestrict() { Mask |= Restrict; } |
276 | |
277 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
278 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
279 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
280 | |
281 | void setCVRQualifiers(unsigned mask) { |
282 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 282, __PRETTY_FUNCTION__)); |
283 | Mask = (Mask & ~CVRMask) | mask; |
284 | } |
285 | void removeCVRQualifiers(unsigned mask) { |
286 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 286, __PRETTY_FUNCTION__)); |
287 | Mask &= ~mask; |
288 | } |
289 | void removeCVRQualifiers() { |
290 | removeCVRQualifiers(CVRMask); |
291 | } |
292 | void addCVRQualifiers(unsigned mask) { |
293 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 293, __PRETTY_FUNCTION__)); |
294 | Mask |= mask; |
295 | } |
296 | void addCVRUQualifiers(unsigned mask) { |
297 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 297, __PRETTY_FUNCTION__)); |
298 | Mask |= mask; |
299 | } |
300 | |
301 | bool hasUnaligned() const { return Mask & UMask; } |
302 | void setUnaligned(bool flag) { |
303 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
304 | } |
305 | void removeUnaligned() { Mask &= ~UMask; } |
306 | void addUnaligned() { Mask |= UMask; } |
307 | |
308 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
309 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
310 | void setObjCGCAttr(GC type) { |
311 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
312 | } |
313 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
314 | void addObjCGCAttr(GC type) { |
315 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 315, __PRETTY_FUNCTION__)); |
316 | setObjCGCAttr(type); |
317 | } |
318 | Qualifiers withoutObjCGCAttr() const { |
319 | Qualifiers qs = *this; |
320 | qs.removeObjCGCAttr(); |
321 | return qs; |
322 | } |
323 | Qualifiers withoutObjCLifetime() const { |
324 | Qualifiers qs = *this; |
325 | qs.removeObjCLifetime(); |
326 | return qs; |
327 | } |
328 | Qualifiers withoutAddressSpace() const { |
329 | Qualifiers qs = *this; |
330 | qs.removeAddressSpace(); |
331 | return qs; |
332 | } |
333 | |
334 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
335 | ObjCLifetime getObjCLifetime() const { |
336 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
337 | } |
338 | void setObjCLifetime(ObjCLifetime type) { |
339 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
340 | } |
341 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
342 | void addObjCLifetime(ObjCLifetime type) { |
343 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 343, __PRETTY_FUNCTION__)); |
344 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 344, __PRETTY_FUNCTION__)); |
345 | Mask |= (type << LifetimeShift); |
346 | } |
347 | |
348 | /// True if the lifetime is neither None or ExplicitNone. |
349 | bool hasNonTrivialObjCLifetime() const { |
350 | ObjCLifetime lifetime = getObjCLifetime(); |
351 | return (lifetime > OCL_ExplicitNone); |
352 | } |
353 | |
354 | /// True if the lifetime is either strong or weak. |
355 | bool hasStrongOrWeakObjCLifetime() const { |
356 | ObjCLifetime lifetime = getObjCLifetime(); |
357 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
358 | } |
359 | |
360 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
361 | LangAS getAddressSpace() const { |
362 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
363 | } |
364 | bool hasTargetSpecificAddressSpace() const { |
365 | return isTargetAddressSpace(getAddressSpace()); |
366 | } |
367 | /// Get the address space attribute value to be printed by diagnostics. |
368 | unsigned getAddressSpaceAttributePrintValue() const { |
369 | auto Addr = getAddressSpace(); |
370 | // This function is not supposed to be used with language specific |
371 | // address spaces. If that happens, the diagnostic message should consider |
372 | // printing the QualType instead of the address space value. |
373 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 373, __PRETTY_FUNCTION__)); |
374 | if (Addr != LangAS::Default) |
375 | return toTargetAddressSpace(Addr); |
376 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
377 | // since it cannot differentiate the situation where 0 denotes the default |
378 | // address space or user specified __attribute__((address_space(0))). |
379 | return 0; |
380 | } |
381 | void setAddressSpace(LangAS space) { |
382 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 382, __PRETTY_FUNCTION__)); |
383 | Mask = (Mask & ~AddressSpaceMask) |
384 | | (((uint32_t) space) << AddressSpaceShift); |
385 | } |
386 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
387 | void addAddressSpace(LangAS space) { |
388 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 388, __PRETTY_FUNCTION__)); |
389 | setAddressSpace(space); |
390 | } |
391 | |
392 | // Fast qualifiers are those that can be allocated directly |
393 | // on a QualType object. |
394 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
395 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
396 | void setFastQualifiers(unsigned mask) { |
397 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 397, __PRETTY_FUNCTION__)); |
398 | Mask = (Mask & ~FastMask) | mask; |
399 | } |
400 | void removeFastQualifiers(unsigned mask) { |
401 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 401, __PRETTY_FUNCTION__)); |
402 | Mask &= ~mask; |
403 | } |
404 | void removeFastQualifiers() { |
405 | removeFastQualifiers(FastMask); |
406 | } |
407 | void addFastQualifiers(unsigned mask) { |
408 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 408, __PRETTY_FUNCTION__)); |
409 | Mask |= mask; |
410 | } |
411 | |
412 | /// Return true if the set contains any qualifiers which require an ExtQuals |
413 | /// node to be allocated. |
414 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
415 | Qualifiers getNonFastQualifiers() const { |
416 | Qualifiers Quals = *this; |
417 | Quals.setFastQualifiers(0); |
418 | return Quals; |
419 | } |
420 | |
421 | /// Return true if the set contains any qualifiers. |
422 | bool hasQualifiers() const { return Mask; } |
423 | bool empty() const { return !Mask; } |
424 | |
425 | /// Add the qualifiers from the given set to this set. |
426 | void addQualifiers(Qualifiers Q) { |
427 | // If the other set doesn't have any non-boolean qualifiers, just |
428 | // bit-or it in. |
429 | if (!(Q.Mask & ~CVRMask)) |
430 | Mask |= Q.Mask; |
431 | else { |
432 | Mask |= (Q.Mask & CVRMask); |
433 | if (Q.hasAddressSpace()) |
434 | addAddressSpace(Q.getAddressSpace()); |
435 | if (Q.hasObjCGCAttr()) |
436 | addObjCGCAttr(Q.getObjCGCAttr()); |
437 | if (Q.hasObjCLifetime()) |
438 | addObjCLifetime(Q.getObjCLifetime()); |
439 | } |
440 | } |
441 | |
442 | /// Remove the qualifiers from the given set from this set. |
443 | void removeQualifiers(Qualifiers Q) { |
444 | // If the other set doesn't have any non-boolean qualifiers, just |
445 | // bit-and the inverse in. |
446 | if (!(Q.Mask & ~CVRMask)) |
447 | Mask &= ~Q.Mask; |
448 | else { |
449 | Mask &= ~(Q.Mask & CVRMask); |
450 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
451 | removeObjCGCAttr(); |
452 | if (getObjCLifetime() == Q.getObjCLifetime()) |
453 | removeObjCLifetime(); |
454 | if (getAddressSpace() == Q.getAddressSpace()) |
455 | removeAddressSpace(); |
456 | } |
457 | } |
458 | |
459 | /// Add the qualifiers from the given set to this set, given that |
460 | /// they don't conflict. |
461 | void addConsistentQualifiers(Qualifiers qs) { |
462 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)) |
463 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)); |
464 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)) |
465 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)); |
466 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)) |
467 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)); |
468 | Mask |= qs.Mask; |
469 | } |
470 | |
471 | /// Returns true if address space A is equal to or a superset of B. |
472 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
473 | /// overlapping address spaces. |
474 | /// CL1.1 or CL1.2: |
475 | /// every address space is a superset of itself. |
476 | /// CL2.0 adds: |
477 | /// __generic is a superset of any address space except for __constant. |
478 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
479 | // Address spaces must match exactly. |
480 | return A == B || |
481 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
482 | // for __constant can be used as __generic. |
483 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || |
484 | // We also define global_device and global_host address spaces, |
485 | // to distinguish global pointers allocated on host from pointers |
486 | // allocated on device, which are a subset of __global. |
487 | (A == LangAS::opencl_global && (B == LangAS::opencl_global_device || |
488 | B == LangAS::opencl_global_host)) || |
489 | // Consider pointer size address spaces to be equivalent to default. |
490 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
491 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)); |
492 | } |
493 | |
494 | /// Returns true if the address space in these qualifiers is equal to or |
495 | /// a superset of the address space in the argument qualifiers. |
496 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
497 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
498 | } |
499 | |
500 | /// Determines if these qualifiers compatibly include another set. |
501 | /// Generally this answers the question of whether an object with the other |
502 | /// qualifiers can be safely used as an object with these qualifiers. |
503 | bool compatiblyIncludes(Qualifiers other) const { |
504 | return isAddressSpaceSupersetOf(other) && |
505 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
506 | // be changed. |
507 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
508 | !other.hasObjCGCAttr()) && |
509 | // ObjC lifetime qualifiers must match exactly. |
510 | getObjCLifetime() == other.getObjCLifetime() && |
511 | // CVR qualifiers may subset. |
512 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
513 | // U qualifier may superset. |
514 | (!other.hasUnaligned() || hasUnaligned()); |
515 | } |
516 | |
517 | /// Determines if these qualifiers compatibly include another set of |
518 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
519 | /// |
520 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
521 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
522 | /// including set also contains the 'const' qualifier, or both are non-__weak |
523 | /// and one is None (which can only happen in non-ARC modes). |
524 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
525 | if (getObjCLifetime() == other.getObjCLifetime()) |
526 | return true; |
527 | |
528 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
529 | return false; |
530 | |
531 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
532 | return true; |
533 | |
534 | return hasConst(); |
535 | } |
536 | |
537 | /// Determine whether this set of qualifiers is a strict superset of |
538 | /// another set of qualifiers, not considering qualifier compatibility. |
539 | bool isStrictSupersetOf(Qualifiers Other) const; |
540 | |
541 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
542 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
543 | |
544 | explicit operator bool() const { return hasQualifiers(); } |
545 | |
546 | Qualifiers &operator+=(Qualifiers R) { |
547 | addQualifiers(R); |
548 | return *this; |
549 | } |
550 | |
551 | // Union two qualifier sets. If an enumerated qualifier appears |
552 | // in both sets, use the one from the right. |
553 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
554 | L += R; |
555 | return L; |
556 | } |
557 | |
558 | Qualifiers &operator-=(Qualifiers R) { |
559 | removeQualifiers(R); |
560 | return *this; |
561 | } |
562 | |
563 | /// Compute the difference between two qualifier sets. |
564 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
565 | L -= R; |
566 | return L; |
567 | } |
568 | |
569 | std::string getAsString() const; |
570 | std::string getAsString(const PrintingPolicy &Policy) const; |
571 | |
572 | static std::string getAddrSpaceAsString(LangAS AS); |
573 | |
574 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
575 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
576 | bool appendSpaceIfNonEmpty = false) const; |
577 | |
578 | void Profile(llvm::FoldingSetNodeID &ID) const { |
579 | ID.AddInteger(Mask); |
580 | } |
581 | |
582 | private: |
583 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
584 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
585 | uint32_t Mask = 0; |
586 | |
587 | static const uint32_t UMask = 0x8; |
588 | static const uint32_t UShift = 3; |
589 | static const uint32_t GCAttrMask = 0x30; |
590 | static const uint32_t GCAttrShift = 4; |
591 | static const uint32_t LifetimeMask = 0x1C0; |
592 | static const uint32_t LifetimeShift = 6; |
593 | static const uint32_t AddressSpaceMask = |
594 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
595 | static const uint32_t AddressSpaceShift = 9; |
596 | }; |
597 | |
598 | /// A std::pair-like structure for storing a qualified type split |
599 | /// into its local qualifiers and its locally-unqualified type. |
600 | struct SplitQualType { |
601 | /// The locally-unqualified type. |
602 | const Type *Ty = nullptr; |
603 | |
604 | /// The local qualifiers. |
605 | Qualifiers Quals; |
606 | |
607 | SplitQualType() = default; |
608 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
609 | |
610 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
611 | |
612 | // Make std::tie work. |
613 | std::pair<const Type *,Qualifiers> asPair() const { |
614 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
615 | } |
616 | |
617 | friend bool operator==(SplitQualType a, SplitQualType b) { |
618 | return a.Ty == b.Ty && a.Quals == b.Quals; |
619 | } |
620 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
621 | return a.Ty != b.Ty || a.Quals != b.Quals; |
622 | } |
623 | }; |
624 | |
625 | /// The kind of type we are substituting Objective-C type arguments into. |
626 | /// |
627 | /// The kind of substitution affects the replacement of type parameters when |
628 | /// no concrete type information is provided, e.g., when dealing with an |
629 | /// unspecialized type. |
630 | enum class ObjCSubstitutionContext { |
631 | /// An ordinary type. |
632 | Ordinary, |
633 | |
634 | /// The result type of a method or function. |
635 | Result, |
636 | |
637 | /// The parameter type of a method or function. |
638 | Parameter, |
639 | |
640 | /// The type of a property. |
641 | Property, |
642 | |
643 | /// The superclass of a type. |
644 | Superclass, |
645 | }; |
646 | |
647 | /// A (possibly-)qualified type. |
648 | /// |
649 | /// For efficiency, we don't store CV-qualified types as nodes on their |
650 | /// own: instead each reference to a type stores the qualifiers. This |
651 | /// greatly reduces the number of nodes we need to allocate for types (for |
652 | /// example we only need one for 'int', 'const int', 'volatile int', |
653 | /// 'const volatile int', etc). |
654 | /// |
655 | /// As an added efficiency bonus, instead of making this a pair, we |
656 | /// just store the two bits we care about in the low bits of the |
657 | /// pointer. To handle the packing/unpacking, we make QualType be a |
658 | /// simple wrapper class that acts like a smart pointer. A third bit |
659 | /// indicates whether there are extended qualifiers present, in which |
660 | /// case the pointer points to a special structure. |
661 | class QualType { |
662 | friend class QualifierCollector; |
663 | |
664 | // Thankfully, these are efficiently composable. |
665 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
666 | Qualifiers::FastWidth> Value; |
667 | |
668 | const ExtQuals *getExtQualsUnsafe() const { |
669 | return Value.getPointer().get<const ExtQuals*>(); |
670 | } |
671 | |
672 | const Type *getTypePtrUnsafe() const { |
673 | return Value.getPointer().get<const Type*>(); |
674 | } |
675 | |
676 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
677 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 677, __PRETTY_FUNCTION__)); |
678 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
679 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
680 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
681 | } |
682 | |
683 | public: |
684 | QualType() = default; |
685 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
686 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
687 | |
688 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
689 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
690 | |
691 | /// Retrieves a pointer to the underlying (unqualified) type. |
692 | /// |
693 | /// This function requires that the type not be NULL. If the type might be |
694 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
695 | const Type *getTypePtr() const; |
696 | |
697 | const Type *getTypePtrOrNull() const; |
698 | |
699 | /// Retrieves a pointer to the name of the base type. |
700 | const IdentifierInfo *getBaseTypeIdentifier() const; |
701 | |
702 | /// Divides a QualType into its unqualified type and a set of local |
703 | /// qualifiers. |
704 | SplitQualType split() const; |
705 | |
706 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
707 | |
708 | static QualType getFromOpaquePtr(const void *Ptr) { |
709 | QualType T; |
710 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
711 | return T; |
712 | } |
713 | |
714 | const Type &operator*() const { |
715 | return *getTypePtr(); |
716 | } |
717 | |
718 | const Type *operator->() const { |
719 | return getTypePtr(); |
720 | } |
721 | |
722 | bool isCanonical() const; |
723 | bool isCanonicalAsParam() const; |
724 | |
725 | /// Return true if this QualType doesn't point to a type yet. |
726 | bool isNull() const { |
727 | return Value.getPointer().isNull(); |
728 | } |
729 | |
730 | /// Determine whether this particular QualType instance has the |
731 | /// "const" qualifier set, without looking through typedefs that may have |
732 | /// added "const" at a different level. |
733 | bool isLocalConstQualified() const { |
734 | return (getLocalFastQualifiers() & Qualifiers::Const); |
735 | } |
736 | |
737 | /// Determine whether this type is const-qualified. |
738 | bool isConstQualified() const; |
739 | |
740 | /// Determine whether this particular QualType instance has the |
741 | /// "restrict" qualifier set, without looking through typedefs that may have |
742 | /// added "restrict" at a different level. |
743 | bool isLocalRestrictQualified() const { |
744 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
745 | } |
746 | |
747 | /// Determine whether this type is restrict-qualified. |
748 | bool isRestrictQualified() const; |
749 | |
750 | /// Determine whether this particular QualType instance has the |
751 | /// "volatile" qualifier set, without looking through typedefs that may have |
752 | /// added "volatile" at a different level. |
753 | bool isLocalVolatileQualified() const { |
754 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
755 | } |
756 | |
757 | /// Determine whether this type is volatile-qualified. |
758 | bool isVolatileQualified() const; |
759 | |
760 | /// Determine whether this particular QualType instance has any |
761 | /// qualifiers, without looking through any typedefs that might add |
762 | /// qualifiers at a different level. |
763 | bool hasLocalQualifiers() const { |
764 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
765 | } |
766 | |
767 | /// Determine whether this type has any qualifiers. |
768 | bool hasQualifiers() const; |
769 | |
770 | /// Determine whether this particular QualType instance has any |
771 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
772 | /// instance. |
773 | bool hasLocalNonFastQualifiers() const { |
774 | return Value.getPointer().is<const ExtQuals*>(); |
775 | } |
776 | |
777 | /// Retrieve the set of qualifiers local to this particular QualType |
778 | /// instance, not including any qualifiers acquired through typedefs or |
779 | /// other sugar. |
780 | Qualifiers getLocalQualifiers() const; |
781 | |
782 | /// Retrieve the set of qualifiers applied to this type. |
783 | Qualifiers getQualifiers() const; |
784 | |
785 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
786 | /// local to this particular QualType instance, not including any qualifiers |
787 | /// acquired through typedefs or other sugar. |
788 | unsigned getLocalCVRQualifiers() const { |
789 | return getLocalFastQualifiers(); |
790 | } |
791 | |
792 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
793 | /// applied to this type. |
794 | unsigned getCVRQualifiers() const; |
795 | |
796 | bool isConstant(const ASTContext& Ctx) const { |
797 | return QualType::isConstant(*this, Ctx); |
798 | } |
799 | |
800 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
801 | bool isPODType(const ASTContext &Context) const; |
802 | |
803 | /// Return true if this is a POD type according to the rules of the C++98 |
804 | /// standard, regardless of the current compilation's language. |
805 | bool isCXX98PODType(const ASTContext &Context) const; |
806 | |
807 | /// Return true if this is a POD type according to the more relaxed rules |
808 | /// of the C++11 standard, regardless of the current compilation's language. |
809 | /// (C++0x [basic.types]p9). Note that, unlike |
810 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
811 | bool isCXX11PODType(const ASTContext &Context) const; |
812 | |
813 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
814 | bool isTrivialType(const ASTContext &Context) const; |
815 | |
816 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
817 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
818 | |
819 | |
820 | /// Returns true if it is a class and it might be dynamic. |
821 | bool mayBeDynamicClass() const; |
822 | |
823 | /// Returns true if it is not a class or if the class might not be dynamic. |
824 | bool mayBeNotDynamicClass() const; |
825 | |
826 | // Don't promise in the API that anything besides 'const' can be |
827 | // easily added. |
828 | |
829 | /// Add the `const` type qualifier to this QualType. |
830 | void addConst() { |
831 | addFastQualifiers(Qualifiers::Const); |
832 | } |
833 | QualType withConst() const { |
834 | return withFastQualifiers(Qualifiers::Const); |
835 | } |
836 | |
837 | /// Add the `volatile` type qualifier to this QualType. |
838 | void addVolatile() { |
839 | addFastQualifiers(Qualifiers::Volatile); |
840 | } |
841 | QualType withVolatile() const { |
842 | return withFastQualifiers(Qualifiers::Volatile); |
843 | } |
844 | |
845 | /// Add the `restrict` qualifier to this QualType. |
846 | void addRestrict() { |
847 | addFastQualifiers(Qualifiers::Restrict); |
848 | } |
849 | QualType withRestrict() const { |
850 | return withFastQualifiers(Qualifiers::Restrict); |
851 | } |
852 | |
853 | QualType withCVRQualifiers(unsigned CVR) const { |
854 | return withFastQualifiers(CVR); |
855 | } |
856 | |
857 | void addFastQualifiers(unsigned TQs) { |
858 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)) |
859 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)); |
860 | Value.setInt(Value.getInt() | TQs); |
861 | } |
862 | |
863 | void removeLocalConst(); |
864 | void removeLocalVolatile(); |
865 | void removeLocalRestrict(); |
866 | void removeLocalCVRQualifiers(unsigned Mask); |
867 | |
868 | void removeLocalFastQualifiers() { Value.setInt(0); } |
869 | void removeLocalFastQualifiers(unsigned Mask) { |
870 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 870, __PRETTY_FUNCTION__)); |
871 | Value.setInt(Value.getInt() & ~Mask); |
872 | } |
873 | |
874 | // Creates a type with the given qualifiers in addition to any |
875 | // qualifiers already on this type. |
876 | QualType withFastQualifiers(unsigned TQs) const { |
877 | QualType T = *this; |
878 | T.addFastQualifiers(TQs); |
879 | return T; |
880 | } |
881 | |
882 | // Creates a type with exactly the given fast qualifiers, removing |
883 | // any existing fast qualifiers. |
884 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
885 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
886 | } |
887 | |
888 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
889 | QualType withoutLocalFastQualifiers() const { |
890 | QualType T = *this; |
891 | T.removeLocalFastQualifiers(); |
892 | return T; |
893 | } |
894 | |
895 | QualType getCanonicalType() const; |
896 | |
897 | /// Return this type with all of the instance-specific qualifiers |
898 | /// removed, but without removing any qualifiers that may have been applied |
899 | /// through typedefs. |
900 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
901 | |
902 | /// Retrieve the unqualified variant of the given type, |
903 | /// removing as little sugar as possible. |
904 | /// |
905 | /// This routine looks through various kinds of sugar to find the |
906 | /// least-desugared type that is unqualified. For example, given: |
907 | /// |
908 | /// \code |
909 | /// typedef int Integer; |
910 | /// typedef const Integer CInteger; |
911 | /// typedef CInteger DifferenceType; |
912 | /// \endcode |
913 | /// |
914 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
915 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
916 | /// |
917 | /// The resulting type might still be qualified if it's sugar for an array |
918 | /// type. To strip qualifiers even from within a sugared array type, use |
919 | /// ASTContext::getUnqualifiedArrayType. |
920 | inline QualType getUnqualifiedType() const; |
921 | |
922 | /// Retrieve the unqualified variant of the given type, removing as little |
923 | /// sugar as possible. |
924 | /// |
925 | /// Like getUnqualifiedType(), but also returns the set of |
926 | /// qualifiers that were built up. |
927 | /// |
928 | /// The resulting type might still be qualified if it's sugar for an array |
929 | /// type. To strip qualifiers even from within a sugared array type, use |
930 | /// ASTContext::getUnqualifiedArrayType. |
931 | inline SplitQualType getSplitUnqualifiedType() const; |
932 | |
933 | /// Determine whether this type is more qualified than the other |
934 | /// given type, requiring exact equality for non-CVR qualifiers. |
935 | bool isMoreQualifiedThan(QualType Other) const; |
936 | |
937 | /// Determine whether this type is at least as qualified as the other |
938 | /// given type, requiring exact equality for non-CVR qualifiers. |
939 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
940 | |
941 | QualType getNonReferenceType() const; |
942 | |
943 | /// Determine the type of a (typically non-lvalue) expression with the |
944 | /// specified result type. |
945 | /// |
946 | /// This routine should be used for expressions for which the return type is |
947 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
948 | /// an lvalue. It removes a top-level reference (since there are no |
949 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
950 | /// from non-class types (in C++) or all types (in C). |
951 | QualType getNonLValueExprType(const ASTContext &Context) const; |
952 | |
953 | /// Remove an outer pack expansion type (if any) from this type. Used as part |
954 | /// of converting the type of a declaration to the type of an expression that |
955 | /// references that expression. It's meaningless for an expression to have a |
956 | /// pack expansion type. |
957 | QualType getNonPackExpansionType() const; |
958 | |
959 | /// Return the specified type with any "sugar" removed from |
960 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
961 | /// the type is already concrete, it returns it unmodified. This is similar |
962 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
963 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
964 | /// concrete. |
965 | /// |
966 | /// Qualifiers are left in place. |
967 | QualType getDesugaredType(const ASTContext &Context) const { |
968 | return getDesugaredType(*this, Context); |
969 | } |
970 | |
971 | SplitQualType getSplitDesugaredType() const { |
972 | return getSplitDesugaredType(*this); |
973 | } |
974 | |
975 | /// Return the specified type with one level of "sugar" removed from |
976 | /// the type. |
977 | /// |
978 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
979 | /// of the type is already concrete, it returns it unmodified. |
980 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
981 | return getSingleStepDesugaredTypeImpl(*this, Context); |
982 | } |
983 | |
984 | /// Returns the specified type after dropping any |
985 | /// outer-level parentheses. |
986 | QualType IgnoreParens() const { |
987 | if (isa<ParenType>(*this)) |
988 | return QualType::IgnoreParens(*this); |
989 | return *this; |
990 | } |
991 | |
992 | /// Indicate whether the specified types and qualifiers are identical. |
993 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
994 | return LHS.Value == RHS.Value; |
995 | } |
996 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
997 | return LHS.Value != RHS.Value; |
998 | } |
999 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
1000 | return LHS.Value < RHS.Value; |
1001 | } |
1002 | |
1003 | static std::string getAsString(SplitQualType split, |
1004 | const PrintingPolicy &Policy) { |
1005 | return getAsString(split.Ty, split.Quals, Policy); |
1006 | } |
1007 | static std::string getAsString(const Type *ty, Qualifiers qs, |
1008 | const PrintingPolicy &Policy); |
1009 | |
1010 | std::string getAsString() const; |
1011 | std::string getAsString(const PrintingPolicy &Policy) const; |
1012 | |
1013 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1014 | const Twine &PlaceHolder = Twine(), |
1015 | unsigned Indentation = 0) const; |
1016 | |
1017 | static void print(SplitQualType split, raw_ostream &OS, |
1018 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1019 | unsigned Indentation = 0) { |
1020 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1021 | } |
1022 | |
1023 | static void print(const Type *ty, Qualifiers qs, |
1024 | raw_ostream &OS, const PrintingPolicy &policy, |
1025 | const Twine &PlaceHolder, |
1026 | unsigned Indentation = 0); |
1027 | |
1028 | void getAsStringInternal(std::string &Str, |
1029 | const PrintingPolicy &Policy) const; |
1030 | |
1031 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1032 | const PrintingPolicy &policy) { |
1033 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1034 | } |
1035 | |
1036 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1037 | std::string &out, |
1038 | const PrintingPolicy &policy); |
1039 | |
1040 | class StreamedQualTypeHelper { |
1041 | const QualType &T; |
1042 | const PrintingPolicy &Policy; |
1043 | const Twine &PlaceHolder; |
1044 | unsigned Indentation; |
1045 | |
1046 | public: |
1047 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1048 | const Twine &PlaceHolder, unsigned Indentation) |
1049 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1050 | Indentation(Indentation) {} |
1051 | |
1052 | friend raw_ostream &operator<<(raw_ostream &OS, |
1053 | const StreamedQualTypeHelper &SQT) { |
1054 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1055 | return OS; |
1056 | } |
1057 | }; |
1058 | |
1059 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1060 | const Twine &PlaceHolder = Twine(), |
1061 | unsigned Indentation = 0) const { |
1062 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1063 | } |
1064 | |
1065 | void dump(const char *s) const; |
1066 | void dump() const; |
1067 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
1068 | |
1069 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1070 | ID.AddPointer(getAsOpaquePtr()); |
1071 | } |
1072 | |
1073 | /// Check if this type has any address space qualifier. |
1074 | inline bool hasAddressSpace() const; |
1075 | |
1076 | /// Return the address space of this type. |
1077 | inline LangAS getAddressSpace() const; |
1078 | |
1079 | /// Returns true if address space qualifiers overlap with T address space |
1080 | /// qualifiers. |
1081 | /// OpenCL C defines conversion rules for pointers to different address spaces |
1082 | /// and notion of overlapping address spaces. |
1083 | /// CL1.1 or CL1.2: |
1084 | /// address spaces overlap iff they are they same. |
1085 | /// OpenCL C v2.0 s6.5.5 adds: |
1086 | /// __generic overlaps with any address space except for __constant. |
1087 | bool isAddressSpaceOverlapping(QualType T) const { |
1088 | Qualifiers Q = getQualifiers(); |
1089 | Qualifiers TQ = T.getQualifiers(); |
1090 | // Address spaces overlap if at least one of them is a superset of another |
1091 | return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); |
1092 | } |
1093 | |
1094 | /// Returns gc attribute of this type. |
1095 | inline Qualifiers::GC getObjCGCAttr() const; |
1096 | |
1097 | /// true when Type is objc's weak. |
1098 | bool isObjCGCWeak() const { |
1099 | return getObjCGCAttr() == Qualifiers::Weak; |
1100 | } |
1101 | |
1102 | /// true when Type is objc's strong. |
1103 | bool isObjCGCStrong() const { |
1104 | return getObjCGCAttr() == Qualifiers::Strong; |
1105 | } |
1106 | |
1107 | /// Returns lifetime attribute of this type. |
1108 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1109 | return getQualifiers().getObjCLifetime(); |
1110 | } |
1111 | |
1112 | bool hasNonTrivialObjCLifetime() const { |
1113 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1114 | } |
1115 | |
1116 | bool hasStrongOrWeakObjCLifetime() const { |
1117 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1118 | } |
1119 | |
1120 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1121 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1122 | |
1123 | enum PrimitiveDefaultInitializeKind { |
1124 | /// The type does not fall into any of the following categories. Note that |
1125 | /// this case is zero-valued so that values of this enum can be used as a |
1126 | /// boolean condition for non-triviality. |
1127 | PDIK_Trivial, |
1128 | |
1129 | /// The type is an Objective-C retainable pointer type that is qualified |
1130 | /// with the ARC __strong qualifier. |
1131 | PDIK_ARCStrong, |
1132 | |
1133 | /// The type is an Objective-C retainable pointer type that is qualified |
1134 | /// with the ARC __weak qualifier. |
1135 | PDIK_ARCWeak, |
1136 | |
1137 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1138 | PDIK_Struct |
1139 | }; |
1140 | |
1141 | /// Functions to query basic properties of non-trivial C struct types. |
1142 | |
1143 | /// Check if this is a non-trivial type that would cause a C struct |
1144 | /// transitively containing this type to be non-trivial to default initialize |
1145 | /// and return the kind. |
1146 | PrimitiveDefaultInitializeKind |
1147 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1148 | |
1149 | enum PrimitiveCopyKind { |
1150 | /// The type does not fall into any of the following categories. Note that |
1151 | /// this case is zero-valued so that values of this enum can be used as a |
1152 | /// boolean condition for non-triviality. |
1153 | PCK_Trivial, |
1154 | |
1155 | /// The type would be trivial except that it is volatile-qualified. Types |
1156 | /// that fall into one of the other non-trivial cases may additionally be |
1157 | /// volatile-qualified. |
1158 | PCK_VolatileTrivial, |
1159 | |
1160 | /// The type is an Objective-C retainable pointer type that is qualified |
1161 | /// with the ARC __strong qualifier. |
1162 | PCK_ARCStrong, |
1163 | |
1164 | /// The type is an Objective-C retainable pointer type that is qualified |
1165 | /// with the ARC __weak qualifier. |
1166 | PCK_ARCWeak, |
1167 | |
1168 | /// The type is a struct containing a field whose type is neither |
1169 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1170 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1171 | /// semantics are too complex to express here, in part because they depend |
1172 | /// on the exact constructor or assignment operator that is chosen by |
1173 | /// overload resolution to do the copy. |
1174 | PCK_Struct |
1175 | }; |
1176 | |
1177 | /// Check if this is a non-trivial type that would cause a C struct |
1178 | /// transitively containing this type to be non-trivial to copy and return the |
1179 | /// kind. |
1180 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1181 | |
1182 | /// Check if this is a non-trivial type that would cause a C struct |
1183 | /// transitively containing this type to be non-trivial to destructively |
1184 | /// move and return the kind. Destructive move in this context is a C++-style |
1185 | /// move in which the source object is placed in a valid but unspecified state |
1186 | /// after it is moved, as opposed to a truly destructive move in which the |
1187 | /// source object is placed in an uninitialized state. |
1188 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1189 | |
1190 | enum DestructionKind { |
1191 | DK_none, |
1192 | DK_cxx_destructor, |
1193 | DK_objc_strong_lifetime, |
1194 | DK_objc_weak_lifetime, |
1195 | DK_nontrivial_c_struct |
1196 | }; |
1197 | |
1198 | /// Returns a nonzero value if objects of this type require |
1199 | /// non-trivial work to clean up after. Non-zero because it's |
1200 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1201 | /// something require destruction. |
1202 | DestructionKind isDestructedType() const { |
1203 | return isDestructedTypeImpl(*this); |
1204 | } |
1205 | |
1206 | /// Check if this is or contains a C union that is non-trivial to |
1207 | /// default-initialize, which is a union that has a member that is non-trivial |
1208 | /// to default-initialize. If this returns true, |
1209 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1210 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1211 | |
1212 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1213 | /// which is a union that has a member that is non-trivial to destruct. If |
1214 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1215 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1216 | |
1217 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1218 | /// is a union that has a member that is non-trivial to copy. If this returns |
1219 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1220 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1221 | |
1222 | /// Determine whether expressions of the given type are forbidden |
1223 | /// from being lvalues in C. |
1224 | /// |
1225 | /// The expression types that are forbidden to be lvalues are: |
1226 | /// - 'void', but not qualified void |
1227 | /// - function types |
1228 | /// |
1229 | /// The exact rule here is C99 6.3.2.1: |
1230 | /// An lvalue is an expression with an object type or an incomplete |
1231 | /// type other than void. |
1232 | bool isCForbiddenLValueType() const; |
1233 | |
1234 | /// Substitute type arguments for the Objective-C type parameters used in the |
1235 | /// subject type. |
1236 | /// |
1237 | /// \param ctx ASTContext in which the type exists. |
1238 | /// |
1239 | /// \param typeArgs The type arguments that will be substituted for the |
1240 | /// Objective-C type parameters in the subject type, which are generally |
1241 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1242 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1243 | /// for the context. |
1244 | /// |
1245 | /// \param context The context in which the subject type was written. |
1246 | /// |
1247 | /// \returns the resulting type. |
1248 | QualType substObjCTypeArgs(ASTContext &ctx, |
1249 | ArrayRef<QualType> typeArgs, |
1250 | ObjCSubstitutionContext context) const; |
1251 | |
1252 | /// Substitute type arguments from an object type for the Objective-C type |
1253 | /// parameters used in the subject type. |
1254 | /// |
1255 | /// This operation combines the computation of type arguments for |
1256 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1257 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1258 | /// callers that need to perform a single substitution in isolation. |
1259 | /// |
1260 | /// \param objectType The type of the object whose member type we're |
1261 | /// substituting into. For example, this might be the receiver of a message |
1262 | /// or the base of a property access. |
1263 | /// |
1264 | /// \param dc The declaration context from which the subject type was |
1265 | /// retrieved, which indicates (for example) which type parameters should |
1266 | /// be substituted. |
1267 | /// |
1268 | /// \param context The context in which the subject type was written. |
1269 | /// |
1270 | /// \returns the subject type after replacing all of the Objective-C type |
1271 | /// parameters with their corresponding arguments. |
1272 | QualType substObjCMemberType(QualType objectType, |
1273 | const DeclContext *dc, |
1274 | ObjCSubstitutionContext context) const; |
1275 | |
1276 | /// Strip Objective-C "__kindof" types from the given type. |
1277 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1278 | |
1279 | /// Remove all qualifiers including _Atomic. |
1280 | QualType getAtomicUnqualifiedType() const; |
1281 | |
1282 | private: |
1283 | // These methods are implemented in a separate translation unit; |
1284 | // "static"-ize them to avoid creating temporary QualTypes in the |
1285 | // caller. |
1286 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1287 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1288 | static SplitQualType getSplitDesugaredType(QualType T); |
1289 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1290 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1291 | const ASTContext &C); |
1292 | static QualType IgnoreParens(QualType T); |
1293 | static DestructionKind isDestructedTypeImpl(QualType type); |
1294 | |
1295 | /// Check if \param RD is or contains a non-trivial C union. |
1296 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1297 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1298 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1299 | }; |
1300 | |
1301 | } // namespace clang |
1302 | |
1303 | namespace llvm { |
1304 | |
1305 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1306 | /// to a specific Type class. |
1307 | template<> struct simplify_type< ::clang::QualType> { |
1308 | using SimpleType = const ::clang::Type *; |
1309 | |
1310 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1311 | return Val.getTypePtr(); |
1312 | } |
1313 | }; |
1314 | |
1315 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1316 | template<> |
1317 | struct PointerLikeTypeTraits<clang::QualType> { |
1318 | static inline void *getAsVoidPointer(clang::QualType P) { |
1319 | return P.getAsOpaquePtr(); |
1320 | } |
1321 | |
1322 | static inline clang::QualType getFromVoidPointer(void *P) { |
1323 | return clang::QualType::getFromOpaquePtr(P); |
1324 | } |
1325 | |
1326 | // Various qualifiers go in low bits. |
1327 | static constexpr int NumLowBitsAvailable = 0; |
1328 | }; |
1329 | |
1330 | } // namespace llvm |
1331 | |
1332 | namespace clang { |
1333 | |
1334 | /// Base class that is common to both the \c ExtQuals and \c Type |
1335 | /// classes, which allows \c QualType to access the common fields between the |
1336 | /// two. |
1337 | class ExtQualsTypeCommonBase { |
1338 | friend class ExtQuals; |
1339 | friend class QualType; |
1340 | friend class Type; |
1341 | |
1342 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1343 | /// a self-referential pointer (for \c Type). |
1344 | /// |
1345 | /// This pointer allows an efficient mapping from a QualType to its |
1346 | /// underlying type pointer. |
1347 | const Type *const BaseType; |
1348 | |
1349 | /// The canonical type of this type. A QualType. |
1350 | QualType CanonicalType; |
1351 | |
1352 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1353 | : BaseType(baseType), CanonicalType(canon) {} |
1354 | }; |
1355 | |
1356 | /// We can encode up to four bits in the low bits of a |
1357 | /// type pointer, but there are many more type qualifiers that we want |
1358 | /// to be able to apply to an arbitrary type. Therefore we have this |
1359 | /// struct, intended to be heap-allocated and used by QualType to |
1360 | /// store qualifiers. |
1361 | /// |
1362 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1363 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1364 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1365 | /// Objective-C GC attributes) are much more rare. |
1366 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1367 | // NOTE: changing the fast qualifiers should be straightforward as |
1368 | // long as you don't make 'const' non-fast. |
1369 | // 1. Qualifiers: |
1370 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1371 | // Fast qualifiers must occupy the low-order bits. |
1372 | // b) Update Qualifiers::FastWidth and FastMask. |
1373 | // 2. QualType: |
1374 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1375 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1376 | // this header. |
1377 | // 3. ASTContext: |
1378 | // a) Update get{Volatile,Restrict}Type. |
1379 | |
1380 | /// The immutable set of qualifiers applied by this node. Always contains |
1381 | /// extended qualifiers. |
1382 | Qualifiers Quals; |
1383 | |
1384 | ExtQuals *this_() { return this; } |
1385 | |
1386 | public: |
1387 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1388 | : ExtQualsTypeCommonBase(baseType, |
1389 | canon.isNull() ? QualType(this_(), 0) : canon), |
1390 | Quals(quals) { |
1391 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)) |
1392 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)); |
1393 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)) |
1394 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)); |
1395 | } |
1396 | |
1397 | Qualifiers getQualifiers() const { return Quals; } |
1398 | |
1399 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1400 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1401 | |
1402 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1403 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1404 | return Quals.getObjCLifetime(); |
1405 | } |
1406 | |
1407 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1408 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1409 | |
1410 | const Type *getBaseType() const { return BaseType; } |
1411 | |
1412 | public: |
1413 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1414 | Profile(ID, getBaseType(), Quals); |
1415 | } |
1416 | |
1417 | static void Profile(llvm::FoldingSetNodeID &ID, |
1418 | const Type *BaseType, |
1419 | Qualifiers Quals) { |
1420 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1420, __PRETTY_FUNCTION__)); |
1421 | ID.AddPointer(BaseType); |
1422 | Quals.Profile(ID); |
1423 | } |
1424 | }; |
1425 | |
1426 | /// The kind of C++11 ref-qualifier associated with a function type. |
1427 | /// This determines whether a member function's "this" object can be an |
1428 | /// lvalue, rvalue, or neither. |
1429 | enum RefQualifierKind { |
1430 | /// No ref-qualifier was provided. |
1431 | RQ_None = 0, |
1432 | |
1433 | /// An lvalue ref-qualifier was provided (\c &). |
1434 | RQ_LValue, |
1435 | |
1436 | /// An rvalue ref-qualifier was provided (\c &&). |
1437 | RQ_RValue |
1438 | }; |
1439 | |
1440 | /// Which keyword(s) were used to create an AutoType. |
1441 | enum class AutoTypeKeyword { |
1442 | /// auto |
1443 | Auto, |
1444 | |
1445 | /// decltype(auto) |
1446 | DecltypeAuto, |
1447 | |
1448 | /// __auto_type (GNU extension) |
1449 | GNUAutoType |
1450 | }; |
1451 | |
1452 | /// The base class of the type hierarchy. |
1453 | /// |
1454 | /// A central concept with types is that each type always has a canonical |
1455 | /// type. A canonical type is the type with any typedef names stripped out |
1456 | /// of it or the types it references. For example, consider: |
1457 | /// |
1458 | /// typedef int foo; |
1459 | /// typedef foo* bar; |
1460 | /// 'int *' 'foo *' 'bar' |
1461 | /// |
1462 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1463 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1464 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1465 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1466 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1467 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1468 | /// is also 'int*'. |
1469 | /// |
1470 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1471 | /// information about typedefs being used. Canonical types are useful for type |
1472 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1473 | /// about whether something has a particular form (e.g. is a function type), |
1474 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1475 | /// |
1476 | /// Types, once created, are immutable. |
1477 | /// |
1478 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1479 | public: |
1480 | enum TypeClass { |
1481 | #define TYPE(Class, Base) Class, |
1482 | #define LAST_TYPE(Class) TypeLast = Class |
1483 | #define ABSTRACT_TYPE(Class, Base) |
1484 | #include "clang/AST/TypeNodes.inc" |
1485 | }; |
1486 | |
1487 | private: |
1488 | /// Bitfields required by the Type class. |
1489 | class TypeBitfields { |
1490 | friend class Type; |
1491 | template <class T> friend class TypePropertyCache; |
1492 | |
1493 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1494 | unsigned TC : 8; |
1495 | |
1496 | /// Store information on the type dependency. |
1497 | unsigned Dependence : llvm::BitWidth<TypeDependence>; |
1498 | |
1499 | /// True if the cache (i.e. the bitfields here starting with |
1500 | /// 'Cache') is valid. |
1501 | mutable unsigned CacheValid : 1; |
1502 | |
1503 | /// Linkage of this type. |
1504 | mutable unsigned CachedLinkage : 3; |
1505 | |
1506 | /// Whether this type involves and local or unnamed types. |
1507 | mutable unsigned CachedLocalOrUnnamed : 1; |
1508 | |
1509 | /// Whether this type comes from an AST file. |
1510 | mutable unsigned FromAST : 1; |
1511 | |
1512 | bool isCacheValid() const { |
1513 | return CacheValid; |
1514 | } |
1515 | |
1516 | Linkage getLinkage() const { |
1517 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1517, __PRETTY_FUNCTION__)); |
1518 | return static_cast<Linkage>(CachedLinkage); |
1519 | } |
1520 | |
1521 | bool hasLocalOrUnnamedType() const { |
1522 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 1522, __PRETTY_FUNCTION__)); |
1523 | return CachedLocalOrUnnamed; |
1524 | } |
1525 | }; |
1526 | enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; |
1527 | |
1528 | protected: |
1529 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1530 | // into Type. |
1531 | |
1532 | class ArrayTypeBitfields { |
1533 | friend class ArrayType; |
1534 | |
1535 | unsigned : NumTypeBits; |
1536 | |
1537 | /// CVR qualifiers from declarations like |
1538 | /// 'int X[static restrict 4]'. For function parameters only. |
1539 | unsigned IndexTypeQuals : 3; |
1540 | |
1541 | /// Storage class qualifiers from declarations like |
1542 | /// 'int X[static restrict 4]'. For function parameters only. |
1543 | /// Actually an ArrayType::ArraySizeModifier. |
1544 | unsigned SizeModifier : 3; |
1545 | }; |
1546 | |
1547 | class ConstantArrayTypeBitfields { |
1548 | friend class ConstantArrayType; |
1549 | |
1550 | unsigned : NumTypeBits + 3 + 3; |
1551 | |
1552 | /// Whether we have a stored size expression. |
1553 | unsigned HasStoredSizeExpr : 1; |
1554 | }; |
1555 | |
1556 | class BuiltinTypeBitfields { |
1557 | friend class BuiltinType; |
1558 | |
1559 | unsigned : NumTypeBits; |
1560 | |
1561 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1562 | unsigned Kind : 8; |
1563 | }; |
1564 | |
1565 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1566 | /// Only common bits are stored here. Additional uncommon bits are stored |
1567 | /// in a trailing object after FunctionProtoType. |
1568 | class FunctionTypeBitfields { |
1569 | friend class FunctionProtoType; |
1570 | friend class FunctionType; |
1571 | |
1572 | unsigned : NumTypeBits; |
1573 | |
1574 | /// Extra information which affects how the function is called, like |
1575 | /// regparm and the calling convention. |
1576 | unsigned ExtInfo : 13; |
1577 | |
1578 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1579 | /// |
1580 | /// This is a value of type \c RefQualifierKind. |
1581 | unsigned RefQualifier : 2; |
1582 | |
1583 | /// Used only by FunctionProtoType, put here to pack with the |
1584 | /// other bitfields. |
1585 | /// The qualifiers are part of FunctionProtoType because... |
1586 | /// |
1587 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1588 | /// cv-qualifier-seq, [...], are part of the function type. |
1589 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1590 | /// Whether this function has extended Qualifiers. |
1591 | unsigned HasExtQuals : 1; |
1592 | |
1593 | /// The number of parameters this function has, not counting '...'. |
1594 | /// According to [implimits] 8 bits should be enough here but this is |
1595 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1596 | /// keep NumParams as wide as reasonably possible. |
1597 | unsigned NumParams : 16; |
1598 | |
1599 | /// The type of exception specification this function has. |
1600 | unsigned ExceptionSpecType : 4; |
1601 | |
1602 | /// Whether this function has extended parameter information. |
1603 | unsigned HasExtParameterInfos : 1; |
1604 | |
1605 | /// Whether the function is variadic. |
1606 | unsigned Variadic : 1; |
1607 | |
1608 | /// Whether this function has a trailing return type. |
1609 | unsigned HasTrailingReturn : 1; |
1610 | }; |
1611 | |
1612 | class ObjCObjectTypeBitfields { |
1613 | friend class ObjCObjectType; |
1614 | |
1615 | unsigned : NumTypeBits; |
1616 | |
1617 | /// The number of type arguments stored directly on this object type. |
1618 | unsigned NumTypeArgs : 7; |
1619 | |
1620 | /// The number of protocols stored directly on this object type. |
1621 | unsigned NumProtocols : 6; |
1622 | |
1623 | /// Whether this is a "kindof" type. |
1624 | unsigned IsKindOf : 1; |
1625 | }; |
1626 | |
1627 | class ReferenceTypeBitfields { |
1628 | friend class ReferenceType; |
1629 | |
1630 | unsigned : NumTypeBits; |
1631 | |
1632 | /// True if the type was originally spelled with an lvalue sigil. |
1633 | /// This is never true of rvalue references but can also be false |
1634 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1635 | /// as follows: |
1636 | /// |
1637 | /// typedef int &ref; // lvalue, spelled lvalue |
1638 | /// typedef int &&rvref; // rvalue |
1639 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1640 | /// ref &&a; // lvalue, inner ref |
1641 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1642 | /// rvref &&a; // rvalue, inner ref |
1643 | unsigned SpelledAsLValue : 1; |
1644 | |
1645 | /// True if the inner type is a reference type. This only happens |
1646 | /// in non-canonical forms. |
1647 | unsigned InnerRef : 1; |
1648 | }; |
1649 | |
1650 | class TypeWithKeywordBitfields { |
1651 | friend class TypeWithKeyword; |
1652 | |
1653 | unsigned : NumTypeBits; |
1654 | |
1655 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1656 | unsigned Keyword : 8; |
1657 | }; |
1658 | |
1659 | enum { NumTypeWithKeywordBits = 8 }; |
1660 | |
1661 | class ElaboratedTypeBitfields { |
1662 | friend class ElaboratedType; |
1663 | |
1664 | unsigned : NumTypeBits; |
1665 | unsigned : NumTypeWithKeywordBits; |
1666 | |
1667 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1668 | unsigned HasOwnedTagDecl : 1; |
1669 | }; |
1670 | |
1671 | class VectorTypeBitfields { |
1672 | friend class VectorType; |
1673 | friend class DependentVectorType; |
1674 | |
1675 | unsigned : NumTypeBits; |
1676 | |
1677 | /// The kind of vector, either a generic vector type or some |
1678 | /// target-specific vector type such as for AltiVec or Neon. |
1679 | unsigned VecKind : 3; |
1680 | /// The number of elements in the vector. |
1681 | uint32_t NumElements; |
1682 | }; |
1683 | |
1684 | class AttributedTypeBitfields { |
1685 | friend class AttributedType; |
1686 | |
1687 | unsigned : NumTypeBits; |
1688 | |
1689 | /// An AttributedType::Kind |
1690 | unsigned AttrKind : 32 - NumTypeBits; |
1691 | }; |
1692 | |
1693 | class AutoTypeBitfields { |
1694 | friend class AutoType; |
1695 | |
1696 | unsigned : NumTypeBits; |
1697 | |
1698 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1699 | /// or '__auto_type'? AutoTypeKeyword value. |
1700 | unsigned Keyword : 2; |
1701 | |
1702 | /// The number of template arguments in the type-constraints, which is |
1703 | /// expected to be able to hold at least 1024 according to [implimits]. |
1704 | /// However as this limit is somewhat easy to hit with template |
1705 | /// metaprogramming we'd prefer to keep it as large as possible. |
1706 | /// At the moment it has been left as a non-bitfield since this type |
1707 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1708 | /// introduce the performance impact of a bitfield. |
1709 | unsigned NumArgs; |
1710 | }; |
1711 | |
1712 | class SubstTemplateTypeParmPackTypeBitfields { |
1713 | friend class SubstTemplateTypeParmPackType; |
1714 | |
1715 | unsigned : NumTypeBits; |
1716 | |
1717 | /// The number of template arguments in \c Arguments, which is |
1718 | /// expected to be able to hold at least 1024 according to [implimits]. |
1719 | /// However as this limit is somewhat easy to hit with template |
1720 | /// metaprogramming we'd prefer to keep it as large as possible. |
1721 | /// At the moment it has been left as a non-bitfield since this type |
1722 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1723 | /// introduce the performance impact of a bitfield. |
1724 | unsigned NumArgs; |
1725 | }; |
1726 | |
1727 | class TemplateSpecializationTypeBitfields { |
1728 | friend class TemplateSpecializationType; |
1729 | |
1730 | unsigned : NumTypeBits; |
1731 | |
1732 | /// Whether this template specialization type is a substituted type alias. |
1733 | unsigned TypeAlias : 1; |
1734 | |
1735 | /// The number of template arguments named in this class template |
1736 | /// specialization, which is expected to be able to hold at least 1024 |
1737 | /// according to [implimits]. However, as this limit is somewhat easy to |
1738 | /// hit with template metaprogramming we'd prefer to keep it as large |
1739 | /// as possible. At the moment it has been left as a non-bitfield since |
1740 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1741 | /// to introduce the performance impact of a bitfield. |
1742 | unsigned NumArgs; |
1743 | }; |
1744 | |
1745 | class DependentTemplateSpecializationTypeBitfields { |
1746 | friend class DependentTemplateSpecializationType; |
1747 | |
1748 | unsigned : NumTypeBits; |
1749 | unsigned : NumTypeWithKeywordBits; |
1750 | |
1751 | /// The number of template arguments named in this class template |
1752 | /// specialization, which is expected to be able to hold at least 1024 |
1753 | /// according to [implimits]. However, as this limit is somewhat easy to |
1754 | /// hit with template metaprogramming we'd prefer to keep it as large |
1755 | /// as possible. At the moment it has been left as a non-bitfield since |
1756 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1757 | /// to introduce the performance impact of a bitfield. |
1758 | unsigned NumArgs; |
1759 | }; |
1760 | |
1761 | class PackExpansionTypeBitfields { |
1762 | friend class PackExpansionType; |
1763 | |
1764 | unsigned : NumTypeBits; |
1765 | |
1766 | /// The number of expansions that this pack expansion will |
1767 | /// generate when substituted (+1), which is expected to be able to |
1768 | /// hold at least 1024 according to [implimits]. However, as this limit |
1769 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1770 | /// keep it as large as possible. At the moment it has been left as a |
1771 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1772 | /// there is no reason to introduce the performance impact of a bitfield. |
1773 | /// |
1774 | /// This field will only have a non-zero value when some of the parameter |
1775 | /// packs that occur within the pattern have been substituted but others |
1776 | /// have not. |
1777 | unsigned NumExpansions; |
1778 | }; |
1779 | |
1780 | union { |
1781 | TypeBitfields TypeBits; |
1782 | ArrayTypeBitfields ArrayTypeBits; |
1783 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1784 | AttributedTypeBitfields AttributedTypeBits; |
1785 | AutoTypeBitfields AutoTypeBits; |
1786 | BuiltinTypeBitfields BuiltinTypeBits; |
1787 | FunctionTypeBitfields FunctionTypeBits; |
1788 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1789 | ReferenceTypeBitfields ReferenceTypeBits; |
1790 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1791 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1792 | VectorTypeBitfields VectorTypeBits; |
1793 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1794 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1795 | DependentTemplateSpecializationTypeBitfields |
1796 | DependentTemplateSpecializationTypeBits; |
1797 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1798 | }; |
1799 | |
1800 | private: |
1801 | template <class T> friend class TypePropertyCache; |
1802 | |
1803 | /// Set whether this type comes from an AST file. |
1804 | void setFromAST(bool V = true) const { |
1805 | TypeBits.FromAST = V; |
1806 | } |
1807 | |
1808 | protected: |
1809 | friend class ASTContext; |
1810 | |
1811 | Type(TypeClass tc, QualType canon, TypeDependence Dependence) |
1812 | : ExtQualsTypeCommonBase(this, |
1813 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1814 | static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), |
1815 | "changing bitfields changed sizeof(Type)!"); |
1816 | static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, |
1817 | "Insufficient alignment!"); |
1818 | TypeBits.TC = tc; |
1819 | TypeBits.Dependence = static_cast<unsigned>(Dependence); |
1820 | TypeBits.CacheValid = false; |
1821 | TypeBits.CachedLocalOrUnnamed = false; |
1822 | TypeBits.CachedLinkage = NoLinkage; |
1823 | TypeBits.FromAST = false; |
1824 | } |
1825 | |
1826 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1827 | Type *this_() { return this; } |
1828 | |
1829 | void setDependence(TypeDependence D) { |
1830 | TypeBits.Dependence = static_cast<unsigned>(D); |
1831 | } |
1832 | |
1833 | void addDependence(TypeDependence D) { setDependence(getDependence() | D); } |
1834 | |
1835 | public: |
1836 | friend class ASTReader; |
1837 | friend class ASTWriter; |
1838 | template <class T> friend class serialization::AbstractTypeReader; |
1839 | template <class T> friend class serialization::AbstractTypeWriter; |
1840 | |
1841 | Type(const Type &) = delete; |
1842 | Type(Type &&) = delete; |
1843 | Type &operator=(const Type &) = delete; |
1844 | Type &operator=(Type &&) = delete; |
1845 | |
1846 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1847 | |
1848 | /// Whether this type comes from an AST file. |
1849 | bool isFromAST() const { return TypeBits.FromAST; } |
1850 | |
1851 | /// Whether this type is or contains an unexpanded parameter |
1852 | /// pack, used to support C++0x variadic templates. |
1853 | /// |
1854 | /// A type that contains a parameter pack shall be expanded by the |
1855 | /// ellipsis operator at some point. For example, the typedef in the |
1856 | /// following example contains an unexpanded parameter pack 'T': |
1857 | /// |
1858 | /// \code |
1859 | /// template<typename ...T> |
1860 | /// struct X { |
1861 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1862 | /// }; |
1863 | /// \endcode |
1864 | /// |
1865 | /// Note that this routine does not specify which |
1866 | bool containsUnexpandedParameterPack() const { |
1867 | return getDependence() & TypeDependence::UnexpandedPack; |
1868 | } |
1869 | |
1870 | /// Determines if this type would be canonical if it had no further |
1871 | /// qualification. |
1872 | bool isCanonicalUnqualified() const { |
1873 | return CanonicalType == QualType(this, 0); |
1874 | } |
1875 | |
1876 | /// Pull a single level of sugar off of this locally-unqualified type. |
1877 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1878 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1879 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1880 | |
1881 | /// As an extension, we classify types as one of "sized" or "sizeless"; |
1882 | /// every type is one or the other. Standard types are all sized; |
1883 | /// sizeless types are purely an extension. |
1884 | /// |
1885 | /// Sizeless types contain data with no specified size, alignment, |
1886 | /// or layout. |
1887 | bool isSizelessType() const; |
1888 | bool isSizelessBuiltinType() const; |
1889 | |
1890 | /// Determines if this is a sizeless type supported by the |
1891 | /// 'arm_sve_vector_bits' type attribute, which can be applied to a single |
1892 | /// SVE vector or predicate, excluding tuple types such as svint32x4_t. |
1893 | bool isVLSTBuiltinType() const; |
1894 | |
1895 | /// Returns the representative type for the element of an SVE builtin type. |
1896 | /// This is used to represent fixed-length SVE vectors created with the |
1897 | /// 'arm_sve_vector_bits' type attribute as VectorType. |
1898 | QualType getSveEltType(const ASTContext &Ctx) const; |
1899 | |
1900 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1901 | /// object types, function types, and incomplete types. |
1902 | |
1903 | /// Return true if this is an incomplete type. |
1904 | /// A type that can describe objects, but which lacks information needed to |
1905 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1906 | /// routine will need to determine if the size is actually required. |
1907 | /// |
1908 | /// Def If non-null, and the type refers to some kind of declaration |
1909 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1910 | /// class), will be set to the declaration. |
1911 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1912 | |
1913 | /// Return true if this is an incomplete or object |
1914 | /// type, in other words, not a function type. |
1915 | bool isIncompleteOrObjectType() const { |
1916 | return !isFunctionType(); |
1917 | } |
1918 | |
1919 | /// Determine whether this type is an object type. |
1920 | bool isObjectType() const { |
1921 | // C++ [basic.types]p8: |
1922 | // An object type is a (possibly cv-qualified) type that is not a |
1923 | // function type, not a reference type, and not a void type. |
1924 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1925 | } |
1926 | |
1927 | /// Return true if this is a literal type |
1928 | /// (C++11 [basic.types]p10) |
1929 | bool isLiteralType(const ASTContext &Ctx) const; |
1930 | |
1931 | /// Determine if this type is a structural type, per C++20 [temp.param]p7. |
1932 | bool isStructuralType() const; |
1933 | |
1934 | /// Test if this type is a standard-layout type. |
1935 | /// (C++0x [basic.type]p9) |
1936 | bool isStandardLayoutType() const; |
1937 | |
1938 | /// Helper methods to distinguish type categories. All type predicates |
1939 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1940 | |
1941 | /// Returns true if the type is a builtin type. |
1942 | bool isBuiltinType() const; |
1943 | |
1944 | /// Test for a particular builtin type. |
1945 | bool isSpecificBuiltinType(unsigned K) const; |
1946 | |
1947 | /// Test for a type which does not represent an actual type-system type but |
1948 | /// is instead used as a placeholder for various convenient purposes within |
1949 | /// Clang. All such types are BuiltinTypes. |
1950 | bool isPlaceholderType() const; |
1951 | const BuiltinType *getAsPlaceholderType() const; |
1952 | |
1953 | /// Test for a specific placeholder type. |
1954 | bool isSpecificPlaceholderType(unsigned K) const; |
1955 | |
1956 | /// Test for a placeholder type other than Overload; see |
1957 | /// BuiltinType::isNonOverloadPlaceholderType. |
1958 | bool isNonOverloadPlaceholderType() const; |
1959 | |
1960 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1961 | /// isComplexIntegerType() can be used to test for complex integers. |
1962 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1963 | bool isEnumeralType() const; |
1964 | |
1965 | /// Determine whether this type is a scoped enumeration type. |
1966 | bool isScopedEnumeralType() const; |
1967 | bool isBooleanType() const; |
1968 | bool isCharType() const; |
1969 | bool isWideCharType() const; |
1970 | bool isChar8Type() const; |
1971 | bool isChar16Type() const; |
1972 | bool isChar32Type() const; |
1973 | bool isAnyCharacterType() const; |
1974 | bool isIntegralType(const ASTContext &Ctx) const; |
1975 | |
1976 | /// Determine whether this type is an integral or enumeration type. |
1977 | bool isIntegralOrEnumerationType() const; |
1978 | |
1979 | /// Determine whether this type is an integral or unscoped enumeration type. |
1980 | bool isIntegralOrUnscopedEnumerationType() const; |
1981 | bool isUnscopedEnumerationType() const; |
1982 | |
1983 | /// Floating point categories. |
1984 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1985 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1986 | /// isComplexIntegerType() can be used to test for complex integers. |
1987 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1988 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1989 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1990 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1991 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1992 | bool isBFloat16Type() const; |
1993 | bool isFloat128Type() const; |
1994 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1995 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1996 | bool isVoidType() const; // C99 6.2.5p19 |
1997 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1998 | bool isAggregateType() const; |
1999 | bool isFundamentalType() const; |
2000 | bool isCompoundType() const; |
2001 | |
2002 | // Type Predicates: Check to see if this type is structurally the specified |
2003 | // type, ignoring typedefs and qualifiers. |
2004 | bool isFunctionType() const; |
2005 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2006 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2007 | bool isPointerType() const; |
2008 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2009 | bool isBlockPointerType() const; |
2010 | bool isVoidPointerType() const; |
2011 | bool isReferenceType() const; |
2012 | bool isLValueReferenceType() const; |
2013 | bool isRValueReferenceType() const; |
2014 | bool isObjectPointerType() const; |
2015 | bool isFunctionPointerType() const; |
2016 | bool isFunctionReferenceType() const; |
2017 | bool isMemberPointerType() const; |
2018 | bool isMemberFunctionPointerType() const; |
2019 | bool isMemberDataPointerType() const; |
2020 | bool isArrayType() const; |
2021 | bool isConstantArrayType() const; |
2022 | bool isIncompleteArrayType() const; |
2023 | bool isVariableArrayType() const; |
2024 | bool isDependentSizedArrayType() const; |
2025 | bool isRecordType() const; |
2026 | bool isClassType() const; |
2027 | bool isStructureType() const; |
2028 | bool isObjCBoxableRecordType() const; |
2029 | bool isInterfaceType() const; |
2030 | bool isStructureOrClassType() const; |
2031 | bool isUnionType() const; |
2032 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2033 | bool isVectorType() const; // GCC vector type. |
2034 | bool isExtVectorType() const; // Extended vector type. |
2035 | bool isMatrixType() const; // Matrix type. |
2036 | bool isConstantMatrixType() const; // Constant matrix type. |
2037 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2038 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2039 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2040 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2041 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2042 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2043 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2044 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2045 | // for the common case. |
2046 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2047 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2048 | bool isObjCQualifiedIdType() const; // id<foo> |
2049 | bool isObjCQualifiedClassType() const; // Class<foo> |
2050 | bool isObjCObjectOrInterfaceType() const; |
2051 | bool isObjCIdType() const; // id |
2052 | bool isDecltypeType() const; |
2053 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2054 | /// qualifier? |
2055 | /// |
2056 | /// This approximates the answer to the following question: if this |
2057 | /// translation unit were compiled in ARC, would this type be qualified |
2058 | /// with __unsafe_unretained? |
2059 | bool isObjCInertUnsafeUnretainedType() const { |
2060 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2061 | } |
2062 | |
2063 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2064 | /// object type, e.g., __kindof NSView * or __kindof id |
2065 | /// <NSCopying>. |
2066 | /// |
2067 | /// \param bound Will be set to the bound on non-id subtype types, |
2068 | /// which will be (possibly specialized) Objective-C class type, or |
2069 | /// null for 'id. |
2070 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2071 | const ObjCObjectType *&bound) const; |
2072 | |
2073 | bool isObjCClassType() const; // Class |
2074 | |
2075 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2076 | /// Class type, e.g., __kindof Class <NSCopying>. |
2077 | /// |
2078 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2079 | /// here because Objective-C's type system cannot express "a class |
2080 | /// object for a subclass of NSFoo". |
2081 | bool isObjCClassOrClassKindOfType() const; |
2082 | |
2083 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2084 | bool isObjCSelType() const; // Class |
2085 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2086 | bool isObjCARCBridgableType() const; |
2087 | bool isCARCBridgableType() const; |
2088 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2089 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2090 | bool isNothrowT() const; // C++ std::nothrow_t |
2091 | bool isAlignValT() const; // C++17 std::align_val_t |
2092 | bool isStdByteType() const; // C++17 std::byte |
2093 | bool isAtomicType() const; // C11 _Atomic() |
2094 | bool isUndeducedAutoType() const; // C++11 auto or |
2095 | // C++14 decltype(auto) |
2096 | bool isTypedefNameType() const; // typedef or alias template |
2097 | |
2098 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2099 | bool is##Id##Type() const; |
2100 | #include "clang/Basic/OpenCLImageTypes.def" |
2101 | |
2102 | bool isImageType() const; // Any OpenCL image type |
2103 | |
2104 | bool isSamplerT() const; // OpenCL sampler_t |
2105 | bool isEventT() const; // OpenCL event_t |
2106 | bool isClkEventT() const; // OpenCL clk_event_t |
2107 | bool isQueueT() const; // OpenCL queue_t |
2108 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2109 | |
2110 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2111 | bool is##Id##Type() const; |
2112 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2113 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2114 | bool isOCLIntelSubgroupAVCType() const; |
2115 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2116 | |
2117 | bool isPipeType() const; // OpenCL pipe type |
2118 | bool isExtIntType() const; // Extended Int Type |
2119 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2120 | |
2121 | /// Determines if this type, which must satisfy |
2122 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2123 | /// than implicitly __strong. |
2124 | bool isObjCARCImplicitlyUnretainedType() const; |
2125 | |
2126 | /// Check if the type is the CUDA device builtin surface type. |
2127 | bool isCUDADeviceBuiltinSurfaceType() const; |
2128 | /// Check if the type is the CUDA device builtin texture type. |
2129 | bool isCUDADeviceBuiltinTextureType() const; |
2130 | |
2131 | /// Return the implicit lifetime for this type, which must not be dependent. |
2132 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2133 | |
2134 | enum ScalarTypeKind { |
2135 | STK_CPointer, |
2136 | STK_BlockPointer, |
2137 | STK_ObjCObjectPointer, |
2138 | STK_MemberPointer, |
2139 | STK_Bool, |
2140 | STK_Integral, |
2141 | STK_Floating, |
2142 | STK_IntegralComplex, |
2143 | STK_FloatingComplex, |
2144 | STK_FixedPoint |
2145 | }; |
2146 | |
2147 | /// Given that this is a scalar type, classify it. |
2148 | ScalarTypeKind getScalarTypeKind() const; |
2149 | |
2150 | TypeDependence getDependence() const { |
2151 | return static_cast<TypeDependence>(TypeBits.Dependence); |
2152 | } |
2153 | |
2154 | /// Whether this type is an error type. |
2155 | bool containsErrors() const { |
2156 | return getDependence() & TypeDependence::Error; |
2157 | } |
2158 | |
2159 | /// Whether this type is a dependent type, meaning that its definition |
2160 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2161 | bool isDependentType() const { |
2162 | return getDependence() & TypeDependence::Dependent; |
2163 | } |
2164 | |
2165 | /// Determine whether this type is an instantiation-dependent type, |
2166 | /// meaning that the type involves a template parameter (even if the |
2167 | /// definition does not actually depend on the type substituted for that |
2168 | /// template parameter). |
2169 | bool isInstantiationDependentType() const { |
2170 | return getDependence() & TypeDependence::Instantiation; |
2171 | } |
2172 | |
2173 | /// Determine whether this type is an undeduced type, meaning that |
2174 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2175 | /// deduced. |
2176 | bool isUndeducedType() const; |
2177 | |
2178 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2179 | bool isVariablyModifiedType() const { |
2180 | return getDependence() & TypeDependence::VariablyModified; |
2181 | } |
2182 | |
2183 | /// Whether this type involves a variable-length array type |
2184 | /// with a definite size. |
2185 | bool hasSizedVLAType() const; |
2186 | |
2187 | /// Whether this type is or contains a local or unnamed type. |
2188 | bool hasUnnamedOrLocalType() const; |
2189 | |
2190 | bool isOverloadableType() const; |
2191 | |
2192 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2193 | bool isElaboratedTypeSpecifier() const; |
2194 | |
2195 | bool canDecayToPointerType() const; |
2196 | |
2197 | /// Whether this type is represented natively as a pointer. This includes |
2198 | /// pointers, references, block pointers, and Objective-C interface, |
2199 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2200 | bool hasPointerRepresentation() const; |
2201 | |
2202 | /// Whether this type can represent an objective pointer type for the |
2203 | /// purpose of GC'ability |
2204 | bool hasObjCPointerRepresentation() const; |
2205 | |
2206 | /// Determine whether this type has an integer representation |
2207 | /// of some sort, e.g., it is an integer type or a vector. |
2208 | bool hasIntegerRepresentation() const; |
2209 | |
2210 | /// Determine whether this type has an signed integer representation |
2211 | /// of some sort, e.g., it is an signed integer type or a vector. |
2212 | bool hasSignedIntegerRepresentation() const; |
2213 | |
2214 | /// Determine whether this type has an unsigned integer representation |
2215 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2216 | bool hasUnsignedIntegerRepresentation() const; |
2217 | |
2218 | /// Determine whether this type has a floating-point representation |
2219 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2220 | bool hasFloatingRepresentation() const; |
2221 | |
2222 | // Type Checking Functions: Check to see if this type is structurally the |
2223 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2224 | // the best type we can. |
2225 | const RecordType *getAsStructureType() const; |
2226 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2227 | const RecordType *getAsUnionType() const; |
2228 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2229 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2230 | |
2231 | // The following is a convenience method that returns an ObjCObjectPointerType |
2232 | // for object declared using an interface. |
2233 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2234 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2235 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2236 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2237 | |
2238 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2239 | /// because the type is a RecordType or because it is the injected-class-name |
2240 | /// type of a class template or class template partial specialization. |
2241 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2242 | |
2243 | /// Retrieves the RecordDecl this type refers to. |
2244 | RecordDecl *getAsRecordDecl() const; |
2245 | |
2246 | /// Retrieves the TagDecl that this type refers to, either |
2247 | /// because the type is a TagType or because it is the injected-class-name |
2248 | /// type of a class template or class template partial specialization. |
2249 | TagDecl *getAsTagDecl() const; |
2250 | |
2251 | /// If this is a pointer or reference to a RecordType, return the |
2252 | /// CXXRecordDecl that the type refers to. |
2253 | /// |
2254 | /// If this is not a pointer or reference, or the type being pointed to does |
2255 | /// not refer to a CXXRecordDecl, returns NULL. |
2256 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2257 | |
2258 | /// Get the DeducedType whose type will be deduced for a variable with |
2259 | /// an initializer of this type. This looks through declarators like pointer |
2260 | /// types, but not through decltype or typedefs. |
2261 | DeducedType *getContainedDeducedType() const; |
2262 | |
2263 | /// Get the AutoType whose type will be deduced for a variable with |
2264 | /// an initializer of this type. This looks through declarators like pointer |
2265 | /// types, but not through decltype or typedefs. |
2266 | AutoType *getContainedAutoType() const { |
2267 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2268 | } |
2269 | |
2270 | /// Determine whether this type was written with a leading 'auto' |
2271 | /// corresponding to a trailing return type (possibly for a nested |
2272 | /// function type within a pointer to function type or similar). |
2273 | bool hasAutoForTrailingReturnType() const; |
2274 | |
2275 | /// Member-template getAs<specific type>'. Look through sugar for |
2276 | /// an instance of \<specific type>. This scheme will eventually |
2277 | /// replace the specific getAsXXXX methods above. |
2278 | /// |
2279 | /// There are some specializations of this member template listed |
2280 | /// immediately following this class. |
2281 | template <typename T> const T *getAs() const; |
2282 | |
2283 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2284 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2285 | /// This is used when you need to walk over sugar nodes that represent some |
2286 | /// kind of type adjustment from a type that was written as a \<specific type> |
2287 | /// to another type that is still canonically a \<specific type>. |
2288 | template <typename T> const T *getAsAdjusted() const; |
2289 | |
2290 | /// A variant of getAs<> for array types which silently discards |
2291 | /// qualifiers from the outermost type. |
2292 | const ArrayType *getAsArrayTypeUnsafe() const; |
2293 | |
2294 | /// Member-template castAs<specific type>. Look through sugar for |
2295 | /// the underlying instance of \<specific type>. |
2296 | /// |
2297 | /// This method has the same relationship to getAs<T> as cast<T> has |
2298 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2299 | /// have the intended type, and this method will never return null. |
2300 | template <typename T> const T *castAs() const; |
2301 | |
2302 | /// A variant of castAs<> for array type which silently discards |
2303 | /// qualifiers from the outermost type. |
2304 | const ArrayType *castAsArrayTypeUnsafe() const; |
2305 | |
2306 | /// Determine whether this type had the specified attribute applied to it |
2307 | /// (looking through top-level type sugar). |
2308 | bool hasAttr(attr::Kind AK) const; |
2309 | |
2310 | /// Get the base element type of this type, potentially discarding type |
2311 | /// qualifiers. This should never be used when type qualifiers |
2312 | /// are meaningful. |
2313 | const Type *getBaseElementTypeUnsafe() const; |
2314 | |
2315 | /// If this is an array type, return the element type of the array, |
2316 | /// potentially with type qualifiers missing. |
2317 | /// This should never be used when type qualifiers are meaningful. |
2318 | const Type *getArrayElementTypeNoTypeQual() const; |
2319 | |
2320 | /// If this is a pointer type, return the pointee type. |
2321 | /// If this is an array type, return the array element type. |
2322 | /// This should never be used when type qualifiers are meaningful. |
2323 | const Type *getPointeeOrArrayElementType() const; |
2324 | |
2325 | /// If this is a pointer, ObjC object pointer, or block |
2326 | /// pointer, this returns the respective pointee. |
2327 | QualType getPointeeType() const; |
2328 | |
2329 | /// Return the specified type with any "sugar" removed from the type, |
2330 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2331 | const Type *getUnqualifiedDesugaredType() const; |
2332 | |
2333 | /// More type predicates useful for type checking/promotion |
2334 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2335 | |
2336 | /// Return true if this is an integer type that is |
2337 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2338 | /// or an enum decl which has a signed representation. |
2339 | bool isSignedIntegerType() const; |
2340 | |
2341 | /// Return true if this is an integer type that is |
2342 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2343 | /// or an enum decl which has an unsigned representation. |
2344 | bool isUnsignedIntegerType() const; |
2345 | |
2346 | /// Determines whether this is an integer type that is signed or an |
2347 | /// enumeration types whose underlying type is a signed integer type. |
2348 | bool isSignedIntegerOrEnumerationType() const; |
2349 | |
2350 | /// Determines whether this is an integer type that is unsigned or an |
2351 | /// enumeration types whose underlying type is a unsigned integer type. |
2352 | bool isUnsignedIntegerOrEnumerationType() const; |
2353 | |
2354 | /// Return true if this is a fixed point type according to |
2355 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2356 | bool isFixedPointType() const; |
2357 | |
2358 | /// Return true if this is a fixed point or integer type. |
2359 | bool isFixedPointOrIntegerType() const; |
2360 | |
2361 | /// Return true if this is a saturated fixed point type according to |
2362 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2363 | bool isSaturatedFixedPointType() const; |
2364 | |
2365 | /// Return true if this is a saturated fixed point type according to |
2366 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2367 | bool isUnsaturatedFixedPointType() const; |
2368 | |
2369 | /// Return true if this is a fixed point type that is signed according |
2370 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2371 | bool isSignedFixedPointType() const; |
2372 | |
2373 | /// Return true if this is a fixed point type that is unsigned according |
2374 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2375 | bool isUnsignedFixedPointType() const; |
2376 | |
2377 | /// Return true if this is not a variable sized type, |
2378 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2379 | /// incomplete types. |
2380 | bool isConstantSizeType() const; |
2381 | |
2382 | /// Returns true if this type can be represented by some |
2383 | /// set of type specifiers. |
2384 | bool isSpecifierType() const; |
2385 | |
2386 | /// Determine the linkage of this type. |
2387 | Linkage getLinkage() const; |
2388 | |
2389 | /// Determine the visibility of this type. |
2390 | Visibility getVisibility() const { |
2391 | return getLinkageAndVisibility().getVisibility(); |
2392 | } |
2393 | |
2394 | /// Return true if the visibility was explicitly set is the code. |
2395 | bool isVisibilityExplicit() const { |
2396 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2397 | } |
2398 | |
2399 | /// Determine the linkage and visibility of this type. |
2400 | LinkageInfo getLinkageAndVisibility() const; |
2401 | |
2402 | /// True if the computed linkage is valid. Used for consistency |
2403 | /// checking. Should always return true. |
2404 | bool isLinkageValid() const; |
2405 | |
2406 | /// Determine the nullability of the given type. |
2407 | /// |
2408 | /// Note that nullability is only captured as sugar within the type |
2409 | /// system, not as part of the canonical type, so nullability will |
2410 | /// be lost by canonicalization and desugaring. |
2411 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2412 | |
2413 | /// Determine whether the given type can have a nullability |
2414 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2415 | /// |
2416 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2417 | /// this type can have nullability because it is dependent. |
2418 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2419 | |
2420 | /// Retrieve the set of substitutions required when accessing a member |
2421 | /// of the Objective-C receiver type that is declared in the given context. |
2422 | /// |
2423 | /// \c *this is the type of the object we're operating on, e.g., the |
2424 | /// receiver for a message send or the base of a property access, and is |
2425 | /// expected to be of some object or object pointer type. |
2426 | /// |
2427 | /// \param dc The declaration context for which we are building up a |
2428 | /// substitution mapping, which should be an Objective-C class, extension, |
2429 | /// category, or method within. |
2430 | /// |
2431 | /// \returns an array of type arguments that can be substituted for |
2432 | /// the type parameters of the given declaration context in any type described |
2433 | /// within that context, or an empty optional to indicate that no |
2434 | /// substitution is required. |
2435 | Optional<ArrayRef<QualType>> |
2436 | getObjCSubstitutions(const DeclContext *dc) const; |
2437 | |
2438 | /// Determines if this is an ObjC interface type that may accept type |
2439 | /// parameters. |
2440 | bool acceptsObjCTypeParams() const; |
2441 | |
2442 | const char *getTypeClassName() const; |
2443 | |
2444 | QualType getCanonicalTypeInternal() const { |
2445 | return CanonicalType; |
2446 | } |
2447 | |
2448 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2449 | void dump() const; |
2450 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
2451 | }; |
2452 | |
2453 | /// This will check for a TypedefType by removing any existing sugar |
2454 | /// until it reaches a TypedefType or a non-sugared type. |
2455 | template <> const TypedefType *Type::getAs() const; |
2456 | |
2457 | /// This will check for a TemplateSpecializationType by removing any |
2458 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2459 | /// non-sugared type. |
2460 | template <> const TemplateSpecializationType *Type::getAs() const; |
2461 | |
2462 | /// This will check for an AttributedType by removing any existing sugar |
2463 | /// until it reaches an AttributedType or a non-sugared type. |
2464 | template <> const AttributedType *Type::getAs() const; |
2465 | |
2466 | // We can do canonical leaf types faster, because we don't have to |
2467 | // worry about preserving child type decoration. |
2468 | #define TYPE(Class, Base) |
2469 | #define LEAF_TYPE(Class) \ |
2470 | template <> inline const Class##Type *Type::getAs() const { \ |
2471 | return dyn_cast<Class##Type>(CanonicalType); \ |
2472 | } \ |
2473 | template <> inline const Class##Type *Type::castAs() const { \ |
2474 | return cast<Class##Type>(CanonicalType); \ |
2475 | } |
2476 | #include "clang/AST/TypeNodes.inc" |
2477 | |
2478 | /// This class is used for builtin types like 'int'. Builtin |
2479 | /// types are always canonical and have a literal name field. |
2480 | class BuiltinType : public Type { |
2481 | public: |
2482 | enum Kind { |
2483 | // OpenCL image types |
2484 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2485 | #include "clang/Basic/OpenCLImageTypes.def" |
2486 | // OpenCL extension types |
2487 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2488 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2489 | // SVE Types |
2490 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2491 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2492 | // PPC MMA Types |
2493 | #define PPC_VECTOR_TYPE(Name, Id, Size) Id, |
2494 | #include "clang/Basic/PPCTypes.def" |
2495 | // RVV Types |
2496 | #define RVV_TYPE(Name, Id, SingletonId) Id, |
2497 | #include "clang/Basic/RISCVVTypes.def" |
2498 | // All other builtin types |
2499 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2500 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2501 | #include "clang/AST/BuiltinTypes.def" |
2502 | }; |
2503 | |
2504 | private: |
2505 | friend class ASTContext; // ASTContext creates these. |
2506 | |
2507 | BuiltinType(Kind K) |
2508 | : Type(Builtin, QualType(), |
2509 | K == Dependent ? TypeDependence::DependentInstantiation |
2510 | : TypeDependence::None) { |
2511 | BuiltinTypeBits.Kind = K; |
2512 | } |
2513 | |
2514 | public: |
2515 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2516 | StringRef getName(const PrintingPolicy &Policy) const; |
2517 | |
2518 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2519 | // The StringRef is null-terminated. |
2520 | StringRef str = getName(Policy); |
2521 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 2521, __PRETTY_FUNCTION__)); |
2522 | return str.data(); |
2523 | } |
2524 | |
2525 | bool isSugared() const { return false; } |
2526 | QualType desugar() const { return QualType(this, 0); } |
2527 | |
2528 | bool isInteger() const { |
2529 | return getKind() >= Bool && getKind() <= Int128; |
2530 | } |
2531 | |
2532 | bool isSignedInteger() const { |
2533 | return getKind() >= Char_S && getKind() <= Int128; |
2534 | } |
2535 | |
2536 | bool isUnsignedInteger() const { |
2537 | return getKind() >= Bool && getKind() <= UInt128; |
2538 | } |
2539 | |
2540 | bool isFloatingPoint() const { |
2541 | return getKind() >= Half && getKind() <= Float128; |
2542 | } |
2543 | |
2544 | /// Determines whether the given kind corresponds to a placeholder type. |
2545 | static bool isPlaceholderTypeKind(Kind K) { |
2546 | return K >= Overload; |
2547 | } |
2548 | |
2549 | /// Determines whether this type is a placeholder type, i.e. a type |
2550 | /// which cannot appear in arbitrary positions in a fully-formed |
2551 | /// expression. |
2552 | bool isPlaceholderType() const { |
2553 | return isPlaceholderTypeKind(getKind()); |
2554 | } |
2555 | |
2556 | /// Determines whether this type is a placeholder type other than |
2557 | /// Overload. Most placeholder types require only syntactic |
2558 | /// information about their context in order to be resolved (e.g. |
2559 | /// whether it is a call expression), which means they can (and |
2560 | /// should) be resolved in an earlier "phase" of analysis. |
2561 | /// Overload expressions sometimes pick up further information |
2562 | /// from their context, like whether the context expects a |
2563 | /// specific function-pointer type, and so frequently need |
2564 | /// special treatment. |
2565 | bool isNonOverloadPlaceholderType() const { |
2566 | return getKind() > Overload; |
2567 | } |
2568 | |
2569 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2570 | }; |
2571 | |
2572 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2573 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2574 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2575 | friend class ASTContext; // ASTContext creates these. |
2576 | |
2577 | QualType ElementType; |
2578 | |
2579 | ComplexType(QualType Element, QualType CanonicalPtr) |
2580 | : Type(Complex, CanonicalPtr, Element->getDependence()), |
2581 | ElementType(Element) {} |
2582 | |
2583 | public: |
2584 | QualType getElementType() const { return ElementType; } |
2585 | |
2586 | bool isSugared() const { return false; } |
2587 | QualType desugar() const { return QualType(this, 0); } |
2588 | |
2589 | void Profile(llvm::FoldingSetNodeID &ID) { |
2590 | Profile(ID, getElementType()); |
2591 | } |
2592 | |
2593 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2594 | ID.AddPointer(Element.getAsOpaquePtr()); |
2595 | } |
2596 | |
2597 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2598 | }; |
2599 | |
2600 | /// Sugar for parentheses used when specifying types. |
2601 | class ParenType : public Type, public llvm::FoldingSetNode { |
2602 | friend class ASTContext; // ASTContext creates these. |
2603 | |
2604 | QualType Inner; |
2605 | |
2606 | ParenType(QualType InnerType, QualType CanonType) |
2607 | : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} |
2608 | |
2609 | public: |
2610 | QualType getInnerType() const { return Inner; } |
2611 | |
2612 | bool isSugared() const { return true; } |
2613 | QualType desugar() const { return getInnerType(); } |
2614 | |
2615 | void Profile(llvm::FoldingSetNodeID &ID) { |
2616 | Profile(ID, getInnerType()); |
2617 | } |
2618 | |
2619 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2620 | Inner.Profile(ID); |
2621 | } |
2622 | |
2623 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2624 | }; |
2625 | |
2626 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2627 | class PointerType : public Type, public llvm::FoldingSetNode { |
2628 | friend class ASTContext; // ASTContext creates these. |
2629 | |
2630 | QualType PointeeType; |
2631 | |
2632 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2633 | : Type(Pointer, CanonicalPtr, Pointee->getDependence()), |
2634 | PointeeType(Pointee) {} |
2635 | |
2636 | public: |
2637 | QualType getPointeeType() const { return PointeeType; } |
2638 | |
2639 | bool isSugared() const { return false; } |
2640 | QualType desugar() const { return QualType(this, 0); } |
2641 | |
2642 | void Profile(llvm::FoldingSetNodeID &ID) { |
2643 | Profile(ID, getPointeeType()); |
2644 | } |
2645 | |
2646 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2647 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2648 | } |
2649 | |
2650 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2651 | }; |
2652 | |
2653 | /// Represents a type which was implicitly adjusted by the semantic |
2654 | /// engine for arbitrary reasons. For example, array and function types can |
2655 | /// decay, and function types can have their calling conventions adjusted. |
2656 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2657 | QualType OriginalTy; |
2658 | QualType AdjustedTy; |
2659 | |
2660 | protected: |
2661 | friend class ASTContext; // ASTContext creates these. |
2662 | |
2663 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2664 | QualType CanonicalPtr) |
2665 | : Type(TC, CanonicalPtr, OriginalTy->getDependence()), |
2666 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2667 | |
2668 | public: |
2669 | QualType getOriginalType() const { return OriginalTy; } |
2670 | QualType getAdjustedType() const { return AdjustedTy; } |
2671 | |
2672 | bool isSugared() const { return true; } |
2673 | QualType desugar() const { return AdjustedTy; } |
2674 | |
2675 | void Profile(llvm::FoldingSetNodeID &ID) { |
2676 | Profile(ID, OriginalTy, AdjustedTy); |
2677 | } |
2678 | |
2679 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2680 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2681 | ID.AddPointer(New.getAsOpaquePtr()); |
2682 | } |
2683 | |
2684 | static bool classof(const Type *T) { |
2685 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2686 | } |
2687 | }; |
2688 | |
2689 | /// Represents a pointer type decayed from an array or function type. |
2690 | class DecayedType : public AdjustedType { |
2691 | friend class ASTContext; // ASTContext creates these. |
2692 | |
2693 | inline |
2694 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2695 | |
2696 | public: |
2697 | QualType getDecayedType() const { return getAdjustedType(); } |
2698 | |
2699 | inline QualType getPointeeType() const; |
2700 | |
2701 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2702 | }; |
2703 | |
2704 | /// Pointer to a block type. |
2705 | /// This type is to represent types syntactically represented as |
2706 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2707 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2708 | friend class ASTContext; // ASTContext creates these. |
2709 | |
2710 | // Block is some kind of pointer type |
2711 | QualType PointeeType; |
2712 | |
2713 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2714 | : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), |
2715 | PointeeType(Pointee) {} |
2716 | |
2717 | public: |
2718 | // Get the pointee type. Pointee is required to always be a function type. |
2719 | QualType getPointeeType() const { return PointeeType; } |
2720 | |
2721 | bool isSugared() const { return false; } |
2722 | QualType desugar() const { return QualType(this, 0); } |
2723 | |
2724 | void Profile(llvm::FoldingSetNodeID &ID) { |
2725 | Profile(ID, getPointeeType()); |
2726 | } |
2727 | |
2728 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2729 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2730 | } |
2731 | |
2732 | static bool classof(const Type *T) { |
2733 | return T->getTypeClass() == BlockPointer; |
2734 | } |
2735 | }; |
2736 | |
2737 | /// Base for LValueReferenceType and RValueReferenceType |
2738 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2739 | QualType PointeeType; |
2740 | |
2741 | protected: |
2742 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2743 | bool SpelledAsLValue) |
2744 | : Type(tc, CanonicalRef, Referencee->getDependence()), |
2745 | PointeeType(Referencee) { |
2746 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2747 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2748 | } |
2749 | |
2750 | public: |
2751 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2752 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2753 | |
2754 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2755 | |
2756 | QualType getPointeeType() const { |
2757 | // FIXME: this might strip inner qualifiers; okay? |
2758 | const ReferenceType *T = this; |
2759 | while (T->isInnerRef()) |
2760 | T = T->PointeeType->castAs<ReferenceType>(); |
2761 | return T->PointeeType; |
2762 | } |
2763 | |
2764 | void Profile(llvm::FoldingSetNodeID &ID) { |
2765 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2766 | } |
2767 | |
2768 | static void Profile(llvm::FoldingSetNodeID &ID, |
2769 | QualType Referencee, |
2770 | bool SpelledAsLValue) { |
2771 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2772 | ID.AddBoolean(SpelledAsLValue); |
2773 | } |
2774 | |
2775 | static bool classof(const Type *T) { |
2776 | return T->getTypeClass() == LValueReference || |
2777 | T->getTypeClass() == RValueReference; |
2778 | } |
2779 | }; |
2780 | |
2781 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2782 | class LValueReferenceType : public ReferenceType { |
2783 | friend class ASTContext; // ASTContext creates these |
2784 | |
2785 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2786 | bool SpelledAsLValue) |
2787 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2788 | SpelledAsLValue) {} |
2789 | |
2790 | public: |
2791 | bool isSugared() const { return false; } |
2792 | QualType desugar() const { return QualType(this, 0); } |
2793 | |
2794 | static bool classof(const Type *T) { |
2795 | return T->getTypeClass() == LValueReference; |
2796 | } |
2797 | }; |
2798 | |
2799 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2800 | class RValueReferenceType : public ReferenceType { |
2801 | friend class ASTContext; // ASTContext creates these |
2802 | |
2803 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2804 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2805 | |
2806 | public: |
2807 | bool isSugared() const { return false; } |
2808 | QualType desugar() const { return QualType(this, 0); } |
2809 | |
2810 | static bool classof(const Type *T) { |
2811 | return T->getTypeClass() == RValueReference; |
2812 | } |
2813 | }; |
2814 | |
2815 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2816 | /// |
2817 | /// This includes both pointers to data members and pointer to member functions. |
2818 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2819 | friend class ASTContext; // ASTContext creates these. |
2820 | |
2821 | QualType PointeeType; |
2822 | |
2823 | /// The class of which the pointee is a member. Must ultimately be a |
2824 | /// RecordType, but could be a typedef or a template parameter too. |
2825 | const Type *Class; |
2826 | |
2827 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2828 | : Type(MemberPointer, CanonicalPtr, |
2829 | (Cls->getDependence() & ~TypeDependence::VariablyModified) | |
2830 | Pointee->getDependence()), |
2831 | PointeeType(Pointee), Class(Cls) {} |
2832 | |
2833 | public: |
2834 | QualType getPointeeType() const { return PointeeType; } |
2835 | |
2836 | /// Returns true if the member type (i.e. the pointee type) is a |
2837 | /// function type rather than a data-member type. |
2838 | bool isMemberFunctionPointer() const { |
2839 | return PointeeType->isFunctionProtoType(); |
2840 | } |
2841 | |
2842 | /// Returns true if the member type (i.e. the pointee type) is a |
2843 | /// data type rather than a function type. |
2844 | bool isMemberDataPointer() const { |
2845 | return !PointeeType->isFunctionProtoType(); |
2846 | } |
2847 | |
2848 | const Type *getClass() const { return Class; } |
2849 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2850 | |
2851 | bool isSugared() const { return false; } |
2852 | QualType desugar() const { return QualType(this, 0); } |
2853 | |
2854 | void Profile(llvm::FoldingSetNodeID &ID) { |
2855 | Profile(ID, getPointeeType(), getClass()); |
2856 | } |
2857 | |
2858 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2859 | const Type *Class) { |
2860 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2861 | ID.AddPointer(Class); |
2862 | } |
2863 | |
2864 | static bool classof(const Type *T) { |
2865 | return T->getTypeClass() == MemberPointer; |
2866 | } |
2867 | }; |
2868 | |
2869 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2870 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2871 | public: |
2872 | /// Capture whether this is a normal array (e.g. int X[4]) |
2873 | /// an array with a static size (e.g. int X[static 4]), or an array |
2874 | /// with a star size (e.g. int X[*]). |
2875 | /// 'static' is only allowed on function parameters. |
2876 | enum ArraySizeModifier { |
2877 | Normal, Static, Star |
2878 | }; |
2879 | |
2880 | private: |
2881 | /// The element type of the array. |
2882 | QualType ElementType; |
2883 | |
2884 | protected: |
2885 | friend class ASTContext; // ASTContext creates these. |
2886 | |
2887 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2888 | unsigned tq, const Expr *sz = nullptr); |
2889 | |
2890 | public: |
2891 | QualType getElementType() const { return ElementType; } |
2892 | |
2893 | ArraySizeModifier getSizeModifier() const { |
2894 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2895 | } |
2896 | |
2897 | Qualifiers getIndexTypeQualifiers() const { |
2898 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2899 | } |
2900 | |
2901 | unsigned getIndexTypeCVRQualifiers() const { |
2902 | return ArrayTypeBits.IndexTypeQuals; |
2903 | } |
2904 | |
2905 | static bool classof(const Type *T) { |
2906 | return T->getTypeClass() == ConstantArray || |
2907 | T->getTypeClass() == VariableArray || |
2908 | T->getTypeClass() == IncompleteArray || |
2909 | T->getTypeClass() == DependentSizedArray; |
2910 | } |
2911 | }; |
2912 | |
2913 | /// Represents the canonical version of C arrays with a specified constant size. |
2914 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2915 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2916 | class ConstantArrayType final |
2917 | : public ArrayType, |
2918 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2919 | friend class ASTContext; // ASTContext creates these. |
2920 | friend TrailingObjects; |
2921 | |
2922 | llvm::APInt Size; // Allows us to unique the type. |
2923 | |
2924 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2925 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2926 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2927 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2928 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2929 | assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size" ) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 2929, __PRETTY_FUNCTION__)); |
2930 | *getTrailingObjects<const Expr*>() = sz; |
2931 | } |
2932 | } |
2933 | |
2934 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2935 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2936 | } |
2937 | |
2938 | public: |
2939 | const llvm::APInt &getSize() const { return Size; } |
2940 | const Expr *getSizeExpr() const { |
2941 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2942 | ? *getTrailingObjects<const Expr *>() |
2943 | : nullptr; |
2944 | } |
2945 | bool isSugared() const { return false; } |
2946 | QualType desugar() const { return QualType(this, 0); } |
2947 | |
2948 | /// Determine the number of bits required to address a member of |
2949 | // an array with the given element type and number of elements. |
2950 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2951 | QualType ElementType, |
2952 | const llvm::APInt &NumElements); |
2953 | |
2954 | /// Determine the maximum number of active bits that an array's size |
2955 | /// can require, which limits the maximum size of the array. |
2956 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2957 | |
2958 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2959 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2960 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2961 | } |
2962 | |
2963 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2964 | QualType ET, const llvm::APInt &ArraySize, |
2965 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2966 | unsigned TypeQuals); |
2967 | |
2968 | static bool classof(const Type *T) { |
2969 | return T->getTypeClass() == ConstantArray; |
2970 | } |
2971 | }; |
2972 | |
2973 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2974 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2975 | /// unspecified. |
2976 | class IncompleteArrayType : public ArrayType { |
2977 | friend class ASTContext; // ASTContext creates these. |
2978 | |
2979 | IncompleteArrayType(QualType et, QualType can, |
2980 | ArraySizeModifier sm, unsigned tq) |
2981 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2982 | |
2983 | public: |
2984 | friend class StmtIteratorBase; |
2985 | |
2986 | bool isSugared() const { return false; } |
2987 | QualType desugar() const { return QualType(this, 0); } |
2988 | |
2989 | static bool classof(const Type *T) { |
2990 | return T->getTypeClass() == IncompleteArray; |
2991 | } |
2992 | |
2993 | void Profile(llvm::FoldingSetNodeID &ID) { |
2994 | Profile(ID, getElementType(), getSizeModifier(), |
2995 | getIndexTypeCVRQualifiers()); |
2996 | } |
2997 | |
2998 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2999 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
3000 | ID.AddPointer(ET.getAsOpaquePtr()); |
3001 | ID.AddInteger(SizeMod); |
3002 | ID.AddInteger(TypeQuals); |
3003 | } |
3004 | }; |
3005 | |
3006 | /// Represents a C array with a specified size that is not an |
3007 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
3008 | /// Since the size expression is an arbitrary expression, we store it as such. |
3009 | /// |
3010 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3011 | /// should not be: two lexically equivalent variable array types could mean |
3012 | /// different things, for example, these variables do not have the same type |
3013 | /// dynamically: |
3014 | /// |
3015 | /// void foo(int x) { |
3016 | /// int Y[x]; |
3017 | /// ++x; |
3018 | /// int Z[x]; |
3019 | /// } |
3020 | class VariableArrayType : public ArrayType { |
3021 | friend class ASTContext; // ASTContext creates these. |
3022 | |
3023 | /// An assignment-expression. VLA's are only permitted within |
3024 | /// a function block. |
3025 | Stmt *SizeExpr; |
3026 | |
3027 | /// The range spanned by the left and right array brackets. |
3028 | SourceRange Brackets; |
3029 | |
3030 | VariableArrayType(QualType et, QualType can, Expr *e, |
3031 | ArraySizeModifier sm, unsigned tq, |
3032 | SourceRange brackets) |
3033 | : ArrayType(VariableArray, et, can, sm, tq, e), |
3034 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3035 | |
3036 | public: |
3037 | friend class StmtIteratorBase; |
3038 | |
3039 | Expr *getSizeExpr() const { |
3040 | // We use C-style casts instead of cast<> here because we do not wish |
3041 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3042 | return (Expr*) SizeExpr; |
3043 | } |
3044 | |
3045 | SourceRange getBracketsRange() const { return Brackets; } |
3046 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3047 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3048 | |
3049 | bool isSugared() const { return false; } |
3050 | QualType desugar() const { return QualType(this, 0); } |
3051 | |
3052 | static bool classof(const Type *T) { |
3053 | return T->getTypeClass() == VariableArray; |
3054 | } |
3055 | |
3056 | void Profile(llvm::FoldingSetNodeID &ID) { |
3057 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 3057); |
3058 | } |
3059 | }; |
3060 | |
3061 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3062 | /// |
3063 | /// For example: |
3064 | /// \code |
3065 | /// template<typename T, int Size> |
3066 | /// class array { |
3067 | /// T data[Size]; |
3068 | /// }; |
3069 | /// \endcode |
3070 | /// |
3071 | /// For these types, we won't actually know what the array bound is |
3072 | /// until template instantiation occurs, at which point this will |
3073 | /// become either a ConstantArrayType or a VariableArrayType. |
3074 | class DependentSizedArrayType : public ArrayType { |
3075 | friend class ASTContext; // ASTContext creates these. |
3076 | |
3077 | const ASTContext &Context; |
3078 | |
3079 | /// An assignment expression that will instantiate to the |
3080 | /// size of the array. |
3081 | /// |
3082 | /// The expression itself might be null, in which case the array |
3083 | /// type will have its size deduced from an initializer. |
3084 | Stmt *SizeExpr; |
3085 | |
3086 | /// The range spanned by the left and right array brackets. |
3087 | SourceRange Brackets; |
3088 | |
3089 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3090 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3091 | SourceRange brackets); |
3092 | |
3093 | public: |
3094 | friend class StmtIteratorBase; |
3095 | |
3096 | Expr *getSizeExpr() const { |
3097 | // We use C-style casts instead of cast<> here because we do not wish |
3098 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3099 | return (Expr*) SizeExpr; |
3100 | } |
3101 | |
3102 | SourceRange getBracketsRange() const { return Brackets; } |
3103 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3104 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3105 | |
3106 | bool isSugared() const { return false; } |
3107 | QualType desugar() const { return QualType(this, 0); } |
3108 | |
3109 | static bool classof(const Type *T) { |
3110 | return T->getTypeClass() == DependentSizedArray; |
3111 | } |
3112 | |
3113 | void Profile(llvm::FoldingSetNodeID &ID) { |
3114 | Profile(ID, Context, getElementType(), |
3115 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3116 | } |
3117 | |
3118 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3119 | QualType ET, ArraySizeModifier SizeMod, |
3120 | unsigned TypeQuals, Expr *E); |
3121 | }; |
3122 | |
3123 | /// Represents an extended address space qualifier where the input address space |
3124 | /// value is dependent. Non-dependent address spaces are not represented with a |
3125 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3126 | /// |
3127 | /// For example: |
3128 | /// \code |
3129 | /// template<typename T, int AddrSpace> |
3130 | /// class AddressSpace { |
3131 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3132 | /// } |
3133 | /// \endcode |
3134 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3135 | friend class ASTContext; |
3136 | |
3137 | const ASTContext &Context; |
3138 | Expr *AddrSpaceExpr; |
3139 | QualType PointeeType; |
3140 | SourceLocation loc; |
3141 | |
3142 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3143 | QualType can, Expr *AddrSpaceExpr, |
3144 | SourceLocation loc); |
3145 | |
3146 | public: |
3147 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3148 | QualType getPointeeType() const { return PointeeType; } |
3149 | SourceLocation getAttributeLoc() const { return loc; } |
3150 | |
3151 | bool isSugared() const { return false; } |
3152 | QualType desugar() const { return QualType(this, 0); } |
3153 | |
3154 | static bool classof(const Type *T) { |
3155 | return T->getTypeClass() == DependentAddressSpace; |
3156 | } |
3157 | |
3158 | void Profile(llvm::FoldingSetNodeID &ID) { |
3159 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3160 | } |
3161 | |
3162 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3163 | QualType PointeeType, Expr *AddrSpaceExpr); |
3164 | }; |
3165 | |
3166 | /// Represents an extended vector type where either the type or size is |
3167 | /// dependent. |
3168 | /// |
3169 | /// For example: |
3170 | /// \code |
3171 | /// template<typename T, int Size> |
3172 | /// class vector { |
3173 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3174 | /// } |
3175 | /// \endcode |
3176 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3177 | friend class ASTContext; |
3178 | |
3179 | const ASTContext &Context; |
3180 | Expr *SizeExpr; |
3181 | |
3182 | /// The element type of the array. |
3183 | QualType ElementType; |
3184 | |
3185 | SourceLocation loc; |
3186 | |
3187 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3188 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3189 | |
3190 | public: |
3191 | Expr *getSizeExpr() const { return SizeExpr; } |
3192 | QualType getElementType() const { return ElementType; } |
3193 | SourceLocation getAttributeLoc() const { return loc; } |
3194 | |
3195 | bool isSugared() const { return false; } |
3196 | QualType desugar() const { return QualType(this, 0); } |
3197 | |
3198 | static bool classof(const Type *T) { |
3199 | return T->getTypeClass() == DependentSizedExtVector; |
3200 | } |
3201 | |
3202 | void Profile(llvm::FoldingSetNodeID &ID) { |
3203 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3204 | } |
3205 | |
3206 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3207 | QualType ElementType, Expr *SizeExpr); |
3208 | }; |
3209 | |
3210 | |
3211 | /// Represents a GCC generic vector type. This type is created using |
3212 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3213 | /// bytes; or from an Altivec __vector or vector declaration. |
3214 | /// Since the constructor takes the number of vector elements, the |
3215 | /// client is responsible for converting the size into the number of elements. |
3216 | class VectorType : public Type, public llvm::FoldingSetNode { |
3217 | public: |
3218 | enum VectorKind { |
3219 | /// not a target-specific vector type |
3220 | GenericVector, |
3221 | |
3222 | /// is AltiVec vector |
3223 | AltiVecVector, |
3224 | |
3225 | /// is AltiVec 'vector Pixel' |
3226 | AltiVecPixel, |
3227 | |
3228 | /// is AltiVec 'vector bool ...' |
3229 | AltiVecBool, |
3230 | |
3231 | /// is ARM Neon vector |
3232 | NeonVector, |
3233 | |
3234 | /// is ARM Neon polynomial vector |
3235 | NeonPolyVector, |
3236 | |
3237 | /// is AArch64 SVE fixed-length data vector |
3238 | SveFixedLengthDataVector, |
3239 | |
3240 | /// is AArch64 SVE fixed-length predicate vector |
3241 | SveFixedLengthPredicateVector |
3242 | }; |
3243 | |
3244 | protected: |
3245 | friend class ASTContext; // ASTContext creates these. |
3246 | |
3247 | /// The element type of the vector. |
3248 | QualType ElementType; |
3249 | |
3250 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3251 | VectorKind vecKind); |
3252 | |
3253 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3254 | QualType canonType, VectorKind vecKind); |
3255 | |
3256 | public: |
3257 | QualType getElementType() const { return ElementType; } |
3258 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3259 | |
3260 | bool isSugared() const { return false; } |
3261 | QualType desugar() const { return QualType(this, 0); } |
3262 | |
3263 | VectorKind getVectorKind() const { |
3264 | return VectorKind(VectorTypeBits.VecKind); |
3265 | } |
3266 | |
3267 | void Profile(llvm::FoldingSetNodeID &ID) { |
3268 | Profile(ID, getElementType(), getNumElements(), |
3269 | getTypeClass(), getVectorKind()); |
3270 | } |
3271 | |
3272 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3273 | unsigned NumElements, TypeClass TypeClass, |
3274 | VectorKind VecKind) { |
3275 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3276 | ID.AddInteger(NumElements); |
3277 | ID.AddInteger(TypeClass); |
3278 | ID.AddInteger(VecKind); |
3279 | } |
3280 | |
3281 | static bool classof(const Type *T) { |
3282 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3283 | } |
3284 | }; |
3285 | |
3286 | /// Represents a vector type where either the type or size is dependent. |
3287 | //// |
3288 | /// For example: |
3289 | /// \code |
3290 | /// template<typename T, int Size> |
3291 | /// class vector { |
3292 | /// typedef T __attribute__((vector_size(Size))) type; |
3293 | /// } |
3294 | /// \endcode |
3295 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3296 | friend class ASTContext; |
3297 | |
3298 | const ASTContext &Context; |
3299 | QualType ElementType; |
3300 | Expr *SizeExpr; |
3301 | SourceLocation Loc; |
3302 | |
3303 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3304 | QualType CanonType, Expr *SizeExpr, |
3305 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3306 | |
3307 | public: |
3308 | Expr *getSizeExpr() const { return SizeExpr; } |
3309 | QualType getElementType() const { return ElementType; } |
3310 | SourceLocation getAttributeLoc() const { return Loc; } |
3311 | VectorType::VectorKind getVectorKind() const { |
3312 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3313 | } |
3314 | |
3315 | bool isSugared() const { return false; } |
3316 | QualType desugar() const { return QualType(this, 0); } |
3317 | |
3318 | static bool classof(const Type *T) { |
3319 | return T->getTypeClass() == DependentVector; |
3320 | } |
3321 | |
3322 | void Profile(llvm::FoldingSetNodeID &ID) { |
3323 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3324 | } |
3325 | |
3326 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3327 | QualType ElementType, const Expr *SizeExpr, |
3328 | VectorType::VectorKind VecKind); |
3329 | }; |
3330 | |
3331 | /// ExtVectorType - Extended vector type. This type is created using |
3332 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3333 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3334 | /// class enables syntactic extensions, like Vector Components for accessing |
3335 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3336 | /// Shading Language). |
3337 | class ExtVectorType : public VectorType { |
3338 | friend class ASTContext; // ASTContext creates these. |
3339 | |
3340 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3341 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3342 | |
3343 | public: |
3344 | static int getPointAccessorIdx(char c) { |
3345 | switch (c) { |
3346 | default: return -1; |
3347 | case 'x': case 'r': return 0; |
3348 | case 'y': case 'g': return 1; |
3349 | case 'z': case 'b': return 2; |
3350 | case 'w': case 'a': return 3; |
3351 | } |
3352 | } |
3353 | |
3354 | static int getNumericAccessorIdx(char c) { |
3355 | switch (c) { |
3356 | default: return -1; |
3357 | case '0': return 0; |
3358 | case '1': return 1; |
3359 | case '2': return 2; |
3360 | case '3': return 3; |
3361 | case '4': return 4; |
3362 | case '5': return 5; |
3363 | case '6': return 6; |
3364 | case '7': return 7; |
3365 | case '8': return 8; |
3366 | case '9': return 9; |
3367 | case 'A': |
3368 | case 'a': return 10; |
3369 | case 'B': |
3370 | case 'b': return 11; |
3371 | case 'C': |
3372 | case 'c': return 12; |
3373 | case 'D': |
3374 | case 'd': return 13; |
3375 | case 'E': |
3376 | case 'e': return 14; |
3377 | case 'F': |
3378 | case 'f': return 15; |
3379 | } |
3380 | } |
3381 | |
3382 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3383 | if (isNumericAccessor) |
3384 | return getNumericAccessorIdx(c); |
3385 | else |
3386 | return getPointAccessorIdx(c); |
3387 | } |
3388 | |
3389 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3390 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3391 | return unsigned(idx-1) < getNumElements(); |
3392 | return false; |
3393 | } |
3394 | |
3395 | bool isSugared() const { return false; } |
3396 | QualType desugar() const { return QualType(this, 0); } |
3397 | |
3398 | static bool classof(const Type *T) { |
3399 | return T->getTypeClass() == ExtVector; |
3400 | } |
3401 | }; |
3402 | |
3403 | /// Represents a matrix type, as defined in the Matrix Types clang extensions. |
3404 | /// __attribute__((matrix_type(rows, columns))), where "rows" specifies |
3405 | /// number of rows and "columns" specifies the number of columns. |
3406 | class MatrixType : public Type, public llvm::FoldingSetNode { |
3407 | protected: |
3408 | friend class ASTContext; |
3409 | |
3410 | /// The element type of the matrix. |
3411 | QualType ElementType; |
3412 | |
3413 | MatrixType(QualType ElementTy, QualType CanonElementTy); |
3414 | |
3415 | MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, |
3416 | const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); |
3417 | |
3418 | public: |
3419 | /// Returns type of the elements being stored in the matrix |
3420 | QualType getElementType() const { return ElementType; } |
3421 | |
3422 | /// Valid elements types are the following: |
3423 | /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types |
3424 | /// and _Bool |
3425 | /// * the standard floating types float or double |
3426 | /// * a half-precision floating point type, if one is supported on the target |
3427 | static bool isValidElementType(QualType T) { |
3428 | return T->isDependentType() || |
3429 | (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); |
3430 | } |
3431 | |
3432 | bool isSugared() const { return false; } |
3433 | QualType desugar() const { return QualType(this, 0); } |
3434 | |
3435 | static bool classof(const Type *T) { |
3436 | return T->getTypeClass() == ConstantMatrix || |
3437 | T->getTypeClass() == DependentSizedMatrix; |
3438 | } |
3439 | }; |
3440 | |
3441 | /// Represents a concrete matrix type with constant number of rows and columns |
3442 | class ConstantMatrixType final : public MatrixType { |
3443 | protected: |
3444 | friend class ASTContext; |
3445 | |
3446 | /// The element type of the matrix. |
3447 | // FIXME: Appears to be unused? There is also MatrixType::ElementType... |
3448 | QualType ElementType; |
3449 | |
3450 | /// Number of rows and columns. |
3451 | unsigned NumRows; |
3452 | unsigned NumColumns; |
3453 | |
3454 | static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1; |
3455 | |
3456 | ConstantMatrixType(QualType MatrixElementType, unsigned NRows, |
3457 | unsigned NColumns, QualType CanonElementType); |
3458 | |
3459 | ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, |
3460 | unsigned NColumns, QualType CanonElementType); |
3461 | |
3462 | public: |
3463 | /// Returns the number of rows in the matrix. |
3464 | unsigned getNumRows() const { return NumRows; } |
3465 | |
3466 | /// Returns the number of columns in the matrix. |
3467 | unsigned getNumColumns() const { return NumColumns; } |
3468 | |
3469 | /// Returns the number of elements required to embed the matrix into a vector. |
3470 | unsigned getNumElementsFlattened() const { |
3471 | return getNumRows() * getNumColumns(); |
3472 | } |
3473 | |
3474 | /// Returns true if \p NumElements is a valid matrix dimension. |
3475 | static constexpr bool isDimensionValid(size_t NumElements) { |
3476 | return NumElements > 0 && NumElements <= MaxElementsPerDimension; |
3477 | } |
3478 | |
3479 | /// Returns the maximum number of elements per dimension. |
3480 | static constexpr unsigned getMaxElementsPerDimension() { |
3481 | return MaxElementsPerDimension; |
3482 | } |
3483 | |
3484 | void Profile(llvm::FoldingSetNodeID &ID) { |
3485 | Profile(ID, getElementType(), getNumRows(), getNumColumns(), |
3486 | getTypeClass()); |
3487 | } |
3488 | |
3489 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3490 | unsigned NumRows, unsigned NumColumns, |
3491 | TypeClass TypeClass) { |
3492 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3493 | ID.AddInteger(NumRows); |
3494 | ID.AddInteger(NumColumns); |
3495 | ID.AddInteger(TypeClass); |
3496 | } |
3497 | |
3498 | static bool classof(const Type *T) { |
3499 | return T->getTypeClass() == ConstantMatrix; |
3500 | } |
3501 | }; |
3502 | |
3503 | /// Represents a matrix type where the type and the number of rows and columns |
3504 | /// is dependent on a template. |
3505 | class DependentSizedMatrixType final : public MatrixType { |
3506 | friend class ASTContext; |
3507 | |
3508 | const ASTContext &Context; |
3509 | Expr *RowExpr; |
3510 | Expr *ColumnExpr; |
3511 | |
3512 | SourceLocation loc; |
3513 | |
3514 | DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, |
3515 | QualType CanonicalType, Expr *RowExpr, |
3516 | Expr *ColumnExpr, SourceLocation loc); |
3517 | |
3518 | public: |
3519 | QualType getElementType() const { return ElementType; } |
3520 | Expr *getRowExpr() const { return RowExpr; } |
3521 | Expr *getColumnExpr() const { return ColumnExpr; } |
3522 | SourceLocation getAttributeLoc() const { return loc; } |
3523 | |
3524 | bool isSugared() const { return false; } |
3525 | QualType desugar() const { return QualType(this, 0); } |
3526 | |
3527 | static bool classof(const Type *T) { |
3528 | return T->getTypeClass() == DependentSizedMatrix; |
3529 | } |
3530 | |
3531 | void Profile(llvm::FoldingSetNodeID &ID) { |
3532 | Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); |
3533 | } |
3534 | |
3535 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3536 | QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); |
3537 | }; |
3538 | |
3539 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3540 | /// class of FunctionNoProtoType and FunctionProtoType. |
3541 | class FunctionType : public Type { |
3542 | // The type returned by the function. |
3543 | QualType ResultType; |
3544 | |
3545 | public: |
3546 | /// Interesting information about a specific parameter that can't simply |
3547 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3548 | /// but is in FunctionType to make this class available during the |
3549 | /// specification of the bases of FunctionProtoType. |
3550 | /// |
3551 | /// It makes sense to model language features this way when there's some |
3552 | /// sort of parameter-specific override (such as an attribute) that |
3553 | /// affects how the function is called. For example, the ARC ns_consumed |
3554 | /// attribute changes whether a parameter is passed at +0 (the default) |
3555 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3556 | /// but isn't really a change to the parameter type. |
3557 | /// |
3558 | /// One serious disadvantage of modelling language features this way is |
3559 | /// that they generally do not work with language features that attempt |
3560 | /// to destructure types. For example, template argument deduction will |
3561 | /// not be able to match a parameter declared as |
3562 | /// T (*)(U) |
3563 | /// against an argument of type |
3564 | /// void (*)(__attribute__((ns_consumed)) id) |
3565 | /// because the substitution of T=void, U=id into the former will |
3566 | /// not produce the latter. |
3567 | class ExtParameterInfo { |
3568 | enum { |
3569 | ABIMask = 0x0F, |
3570 | IsConsumed = 0x10, |
3571 | HasPassObjSize = 0x20, |
3572 | IsNoEscape = 0x40, |
3573 | }; |
3574 | unsigned char Data = 0; |
3575 | |
3576 | public: |
3577 | ExtParameterInfo() = default; |
3578 | |
3579 | /// Return the ABI treatment of this parameter. |
3580 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3581 | ExtParameterInfo withABI(ParameterABI kind) const { |
3582 | ExtParameterInfo copy = *this; |
3583 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3584 | return copy; |
3585 | } |
3586 | |
3587 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3588 | /// Consumed parameters must have retainable object type. |
3589 | bool isConsumed() const { return (Data & IsConsumed); } |
3590 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3591 | ExtParameterInfo copy = *this; |
3592 | if (consumed) |
3593 | copy.Data |= IsConsumed; |
3594 | else |
3595 | copy.Data &= ~IsConsumed; |
3596 | return copy; |
3597 | } |
3598 | |
3599 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3600 | ExtParameterInfo withHasPassObjectSize() const { |
3601 | ExtParameterInfo Copy = *this; |
3602 | Copy.Data |= HasPassObjSize; |
3603 | return Copy; |
3604 | } |
3605 | |
3606 | bool isNoEscape() const { return Data & IsNoEscape; } |
3607 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3608 | ExtParameterInfo Copy = *this; |
3609 | if (NoEscape) |
3610 | Copy.Data |= IsNoEscape; |
3611 | else |
3612 | Copy.Data &= ~IsNoEscape; |
3613 | return Copy; |
3614 | } |
3615 | |
3616 | unsigned char getOpaqueValue() const { return Data; } |
3617 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3618 | ExtParameterInfo result; |
3619 | result.Data = data; |
3620 | return result; |
3621 | } |
3622 | |
3623 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3624 | return lhs.Data == rhs.Data; |
3625 | } |
3626 | |
3627 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3628 | return lhs.Data != rhs.Data; |
3629 | } |
3630 | }; |
3631 | |
3632 | /// A class which abstracts out some details necessary for |
3633 | /// making a call. |
3634 | /// |
3635 | /// It is not actually used directly for storing this information in |
3636 | /// a FunctionType, although FunctionType does currently use the |
3637 | /// same bit-pattern. |
3638 | /// |
3639 | // If you add a field (say Foo), other than the obvious places (both, |
3640 | // constructors, compile failures), what you need to update is |
3641 | // * Operator== |
3642 | // * getFoo |
3643 | // * withFoo |
3644 | // * functionType. Add Foo, getFoo. |
3645 | // * ASTContext::getFooType |
3646 | // * ASTContext::mergeFunctionTypes |
3647 | // * FunctionNoProtoType::Profile |
3648 | // * FunctionProtoType::Profile |
3649 | // * TypePrinter::PrintFunctionProto |
3650 | // * AST read and write |
3651 | // * Codegen |
3652 | class ExtInfo { |
3653 | friend class FunctionType; |
3654 | |
3655 | // Feel free to rearrange or add bits, but if you go over 16, you'll need to |
3656 | // adjust the Bits field below, and if you add bits, you'll need to adjust |
3657 | // Type::FunctionTypeBitfields::ExtInfo as well. |
3658 | |
3659 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| |
3660 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | |
3661 | // |
3662 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3663 | enum { CallConvMask = 0x1F }; |
3664 | enum { NoReturnMask = 0x20 }; |
3665 | enum { ProducesResultMask = 0x40 }; |
3666 | enum { NoCallerSavedRegsMask = 0x80 }; |
3667 | enum { |
3668 | RegParmMask = 0x700, |
3669 | RegParmOffset = 8 |
3670 | }; |
3671 | enum { NoCfCheckMask = 0x800 }; |
3672 | enum { CmseNSCallMask = 0x1000 }; |
3673 | uint16_t Bits = CC_C; |
3674 | |
3675 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3676 | |
3677 | public: |
3678 | // Constructor with no defaults. Use this when you know that you |
3679 | // have all the elements (when reading an AST file for example). |
3680 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3681 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, |
3682 | bool cmseNSCall) { |
3683 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 3683, __PRETTY_FUNCTION__)); |
3684 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3685 | (producesResult ? ProducesResultMask : 0) | |
3686 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3687 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3688 | (NoCfCheck ? NoCfCheckMask : 0) | |
3689 | (cmseNSCall ? CmseNSCallMask : 0); |
3690 | } |
3691 | |
3692 | // Constructor with all defaults. Use when for example creating a |
3693 | // function known to use defaults. |
3694 | ExtInfo() = default; |
3695 | |
3696 | // Constructor with just the calling convention, which is an important part |
3697 | // of the canonical type. |
3698 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3699 | |
3700 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3701 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3702 | bool getCmseNSCall() const { return Bits & CmseNSCallMask; } |
3703 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3704 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3705 | bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } |
3706 | |
3707 | unsigned getRegParm() const { |
3708 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3709 | if (RegParm > 0) |
3710 | --RegParm; |
3711 | return RegParm; |
3712 | } |
3713 | |
3714 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3715 | |
3716 | bool operator==(ExtInfo Other) const { |
3717 | return Bits == Other.Bits; |
3718 | } |
3719 | bool operator!=(ExtInfo Other) const { |
3720 | return Bits != Other.Bits; |
3721 | } |
3722 | |
3723 | // Note that we don't have setters. That is by design, use |
3724 | // the following with methods instead of mutating these objects. |
3725 | |
3726 | ExtInfo withNoReturn(bool noReturn) const { |
3727 | if (noReturn) |
3728 | return ExtInfo(Bits | NoReturnMask); |
3729 | else |
3730 | return ExtInfo(Bits & ~NoReturnMask); |
3731 | } |
3732 | |
3733 | ExtInfo withProducesResult(bool producesResult) const { |
3734 | if (producesResult) |
3735 | return ExtInfo(Bits | ProducesResultMask); |
3736 | else |
3737 | return ExtInfo(Bits & ~ProducesResultMask); |
3738 | } |
3739 | |
3740 | ExtInfo withCmseNSCall(bool cmseNSCall) const { |
3741 | if (cmseNSCall) |
3742 | return ExtInfo(Bits | CmseNSCallMask); |
3743 | else |
3744 | return ExtInfo(Bits & ~CmseNSCallMask); |
3745 | } |
3746 | |
3747 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3748 | if (noCallerSavedRegs) |
3749 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3750 | else |
3751 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3752 | } |
3753 | |
3754 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3755 | if (noCfCheck) |
3756 | return ExtInfo(Bits | NoCfCheckMask); |
3757 | else |
3758 | return ExtInfo(Bits & ~NoCfCheckMask); |
3759 | } |
3760 | |
3761 | ExtInfo withRegParm(unsigned RegParm) const { |
3762 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 3762, __PRETTY_FUNCTION__)); |
3763 | return ExtInfo((Bits & ~RegParmMask) | |
3764 | ((RegParm + 1) << RegParmOffset)); |
3765 | } |
3766 | |
3767 | ExtInfo withCallingConv(CallingConv cc) const { |
3768 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3769 | } |
3770 | |
3771 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3772 | ID.AddInteger(Bits); |
3773 | } |
3774 | }; |
3775 | |
3776 | /// A simple holder for a QualType representing a type in an |
3777 | /// exception specification. Unfortunately needed by FunctionProtoType |
3778 | /// because TrailingObjects cannot handle repeated types. |
3779 | struct ExceptionType { QualType Type; }; |
3780 | |
3781 | /// A simple holder for various uncommon bits which do not fit in |
3782 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3783 | /// alignment of subsequent objects in TrailingObjects. You must update |
3784 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3785 | struct alignas(void *) FunctionTypeExtraBitfields { |
3786 | /// The number of types in the exception specification. |
3787 | /// A whole unsigned is not needed here and according to |
3788 | /// [implimits] 8 bits would be enough here. |
3789 | unsigned NumExceptionType; |
3790 | }; |
3791 | |
3792 | protected: |
3793 | FunctionType(TypeClass tc, QualType res, QualType Canonical, |
3794 | TypeDependence Dependence, ExtInfo Info) |
3795 | : Type(tc, Canonical, Dependence), ResultType(res) { |
3796 | FunctionTypeBits.ExtInfo = Info.Bits; |
3797 | } |
3798 | |
3799 | Qualifiers getFastTypeQuals() const { |
3800 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3801 | } |
3802 | |
3803 | public: |
3804 | QualType getReturnType() const { return ResultType; } |
3805 | |
3806 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3807 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3808 | |
3809 | /// Determine whether this function type includes the GNU noreturn |
3810 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3811 | /// type. |
3812 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3813 | |
3814 | bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } |
3815 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3816 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3817 | |
3818 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3819 | "Const, volatile and restrict are assumed to be a subset of " |
3820 | "the fast qualifiers."); |
3821 | |
3822 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3823 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3824 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3825 | |
3826 | /// Determine the type of an expression that calls a function of |
3827 | /// this type. |
3828 | QualType getCallResultType(const ASTContext &Context) const { |
3829 | return getReturnType().getNonLValueExprType(Context); |
3830 | } |
3831 | |
3832 | static StringRef getNameForCallConv(CallingConv CC); |
3833 | |
3834 | static bool classof(const Type *T) { |
3835 | return T->getTypeClass() == FunctionNoProto || |
3836 | T->getTypeClass() == FunctionProto; |
3837 | } |
3838 | }; |
3839 | |
3840 | /// Represents a K&R-style 'int foo()' function, which has |
3841 | /// no information available about its arguments. |
3842 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3843 | friend class ASTContext; // ASTContext creates these. |
3844 | |
3845 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3846 | : FunctionType(FunctionNoProto, Result, Canonical, |
3847 | Result->getDependence() & |
3848 | ~(TypeDependence::DependentInstantiation | |
3849 | TypeDependence::UnexpandedPack), |
3850 | Info) {} |
3851 | |
3852 | public: |
3853 | // No additional state past what FunctionType provides. |
3854 | |
3855 | bool isSugared() const { return false; } |
3856 | QualType desugar() const { return QualType(this, 0); } |
3857 | |
3858 | void Profile(llvm::FoldingSetNodeID &ID) { |
3859 | Profile(ID, getReturnType(), getExtInfo()); |
3860 | } |
3861 | |
3862 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3863 | ExtInfo Info) { |
3864 | Info.Profile(ID); |
3865 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3866 | } |
3867 | |
3868 | static bool classof(const Type *T) { |
3869 | return T->getTypeClass() == FunctionNoProto; |
3870 | } |
3871 | }; |
3872 | |
3873 | /// Represents a prototype with parameter type info, e.g. |
3874 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3875 | /// parameters, not as having a single void parameter. Such a type can have |
3876 | /// an exception specification, but this specification is not part of the |
3877 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3878 | /// which optional. For more information about the trailing objects see |
3879 | /// the first comment inside FunctionProtoType. |
3880 | class FunctionProtoType final |
3881 | : public FunctionType, |
3882 | public llvm::FoldingSetNode, |
3883 | private llvm::TrailingObjects< |
3884 | FunctionProtoType, QualType, SourceLocation, |
3885 | FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, |
3886 | Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { |
3887 | friend class ASTContext; // ASTContext creates these. |
3888 | friend TrailingObjects; |
3889 | |
3890 | // FunctionProtoType is followed by several trailing objects, some of |
3891 | // which optional. They are in order: |
3892 | // |
3893 | // * An array of getNumParams() QualType holding the parameter types. |
3894 | // Always present. Note that for the vast majority of FunctionProtoType, |
3895 | // these will be the only trailing objects. |
3896 | // |
3897 | // * Optionally if the function is variadic, the SourceLocation of the |
3898 | // ellipsis. |
3899 | // |
3900 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3901 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3902 | // a single FunctionTypeExtraBitfields. Present if and only if |
3903 | // hasExtraBitfields() is true. |
3904 | // |
3905 | // * Optionally exactly one of: |
3906 | // * an array of getNumExceptions() ExceptionType, |
3907 | // * a single Expr *, |
3908 | // * a pair of FunctionDecl *, |
3909 | // * a single FunctionDecl * |
3910 | // used to store information about the various types of exception |
3911 | // specification. See getExceptionSpecSize for the details. |
3912 | // |
3913 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3914 | // an ExtParameterInfo for each of the parameters. Present if and |
3915 | // only if hasExtParameterInfos() is true. |
3916 | // |
3917 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3918 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3919 | // if hasExtQualifiers() is true. |
3920 | // |
3921 | // The optional FunctionTypeExtraBitfields has to be before the data |
3922 | // related to the exception specification since it contains the number |
3923 | // of exception types. |
3924 | // |
3925 | // We put the ExtParameterInfos last. If all were equal, it would make |
3926 | // more sense to put these before the exception specification, because |
3927 | // it's much easier to skip past them compared to the elaborate switch |
3928 | // required to skip the exception specification. However, all is not |
3929 | // equal; ExtParameterInfos are used to model very uncommon features, |
3930 | // and it's better not to burden the more common paths. |
3931 | |
3932 | public: |
3933 | /// Holds information about the various types of exception specification. |
3934 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3935 | /// used to group together the various bits of information about the |
3936 | /// exception specification. |
3937 | struct ExceptionSpecInfo { |
3938 | /// The kind of exception specification this is. |
3939 | ExceptionSpecificationType Type = EST_None; |
3940 | |
3941 | /// Explicitly-specified list of exception types. |
3942 | ArrayRef<QualType> Exceptions; |
3943 | |
3944 | /// Noexcept expression, if this is a computed noexcept specification. |
3945 | Expr *NoexceptExpr = nullptr; |
3946 | |
3947 | /// The function whose exception specification this is, for |
3948 | /// EST_Unevaluated and EST_Uninstantiated. |
3949 | FunctionDecl *SourceDecl = nullptr; |
3950 | |
3951 | /// The function template whose exception specification this is instantiated |
3952 | /// from, for EST_Uninstantiated. |
3953 | FunctionDecl *SourceTemplate = nullptr; |
3954 | |
3955 | ExceptionSpecInfo() = default; |
3956 | |
3957 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3958 | }; |
3959 | |
3960 | /// Extra information about a function prototype. ExtProtoInfo is not |
3961 | /// stored as such in FunctionProtoType but is used to group together |
3962 | /// the various bits of extra information about a function prototype. |
3963 | struct ExtProtoInfo { |
3964 | FunctionType::ExtInfo ExtInfo; |
3965 | bool Variadic : 1; |
3966 | bool HasTrailingReturn : 1; |
3967 | Qualifiers TypeQuals; |
3968 | RefQualifierKind RefQualifier = RQ_None; |
3969 | ExceptionSpecInfo ExceptionSpec; |
3970 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3971 | SourceLocation EllipsisLoc; |
3972 | |
3973 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3974 | |
3975 | ExtProtoInfo(CallingConv CC) |
3976 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3977 | |
3978 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3979 | ExtProtoInfo Result(*this); |
3980 | Result.ExceptionSpec = ESI; |
3981 | return Result; |
3982 | } |
3983 | }; |
3984 | |
3985 | private: |
3986 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3987 | return getNumParams(); |
3988 | } |
3989 | |
3990 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
3991 | return isVariadic(); |
3992 | } |
3993 | |
3994 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3995 | return hasExtraBitfields(); |
3996 | } |
3997 | |
3998 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3999 | return getExceptionSpecSize().NumExceptionType; |
4000 | } |
4001 | |
4002 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
4003 | return getExceptionSpecSize().NumExprPtr; |
4004 | } |
4005 | |
4006 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
4007 | return getExceptionSpecSize().NumFunctionDeclPtr; |
4008 | } |
4009 | |
4010 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
4011 | return hasExtParameterInfos() ? getNumParams() : 0; |
4012 | } |
4013 | |
4014 | /// Determine whether there are any argument types that |
4015 | /// contain an unexpanded parameter pack. |
4016 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
4017 | unsigned numArgs) { |
4018 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
4019 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
4020 | return true; |
4021 | |
4022 | return false; |
4023 | } |
4024 | |
4025 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
4026 | QualType canonical, const ExtProtoInfo &epi); |
4027 | |
4028 | /// This struct is returned by getExceptionSpecSize and is used to |
4029 | /// translate an ExceptionSpecificationType to the number and kind |
4030 | /// of trailing objects related to the exception specification. |
4031 | struct ExceptionSpecSizeHolder { |
4032 | unsigned NumExceptionType; |
4033 | unsigned NumExprPtr; |
4034 | unsigned NumFunctionDeclPtr; |
4035 | }; |
4036 | |
4037 | /// Return the number and kind of trailing objects |
4038 | /// related to the exception specification. |
4039 | static ExceptionSpecSizeHolder |
4040 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
4041 | switch (EST) { |
4042 | case EST_None: |
4043 | case EST_DynamicNone: |
4044 | case EST_MSAny: |
4045 | case EST_BasicNoexcept: |
4046 | case EST_Unparsed: |
4047 | case EST_NoThrow: |
4048 | return {0, 0, 0}; |
4049 | |
4050 | case EST_Dynamic: |
4051 | return {NumExceptions, 0, 0}; |
4052 | |
4053 | case EST_DependentNoexcept: |
4054 | case EST_NoexceptFalse: |
4055 | case EST_NoexceptTrue: |
4056 | return {0, 1, 0}; |
4057 | |
4058 | case EST_Uninstantiated: |
4059 | return {0, 0, 2}; |
4060 | |
4061 | case EST_Unevaluated: |
4062 | return {0, 0, 1}; |
4063 | } |
4064 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4064); |
4065 | } |
4066 | |
4067 | /// Return the number and kind of trailing objects |
4068 | /// related to the exception specification. |
4069 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
4070 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
4071 | } |
4072 | |
4073 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4074 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
4075 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
4076 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
4077 | return EST == EST_Dynamic; |
4078 | } |
4079 | |
4080 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4081 | bool hasExtraBitfields() const { |
4082 | return hasExtraBitfields(getExceptionSpecType()); |
4083 | } |
4084 | |
4085 | bool hasExtQualifiers() const { |
4086 | return FunctionTypeBits.HasExtQuals; |
4087 | } |
4088 | |
4089 | public: |
4090 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
4091 | |
4092 | QualType getParamType(unsigned i) const { |
4093 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4093, __PRETTY_FUNCTION__)); |
4094 | return param_type_begin()[i]; |
4095 | } |
4096 | |
4097 | ArrayRef<QualType> getParamTypes() const { |
4098 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
4099 | } |
4100 | |
4101 | ExtProtoInfo getExtProtoInfo() const { |
4102 | ExtProtoInfo EPI; |
4103 | EPI.ExtInfo = getExtInfo(); |
4104 | EPI.Variadic = isVariadic(); |
4105 | EPI.EllipsisLoc = getEllipsisLoc(); |
4106 | EPI.HasTrailingReturn = hasTrailingReturn(); |
4107 | EPI.ExceptionSpec = getExceptionSpecInfo(); |
4108 | EPI.TypeQuals = getMethodQuals(); |
4109 | EPI.RefQualifier = getRefQualifier(); |
4110 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
4111 | return EPI; |
4112 | } |
4113 | |
4114 | /// Get the kind of exception specification on this function. |
4115 | ExceptionSpecificationType getExceptionSpecType() const { |
4116 | return static_cast<ExceptionSpecificationType>( |
4117 | FunctionTypeBits.ExceptionSpecType); |
4118 | } |
4119 | |
4120 | /// Return whether this function has any kind of exception spec. |
4121 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
4122 | |
4123 | /// Return whether this function has a dynamic (throw) exception spec. |
4124 | bool hasDynamicExceptionSpec() const { |
4125 | return isDynamicExceptionSpec(getExceptionSpecType()); |
4126 | } |
4127 | |
4128 | /// Return whether this function has a noexcept exception spec. |
4129 | bool hasNoexceptExceptionSpec() const { |
4130 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
4131 | } |
4132 | |
4133 | /// Return whether this function has a dependent exception spec. |
4134 | bool hasDependentExceptionSpec() const; |
4135 | |
4136 | /// Return whether this function has an instantiation-dependent exception |
4137 | /// spec. |
4138 | bool hasInstantiationDependentExceptionSpec() const; |
4139 | |
4140 | /// Return all the available information about this type's exception spec. |
4141 | ExceptionSpecInfo getExceptionSpecInfo() const { |
4142 | ExceptionSpecInfo Result; |
4143 | Result.Type = getExceptionSpecType(); |
4144 | if (Result.Type == EST_Dynamic) { |
4145 | Result.Exceptions = exceptions(); |
4146 | } else if (isComputedNoexcept(Result.Type)) { |
4147 | Result.NoexceptExpr = getNoexceptExpr(); |
4148 | } else if (Result.Type == EST_Uninstantiated) { |
4149 | Result.SourceDecl = getExceptionSpecDecl(); |
4150 | Result.SourceTemplate = getExceptionSpecTemplate(); |
4151 | } else if (Result.Type == EST_Unevaluated) { |
4152 | Result.SourceDecl = getExceptionSpecDecl(); |
4153 | } |
4154 | return Result; |
4155 | } |
4156 | |
4157 | /// Return the number of types in the exception specification. |
4158 | unsigned getNumExceptions() const { |
4159 | return getExceptionSpecType() == EST_Dynamic |
4160 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
4161 | ->NumExceptionType |
4162 | : 0; |
4163 | } |
4164 | |
4165 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
4166 | QualType getExceptionType(unsigned i) const { |
4167 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4167, __PRETTY_FUNCTION__)); |
4168 | return exception_begin()[i]; |
4169 | } |
4170 | |
4171 | /// Return the expression inside noexcept(expression), or a null pointer |
4172 | /// if there is none (because the exception spec is not of this form). |
4173 | Expr *getNoexceptExpr() const { |
4174 | if (!isComputedNoexcept(getExceptionSpecType())) |
4175 | return nullptr; |
4176 | return *getTrailingObjects<Expr *>(); |
4177 | } |
4178 | |
4179 | /// If this function type has an exception specification which hasn't |
4180 | /// been determined yet (either because it has not been evaluated or because |
4181 | /// it has not been instantiated), this is the function whose exception |
4182 | /// specification is represented by this type. |
4183 | FunctionDecl *getExceptionSpecDecl() const { |
4184 | if (getExceptionSpecType() != EST_Uninstantiated && |
4185 | getExceptionSpecType() != EST_Unevaluated) |
4186 | return nullptr; |
4187 | return getTrailingObjects<FunctionDecl *>()[0]; |
4188 | } |
4189 | |
4190 | /// If this function type has an uninstantiated exception |
4191 | /// specification, this is the function whose exception specification |
4192 | /// should be instantiated to find the exception specification for |
4193 | /// this type. |
4194 | FunctionDecl *getExceptionSpecTemplate() const { |
4195 | if (getExceptionSpecType() != EST_Uninstantiated) |
4196 | return nullptr; |
4197 | return getTrailingObjects<FunctionDecl *>()[1]; |
4198 | } |
4199 | |
4200 | /// Determine whether this function type has a non-throwing exception |
4201 | /// specification. |
4202 | CanThrowResult canThrow() const; |
4203 | |
4204 | /// Determine whether this function type has a non-throwing exception |
4205 | /// specification. If this depends on template arguments, returns |
4206 | /// \c ResultIfDependent. |
4207 | bool isNothrow(bool ResultIfDependent = false) const { |
4208 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4209 | } |
4210 | |
4211 | /// Whether this function prototype is variadic. |
4212 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4213 | |
4214 | SourceLocation getEllipsisLoc() const { |
4215 | return isVariadic() ? *getTrailingObjects<SourceLocation>() |
4216 | : SourceLocation(); |
4217 | } |
4218 | |
4219 | /// Determines whether this function prototype contains a |
4220 | /// parameter pack at the end. |
4221 | /// |
4222 | /// A function template whose last parameter is a parameter pack can be |
4223 | /// called with an arbitrary number of arguments, much like a variadic |
4224 | /// function. |
4225 | bool isTemplateVariadic() const; |
4226 | |
4227 | /// Whether this function prototype has a trailing return type. |
4228 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4229 | |
4230 | Qualifiers getMethodQuals() const { |
4231 | if (hasExtQualifiers()) |
4232 | return *getTrailingObjects<Qualifiers>(); |
4233 | else |
4234 | return getFastTypeQuals(); |
4235 | } |
4236 | |
4237 | /// Retrieve the ref-qualifier associated with this function type. |
4238 | RefQualifierKind getRefQualifier() const { |
4239 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4240 | } |
4241 | |
4242 | using param_type_iterator = const QualType *; |
4243 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4244 | |
4245 | param_type_range param_types() const { |
4246 | return param_type_range(param_type_begin(), param_type_end()); |
4247 | } |
4248 | |
4249 | param_type_iterator param_type_begin() const { |
4250 | return getTrailingObjects<QualType>(); |
4251 | } |
4252 | |
4253 | param_type_iterator param_type_end() const { |
4254 | return param_type_begin() + getNumParams(); |
4255 | } |
4256 | |
4257 | using exception_iterator = const QualType *; |
4258 | |
4259 | ArrayRef<QualType> exceptions() const { |
4260 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4261 | } |
4262 | |
4263 | exception_iterator exception_begin() const { |
4264 | return reinterpret_cast<exception_iterator>( |
4265 | getTrailingObjects<ExceptionType>()); |
4266 | } |
4267 | |
4268 | exception_iterator exception_end() const { |
4269 | return exception_begin() + getNumExceptions(); |
4270 | } |
4271 | |
4272 | /// Is there any interesting extra information for any of the parameters |
4273 | /// of this function type? |
4274 | bool hasExtParameterInfos() const { |
4275 | return FunctionTypeBits.HasExtParameterInfos; |
4276 | } |
4277 | |
4278 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4279 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4279, __PRETTY_FUNCTION__)); |
4280 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4281 | getNumParams()); |
4282 | } |
4283 | |
4284 | /// Return a pointer to the beginning of the array of extra parameter |
4285 | /// information, if present, or else null if none of the parameters |
4286 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4287 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4288 | if (!hasExtParameterInfos()) |
4289 | return nullptr; |
4290 | return getTrailingObjects<ExtParameterInfo>(); |
4291 | } |
4292 | |
4293 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4294 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4294, __PRETTY_FUNCTION__)); |
4295 | if (hasExtParameterInfos()) |
4296 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4297 | return ExtParameterInfo(); |
4298 | } |
4299 | |
4300 | ParameterABI getParameterABI(unsigned I) const { |
4301 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4301, __PRETTY_FUNCTION__)); |
4302 | if (hasExtParameterInfos()) |
4303 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4304 | return ParameterABI::Ordinary; |
4305 | } |
4306 | |
4307 | bool isParamConsumed(unsigned I) const { |
4308 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4308, __PRETTY_FUNCTION__)); |
4309 | if (hasExtParameterInfos()) |
4310 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4311 | return false; |
4312 | } |
4313 | |
4314 | bool isSugared() const { return false; } |
4315 | QualType desugar() const { return QualType(this, 0); } |
4316 | |
4317 | void printExceptionSpecification(raw_ostream &OS, |
4318 | const PrintingPolicy &Policy) const; |
4319 | |
4320 | static bool classof(const Type *T) { |
4321 | return T->getTypeClass() == FunctionProto; |
4322 | } |
4323 | |
4324 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4325 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4326 | param_type_iterator ArgTys, unsigned NumArgs, |
4327 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4328 | bool Canonical); |
4329 | }; |
4330 | |
4331 | /// Represents the dependent type named by a dependently-scoped |
4332 | /// typename using declaration, e.g. |
4333 | /// using typename Base<T>::foo; |
4334 | /// |
4335 | /// Template instantiation turns these into the underlying type. |
4336 | class UnresolvedUsingType : public Type { |
4337 | friend class ASTContext; // ASTContext creates these. |
4338 | |
4339 | UnresolvedUsingTypenameDecl *Decl; |
4340 | |
4341 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4342 | : Type(UnresolvedUsing, QualType(), |
4343 | TypeDependence::DependentInstantiation), |
4344 | Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {} |
4345 | |
4346 | public: |
4347 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4348 | |
4349 | bool isSugared() const { return false; } |
4350 | QualType desugar() const { return QualType(this, 0); } |
4351 | |
4352 | static bool classof(const Type *T) { |
4353 | return T->getTypeClass() == UnresolvedUsing; |
4354 | } |
4355 | |
4356 | void Profile(llvm::FoldingSetNodeID &ID) { |
4357 | return Profile(ID, Decl); |
4358 | } |
4359 | |
4360 | static void Profile(llvm::FoldingSetNodeID &ID, |
4361 | UnresolvedUsingTypenameDecl *D) { |
4362 | ID.AddPointer(D); |
4363 | } |
4364 | }; |
4365 | |
4366 | class TypedefType : public Type { |
4367 | TypedefNameDecl *Decl; |
4368 | |
4369 | private: |
4370 | friend class ASTContext; // ASTContext creates these. |
4371 | |
4372 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying, |
4373 | QualType can); |
4374 | |
4375 | public: |
4376 | TypedefNameDecl *getDecl() const { return Decl; } |
4377 | |
4378 | bool isSugared() const { return true; } |
4379 | QualType desugar() const; |
4380 | |
4381 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4382 | }; |
4383 | |
4384 | /// Sugar type that represents a type that was qualified by a qualifier written |
4385 | /// as a macro invocation. |
4386 | class MacroQualifiedType : public Type { |
4387 | friend class ASTContext; // ASTContext creates these. |
4388 | |
4389 | QualType UnderlyingTy; |
4390 | const IdentifierInfo *MacroII; |
4391 | |
4392 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4393 | const IdentifierInfo *MacroII) |
4394 | : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()), |
4395 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4396 | assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4397, __PRETTY_FUNCTION__)) |
4397 | "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4397, __PRETTY_FUNCTION__)); |
4398 | } |
4399 | |
4400 | public: |
4401 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4402 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4403 | |
4404 | /// Return this attributed type's modified type with no qualifiers attached to |
4405 | /// it. |
4406 | QualType getModifiedType() const; |
4407 | |
4408 | bool isSugared() const { return true; } |
4409 | QualType desugar() const; |
4410 | |
4411 | static bool classof(const Type *T) { |
4412 | return T->getTypeClass() == MacroQualified; |
4413 | } |
4414 | }; |
4415 | |
4416 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4417 | class TypeOfExprType : public Type { |
4418 | Expr *TOExpr; |
4419 | |
4420 | protected: |
4421 | friend class ASTContext; // ASTContext creates these. |
4422 | |
4423 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4424 | |
4425 | public: |
4426 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4427 | |
4428 | /// Remove a single level of sugar. |
4429 | QualType desugar() const; |
4430 | |
4431 | /// Returns whether this type directly provides sugar. |
4432 | bool isSugared() const; |
4433 | |
4434 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4435 | }; |
4436 | |
4437 | /// Internal representation of canonical, dependent |
4438 | /// `typeof(expr)` types. |
4439 | /// |
4440 | /// This class is used internally by the ASTContext to manage |
4441 | /// canonical, dependent types, only. Clients will only see instances |
4442 | /// of this class via TypeOfExprType nodes. |
4443 | class DependentTypeOfExprType |
4444 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4445 | const ASTContext &Context; |
4446 | |
4447 | public: |
4448 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4449 | : TypeOfExprType(E), Context(Context) {} |
4450 | |
4451 | void Profile(llvm::FoldingSetNodeID &ID) { |
4452 | Profile(ID, Context, getUnderlyingExpr()); |
4453 | } |
4454 | |
4455 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4456 | Expr *E); |
4457 | }; |
4458 | |
4459 | /// Represents `typeof(type)`, a GCC extension. |
4460 | class TypeOfType : public Type { |
4461 | friend class ASTContext; // ASTContext creates these. |
4462 | |
4463 | QualType TOType; |
4464 | |
4465 | TypeOfType(QualType T, QualType can) |
4466 | : Type(TypeOf, can, T->getDependence()), TOType(T) { |
4467 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4467, __PRETTY_FUNCTION__)); |
4468 | } |
4469 | |
4470 | public: |
4471 | QualType getUnderlyingType() const { return TOType; } |
4472 | |
4473 | /// Remove a single level of sugar. |
4474 | QualType desugar() const { return getUnderlyingType(); } |
4475 | |
4476 | /// Returns whether this type directly provides sugar. |
4477 | bool isSugared() const { return true; } |
4478 | |
4479 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4480 | }; |
4481 | |
4482 | /// Represents the type `decltype(expr)` (C++11). |
4483 | class DecltypeType : public Type { |
4484 | Expr *E; |
4485 | QualType UnderlyingType; |
4486 | |
4487 | protected: |
4488 | friend class ASTContext; // ASTContext creates these. |
4489 | |
4490 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4491 | |
4492 | public: |
4493 | Expr *getUnderlyingExpr() const { return E; } |
4494 | QualType getUnderlyingType() const { return UnderlyingType; } |
4495 | |
4496 | /// Remove a single level of sugar. |
4497 | QualType desugar() const; |
4498 | |
4499 | /// Returns whether this type directly provides sugar. |
4500 | bool isSugared() const; |
4501 | |
4502 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4503 | }; |
4504 | |
4505 | /// Internal representation of canonical, dependent |
4506 | /// decltype(expr) types. |
4507 | /// |
4508 | /// This class is used internally by the ASTContext to manage |
4509 | /// canonical, dependent types, only. Clients will only see instances |
4510 | /// of this class via DecltypeType nodes. |
4511 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4512 | const ASTContext &Context; |
4513 | |
4514 | public: |
4515 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4516 | |
4517 | void Profile(llvm::FoldingSetNodeID &ID) { |
4518 | Profile(ID, Context, getUnderlyingExpr()); |
4519 | } |
4520 | |
4521 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4522 | Expr *E); |
4523 | }; |
4524 | |
4525 | /// A unary type transform, which is a type constructed from another. |
4526 | class UnaryTransformType : public Type { |
4527 | public: |
4528 | enum UTTKind { |
4529 | EnumUnderlyingType |
4530 | }; |
4531 | |
4532 | private: |
4533 | /// The untransformed type. |
4534 | QualType BaseType; |
4535 | |
4536 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4537 | QualType UnderlyingType; |
4538 | |
4539 | UTTKind UKind; |
4540 | |
4541 | protected: |
4542 | friend class ASTContext; |
4543 | |
4544 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4545 | QualType CanonicalTy); |
4546 | |
4547 | public: |
4548 | bool isSugared() const { return !isDependentType(); } |
4549 | QualType desugar() const { return UnderlyingType; } |
4550 | |
4551 | QualType getUnderlyingType() const { return UnderlyingType; } |
4552 | QualType getBaseType() const { return BaseType; } |
4553 | |
4554 | UTTKind getUTTKind() const { return UKind; } |
4555 | |
4556 | static bool classof(const Type *T) { |
4557 | return T->getTypeClass() == UnaryTransform; |
4558 | } |
4559 | }; |
4560 | |
4561 | /// Internal representation of canonical, dependent |
4562 | /// __underlying_type(type) types. |
4563 | /// |
4564 | /// This class is used internally by the ASTContext to manage |
4565 | /// canonical, dependent types, only. Clients will only see instances |
4566 | /// of this class via UnaryTransformType nodes. |
4567 | class DependentUnaryTransformType : public UnaryTransformType, |
4568 | public llvm::FoldingSetNode { |
4569 | public: |
4570 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4571 | UTTKind UKind); |
4572 | |
4573 | void Profile(llvm::FoldingSetNodeID &ID) { |
4574 | Profile(ID, getBaseType(), getUTTKind()); |
4575 | } |
4576 | |
4577 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4578 | UTTKind UKind) { |
4579 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4580 | ID.AddInteger((unsigned)UKind); |
4581 | } |
4582 | }; |
4583 | |
4584 | class TagType : public Type { |
4585 | friend class ASTReader; |
4586 | template <class T> friend class serialization::AbstractTypeReader; |
4587 | |
4588 | /// Stores the TagDecl associated with this type. The decl may point to any |
4589 | /// TagDecl that declares the entity. |
4590 | TagDecl *decl; |
4591 | |
4592 | protected: |
4593 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4594 | |
4595 | public: |
4596 | TagDecl *getDecl() const; |
4597 | |
4598 | /// Determines whether this type is in the process of being defined. |
4599 | bool isBeingDefined() const; |
4600 | |
4601 | static bool classof(const Type *T) { |
4602 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4603 | } |
4604 | }; |
4605 | |
4606 | /// A helper class that allows the use of isa/cast/dyncast |
4607 | /// to detect TagType objects of structs/unions/classes. |
4608 | class RecordType : public TagType { |
4609 | protected: |
4610 | friend class ASTContext; // ASTContext creates these. |
4611 | |
4612 | explicit RecordType(const RecordDecl *D) |
4613 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4614 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4615 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4616 | |
4617 | public: |
4618 | RecordDecl *getDecl() const { |
4619 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4620 | } |
4621 | |
4622 | /// Recursively check all fields in the record for const-ness. If any field |
4623 | /// is declared const, return true. Otherwise, return false. |
4624 | bool hasConstFields() const; |
4625 | |
4626 | bool isSugared() const { return false; } |
4627 | QualType desugar() const { return QualType(this, 0); } |
4628 | |
4629 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4630 | }; |
4631 | |
4632 | /// A helper class that allows the use of isa/cast/dyncast |
4633 | /// to detect TagType objects of enums. |
4634 | class EnumType : public TagType { |
4635 | friend class ASTContext; // ASTContext creates these. |
4636 | |
4637 | explicit EnumType(const EnumDecl *D) |
4638 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4639 | |
4640 | public: |
4641 | EnumDecl *getDecl() const { |
4642 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4643 | } |
4644 | |
4645 | bool isSugared() const { return false; } |
4646 | QualType desugar() const { return QualType(this, 0); } |
4647 | |
4648 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4649 | }; |
4650 | |
4651 | /// An attributed type is a type to which a type attribute has been applied. |
4652 | /// |
4653 | /// The "modified type" is the fully-sugared type to which the attributed |
4654 | /// type was applied; generally it is not canonically equivalent to the |
4655 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4656 | /// which the type is canonically equivalent to. |
4657 | /// |
4658 | /// For example, in the following attributed type: |
4659 | /// int32_t __attribute__((vector_size(16))) |
4660 | /// - the modified type is the TypedefType for int32_t |
4661 | /// - the equivalent type is VectorType(16, int32_t) |
4662 | /// - the canonical type is VectorType(16, int) |
4663 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4664 | public: |
4665 | using Kind = attr::Kind; |
4666 | |
4667 | private: |
4668 | friend class ASTContext; // ASTContext creates these |
4669 | |
4670 | QualType ModifiedType; |
4671 | QualType EquivalentType; |
4672 | |
4673 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4674 | QualType equivalent) |
4675 | : Type(Attributed, canon, equivalent->getDependence()), |
4676 | ModifiedType(modified), EquivalentType(equivalent) { |
4677 | AttributedTypeBits.AttrKind = attrKind; |
4678 | } |
4679 | |
4680 | public: |
4681 | Kind getAttrKind() const { |
4682 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4683 | } |
4684 | |
4685 | QualType getModifiedType() const { return ModifiedType; } |
4686 | QualType getEquivalentType() const { return EquivalentType; } |
4687 | |
4688 | bool isSugared() const { return true; } |
4689 | QualType desugar() const { return getEquivalentType(); } |
4690 | |
4691 | /// Does this attribute behave like a type qualifier? |
4692 | /// |
4693 | /// A type qualifier adjusts a type to provide specialized rules for |
4694 | /// a specific object, like the standard const and volatile qualifiers. |
4695 | /// This includes attributes controlling things like nullability, |
4696 | /// address spaces, and ARC ownership. The value of the object is still |
4697 | /// largely described by the modified type. |
4698 | /// |
4699 | /// In contrast, many type attributes "rewrite" their modified type to |
4700 | /// produce a fundamentally different type, not necessarily related in any |
4701 | /// formalizable way to the original type. For example, calling convention |
4702 | /// and vector attributes are not simple type qualifiers. |
4703 | /// |
4704 | /// Type qualifiers are often, but not always, reflected in the canonical |
4705 | /// type. |
4706 | bool isQualifier() const; |
4707 | |
4708 | bool isMSTypeSpec() const; |
4709 | |
4710 | bool isCallingConv() const; |
4711 | |
4712 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4713 | |
4714 | /// Retrieve the attribute kind corresponding to the given |
4715 | /// nullability kind. |
4716 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4717 | switch (kind) { |
4718 | case NullabilityKind::NonNull: |
4719 | return attr::TypeNonNull; |
4720 | |
4721 | case NullabilityKind::Nullable: |
4722 | return attr::TypeNullable; |
4723 | |
4724 | case NullabilityKind::NullableResult: |
4725 | return attr::TypeNullableResult; |
4726 | |
4727 | case NullabilityKind::Unspecified: |
4728 | return attr::TypeNullUnspecified; |
4729 | } |
4730 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 4730); |
4731 | } |
4732 | |
4733 | /// Strip off the top-level nullability annotation on the given |
4734 | /// type, if it's there. |
4735 | /// |
4736 | /// \param T The type to strip. If the type is exactly an |
4737 | /// AttributedType specifying nullability (without looking through |
4738 | /// type sugar), the nullability is returned and this type changed |
4739 | /// to the underlying modified type. |
4740 | /// |
4741 | /// \returns the top-level nullability, if present. |
4742 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4743 | |
4744 | void Profile(llvm::FoldingSetNodeID &ID) { |
4745 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4746 | } |
4747 | |
4748 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4749 | QualType modified, QualType equivalent) { |
4750 | ID.AddInteger(attrKind); |
4751 | ID.AddPointer(modified.getAsOpaquePtr()); |
4752 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4753 | } |
4754 | |
4755 | static bool classof(const Type *T) { |
4756 | return T->getTypeClass() == Attributed; |
4757 | } |
4758 | }; |
4759 | |
4760 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4761 | friend class ASTContext; // ASTContext creates these |
4762 | |
4763 | // Helper data collector for canonical types. |
4764 | struct CanonicalTTPTInfo { |
4765 | unsigned Depth : 15; |
4766 | unsigned ParameterPack : 1; |
4767 | unsigned Index : 16; |
4768 | }; |
4769 | |
4770 | union { |
4771 | // Info for the canonical type. |
4772 | CanonicalTTPTInfo CanTTPTInfo; |
4773 | |
4774 | // Info for the non-canonical type. |
4775 | TemplateTypeParmDecl *TTPDecl; |
4776 | }; |
4777 | |
4778 | /// Build a non-canonical type. |
4779 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4780 | : Type(TemplateTypeParm, Canon, |
4781 | TypeDependence::DependentInstantiation | |
4782 | (Canon->getDependence() & TypeDependence::UnexpandedPack)), |
4783 | TTPDecl(TTPDecl) {} |
4784 | |
4785 | /// Build the canonical type. |
4786 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4787 | : Type(TemplateTypeParm, QualType(this, 0), |
4788 | TypeDependence::DependentInstantiation | |
4789 | (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) { |
4790 | CanTTPTInfo.Depth = D; |
4791 | CanTTPTInfo.Index = I; |
4792 | CanTTPTInfo.ParameterPack = PP; |
4793 | } |
4794 | |
4795 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4796 | QualType Can = getCanonicalTypeInternal(); |
4797 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4798 | } |
4799 | |
4800 | public: |
4801 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4802 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4803 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4804 | |
4805 | TemplateTypeParmDecl *getDecl() const { |
4806 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4807 | } |
4808 | |
4809 | IdentifierInfo *getIdentifier() const; |
4810 | |
4811 | bool isSugared() const { return false; } |
4812 | QualType desugar() const { return QualType(this, 0); } |
4813 | |
4814 | void Profile(llvm::FoldingSetNodeID &ID) { |
4815 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4816 | } |
4817 | |
4818 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4819 | unsigned Index, bool ParameterPack, |
4820 | TemplateTypeParmDecl *TTPDecl) { |
4821 | ID.AddInteger(Depth); |
4822 | ID.AddInteger(Index); |
4823 | ID.AddBoolean(ParameterPack); |
4824 | ID.AddPointer(TTPDecl); |
4825 | } |
4826 | |
4827 | static bool classof(const Type *T) { |
4828 | return T->getTypeClass() == TemplateTypeParm; |
4829 | } |
4830 | }; |
4831 | |
4832 | /// Represents the result of substituting a type for a template |
4833 | /// type parameter. |
4834 | /// |
4835 | /// Within an instantiated template, all template type parameters have |
4836 | /// been replaced with these. They are used solely to record that a |
4837 | /// type was originally written as a template type parameter; |
4838 | /// therefore they are never canonical. |
4839 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4840 | friend class ASTContext; |
4841 | |
4842 | // The original type parameter. |
4843 | const TemplateTypeParmType *Replaced; |
4844 | |
4845 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4846 | : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), |
4847 | Replaced(Param) {} |
4848 | |
4849 | public: |
4850 | /// Gets the template parameter that was substituted for. |
4851 | const TemplateTypeParmType *getReplacedParameter() const { |
4852 | return Replaced; |
4853 | } |
4854 | |
4855 | /// Gets the type that was substituted for the template |
4856 | /// parameter. |
4857 | QualType getReplacementType() const { |
4858 | return getCanonicalTypeInternal(); |
4859 | } |
4860 | |
4861 | bool isSugared() const { return true; } |
4862 | QualType desugar() const { return getReplacementType(); } |
4863 | |
4864 | void Profile(llvm::FoldingSetNodeID &ID) { |
4865 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4866 | } |
4867 | |
4868 | static void Profile(llvm::FoldingSetNodeID &ID, |
4869 | const TemplateTypeParmType *Replaced, |
4870 | QualType Replacement) { |
4871 | ID.AddPointer(Replaced); |
4872 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4873 | } |
4874 | |
4875 | static bool classof(const Type *T) { |
4876 | return T->getTypeClass() == SubstTemplateTypeParm; |
4877 | } |
4878 | }; |
4879 | |
4880 | /// Represents the result of substituting a set of types for a template |
4881 | /// type parameter pack. |
4882 | /// |
4883 | /// When a pack expansion in the source code contains multiple parameter packs |
4884 | /// and those parameter packs correspond to different levels of template |
4885 | /// parameter lists, this type node is used to represent a template type |
4886 | /// parameter pack from an outer level, which has already had its argument pack |
4887 | /// substituted but that still lives within a pack expansion that itself |
4888 | /// could not be instantiated. When actually performing a substitution into |
4889 | /// that pack expansion (e.g., when all template parameters have corresponding |
4890 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4891 | /// at the current pack substitution index. |
4892 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4893 | friend class ASTContext; |
4894 | |
4895 | /// The original type parameter. |
4896 | const TemplateTypeParmType *Replaced; |
4897 | |
4898 | /// A pointer to the set of template arguments that this |
4899 | /// parameter pack is instantiated with. |
4900 | const TemplateArgument *Arguments; |
4901 | |
4902 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4903 | QualType Canon, |
4904 | const TemplateArgument &ArgPack); |
4905 | |
4906 | public: |
4907 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4908 | |
4909 | /// Gets the template parameter that was substituted for. |
4910 | const TemplateTypeParmType *getReplacedParameter() const { |
4911 | return Replaced; |
4912 | } |
4913 | |
4914 | unsigned getNumArgs() const { |
4915 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4916 | } |
4917 | |
4918 | bool isSugared() const { return false; } |
4919 | QualType desugar() const { return QualType(this, 0); } |
4920 | |
4921 | TemplateArgument getArgumentPack() const; |
4922 | |
4923 | void Profile(llvm::FoldingSetNodeID &ID); |
4924 | static void Profile(llvm::FoldingSetNodeID &ID, |
4925 | const TemplateTypeParmType *Replaced, |
4926 | const TemplateArgument &ArgPack); |
4927 | |
4928 | static bool classof(const Type *T) { |
4929 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4930 | } |
4931 | }; |
4932 | |
4933 | /// Common base class for placeholders for types that get replaced by |
4934 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4935 | /// class template types, and constrained type names. |
4936 | /// |
4937 | /// These types are usually a placeholder for a deduced type. However, before |
4938 | /// the initializer is attached, or (usually) if the initializer is |
4939 | /// type-dependent, there is no deduced type and the type is canonical. In |
4940 | /// the latter case, it is also a dependent type. |
4941 | class DeducedType : public Type { |
4942 | protected: |
4943 | DeducedType(TypeClass TC, QualType DeducedAsType, |
4944 | TypeDependence ExtraDependence) |
4945 | : Type(TC, |
4946 | // FIXME: Retain the sugared deduced type? |
4947 | DeducedAsType.isNull() ? QualType(this, 0) |
4948 | : DeducedAsType.getCanonicalType(), |
4949 | ExtraDependence | (DeducedAsType.isNull() |
4950 | ? TypeDependence::None |
4951 | : DeducedAsType->getDependence() & |
4952 | ~TypeDependence::VariablyModified)) {} |
4953 | |
4954 | public: |
4955 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4956 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4957 | |
4958 | /// Get the type deduced for this placeholder type, or null if it's |
4959 | /// either not been deduced or was deduced to a dependent type. |
4960 | QualType getDeducedType() const { |
4961 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4962 | } |
4963 | bool isDeduced() const { |
4964 | return !isCanonicalUnqualified() || isDependentType(); |
4965 | } |
4966 | |
4967 | static bool classof(const Type *T) { |
4968 | return T->getTypeClass() == Auto || |
4969 | T->getTypeClass() == DeducedTemplateSpecialization; |
4970 | } |
4971 | }; |
4972 | |
4973 | /// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained |
4974 | /// by a type-constraint. |
4975 | class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode { |
4976 | friend class ASTContext; // ASTContext creates these |
4977 | |
4978 | ConceptDecl *TypeConstraintConcept; |
4979 | |
4980 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4981 | TypeDependence ExtraDependence, ConceptDecl *CD, |
4982 | ArrayRef<TemplateArgument> TypeConstraintArgs); |
4983 | |
4984 | const TemplateArgument *getArgBuffer() const { |
4985 | return reinterpret_cast<const TemplateArgument*>(this+1); |
4986 | } |
4987 | |
4988 | TemplateArgument *getArgBuffer() { |
4989 | return reinterpret_cast<TemplateArgument*>(this+1); |
4990 | } |
4991 | |
4992 | public: |
4993 | /// Retrieve the template arguments. |
4994 | const TemplateArgument *getArgs() const { |
4995 | return getArgBuffer(); |
4996 | } |
4997 | |
4998 | /// Retrieve the number of template arguments. |
4999 | unsigned getNumArgs() const { |
5000 | return AutoTypeBits.NumArgs; |
5001 | } |
5002 | |
5003 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5004 | |
5005 | ArrayRef<TemplateArgument> getTypeConstraintArguments() const { |
5006 | return {getArgs(), getNumArgs()}; |
5007 | } |
5008 | |
5009 | ConceptDecl *getTypeConstraintConcept() const { |
5010 | return TypeConstraintConcept; |
5011 | } |
5012 | |
5013 | bool isConstrained() const { |
5014 | return TypeConstraintConcept != nullptr; |
5015 | } |
5016 | |
5017 | bool isDecltypeAuto() const { |
5018 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
5019 | } |
5020 | |
5021 | AutoTypeKeyword getKeyword() const { |
5022 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
5023 | } |
5024 | |
5025 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5026 | Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), |
5027 | getTypeConstraintConcept(), getTypeConstraintArguments()); |
5028 | } |
5029 | |
5030 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
5031 | QualType Deduced, AutoTypeKeyword Keyword, |
5032 | bool IsDependent, ConceptDecl *CD, |
5033 | ArrayRef<TemplateArgument> Arguments); |
5034 | |
5035 | static bool classof(const Type *T) { |
5036 | return T->getTypeClass() == Auto; |
5037 | } |
5038 | }; |
5039 | |
5040 | /// Represents a C++17 deduced template specialization type. |
5041 | class DeducedTemplateSpecializationType : public DeducedType, |
5042 | public llvm::FoldingSetNode { |
5043 | friend class ASTContext; // ASTContext creates these |
5044 | |
5045 | /// The name of the template whose arguments will be deduced. |
5046 | TemplateName Template; |
5047 | |
5048 | DeducedTemplateSpecializationType(TemplateName Template, |
5049 | QualType DeducedAsType, |
5050 | bool IsDeducedAsDependent) |
5051 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
5052 | toTypeDependence(Template.getDependence()) | |
5053 | (IsDeducedAsDependent |
5054 | ? TypeDependence::DependentInstantiation |
5055 | : TypeDependence::None)), |
5056 | Template(Template) {} |
5057 | |
5058 | public: |
5059 | /// Retrieve the name of the template that we are deducing. |
5060 | TemplateName getTemplateName() const { return Template;} |
5061 | |
5062 | void Profile(llvm::FoldingSetNodeID &ID) { |
5063 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
5064 | } |
5065 | |
5066 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
5067 | QualType Deduced, bool IsDependent) { |
5068 | Template.Profile(ID); |
5069 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
5070 | ID.AddBoolean(IsDependent); |
5071 | } |
5072 | |
5073 | static bool classof(const Type *T) { |
5074 | return T->getTypeClass() == DeducedTemplateSpecialization; |
5075 | } |
5076 | }; |
5077 | |
5078 | /// Represents a type template specialization; the template |
5079 | /// must be a class template, a type alias template, or a template |
5080 | /// template parameter. A template which cannot be resolved to one of |
5081 | /// these, e.g. because it is written with a dependent scope |
5082 | /// specifier, is instead represented as a |
5083 | /// @c DependentTemplateSpecializationType. |
5084 | /// |
5085 | /// A non-dependent template specialization type is always "sugar", |
5086 | /// typically for a \c RecordType. For example, a class template |
5087 | /// specialization type of \c vector<int> will refer to a tag type for |
5088 | /// the instantiation \c std::vector<int, std::allocator<int>> |
5089 | /// |
5090 | /// Template specializations are dependent if either the template or |
5091 | /// any of the template arguments are dependent, in which case the |
5092 | /// type may also be canonical. |
5093 | /// |
5094 | /// Instances of this type are allocated with a trailing array of |
5095 | /// TemplateArguments, followed by a QualType representing the |
5096 | /// non-canonical aliased type when the template is a type alias |
5097 | /// template. |
5098 | class alignas(8) TemplateSpecializationType |
5099 | : public Type, |
5100 | public llvm::FoldingSetNode { |
5101 | friend class ASTContext; // ASTContext creates these |
5102 | |
5103 | /// The name of the template being specialized. This is |
5104 | /// either a TemplateName::Template (in which case it is a |
5105 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
5106 | /// TypeAliasTemplateDecl*), a |
5107 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
5108 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
5109 | /// replacement must, recursively, be one of these). |
5110 | TemplateName Template; |
5111 | |
5112 | TemplateSpecializationType(TemplateName T, |
5113 | ArrayRef<TemplateArgument> Args, |
5114 | QualType Canon, |
5115 | QualType Aliased); |
5116 | |
5117 | public: |
5118 | /// Determine whether any of the given template arguments are dependent. |
5119 | /// |
5120 | /// The converted arguments should be supplied when known; whether an |
5121 | /// argument is dependent can depend on the conversions performed on it |
5122 | /// (for example, a 'const int' passed as a template argument might be |
5123 | /// dependent if the parameter is a reference but non-dependent if the |
5124 | /// parameter is an int). |
5125 | /// |
5126 | /// Note that the \p Args parameter is unused: this is intentional, to remind |
5127 | /// the caller that they need to pass in the converted arguments, not the |
5128 | /// specified arguments. |
5129 | static bool |
5130 | anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
5131 | ArrayRef<TemplateArgument> Converted); |
5132 | static bool |
5133 | anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
5134 | ArrayRef<TemplateArgument> Converted); |
5135 | static bool anyInstantiationDependentTemplateArguments( |
5136 | ArrayRef<TemplateArgumentLoc> Args); |
5137 | |
5138 | /// True if this template specialization type matches a current |
5139 | /// instantiation in the context in which it is found. |
5140 | bool isCurrentInstantiation() const { |
5141 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
5142 | } |
5143 | |
5144 | /// Determine if this template specialization type is for a type alias |
5145 | /// template that has been substituted. |
5146 | /// |
5147 | /// Nearly every template specialization type whose template is an alias |
5148 | /// template will be substituted. However, this is not the case when |
5149 | /// the specialization contains a pack expansion but the template alias |
5150 | /// does not have a corresponding parameter pack, e.g., |
5151 | /// |
5152 | /// \code |
5153 | /// template<typename T, typename U, typename V> struct S; |
5154 | /// template<typename T, typename U> using A = S<T, int, U>; |
5155 | /// template<typename... Ts> struct X { |
5156 | /// typedef A<Ts...> type; // not a type alias |
5157 | /// }; |
5158 | /// \endcode |
5159 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
5160 | |
5161 | /// Get the aliased type, if this is a specialization of a type alias |
5162 | /// template. |
5163 | QualType getAliasedType() const { |
5164 | assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization" ) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5164, __PRETTY_FUNCTION__)); |
5165 | return *reinterpret_cast<const QualType*>(end()); |
5166 | } |
5167 | |
5168 | using iterator = const TemplateArgument *; |
5169 | |
5170 | iterator begin() const { return getArgs(); } |
5171 | iterator end() const; // defined inline in TemplateBase.h |
5172 | |
5173 | /// Retrieve the name of the template that we are specializing. |
5174 | TemplateName getTemplateName() const { return Template; } |
5175 | |
5176 | /// Retrieve the template arguments. |
5177 | const TemplateArgument *getArgs() const { |
5178 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
5179 | } |
5180 | |
5181 | /// Retrieve the number of template arguments. |
5182 | unsigned getNumArgs() const { |
5183 | return TemplateSpecializationTypeBits.NumArgs; |
5184 | } |
5185 | |
5186 | /// Retrieve a specific template argument as a type. |
5187 | /// \pre \c isArgType(Arg) |
5188 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5189 | |
5190 | ArrayRef<TemplateArgument> template_arguments() const { |
5191 | return {getArgs(), getNumArgs()}; |
5192 | } |
5193 | |
5194 | bool isSugared() const { |
5195 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5196 | } |
5197 | |
5198 | QualType desugar() const { |
5199 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5200 | } |
5201 | |
5202 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5203 | Profile(ID, Template, template_arguments(), Ctx); |
5204 | if (isTypeAlias()) |
5205 | getAliasedType().Profile(ID); |
5206 | } |
5207 | |
5208 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5209 | ArrayRef<TemplateArgument> Args, |
5210 | const ASTContext &Context); |
5211 | |
5212 | static bool classof(const Type *T) { |
5213 | return T->getTypeClass() == TemplateSpecialization; |
5214 | } |
5215 | }; |
5216 | |
5217 | /// Print a template argument list, including the '<' and '>' |
5218 | /// enclosing the template arguments. |
5219 | void printTemplateArgumentList(raw_ostream &OS, |
5220 | ArrayRef<TemplateArgument> Args, |
5221 | const PrintingPolicy &Policy, |
5222 | const TemplateParameterList *TPL = nullptr); |
5223 | |
5224 | void printTemplateArgumentList(raw_ostream &OS, |
5225 | ArrayRef<TemplateArgumentLoc> Args, |
5226 | const PrintingPolicy &Policy, |
5227 | const TemplateParameterList *TPL = nullptr); |
5228 | |
5229 | void printTemplateArgumentList(raw_ostream &OS, |
5230 | const TemplateArgumentListInfo &Args, |
5231 | const PrintingPolicy &Policy, |
5232 | const TemplateParameterList *TPL = nullptr); |
5233 | |
5234 | /// The injected class name of a C++ class template or class |
5235 | /// template partial specialization. Used to record that a type was |
5236 | /// spelled with a bare identifier rather than as a template-id; the |
5237 | /// equivalent for non-templated classes is just RecordType. |
5238 | /// |
5239 | /// Injected class name types are always dependent. Template |
5240 | /// instantiation turns these into RecordTypes. |
5241 | /// |
5242 | /// Injected class name types are always canonical. This works |
5243 | /// because it is impossible to compare an injected class name type |
5244 | /// with the corresponding non-injected template type, for the same |
5245 | /// reason that it is impossible to directly compare template |
5246 | /// parameters from different dependent contexts: injected class name |
5247 | /// types can only occur within the scope of a particular templated |
5248 | /// declaration, and within that scope every template specialization |
5249 | /// will canonicalize to the injected class name (when appropriate |
5250 | /// according to the rules of the language). |
5251 | class InjectedClassNameType : public Type { |
5252 | friend class ASTContext; // ASTContext creates these. |
5253 | friend class ASTNodeImporter; |
5254 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5255 | // currently suitable for AST reading, too much |
5256 | // interdependencies. |
5257 | template <class T> friend class serialization::AbstractTypeReader; |
5258 | |
5259 | CXXRecordDecl *Decl; |
5260 | |
5261 | /// The template specialization which this type represents. |
5262 | /// For example, in |
5263 | /// template <class T> class A { ... }; |
5264 | /// this is A<T>, whereas in |
5265 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5266 | /// this is A<B<X,Y> >. |
5267 | /// |
5268 | /// It is always unqualified, always a template specialization type, |
5269 | /// and always dependent. |
5270 | QualType InjectedType; |
5271 | |
5272 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5273 | : Type(InjectedClassName, QualType(), |
5274 | TypeDependence::DependentInstantiation), |
5275 | Decl(D), InjectedType(TST) { |
5276 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5276, __PRETTY_FUNCTION__)); |
5277 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5277, __PRETTY_FUNCTION__)); |
5278 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5278, __PRETTY_FUNCTION__)); |
5279 | } |
5280 | |
5281 | public: |
5282 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5283 | |
5284 | const TemplateSpecializationType *getInjectedTST() const { |
5285 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5286 | } |
5287 | |
5288 | TemplateName getTemplateName() const { |
5289 | return getInjectedTST()->getTemplateName(); |
5290 | } |
5291 | |
5292 | CXXRecordDecl *getDecl() const; |
5293 | |
5294 | bool isSugared() const { return false; } |
5295 | QualType desugar() const { return QualType(this, 0); } |
5296 | |
5297 | static bool classof(const Type *T) { |
5298 | return T->getTypeClass() == InjectedClassName; |
5299 | } |
5300 | }; |
5301 | |
5302 | /// The kind of a tag type. |
5303 | enum TagTypeKind { |
5304 | /// The "struct" keyword. |
5305 | TTK_Struct, |
5306 | |
5307 | /// The "__interface" keyword. |
5308 | TTK_Interface, |
5309 | |
5310 | /// The "union" keyword. |
5311 | TTK_Union, |
5312 | |
5313 | /// The "class" keyword. |
5314 | TTK_Class, |
5315 | |
5316 | /// The "enum" keyword. |
5317 | TTK_Enum |
5318 | }; |
5319 | |
5320 | /// The elaboration keyword that precedes a qualified type name or |
5321 | /// introduces an elaborated-type-specifier. |
5322 | enum ElaboratedTypeKeyword { |
5323 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5324 | ETK_Struct, |
5325 | |
5326 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5327 | ETK_Interface, |
5328 | |
5329 | /// The "union" keyword introduces the elaborated-type-specifier. |
5330 | ETK_Union, |
5331 | |
5332 | /// The "class" keyword introduces the elaborated-type-specifier. |
5333 | ETK_Class, |
5334 | |
5335 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5336 | ETK_Enum, |
5337 | |
5338 | /// The "typename" keyword precedes the qualified type name, e.g., |
5339 | /// \c typename T::type. |
5340 | ETK_Typename, |
5341 | |
5342 | /// No keyword precedes the qualified type name. |
5343 | ETK_None |
5344 | }; |
5345 | |
5346 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5347 | /// The keyword in stored in the free bits of the base class. |
5348 | /// Also provides a few static helpers for converting and printing |
5349 | /// elaborated type keyword and tag type kind enumerations. |
5350 | class TypeWithKeyword : public Type { |
5351 | protected: |
5352 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5353 | QualType Canonical, TypeDependence Dependence) |
5354 | : Type(tc, Canonical, Dependence) { |
5355 | TypeWithKeywordBits.Keyword = Keyword; |
5356 | } |
5357 | |
5358 | public: |
5359 | ElaboratedTypeKeyword getKeyword() const { |
5360 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5361 | } |
5362 | |
5363 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5364 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5365 | |
5366 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5367 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5368 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5369 | |
5370 | /// Converts a TagTypeKind into an elaborated type keyword. |
5371 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5372 | |
5373 | /// Converts an elaborated type keyword into a TagTypeKind. |
5374 | /// It is an error to provide an elaborated type keyword |
5375 | /// which *isn't* a tag kind here. |
5376 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5377 | |
5378 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5379 | |
5380 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5381 | |
5382 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5383 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5384 | } |
5385 | |
5386 | class CannotCastToThisType {}; |
5387 | static CannotCastToThisType classof(const Type *); |
5388 | }; |
5389 | |
5390 | /// Represents a type that was referred to using an elaborated type |
5391 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5392 | /// or both. |
5393 | /// |
5394 | /// This type is used to keep track of a type name as written in the |
5395 | /// source code, including tag keywords and any nested-name-specifiers. |
5396 | /// The type itself is always "sugar", used to express what was written |
5397 | /// in the source code but containing no additional semantic information. |
5398 | class ElaboratedType final |
5399 | : public TypeWithKeyword, |
5400 | public llvm::FoldingSetNode, |
5401 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5402 | friend class ASTContext; // ASTContext creates these |
5403 | friend TrailingObjects; |
5404 | |
5405 | /// The nested name specifier containing the qualifier. |
5406 | NestedNameSpecifier *NNS; |
5407 | |
5408 | /// The type that this qualified name refers to. |
5409 | QualType NamedType; |
5410 | |
5411 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5412 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5413 | /// it, or obtain a null pointer if there is none. |
5414 | |
5415 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5416 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5417 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5418 | // Any semantic dependence on the qualifier will have |
5419 | // been incorporated into NamedType. We still need to |
5420 | // track syntactic (instantiation / error / pack) |
5421 | // dependence on the qualifier. |
5422 | NamedType->getDependence() | |
5423 | (NNS ? toSyntacticDependence( |
5424 | toTypeDependence(NNS->getDependence())) |
5425 | : TypeDependence::None)), |
5426 | NNS(NNS), NamedType(NamedType) { |
5427 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5428 | if (OwnedTagDecl) { |
5429 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5430 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5431 | } |
5432 | assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5434, __PRETTY_FUNCTION__)) |
5433 | "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5434, __PRETTY_FUNCTION__)) |
5434 | "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5434, __PRETTY_FUNCTION__)); |
5435 | } |
5436 | |
5437 | public: |
5438 | /// Retrieve the qualification on this type. |
5439 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5440 | |
5441 | /// Retrieve the type named by the qualified-id. |
5442 | QualType getNamedType() const { return NamedType; } |
5443 | |
5444 | /// Remove a single level of sugar. |
5445 | QualType desugar() const { return getNamedType(); } |
5446 | |
5447 | /// Returns whether this type directly provides sugar. |
5448 | bool isSugared() const { return true; } |
5449 | |
5450 | /// Return the (re)declaration of this type owned by this occurrence of this |
5451 | /// type, or nullptr if there is none. |
5452 | TagDecl *getOwnedTagDecl() const { |
5453 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5454 | : nullptr; |
5455 | } |
5456 | |
5457 | void Profile(llvm::FoldingSetNodeID &ID) { |
5458 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5459 | } |
5460 | |
5461 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5462 | NestedNameSpecifier *NNS, QualType NamedType, |
5463 | TagDecl *OwnedTagDecl) { |
5464 | ID.AddInteger(Keyword); |
5465 | ID.AddPointer(NNS); |
5466 | NamedType.Profile(ID); |
5467 | ID.AddPointer(OwnedTagDecl); |
5468 | } |
5469 | |
5470 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5471 | }; |
5472 | |
5473 | /// Represents a qualified type name for which the type name is |
5474 | /// dependent. |
5475 | /// |
5476 | /// DependentNameType represents a class of dependent types that involve a |
5477 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5478 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5479 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5480 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5481 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5482 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5483 | /// mode, this type is used with non-dependent names to delay name lookup until |
5484 | /// instantiation. |
5485 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5486 | friend class ASTContext; // ASTContext creates these |
5487 | |
5488 | /// The nested name specifier containing the qualifier. |
5489 | NestedNameSpecifier *NNS; |
5490 | |
5491 | /// The type that this typename specifier refers to. |
5492 | const IdentifierInfo *Name; |
5493 | |
5494 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5495 | const IdentifierInfo *Name, QualType CanonType) |
5496 | : TypeWithKeyword(Keyword, DependentName, CanonType, |
5497 | TypeDependence::DependentInstantiation | |
5498 | toTypeDependence(NNS->getDependence())), |
5499 | NNS(NNS), Name(Name) {} |
5500 | |
5501 | public: |
5502 | /// Retrieve the qualification on this type. |
5503 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5504 | |
5505 | /// Retrieve the type named by the typename specifier as an identifier. |
5506 | /// |
5507 | /// This routine will return a non-NULL identifier pointer when the |
5508 | /// form of the original typename was terminated by an identifier, |
5509 | /// e.g., "typename T::type". |
5510 | const IdentifierInfo *getIdentifier() const { |
5511 | return Name; |
5512 | } |
5513 | |
5514 | bool isSugared() const { return false; } |
5515 | QualType desugar() const { return QualType(this, 0); } |
5516 | |
5517 | void Profile(llvm::FoldingSetNodeID &ID) { |
5518 | Profile(ID, getKeyword(), NNS, Name); |
5519 | } |
5520 | |
5521 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5522 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5523 | ID.AddInteger(Keyword); |
5524 | ID.AddPointer(NNS); |
5525 | ID.AddPointer(Name); |
5526 | } |
5527 | |
5528 | static bool classof(const Type *T) { |
5529 | return T->getTypeClass() == DependentName; |
5530 | } |
5531 | }; |
5532 | |
5533 | /// Represents a template specialization type whose template cannot be |
5534 | /// resolved, e.g. |
5535 | /// A<T>::template B<T> |
5536 | class alignas(8) DependentTemplateSpecializationType |
5537 | : public TypeWithKeyword, |
5538 | public llvm::FoldingSetNode { |
5539 | friend class ASTContext; // ASTContext creates these |
5540 | |
5541 | /// The nested name specifier containing the qualifier. |
5542 | NestedNameSpecifier *NNS; |
5543 | |
5544 | /// The identifier of the template. |
5545 | const IdentifierInfo *Name; |
5546 | |
5547 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5548 | NestedNameSpecifier *NNS, |
5549 | const IdentifierInfo *Name, |
5550 | ArrayRef<TemplateArgument> Args, |
5551 | QualType Canon); |
5552 | |
5553 | const TemplateArgument *getArgBuffer() const { |
5554 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5555 | } |
5556 | |
5557 | TemplateArgument *getArgBuffer() { |
5558 | return reinterpret_cast<TemplateArgument*>(this+1); |
5559 | } |
5560 | |
5561 | public: |
5562 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5563 | const IdentifierInfo *getIdentifier() const { return Name; } |
5564 | |
5565 | /// Retrieve the template arguments. |
5566 | const TemplateArgument *getArgs() const { |
5567 | return getArgBuffer(); |
5568 | } |
5569 | |
5570 | /// Retrieve the number of template arguments. |
5571 | unsigned getNumArgs() const { |
5572 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5573 | } |
5574 | |
5575 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5576 | |
5577 | ArrayRef<TemplateArgument> template_arguments() const { |
5578 | return {getArgs(), getNumArgs()}; |
5579 | } |
5580 | |
5581 | using iterator = const TemplateArgument *; |
5582 | |
5583 | iterator begin() const { return getArgs(); } |
5584 | iterator end() const; // inline in TemplateBase.h |
5585 | |
5586 | bool isSugared() const { return false; } |
5587 | QualType desugar() const { return QualType(this, 0); } |
5588 | |
5589 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5590 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5591 | } |
5592 | |
5593 | static void Profile(llvm::FoldingSetNodeID &ID, |
5594 | const ASTContext &Context, |
5595 | ElaboratedTypeKeyword Keyword, |
5596 | NestedNameSpecifier *Qualifier, |
5597 | const IdentifierInfo *Name, |
5598 | ArrayRef<TemplateArgument> Args); |
5599 | |
5600 | static bool classof(const Type *T) { |
5601 | return T->getTypeClass() == DependentTemplateSpecialization; |
5602 | } |
5603 | }; |
5604 | |
5605 | /// Represents a pack expansion of types. |
5606 | /// |
5607 | /// Pack expansions are part of C++11 variadic templates. A pack |
5608 | /// expansion contains a pattern, which itself contains one or more |
5609 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5610 | /// produces a series of types, each instantiated from the pattern of |
5611 | /// the expansion, where the Ith instantiation of the pattern uses the |
5612 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5613 | /// pack expansion is considered to "expand" these unexpanded |
5614 | /// parameter packs. |
5615 | /// |
5616 | /// \code |
5617 | /// template<typename ...Types> struct tuple; |
5618 | /// |
5619 | /// template<typename ...Types> |
5620 | /// struct tuple_of_references { |
5621 | /// typedef tuple<Types&...> type; |
5622 | /// }; |
5623 | /// \endcode |
5624 | /// |
5625 | /// Here, the pack expansion \c Types&... is represented via a |
5626 | /// PackExpansionType whose pattern is Types&. |
5627 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5628 | friend class ASTContext; // ASTContext creates these |
5629 | |
5630 | /// The pattern of the pack expansion. |
5631 | QualType Pattern; |
5632 | |
5633 | PackExpansionType(QualType Pattern, QualType Canon, |
5634 | Optional<unsigned> NumExpansions) |
5635 | : Type(PackExpansion, Canon, |
5636 | (Pattern->getDependence() | TypeDependence::Dependent | |
5637 | TypeDependence::Instantiation) & |
5638 | ~TypeDependence::UnexpandedPack), |
5639 | Pattern(Pattern) { |
5640 | PackExpansionTypeBits.NumExpansions = |
5641 | NumExpansions ? *NumExpansions + 1 : 0; |
5642 | } |
5643 | |
5644 | public: |
5645 | /// Retrieve the pattern of this pack expansion, which is the |
5646 | /// type that will be repeatedly instantiated when instantiating the |
5647 | /// pack expansion itself. |
5648 | QualType getPattern() const { return Pattern; } |
5649 | |
5650 | /// Retrieve the number of expansions that this pack expansion will |
5651 | /// generate, if known. |
5652 | Optional<unsigned> getNumExpansions() const { |
5653 | if (PackExpansionTypeBits.NumExpansions) |
5654 | return PackExpansionTypeBits.NumExpansions - 1; |
5655 | return None; |
5656 | } |
5657 | |
5658 | bool isSugared() const { return false; } |
5659 | QualType desugar() const { return QualType(this, 0); } |
5660 | |
5661 | void Profile(llvm::FoldingSetNodeID &ID) { |
5662 | Profile(ID, getPattern(), getNumExpansions()); |
5663 | } |
5664 | |
5665 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5666 | Optional<unsigned> NumExpansions) { |
5667 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5668 | ID.AddBoolean(NumExpansions.hasValue()); |
5669 | if (NumExpansions) |
5670 | ID.AddInteger(*NumExpansions); |
5671 | } |
5672 | |
5673 | static bool classof(const Type *T) { |
5674 | return T->getTypeClass() == PackExpansion; |
5675 | } |
5676 | }; |
5677 | |
5678 | /// This class wraps the list of protocol qualifiers. For types that can |
5679 | /// take ObjC protocol qualifers, they can subclass this class. |
5680 | template <class T> |
5681 | class ObjCProtocolQualifiers { |
5682 | protected: |
5683 | ObjCProtocolQualifiers() = default; |
5684 | |
5685 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5686 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5687 | } |
5688 | |
5689 | ObjCProtocolDecl **getProtocolStorage() { |
5690 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5691 | } |
5692 | |
5693 | void setNumProtocols(unsigned N) { |
5694 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5695 | } |
5696 | |
5697 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5698 | setNumProtocols(protocols.size()); |
5699 | assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5700, __PRETTY_FUNCTION__)) |
5700 | "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5700, __PRETTY_FUNCTION__)); |
5701 | if (!protocols.empty()) |
5702 | memcpy(getProtocolStorage(), protocols.data(), |
5703 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5704 | } |
5705 | |
5706 | public: |
5707 | using qual_iterator = ObjCProtocolDecl * const *; |
5708 | using qual_range = llvm::iterator_range<qual_iterator>; |
5709 | |
5710 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5711 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5712 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5713 | |
5714 | bool qual_empty() const { return getNumProtocols() == 0; } |
5715 | |
5716 | /// Return the number of qualifying protocols in this type, or 0 if |
5717 | /// there are none. |
5718 | unsigned getNumProtocols() const { |
5719 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5720 | } |
5721 | |
5722 | /// Fetch a protocol by index. |
5723 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5724 | assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access" ) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5724, __PRETTY_FUNCTION__)); |
5725 | return qual_begin()[I]; |
5726 | } |
5727 | |
5728 | /// Retrieve all of the protocol qualifiers. |
5729 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5730 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5731 | } |
5732 | }; |
5733 | |
5734 | /// Represents a type parameter type in Objective C. It can take |
5735 | /// a list of protocols. |
5736 | class ObjCTypeParamType : public Type, |
5737 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5738 | public llvm::FoldingSetNode { |
5739 | friend class ASTContext; |
5740 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5741 | |
5742 | /// The number of protocols stored on this type. |
5743 | unsigned NumProtocols : 6; |
5744 | |
5745 | ObjCTypeParamDecl *OTPDecl; |
5746 | |
5747 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5748 | /// canonical type, the list of protocols are sorted alphabetically |
5749 | /// and uniqued. |
5750 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5751 | |
5752 | /// Return the number of qualifying protocols in this interface type, |
5753 | /// or 0 if there are none. |
5754 | unsigned getNumProtocolsImpl() const { |
5755 | return NumProtocols; |
5756 | } |
5757 | |
5758 | void setNumProtocolsImpl(unsigned N) { |
5759 | NumProtocols = N; |
5760 | } |
5761 | |
5762 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5763 | QualType can, |
5764 | ArrayRef<ObjCProtocolDecl *> protocols); |
5765 | |
5766 | public: |
5767 | bool isSugared() const { return true; } |
5768 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5769 | |
5770 | static bool classof(const Type *T) { |
5771 | return T->getTypeClass() == ObjCTypeParam; |
5772 | } |
5773 | |
5774 | void Profile(llvm::FoldingSetNodeID &ID); |
5775 | static void Profile(llvm::FoldingSetNodeID &ID, |
5776 | const ObjCTypeParamDecl *OTPDecl, |
5777 | QualType CanonicalType, |
5778 | ArrayRef<ObjCProtocolDecl *> protocols); |
5779 | |
5780 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5781 | }; |
5782 | |
5783 | /// Represents a class type in Objective C. |
5784 | /// |
5785 | /// Every Objective C type is a combination of a base type, a set of |
5786 | /// type arguments (optional, for parameterized classes) and a list of |
5787 | /// protocols. |
5788 | /// |
5789 | /// Given the following declarations: |
5790 | /// \code |
5791 | /// \@class C<T>; |
5792 | /// \@protocol P; |
5793 | /// \endcode |
5794 | /// |
5795 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5796 | /// with base C and no protocols. |
5797 | /// |
5798 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5799 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5800 | /// protocol list. |
5801 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5802 | /// and protocol list [P]. |
5803 | /// |
5804 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5805 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5806 | /// and no protocols. |
5807 | /// |
5808 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5809 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5810 | /// this should get its own sugar class to better represent the source. |
5811 | class ObjCObjectType : public Type, |
5812 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5813 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5814 | |
5815 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5816 | // after the ObjCObjectPointerType node. |
5817 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5818 | // after the type arguments of ObjCObjectPointerType node. |
5819 | // |
5820 | // These protocols are those written directly on the type. If |
5821 | // protocol qualifiers ever become additive, the iterators will need |
5822 | // to get kindof complicated. |
5823 | // |
5824 | // In the canonical object type, these are sorted alphabetically |
5825 | // and uniqued. |
5826 | |
5827 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5828 | QualType BaseType; |
5829 | |
5830 | /// Cached superclass type. |
5831 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5832 | CachedSuperClassType; |
5833 | |
5834 | QualType *getTypeArgStorage(); |
5835 | const QualType *getTypeArgStorage() const { |
5836 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5837 | } |
5838 | |
5839 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5840 | /// Return the number of qualifying protocols in this interface type, |
5841 | /// or 0 if there are none. |
5842 | unsigned getNumProtocolsImpl() const { |
5843 | return ObjCObjectTypeBits.NumProtocols; |
5844 | } |
5845 | void setNumProtocolsImpl(unsigned N) { |
5846 | ObjCObjectTypeBits.NumProtocols = N; |
5847 | } |
5848 | |
5849 | protected: |
5850 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5851 | |
5852 | ObjCObjectType(QualType Canonical, QualType Base, |
5853 | ArrayRef<QualType> typeArgs, |
5854 | ArrayRef<ObjCProtocolDecl *> protocols, |
5855 | bool isKindOf); |
5856 | |
5857 | ObjCObjectType(enum Nonce_ObjCInterface) |
5858 | : Type(ObjCInterface, QualType(), TypeDependence::None), |
5859 | BaseType(QualType(this_(), 0)) { |
5860 | ObjCObjectTypeBits.NumProtocols = 0; |
5861 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5862 | ObjCObjectTypeBits.IsKindOf = 0; |
5863 | } |
5864 | |
5865 | void computeSuperClassTypeSlow() const; |
5866 | |
5867 | public: |
5868 | /// Gets the base type of this object type. This is always (possibly |
5869 | /// sugar for) one of: |
5870 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5871 | /// user, which is a typedef for an ObjCObjectPointerType) |
5872 | /// - the 'Class' builtin type (same caveat) |
5873 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5874 | QualType getBaseType() const { return BaseType; } |
5875 | |
5876 | bool isObjCId() const { |
5877 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5878 | } |
5879 | |
5880 | bool isObjCClass() const { |
5881 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5882 | } |
5883 | |
5884 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5885 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5886 | bool isObjCUnqualifiedIdOrClass() const { |
5887 | if (!qual_empty()) return false; |
5888 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5889 | return T->getKind() == BuiltinType::ObjCId || |
5890 | T->getKind() == BuiltinType::ObjCClass; |
5891 | return false; |
5892 | } |
5893 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5894 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5895 | |
5896 | /// Gets the interface declaration for this object type, if the base type |
5897 | /// really is an interface. |
5898 | ObjCInterfaceDecl *getInterface() const; |
5899 | |
5900 | /// Determine whether this object type is "specialized", meaning |
5901 | /// that it has type arguments. |
5902 | bool isSpecialized() const; |
5903 | |
5904 | /// Determine whether this object type was written with type arguments. |
5905 | bool isSpecializedAsWritten() const { |
5906 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5907 | } |
5908 | |
5909 | /// Determine whether this object type is "unspecialized", meaning |
5910 | /// that it has no type arguments. |
5911 | bool isUnspecialized() const { return !isSpecialized(); } |
5912 | |
5913 | /// Determine whether this object type is "unspecialized" as |
5914 | /// written, meaning that it has no type arguments. |
5915 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5916 | |
5917 | /// Retrieve the type arguments of this object type (semantically). |
5918 | ArrayRef<QualType> getTypeArgs() const; |
5919 | |
5920 | /// Retrieve the type arguments of this object type as they were |
5921 | /// written. |
5922 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5923 | return llvm::makeArrayRef(getTypeArgStorage(), |
5924 | ObjCObjectTypeBits.NumTypeArgs); |
5925 | } |
5926 | |
5927 | /// Whether this is a "__kindof" type as written. |
5928 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5929 | |
5930 | /// Whether this ia a "__kindof" type (semantically). |
5931 | bool isKindOfType() const; |
5932 | |
5933 | /// Retrieve the type of the superclass of this object type. |
5934 | /// |
5935 | /// This operation substitutes any type arguments into the |
5936 | /// superclass of the current class type, potentially producing a |
5937 | /// specialization of the superclass type. Produces a null type if |
5938 | /// there is no superclass. |
5939 | QualType getSuperClassType() const { |
5940 | if (!CachedSuperClassType.getInt()) |
5941 | computeSuperClassTypeSlow(); |
5942 | |
5943 | assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?" ) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 5943, __PRETTY_FUNCTION__)); |
5944 | return QualType(CachedSuperClassType.getPointer(), 0); |
5945 | } |
5946 | |
5947 | /// Strip off the Objective-C "kindof" type and (with it) any |
5948 | /// protocol qualifiers. |
5949 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5950 | |
5951 | bool isSugared() const { return false; } |
5952 | QualType desugar() const { return QualType(this, 0); } |
5953 | |
5954 | static bool classof(const Type *T) { |
5955 | return T->getTypeClass() == ObjCObject || |
5956 | T->getTypeClass() == ObjCInterface; |
5957 | } |
5958 | }; |
5959 | |
5960 | /// A class providing a concrete implementation |
5961 | /// of ObjCObjectType, so as to not increase the footprint of |
5962 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5963 | /// system should not reference this type. |
5964 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5965 | friend class ASTContext; |
5966 | |
5967 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5968 | // will need to be modified. |
5969 | |
5970 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5971 | ArrayRef<QualType> typeArgs, |
5972 | ArrayRef<ObjCProtocolDecl *> protocols, |
5973 | bool isKindOf) |
5974 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5975 | |
5976 | public: |
5977 | void Profile(llvm::FoldingSetNodeID &ID); |
5978 | static void Profile(llvm::FoldingSetNodeID &ID, |
5979 | QualType Base, |
5980 | ArrayRef<QualType> typeArgs, |
5981 | ArrayRef<ObjCProtocolDecl *> protocols, |
5982 | bool isKindOf); |
5983 | }; |
5984 | |
5985 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5986 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5987 | } |
5988 | |
5989 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5990 | return reinterpret_cast<ObjCProtocolDecl**>( |
5991 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5992 | } |
5993 | |
5994 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5995 | return reinterpret_cast<ObjCProtocolDecl**>( |
5996 | static_cast<ObjCTypeParamType*>(this)+1); |
5997 | } |
5998 | |
5999 | /// Interfaces are the core concept in Objective-C for object oriented design. |
6000 | /// They basically correspond to C++ classes. There are two kinds of interface |
6001 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
6002 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
6003 | /// |
6004 | /// ObjCInterfaceType guarantees the following properties when considered |
6005 | /// as a subtype of its superclass, ObjCObjectType: |
6006 | /// - There are no protocol qualifiers. To reinforce this, code which |
6007 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
6008 | /// fail to compile. |
6009 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
6010 | /// T->getBaseType() == QualType(T, 0). |
6011 | class ObjCInterfaceType : public ObjCObjectType { |
6012 | friend class ASTContext; // ASTContext creates these. |
6013 | friend class ASTReader; |
6014 | friend class ObjCInterfaceDecl; |
6015 | template <class T> friend class serialization::AbstractTypeReader; |
6016 | |
6017 | mutable ObjCInterfaceDecl *Decl; |
6018 | |
6019 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
6020 | : ObjCObjectType(Nonce_ObjCInterface), |
6021 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
6022 | |
6023 | public: |
6024 | /// Get the declaration of this interface. |
6025 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
6026 | |
6027 | bool isSugared() const { return false; } |
6028 | QualType desugar() const { return QualType(this, 0); } |
6029 | |
6030 | static bool classof(const Type *T) { |
6031 | return T->getTypeClass() == ObjCInterface; |
6032 | } |
6033 | |
6034 | // Nonsense to "hide" certain members of ObjCObjectType within this |
6035 | // class. People asking for protocols on an ObjCInterfaceType are |
6036 | // not going to get what they want: ObjCInterfaceTypes are |
6037 | // guaranteed to have no protocols. |
6038 | enum { |
6039 | qual_iterator, |
6040 | qual_begin, |
6041 | qual_end, |
6042 | getNumProtocols, |
6043 | getProtocol |
6044 | }; |
6045 | }; |
6046 | |
6047 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
6048 | QualType baseType = getBaseType(); |
6049 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
6050 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
6051 | return T->getDecl(); |
6052 | |
6053 | baseType = ObjT->getBaseType(); |
6054 | } |
6055 | |
6056 | return nullptr; |
6057 | } |
6058 | |
6059 | /// Represents a pointer to an Objective C object. |
6060 | /// |
6061 | /// These are constructed from pointer declarators when the pointee type is |
6062 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
6063 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
6064 | /// and 'Class<P>' are translated into these. |
6065 | /// |
6066 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
6067 | /// only the first level of pointer gets it own type implementation. |
6068 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
6069 | friend class ASTContext; // ASTContext creates these. |
6070 | |
6071 | QualType PointeeType; |
6072 | |
6073 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
6074 | : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()), |
6075 | PointeeType(Pointee) {} |
6076 | |
6077 | public: |
6078 | /// Gets the type pointed to by this ObjC pointer. |
6079 | /// The result will always be an ObjCObjectType or sugar thereof. |
6080 | QualType getPointeeType() const { return PointeeType; } |
6081 | |
6082 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
6083 | /// |
6084 | /// This method is equivalent to getPointeeType() except that |
6085 | /// it discards any typedefs (or other sugar) between this |
6086 | /// type and the "outermost" object type. So for: |
6087 | /// \code |
6088 | /// \@class A; \@protocol P; \@protocol Q; |
6089 | /// typedef A<P> AP; |
6090 | /// typedef A A1; |
6091 | /// typedef A1<P> A1P; |
6092 | /// typedef A1P<Q> A1PQ; |
6093 | /// \endcode |
6094 | /// For 'A*', getObjectType() will return 'A'. |
6095 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
6096 | /// For 'AP*', getObjectType() will return 'A<P>'. |
6097 | /// For 'A1*', getObjectType() will return 'A'. |
6098 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
6099 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
6100 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
6101 | /// adding protocols to a protocol-qualified base discards the |
6102 | /// old qualifiers (for now). But if it didn't, getObjectType() |
6103 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
6104 | /// qualifiers more complicated). |
6105 | const ObjCObjectType *getObjectType() const { |
6106 | return PointeeType->castAs<ObjCObjectType>(); |
6107 | } |
6108 | |
6109 | /// If this pointer points to an Objective C |
6110 | /// \@interface type, gets the type for that interface. Any protocol |
6111 | /// qualifiers on the interface are ignored. |
6112 | /// |
6113 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6114 | const ObjCInterfaceType *getInterfaceType() const; |
6115 | |
6116 | /// If this pointer points to an Objective \@interface |
6117 | /// type, gets the declaration for that interface. |
6118 | /// |
6119 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6120 | ObjCInterfaceDecl *getInterfaceDecl() const { |
6121 | return getObjectType()->getInterface(); |
6122 | } |
6123 | |
6124 | /// True if this is equivalent to the 'id' type, i.e. if |
6125 | /// its object type is the primitive 'id' type with no protocols. |
6126 | bool isObjCIdType() const { |
6127 | return getObjectType()->isObjCUnqualifiedId(); |
6128 | } |
6129 | |
6130 | /// True if this is equivalent to the 'Class' type, |
6131 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
6132 | bool isObjCClassType() const { |
6133 | return getObjectType()->isObjCUnqualifiedClass(); |
6134 | } |
6135 | |
6136 | /// True if this is equivalent to the 'id' or 'Class' type, |
6137 | bool isObjCIdOrClassType() const { |
6138 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
6139 | } |
6140 | |
6141 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
6142 | /// protocols. |
6143 | bool isObjCQualifiedIdType() const { |
6144 | return getObjectType()->isObjCQualifiedId(); |
6145 | } |
6146 | |
6147 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
6148 | /// protocols. |
6149 | bool isObjCQualifiedClassType() const { |
6150 | return getObjectType()->isObjCQualifiedClass(); |
6151 | } |
6152 | |
6153 | /// Whether this is a "__kindof" type. |
6154 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
6155 | |
6156 | /// Whether this type is specialized, meaning that it has type arguments. |
6157 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
6158 | |
6159 | /// Whether this type is specialized, meaning that it has type arguments. |
6160 | bool isSpecializedAsWritten() const { |
6161 | return getObjectType()->isSpecializedAsWritten(); |
6162 | } |
6163 | |
6164 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
6165 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
6166 | |
6167 | /// Determine whether this object type is "unspecialized" as |
6168 | /// written, meaning that it has no type arguments. |
6169 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
6170 | |
6171 | /// Retrieve the type arguments for this type. |
6172 | ArrayRef<QualType> getTypeArgs() const { |
6173 | return getObjectType()->getTypeArgs(); |
6174 | } |
6175 | |
6176 | /// Retrieve the type arguments for this type. |
6177 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
6178 | return getObjectType()->getTypeArgsAsWritten(); |
6179 | } |
6180 | |
6181 | /// An iterator over the qualifiers on the object type. Provided |
6182 | /// for convenience. This will always iterate over the full set of |
6183 | /// protocols on a type, not just those provided directly. |
6184 | using qual_iterator = ObjCObjectType::qual_iterator; |
6185 | using qual_range = llvm::iterator_range<qual_iterator>; |
6186 | |
6187 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
6188 | |
6189 | qual_iterator qual_begin() const { |
6190 | return getObjectType()->qual_begin(); |
6191 | } |
6192 | |
6193 | qual_iterator qual_end() const { |
6194 | return getObjectType()->qual_end(); |
6195 | } |
6196 | |
6197 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6198 | |
6199 | /// Return the number of qualifying protocols on the object type. |
6200 | unsigned getNumProtocols() const { |
6201 | return getObjectType()->getNumProtocols(); |
6202 | } |
6203 | |
6204 | /// Retrieve a qualifying protocol by index on the object type. |
6205 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6206 | return getObjectType()->getProtocol(I); |
6207 | } |
6208 | |
6209 | bool isSugared() const { return false; } |
6210 | QualType desugar() const { return QualType(this, 0); } |
6211 | |
6212 | /// Retrieve the type of the superclass of this object pointer type. |
6213 | /// |
6214 | /// This operation substitutes any type arguments into the |
6215 | /// superclass of the current class type, potentially producing a |
6216 | /// pointer to a specialization of the superclass type. Produces a |
6217 | /// null type if there is no superclass. |
6218 | QualType getSuperClassType() const; |
6219 | |
6220 | /// Strip off the Objective-C "kindof" type and (with it) any |
6221 | /// protocol qualifiers. |
6222 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6223 | const ASTContext &ctx) const; |
6224 | |
6225 | void Profile(llvm::FoldingSetNodeID &ID) { |
6226 | Profile(ID, getPointeeType()); |
6227 | } |
6228 | |
6229 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6230 | ID.AddPointer(T.getAsOpaquePtr()); |
6231 | } |
6232 | |
6233 | static bool classof(const Type *T) { |
6234 | return T->getTypeClass() == ObjCObjectPointer; |
6235 | } |
6236 | }; |
6237 | |
6238 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6239 | friend class ASTContext; // ASTContext creates these. |
6240 | |
6241 | QualType ValueType; |
6242 | |
6243 | AtomicType(QualType ValTy, QualType Canonical) |
6244 | : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {} |
6245 | |
6246 | public: |
6247 | /// Gets the type contained by this atomic type, i.e. |
6248 | /// the type returned by performing an atomic load of this atomic type. |
6249 | QualType getValueType() const { return ValueType; } |
6250 | |
6251 | bool isSugared() const { return false; } |
6252 | QualType desugar() const { return QualType(this, 0); } |
6253 | |
6254 | void Profile(llvm::FoldingSetNodeID &ID) { |
6255 | Profile(ID, getValueType()); |
6256 | } |
6257 | |
6258 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6259 | ID.AddPointer(T.getAsOpaquePtr()); |
6260 | } |
6261 | |
6262 | static bool classof(const Type *T) { |
6263 | return T->getTypeClass() == Atomic; |
6264 | } |
6265 | }; |
6266 | |
6267 | /// PipeType - OpenCL20. |
6268 | class PipeType : public Type, public llvm::FoldingSetNode { |
6269 | friend class ASTContext; // ASTContext creates these. |
6270 | |
6271 | QualType ElementType; |
6272 | bool isRead; |
6273 | |
6274 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6275 | : Type(Pipe, CanonicalPtr, elemType->getDependence()), |
6276 | ElementType(elemType), isRead(isRead) {} |
6277 | |
6278 | public: |
6279 | QualType getElementType() const { return ElementType; } |
6280 | |
6281 | bool isSugared() const { return false; } |
6282 | |
6283 | QualType desugar() const { return QualType(this, 0); } |
6284 | |
6285 | void Profile(llvm::FoldingSetNodeID &ID) { |
6286 | Profile(ID, getElementType(), isReadOnly()); |
6287 | } |
6288 | |
6289 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6290 | ID.AddPointer(T.getAsOpaquePtr()); |
6291 | ID.AddBoolean(isRead); |
6292 | } |
6293 | |
6294 | static bool classof(const Type *T) { |
6295 | return T->getTypeClass() == Pipe; |
6296 | } |
6297 | |
6298 | bool isReadOnly() const { return isRead; } |
6299 | }; |
6300 | |
6301 | /// A fixed int type of a specified bitwidth. |
6302 | class ExtIntType final : public Type, public llvm::FoldingSetNode { |
6303 | friend class ASTContext; |
6304 | unsigned IsUnsigned : 1; |
6305 | unsigned NumBits : 24; |
6306 | |
6307 | protected: |
6308 | ExtIntType(bool isUnsigned, unsigned NumBits); |
6309 | |
6310 | public: |
6311 | bool isUnsigned() const { return IsUnsigned; } |
6312 | bool isSigned() const { return !IsUnsigned; } |
6313 | unsigned getNumBits() const { return NumBits; } |
6314 | |
6315 | bool isSugared() const { return false; } |
6316 | QualType desugar() const { return QualType(this, 0); } |
6317 | |
6318 | void Profile(llvm::FoldingSetNodeID &ID) { |
6319 | Profile(ID, isUnsigned(), getNumBits()); |
6320 | } |
6321 | |
6322 | static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned, |
6323 | unsigned NumBits) { |
6324 | ID.AddBoolean(IsUnsigned); |
6325 | ID.AddInteger(NumBits); |
6326 | } |
6327 | |
6328 | static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; } |
6329 | }; |
6330 | |
6331 | class DependentExtIntType final : public Type, public llvm::FoldingSetNode { |
6332 | friend class ASTContext; |
6333 | const ASTContext &Context; |
6334 | llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned; |
6335 | |
6336 | protected: |
6337 | DependentExtIntType(const ASTContext &Context, bool IsUnsigned, |
6338 | Expr *NumBits); |
6339 | |
6340 | public: |
6341 | bool isUnsigned() const; |
6342 | bool isSigned() const { return !isUnsigned(); } |
6343 | Expr *getNumBitsExpr() const; |
6344 | |
6345 | bool isSugared() const { return false; } |
6346 | QualType desugar() const { return QualType(this, 0); } |
6347 | |
6348 | void Profile(llvm::FoldingSetNodeID &ID) { |
6349 | Profile(ID, Context, isUnsigned(), getNumBitsExpr()); |
6350 | } |
6351 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
6352 | bool IsUnsigned, Expr *NumBitsExpr); |
6353 | |
6354 | static bool classof(const Type *T) { |
6355 | return T->getTypeClass() == DependentExtInt; |
6356 | } |
6357 | }; |
6358 | |
6359 | /// A qualifier set is used to build a set of qualifiers. |
6360 | class QualifierCollector : public Qualifiers { |
6361 | public: |
6362 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6363 | |
6364 | /// Collect any qualifiers on the given type and return an |
6365 | /// unqualified type. The qualifiers are assumed to be consistent |
6366 | /// with those already in the type. |
6367 | const Type *strip(QualType type) { |
6368 | addFastQualifiers(type.getLocalFastQualifiers()); |
6369 | if (!type.hasLocalNonFastQualifiers()) |
6370 | return type.getTypePtrUnsafe(); |
6371 | |
6372 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6373 | addConsistentQualifiers(extQuals->getQualifiers()); |
6374 | return extQuals->getBaseType(); |
6375 | } |
6376 | |
6377 | /// Apply the collected qualifiers to the given type. |
6378 | QualType apply(const ASTContext &Context, QualType QT) const; |
6379 | |
6380 | /// Apply the collected qualifiers to the given type. |
6381 | QualType apply(const ASTContext &Context, const Type* T) const; |
6382 | }; |
6383 | |
6384 | /// A container of type source information. |
6385 | /// |
6386 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
6387 | /// @code |
6388 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
6389 | /// TL.getBeginLoc().print(OS, SrcMgr); |
6390 | /// @endcode |
6391 | class alignas(8) TypeSourceInfo { |
6392 | // Contains a memory block after the class, used for type source information, |
6393 | // allocated by ASTContext. |
6394 | friend class ASTContext; |
6395 | |
6396 | QualType Ty; |
6397 | |
6398 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
6399 | |
6400 | public: |
6401 | /// Return the type wrapped by this type source info. |
6402 | QualType getType() const { return Ty; } |
6403 | |
6404 | /// Return the TypeLoc wrapper for the type source info. |
6405 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
6406 | |
6407 | /// Override the type stored in this TypeSourceInfo. Use with caution! |
6408 | void overrideType(QualType T) { Ty = T; } |
6409 | }; |
6410 | |
6411 | // Inline function definitions. |
6412 | |
6413 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6414 | SplitQualType desugar = |
6415 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6416 | desugar.Quals.addConsistentQualifiers(Quals); |
6417 | return desugar; |
6418 | } |
6419 | |
6420 | inline const Type *QualType::getTypePtr() const { |
6421 | return getCommonPtr()->BaseType; |
6422 | } |
6423 | |
6424 | inline const Type *QualType::getTypePtrOrNull() const { |
6425 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6426 | } |
6427 | |
6428 | inline SplitQualType QualType::split() const { |
6429 | if (!hasLocalNonFastQualifiers()) |
6430 | return SplitQualType(getTypePtrUnsafe(), |
6431 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6432 | |
6433 | const ExtQuals *eq = getExtQualsUnsafe(); |
6434 | Qualifiers qs = eq->getQualifiers(); |
6435 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6436 | return SplitQualType(eq->getBaseType(), qs); |
6437 | } |
6438 | |
6439 | inline Qualifiers QualType::getLocalQualifiers() const { |
6440 | Qualifiers Quals; |
6441 | if (hasLocalNonFastQualifiers()) |
6442 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6443 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6444 | return Quals; |
6445 | } |
6446 | |
6447 | inline Qualifiers QualType::getQualifiers() const { |
6448 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6449 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6450 | return quals; |
6451 | } |
6452 | |
6453 | inline unsigned QualType::getCVRQualifiers() const { |
6454 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6455 | cvr |= getLocalCVRQualifiers(); |
6456 | return cvr; |
6457 | } |
6458 | |
6459 | inline QualType QualType::getCanonicalType() const { |
6460 | QualType canon = getCommonPtr()->CanonicalType; |
6461 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6462 | } |
6463 | |
6464 | inline bool QualType::isCanonical() const { |
6465 | return getTypePtr()->isCanonicalUnqualified(); |
6466 | } |
6467 | |
6468 | inline bool QualType::isCanonicalAsParam() const { |
6469 | if (!isCanonical()) return false; |
6470 | if (hasLocalQualifiers()) return false; |
6471 | |
6472 | const Type *T = getTypePtr(); |
6473 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6474 | return false; |
6475 | |
6476 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6477 | } |
6478 | |
6479 | inline bool QualType::isConstQualified() const { |
6480 | return isLocalConstQualified() || |
6481 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6482 | } |
6483 | |
6484 | inline bool QualType::isRestrictQualified() const { |
6485 | return isLocalRestrictQualified() || |
6486 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6487 | } |
6488 | |
6489 | |
6490 | inline bool QualType::isVolatileQualified() const { |
6491 | return isLocalVolatileQualified() || |
6492 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6493 | } |
6494 | |
6495 | inline bool QualType::hasQualifiers() const { |
6496 | return hasLocalQualifiers() || |
6497 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6498 | } |
6499 | |
6500 | inline QualType QualType::getUnqualifiedType() const { |
6501 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6502 | return QualType(getTypePtr(), 0); |
6503 | |
6504 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6505 | } |
6506 | |
6507 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6508 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6509 | return split(); |
6510 | |
6511 | return getSplitUnqualifiedTypeImpl(*this); |
6512 | } |
6513 | |
6514 | inline void QualType::removeLocalConst() { |
6515 | removeLocalFastQualifiers(Qualifiers::Const); |
6516 | } |
6517 | |
6518 | inline void QualType::removeLocalRestrict() { |
6519 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6520 | } |
6521 | |
6522 | inline void QualType::removeLocalVolatile() { |
6523 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6524 | } |
6525 | |
6526 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6527 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 6527, __PRETTY_FUNCTION__)); |
6528 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6529 | "Fast bits differ from CVR bits!"); |
6530 | |
6531 | // Fast path: we don't need to touch the slow qualifiers. |
6532 | removeLocalFastQualifiers(Mask); |
6533 | } |
6534 | |
6535 | /// Check if this type has any address space qualifier. |
6536 | inline bool QualType::hasAddressSpace() const { |
6537 | return getQualifiers().hasAddressSpace(); |
6538 | } |
6539 | |
6540 | /// Return the address space of this type. |
6541 | inline LangAS QualType::getAddressSpace() const { |
6542 | return getQualifiers().getAddressSpace(); |
6543 | } |
6544 | |
6545 | /// Return the gc attribute of this type. |
6546 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6547 | return getQualifiers().getObjCGCAttr(); |
6548 | } |
6549 | |
6550 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6551 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6552 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6553 | return false; |
6554 | } |
6555 | |
6556 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6557 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6558 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6559 | return false; |
6560 | } |
6561 | |
6562 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6563 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6564 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6565 | return false; |
6566 | } |
6567 | |
6568 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6569 | if (const auto *PT = t.getAs<PointerType>()) { |
6570 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6571 | return FT->getExtInfo(); |
6572 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6573 | return FT->getExtInfo(); |
6574 | |
6575 | return FunctionType::ExtInfo(); |
6576 | } |
6577 | |
6578 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6579 | return getFunctionExtInfo(*t); |
6580 | } |
6581 | |
6582 | /// Determine whether this type is more |
6583 | /// qualified than the Other type. For example, "const volatile int" |
6584 | /// is more qualified than "const int", "volatile int", and |
6585 | /// "int". However, it is not more qualified than "const volatile |
6586 | /// int". |
6587 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6588 | Qualifiers MyQuals = getQualifiers(); |
6589 | Qualifiers OtherQuals = other.getQualifiers(); |
6590 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6591 | } |
6592 | |
6593 | /// Determine whether this type is at last |
6594 | /// as qualified as the Other type. For example, "const volatile |
6595 | /// int" is at least as qualified as "const int", "volatile int", |
6596 | /// "int", and "const volatile int". |
6597 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6598 | Qualifiers OtherQuals = other.getQualifiers(); |
6599 | |
6600 | // Ignore __unaligned qualifier if this type is a void. |
6601 | if (getUnqualifiedType()->isVoidType()) |
6602 | OtherQuals.removeUnaligned(); |
6603 | |
6604 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6605 | } |
6606 | |
6607 | /// If Type is a reference type (e.g., const |
6608 | /// int&), returns the type that the reference refers to ("const |
6609 | /// int"). Otherwise, returns the type itself. This routine is used |
6610 | /// throughout Sema to implement C++ 5p6: |
6611 | /// |
6612 | /// If an expression initially has the type "reference to T" (8.3.2, |
6613 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6614 | /// analysis, the expression designates the object or function |
6615 | /// denoted by the reference, and the expression is an lvalue. |
6616 | inline QualType QualType::getNonReferenceType() const { |
6617 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6618 | return RefType->getPointeeType(); |
6619 | else |
6620 | return *this; |
6621 | } |
6622 | |
6623 | inline bool QualType::isCForbiddenLValueType() const { |
6624 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6625 | getTypePtr()->isFunctionType()); |
6626 | } |
6627 | |
6628 | /// Tests whether the type is categorized as a fundamental type. |
6629 | /// |
6630 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6631 | inline bool Type::isFundamentalType() const { |
6632 | return isVoidType() || |
6633 | isNullPtrType() || |
6634 | // FIXME: It's really annoying that we don't have an |
6635 | // 'isArithmeticType()' which agrees with the standard definition. |
6636 | (isArithmeticType() && !isEnumeralType()); |
6637 | } |
6638 | |
6639 | /// Tests whether the type is categorized as a compound type. |
6640 | /// |
6641 | /// \returns True for types specified in C++0x [basic.compound]. |
6642 | inline bool Type::isCompoundType() const { |
6643 | // C++0x [basic.compound]p1: |
6644 | // Compound types can be constructed in the following ways: |
6645 | // -- arrays of objects of a given type [...]; |
6646 | return isArrayType() || |
6647 | // -- functions, which have parameters of given types [...]; |
6648 | isFunctionType() || |
6649 | // -- pointers to void or objects or functions [...]; |
6650 | isPointerType() || |
6651 | // -- references to objects or functions of a given type. [...] |
6652 | isReferenceType() || |
6653 | // -- classes containing a sequence of objects of various types, [...]; |
6654 | isRecordType() || |
6655 | // -- unions, which are classes capable of containing objects of different |
6656 | // types at different times; |
6657 | isUnionType() || |
6658 | // -- enumerations, which comprise a set of named constant values. [...]; |
6659 | isEnumeralType() || |
6660 | // -- pointers to non-static class members, [...]. |
6661 | isMemberPointerType(); |
6662 | } |
6663 | |
6664 | inline bool Type::isFunctionType() const { |
6665 | return isa<FunctionType>(CanonicalType); |
6666 | } |
6667 | |
6668 | inline bool Type::isPointerType() const { |
6669 | return isa<PointerType>(CanonicalType); |
6670 | } |
6671 | |
6672 | inline bool Type::isAnyPointerType() const { |
6673 | return isPointerType() || isObjCObjectPointerType(); |
6674 | } |
6675 | |
6676 | inline bool Type::isBlockPointerType() const { |
6677 | return isa<BlockPointerType>(CanonicalType); |
6678 | } |
6679 | |
6680 | inline bool Type::isReferenceType() const { |
6681 | return isa<ReferenceType>(CanonicalType); |
6682 | } |
6683 | |
6684 | inline bool Type::isLValueReferenceType() const { |
6685 | return isa<LValueReferenceType>(CanonicalType); |
6686 | } |
6687 | |
6688 | inline bool Type::isRValueReferenceType() const { |
6689 | return isa<RValueReferenceType>(CanonicalType); |
6690 | } |
6691 | |
6692 | inline bool Type::isObjectPointerType() const { |
6693 | // Note: an "object pointer type" is not the same thing as a pointer to an |
6694 | // object type; rather, it is a pointer to an object type or a pointer to cv |
6695 | // void. |
6696 | if (const auto *T = getAs<PointerType>()) |
6697 | return !T->getPointeeType()->isFunctionType(); |
6698 | else |
6699 | return false; |
6700 | } |
6701 | |
6702 | inline bool Type::isFunctionPointerType() const { |
6703 | if (const auto *T = getAs<PointerType>()) |
6704 | return T->getPointeeType()->isFunctionType(); |
6705 | else |
6706 | return false; |
6707 | } |
6708 | |
6709 | inline bool Type::isFunctionReferenceType() const { |
6710 | if (const auto *T = getAs<ReferenceType>()) |
6711 | return T->getPointeeType()->isFunctionType(); |
6712 | else |
6713 | return false; |
6714 | } |
6715 | |
6716 | inline bool Type::isMemberPointerType() const { |
6717 | return isa<MemberPointerType>(CanonicalType); |
6718 | } |
6719 | |
6720 | inline bool Type::isMemberFunctionPointerType() const { |
6721 | if (const auto *T = getAs<MemberPointerType>()) |
6722 | return T->isMemberFunctionPointer(); |
6723 | else |
6724 | return false; |
6725 | } |
6726 | |
6727 | inline bool Type::isMemberDataPointerType() const { |
6728 | if (const auto *T = getAs<MemberPointerType>()) |
6729 | return T->isMemberDataPointer(); |
6730 | else |
6731 | return false; |
6732 | } |
6733 | |
6734 | inline bool Type::isArrayType() const { |
6735 | return isa<ArrayType>(CanonicalType); |
6736 | } |
6737 | |
6738 | inline bool Type::isConstantArrayType() const { |
6739 | return isa<ConstantArrayType>(CanonicalType); |
6740 | } |
6741 | |
6742 | inline bool Type::isIncompleteArrayType() const { |
6743 | return isa<IncompleteArrayType>(CanonicalType); |
6744 | } |
6745 | |
6746 | inline bool Type::isVariableArrayType() const { |
6747 | return isa<VariableArrayType>(CanonicalType); |
6748 | } |
6749 | |
6750 | inline bool Type::isDependentSizedArrayType() const { |
6751 | return isa<DependentSizedArrayType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isBuiltinType() const { |
6755 | return isa<BuiltinType>(CanonicalType); |
6756 | } |
6757 | |
6758 | inline bool Type::isRecordType() const { |
6759 | return isa<RecordType>(CanonicalType); |
6760 | } |
6761 | |
6762 | inline bool Type::isEnumeralType() const { |
6763 | return isa<EnumType>(CanonicalType); |
6764 | } |
6765 | |
6766 | inline bool Type::isAnyComplexType() const { |
6767 | return isa<ComplexType>(CanonicalType); |
6768 | } |
6769 | |
6770 | inline bool Type::isVectorType() const { |
6771 | return isa<VectorType>(CanonicalType); |
6772 | } |
6773 | |
6774 | inline bool Type::isExtVectorType() const { |
6775 | return isa<ExtVectorType>(CanonicalType); |
6776 | } |
6777 | |
6778 | inline bool Type::isMatrixType() const { |
6779 | return isa<MatrixType>(CanonicalType); |
6780 | } |
6781 | |
6782 | inline bool Type::isConstantMatrixType() const { |
6783 | return isa<ConstantMatrixType>(CanonicalType); |
6784 | } |
6785 | |
6786 | inline bool Type::isDependentAddressSpaceType() const { |
6787 | return isa<DependentAddressSpaceType>(CanonicalType); |
6788 | } |
6789 | |
6790 | inline bool Type::isObjCObjectPointerType() const { |
6791 | return isa<ObjCObjectPointerType>(CanonicalType); |
6792 | } |
6793 | |
6794 | inline bool Type::isObjCObjectType() const { |
6795 | return isa<ObjCObjectType>(CanonicalType); |
6796 | } |
6797 | |
6798 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6799 | return isa<ObjCInterfaceType>(CanonicalType) || |
6800 | isa<ObjCObjectType>(CanonicalType); |
6801 | } |
6802 | |
6803 | inline bool Type::isAtomicType() const { |
6804 | return isa<AtomicType>(CanonicalType); |
6805 | } |
6806 | |
6807 | inline bool Type::isUndeducedAutoType() const { |
6808 | return isa<AutoType>(CanonicalType); |
6809 | } |
6810 | |
6811 | inline bool Type::isObjCQualifiedIdType() const { |
6812 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6813 | return OPT->isObjCQualifiedIdType(); |
6814 | return false; |
6815 | } |
6816 | |
6817 | inline bool Type::isObjCQualifiedClassType() const { |
6818 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6819 | return OPT->isObjCQualifiedClassType(); |
6820 | return false; |
6821 | } |
6822 | |
6823 | inline bool Type::isObjCIdType() const { |
6824 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6825 | return OPT->isObjCIdType(); |
6826 | return false; |
6827 | } |
6828 | |
6829 | inline bool Type::isObjCClassType() const { |
6830 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6831 | return OPT->isObjCClassType(); |
6832 | return false; |
6833 | } |
6834 | |
6835 | inline bool Type::isObjCSelType() const { |
6836 | if (const auto *OPT = getAs<PointerType>()) |
6837 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6838 | return false; |
6839 | } |
6840 | |
6841 | inline bool Type::isObjCBuiltinType() const { |
6842 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6843 | } |
6844 | |
6845 | inline bool Type::isDecltypeType() const { |
6846 | return isa<DecltypeType>(this); |
6847 | } |
6848 | |
6849 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6850 | inline bool Type::is##Id##Type() const { \ |
6851 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6852 | } |
6853 | #include "clang/Basic/OpenCLImageTypes.def" |
6854 | |
6855 | inline bool Type::isSamplerT() const { |
6856 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6857 | } |
6858 | |
6859 | inline bool Type::isEventT() const { |
6860 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6861 | } |
6862 | |
6863 | inline bool Type::isClkEventT() const { |
6864 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6865 | } |
6866 | |
6867 | inline bool Type::isQueueT() const { |
6868 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6869 | } |
6870 | |
6871 | inline bool Type::isReserveIDT() const { |
6872 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6873 | } |
6874 | |
6875 | inline bool Type::isImageType() const { |
6876 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6877 | return |
6878 | #include "clang/Basic/OpenCLImageTypes.def" |
6879 | false; // end boolean or operation |
6880 | } |
6881 | |
6882 | inline bool Type::isPipeType() const { |
6883 | return isa<PipeType>(CanonicalType); |
6884 | } |
6885 | |
6886 | inline bool Type::isExtIntType() const { |
6887 | return isa<ExtIntType>(CanonicalType); |
6888 | } |
6889 | |
6890 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6891 | inline bool Type::is##Id##Type() const { \ |
6892 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6893 | } |
6894 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6895 | |
6896 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6897 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6898 | isOCLIntelSubgroupAVC##Id##Type() || |
6899 | return |
6900 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6901 | false; // end of boolean or operation |
6902 | } |
6903 | |
6904 | inline bool Type::isOCLExtOpaqueType() const { |
6905 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6906 | return |
6907 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6908 | false; // end of boolean or operation |
6909 | } |
6910 | |
6911 | inline bool Type::isOpenCLSpecificType() const { |
6912 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6913 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6914 | } |
6915 | |
6916 | inline bool Type::isTemplateTypeParmType() const { |
6917 | return isa<TemplateTypeParmType>(CanonicalType); |
6918 | } |
6919 | |
6920 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6921 | if (const BuiltinType *BT = getAs<BuiltinType>()) { |
6922 | return BT->getKind() == static_cast<BuiltinType::Kind>(K); |
6923 | } |
6924 | return false; |
6925 | } |
6926 | |
6927 | inline bool Type::isPlaceholderType() const { |
6928 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6929 | return BT->isPlaceholderType(); |
6930 | return false; |
6931 | } |
6932 | |
6933 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6934 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6935 | if (BT->isPlaceholderType()) |
6936 | return BT; |
6937 | return nullptr; |
6938 | } |
6939 | |
6940 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6941 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ? static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 6941, __PRETTY_FUNCTION__)); |
6942 | return isSpecificBuiltinType(K); |
6943 | } |
6944 | |
6945 | inline bool Type::isNonOverloadPlaceholderType() const { |
6946 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6947 | return BT->isNonOverloadPlaceholderType(); |
6948 | return false; |
6949 | } |
6950 | |
6951 | inline bool Type::isVoidType() const { |
6952 | return isSpecificBuiltinType(BuiltinType::Void); |
6953 | } |
6954 | |
6955 | inline bool Type::isHalfType() const { |
6956 | // FIXME: Should we allow complex __fp16? Probably not. |
6957 | return isSpecificBuiltinType(BuiltinType::Half); |
6958 | } |
6959 | |
6960 | inline bool Type::isFloat16Type() const { |
6961 | return isSpecificBuiltinType(BuiltinType::Float16); |
6962 | } |
6963 | |
6964 | inline bool Type::isBFloat16Type() const { |
6965 | return isSpecificBuiltinType(BuiltinType::BFloat16); |
6966 | } |
6967 | |
6968 | inline bool Type::isFloat128Type() const { |
6969 | return isSpecificBuiltinType(BuiltinType::Float128); |
6970 | } |
6971 | |
6972 | inline bool Type::isNullPtrType() const { |
6973 | return isSpecificBuiltinType(BuiltinType::NullPtr); |
6974 | } |
6975 | |
6976 | bool IsEnumDeclComplete(EnumDecl *); |
6977 | bool IsEnumDeclScoped(EnumDecl *); |
6978 | |
6979 | inline bool Type::isIntegerType() const { |
6980 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6981 | return BT->getKind() >= BuiltinType::Bool && |
6982 | BT->getKind() <= BuiltinType::Int128; |
6983 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6984 | // Incomplete enum types are not treated as integer types. |
6985 | // FIXME: In C++, enum types are never integer types. |
6986 | return IsEnumDeclComplete(ET->getDecl()) && |
6987 | !IsEnumDeclScoped(ET->getDecl()); |
6988 | } |
6989 | return isExtIntType(); |
6990 | } |
6991 | |
6992 | inline bool Type::isFixedPointType() const { |
6993 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6994 | return BT->getKind() >= BuiltinType::ShortAccum && |
6995 | BT->getKind() <= BuiltinType::SatULongFract; |
6996 | } |
6997 | return false; |
6998 | } |
6999 | |
7000 | inline bool Type::isFixedPointOrIntegerType() const { |
7001 | return isFixedPointType() || isIntegerType(); |
7002 | } |
7003 | |
7004 | inline bool Type::isSaturatedFixedPointType() const { |
7005 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
7006 | return BT->getKind() >= BuiltinType::SatShortAccum && |
7007 | BT->getKind() <= BuiltinType::SatULongFract; |
7008 | } |
7009 | return false; |
7010 | } |
7011 | |
7012 | inline bool Type::isUnsaturatedFixedPointType() const { |
7013 | return isFixedPointType() && !isSaturatedFixedPointType(); |
7014 | } |
7015 | |
7016 | inline bool Type::isSignedFixedPointType() const { |
7017 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
7018 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
7019 | BT->getKind() <= BuiltinType::LongAccum) || |
7020 | (BT->getKind() >= BuiltinType::ShortFract && |
7021 | BT->getKind() <= BuiltinType::LongFract) || |
7022 | (BT->getKind() >= BuiltinType::SatShortAccum && |
7023 | BT->getKind() <= BuiltinType::SatLongAccum) || |
7024 | (BT->getKind() >= BuiltinType::SatShortFract && |
7025 | BT->getKind() <= BuiltinType::SatLongFract)); |
7026 | } |
7027 | return false; |
7028 | } |
7029 | |
7030 | inline bool Type::isUnsignedFixedPointType() const { |
7031 | return isFixedPointType() && !isSignedFixedPointType(); |
7032 | } |
7033 | |
7034 | inline bool Type::isScalarType() const { |
7035 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7036 | return BT->getKind() > BuiltinType::Void && |
7037 | BT->getKind() <= BuiltinType::NullPtr; |
7038 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
7039 | // Enums are scalar types, but only if they are defined. Incomplete enums |
7040 | // are not treated as scalar types. |
7041 | return IsEnumDeclComplete(ET->getDecl()); |
7042 | return isa<PointerType>(CanonicalType) || |
7043 | isa<BlockPointerType>(CanonicalType) || |
7044 | isa<MemberPointerType>(CanonicalType) || |
7045 | isa<ComplexType>(CanonicalType) || |
7046 | isa<ObjCObjectPointerType>(CanonicalType) || |
7047 | isExtIntType(); |
7048 | } |
7049 | |
7050 | inline bool Type::isIntegralOrEnumerationType() const { |
7051 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7052 | return BT->getKind() >= BuiltinType::Bool && |
7053 | BT->getKind() <= BuiltinType::Int128; |
7054 | |
7055 | // Check for a complete enum type; incomplete enum types are not properly an |
7056 | // enumeration type in the sense required here. |
7057 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
7058 | return IsEnumDeclComplete(ET->getDecl()); |
7059 | |
7060 | return isExtIntType(); |
7061 | } |
7062 | |
7063 | inline bool Type::isBooleanType() const { |
7064 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7065 | return BT->getKind() == BuiltinType::Bool; |
7066 | return false; |
7067 | } |
7068 | |
7069 | inline bool Type::isUndeducedType() const { |
7070 | auto *DT = getContainedDeducedType(); |
7071 | return DT && !DT->isDeduced(); |
7072 | } |
7073 | |
7074 | /// Determines whether this is a type for which one can define |
7075 | /// an overloaded operator. |
7076 | inline bool Type::isOverloadableType() const { |
7077 | return isDependentType() || isRecordType() || isEnumeralType(); |
7078 | } |
7079 | |
7080 | /// Determines whether this type is written as a typedef-name. |
7081 | inline bool Type::isTypedefNameType() const { |
7082 | if (getAs<TypedefType>()) |
7083 | return true; |
7084 | if (auto *TST = getAs<TemplateSpecializationType>()) |
7085 | return TST->isTypeAlias(); |
7086 | return false; |
7087 | } |
7088 | |
7089 | /// Determines whether this type can decay to a pointer type. |
7090 | inline bool Type::canDecayToPointerType() const { |
7091 | return isFunctionType() || isArrayType(); |
7092 | } |
7093 | |
7094 | inline bool Type::hasPointerRepresentation() const { |
7095 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
7096 | isObjCObjectPointerType() || isNullPtrType()); |
7097 | } |
7098 | |
7099 | inline bool Type::hasObjCPointerRepresentation() const { |
7100 | return isObjCObjectPointerType(); |
7101 | } |
7102 | |
7103 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
7104 | const Type *type = this; |
7105 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
7106 | type = arrayType->getElementType().getTypePtr(); |
7107 | return type; |
7108 | } |
7109 | |
7110 | inline const Type *Type::getPointeeOrArrayElementType() const { |
7111 | const Type *type = this; |
7112 | if (type->isAnyPointerType()) |
7113 | return type->getPointeeType().getTypePtr(); |
7114 | else if (type->isArrayType()) |
7115 | return type->getBaseElementTypeUnsafe(); |
7116 | return type; |
7117 | } |
7118 | /// Insertion operator for partial diagnostics. This allows sending adress |
7119 | /// spaces into a diagnostic with <<. |
7120 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7121 | LangAS AS) { |
7122 | PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), |
7123 | DiagnosticsEngine::ArgumentKind::ak_addrspace); |
7124 | return PD; |
7125 | } |
7126 | |
7127 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
7128 | /// into a diagnostic with <<. |
7129 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7130 | Qualifiers Q) { |
7131 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
7132 | DiagnosticsEngine::ArgumentKind::ak_qual); |
7133 | return PD; |
7134 | } |
7135 | |
7136 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
7137 | /// into a diagnostic with <<. |
7138 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7139 | QualType T) { |
7140 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
7141 | DiagnosticsEngine::ak_qualtype); |
7142 | return PD; |
7143 | } |
7144 | |
7145 | // Helper class template that is used by Type::getAs to ensure that one does |
7146 | // not try to look through a qualified type to get to an array type. |
7147 | template <typename T> |
7148 | using TypeIsArrayType = |
7149 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
7150 | std::is_base_of<ArrayType, T>::value>; |
7151 | |
7152 | // Member-template getAs<specific type>'. |
7153 | template <typename T> const T *Type::getAs() const { |
7154 | static_assert(!TypeIsArrayType<T>::value, |
7155 | "ArrayType cannot be used with getAs!"); |
7156 | |
7157 | // If this is directly a T type, return it. |
7158 | if (const auto *Ty = dyn_cast<T>(this)) |
7159 | return Ty; |
7160 | |
7161 | // If the canonical form of this type isn't the right kind, reject it. |
7162 | if (!isa<T>(CanonicalType)) |
7163 | return nullptr; |
7164 | |
7165 | // If this is a typedef for the type, strip the typedef off without |
7166 | // losing all typedef information. |
7167 | return cast<T>(getUnqualifiedDesugaredType()); |
7168 | } |
7169 | |
7170 | template <typename T> const T *Type::getAsAdjusted() const { |
7171 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
7172 | |
7173 | // If this is directly a T type, return it. |
7174 | if (const auto *Ty = dyn_cast<T>(this)) |
7175 | return Ty; |
7176 | |
7177 | // If the canonical form of this type isn't the right kind, reject it. |
7178 | if (!isa<T>(CanonicalType)) |
7179 | return nullptr; |
7180 | |
7181 | // Strip off type adjustments that do not modify the underlying nature of the |
7182 | // type. |
7183 | const Type *Ty = this; |
7184 | while (Ty) { |
7185 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
7186 | Ty = A->getModifiedType().getTypePtr(); |
7187 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
7188 | Ty = E->desugar().getTypePtr(); |
7189 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
7190 | Ty = P->desugar().getTypePtr(); |
7191 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
7192 | Ty = A->desugar().getTypePtr(); |
7193 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
7194 | Ty = M->desugar().getTypePtr(); |
7195 | else |
7196 | break; |
7197 | } |
7198 | |
7199 | // Just because the canonical type is correct does not mean we can use cast<>, |
7200 | // since we may not have stripped off all the sugar down to the base type. |
7201 | return dyn_cast<T>(Ty); |
7202 | } |
7203 | |
7204 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
7205 | // If this is directly an array type, return it. |
7206 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
7207 | return arr; |
7208 | |
7209 | // If the canonical form of this type isn't the right kind, reject it. |
7210 | if (!isa<ArrayType>(CanonicalType)) |
7211 | return nullptr; |
7212 | |
7213 | // If this is a typedef for the type, strip the typedef off without |
7214 | // losing all typedef information. |
7215 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7216 | } |
7217 | |
7218 | template <typename T> const T *Type::castAs() const { |
7219 | static_assert(!TypeIsArrayType<T>::value, |
7220 | "ArrayType cannot be used with castAs!"); |
7221 | |
7222 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
7223 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 7223, __PRETTY_FUNCTION__)); |
7224 | return cast<T>(getUnqualifiedDesugaredType()); |
7225 | } |
7226 | |
7227 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
7228 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 7228, __PRETTY_FUNCTION__)); |
7229 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
7230 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7231 | } |
7232 | |
7233 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
7234 | QualType CanonicalPtr) |
7235 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
7236 | #ifndef NDEBUG |
7237 | QualType Adjusted = getAdjustedType(); |
7238 | (void)AttributedType::stripOuterNullability(Adjusted); |
7239 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h" , 7239, __PRETTY_FUNCTION__)); |
7240 | #endif |
7241 | } |
7242 | |
7243 | QualType DecayedType::getPointeeType() const { |
7244 | QualType Decayed = getDecayedType(); |
7245 | (void)AttributedType::stripOuterNullability(Decayed); |
7246 | return cast<PointerType>(Decayed)->getPointeeType(); |
7247 | } |
7248 | |
7249 | // Get the decimal string representation of a fixed point type, represented |
7250 | // as a scaled integer. |
7251 | // TODO: At some point, we should change the arguments to instead just accept an |
7252 | // APFixedPoint instead of APSInt and scale. |
7253 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
7254 | unsigned Scale); |
7255 | |
7256 | } // namespace clang |
7257 | |
7258 | #endif // LLVM_CLANG_AST_TYPE_H |