File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 9097, column 27 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// | ||||||||
2 | // | ||||||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||||||
6 | // | ||||||||
7 | //===----------------------------------------------------------------------===// | ||||||||
8 | // | ||||||||
9 | // This file implements semantic analysis for expressions. | ||||||||
10 | // | ||||||||
11 | //===----------------------------------------------------------------------===// | ||||||||
12 | |||||||||
13 | #include "TreeTransform.h" | ||||||||
14 | #include "UsedDeclVisitor.h" | ||||||||
15 | #include "clang/AST/ASTConsumer.h" | ||||||||
16 | #include "clang/AST/ASTContext.h" | ||||||||
17 | #include "clang/AST/ASTLambda.h" | ||||||||
18 | #include "clang/AST/ASTMutationListener.h" | ||||||||
19 | #include "clang/AST/CXXInheritance.h" | ||||||||
20 | #include "clang/AST/DeclObjC.h" | ||||||||
21 | #include "clang/AST/DeclTemplate.h" | ||||||||
22 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||||||
23 | #include "clang/AST/Expr.h" | ||||||||
24 | #include "clang/AST/ExprCXX.h" | ||||||||
25 | #include "clang/AST/ExprObjC.h" | ||||||||
26 | #include "clang/AST/ExprOpenMP.h" | ||||||||
27 | #include "clang/AST/OperationKinds.h" | ||||||||
28 | #include "clang/AST/RecursiveASTVisitor.h" | ||||||||
29 | #include "clang/AST/TypeLoc.h" | ||||||||
30 | #include "clang/Basic/Builtins.h" | ||||||||
31 | #include "clang/Basic/PartialDiagnostic.h" | ||||||||
32 | #include "clang/Basic/SourceManager.h" | ||||||||
33 | #include "clang/Basic/TargetInfo.h" | ||||||||
34 | #include "clang/Lex/LiteralSupport.h" | ||||||||
35 | #include "clang/Lex/Preprocessor.h" | ||||||||
36 | #include "clang/Sema/AnalysisBasedWarnings.h" | ||||||||
37 | #include "clang/Sema/DeclSpec.h" | ||||||||
38 | #include "clang/Sema/DelayedDiagnostic.h" | ||||||||
39 | #include "clang/Sema/Designator.h" | ||||||||
40 | #include "clang/Sema/Initialization.h" | ||||||||
41 | #include "clang/Sema/Lookup.h" | ||||||||
42 | #include "clang/Sema/Overload.h" | ||||||||
43 | #include "clang/Sema/ParsedTemplate.h" | ||||||||
44 | #include "clang/Sema/Scope.h" | ||||||||
45 | #include "clang/Sema/ScopeInfo.h" | ||||||||
46 | #include "clang/Sema/SemaFixItUtils.h" | ||||||||
47 | #include "clang/Sema/SemaInternal.h" | ||||||||
48 | #include "clang/Sema/Template.h" | ||||||||
49 | #include "llvm/Support/ConvertUTF.h" | ||||||||
50 | #include "llvm/Support/SaveAndRestore.h" | ||||||||
51 | using namespace clang; | ||||||||
52 | using namespace sema; | ||||||||
53 | using llvm::RoundingMode; | ||||||||
54 | |||||||||
55 | /// Determine whether the use of this declaration is valid, without | ||||||||
56 | /// emitting diagnostics. | ||||||||
57 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||||||
58 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||||||
59 | if (ParsingInitForAutoVars.count(D)) | ||||||||
60 | return false; | ||||||||
61 | |||||||||
62 | // See if this is a deleted function. | ||||||||
63 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
64 | if (FD->isDeleted()) | ||||||||
65 | return false; | ||||||||
66 | |||||||||
67 | // If the function has a deduced return type, and we can't deduce it, | ||||||||
68 | // then we can't use it either. | ||||||||
69 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||||||
70 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||||||
71 | return false; | ||||||||
72 | |||||||||
73 | // See if this is an aligned allocation/deallocation function that is | ||||||||
74 | // unavailable. | ||||||||
75 | if (TreatUnavailableAsInvalid && | ||||||||
76 | isUnavailableAlignedAllocationFunction(*FD)) | ||||||||
77 | return false; | ||||||||
78 | } | ||||||||
79 | |||||||||
80 | // See if this function is unavailable. | ||||||||
81 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||||||
82 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||||||
83 | return false; | ||||||||
84 | |||||||||
85 | return true; | ||||||||
86 | } | ||||||||
87 | |||||||||
88 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||||||
89 | // Warn if this is used but marked unused. | ||||||||
90 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||||||
91 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||||||
92 | // should diagnose them. | ||||||||
93 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||||||
94 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||||||
95 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||||||
96 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||||||
97 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||||||
98 | } | ||||||||
99 | } | ||||||||
100 | } | ||||||||
101 | |||||||||
102 | /// Emit a note explaining that this function is deleted. | ||||||||
103 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||||||
104 | assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void > (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 104, __PRETTY_FUNCTION__)); | ||||||||
105 | |||||||||
106 | if (Decl->isDefaulted()) { | ||||||||
107 | // If the method was explicitly defaulted, point at that declaration. | ||||||||
108 | if (!Decl->isImplicit()) | ||||||||
109 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||||||
110 | |||||||||
111 | // Try to diagnose why this special member function was implicitly | ||||||||
112 | // deleted. This might fail, if that reason no longer applies. | ||||||||
113 | DiagnoseDeletedDefaultedFunction(Decl); | ||||||||
114 | return; | ||||||||
115 | } | ||||||||
116 | |||||||||
117 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||||||
118 | if (Ctor && Ctor->isInheritingConstructor()) | ||||||||
119 | return NoteDeletedInheritingConstructor(Ctor); | ||||||||
120 | |||||||||
121 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||||||
122 | << Decl << 1; | ||||||||
123 | } | ||||||||
124 | |||||||||
125 | /// Determine whether a FunctionDecl was ever declared with an | ||||||||
126 | /// explicit storage class. | ||||||||
127 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||||||
128 | for (auto I : D->redecls()) { | ||||||||
129 | if (I->getStorageClass() != SC_None) | ||||||||
130 | return true; | ||||||||
131 | } | ||||||||
132 | return false; | ||||||||
133 | } | ||||||||
134 | |||||||||
135 | /// Check whether we're in an extern inline function and referring to a | ||||||||
136 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||||||
137 | /// | ||||||||
138 | /// This is only a warning because we used to silently accept this code, but | ||||||||
139 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||||||
140 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||||||
141 | /// and so while there may still be user mistakes, most of the time we can't | ||||||||
142 | /// prove that there are errors. | ||||||||
143 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||||||
144 | const NamedDecl *D, | ||||||||
145 | SourceLocation Loc) { | ||||||||
146 | // This is disabled under C++; there are too many ways for this to fire in | ||||||||
147 | // contexts where the warning is a false positive, or where it is technically | ||||||||
148 | // correct but benign. | ||||||||
149 | if (S.getLangOpts().CPlusPlus) | ||||||||
150 | return; | ||||||||
151 | |||||||||
152 | // Check if this is an inlined function or method. | ||||||||
153 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||||||
154 | if (!Current) | ||||||||
155 | return; | ||||||||
156 | if (!Current->isInlined()) | ||||||||
157 | return; | ||||||||
158 | if (!Current->isExternallyVisible()) | ||||||||
159 | return; | ||||||||
160 | |||||||||
161 | // Check if the decl has internal linkage. | ||||||||
162 | if (D->getFormalLinkage() != InternalLinkage) | ||||||||
163 | return; | ||||||||
164 | |||||||||
165 | // Downgrade from ExtWarn to Extension if | ||||||||
166 | // (1) the supposedly external inline function is in the main file, | ||||||||
167 | // and probably won't be included anywhere else. | ||||||||
168 | // (2) the thing we're referencing is a pure function. | ||||||||
169 | // (3) the thing we're referencing is another inline function. | ||||||||
170 | // This last can give us false negatives, but it's better than warning on | ||||||||
171 | // wrappers for simple C library functions. | ||||||||
172 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||||||
173 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||||||
174 | if (!DowngradeWarning && UsedFn) | ||||||||
175 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||||||
176 | |||||||||
177 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||||||
178 | : diag::ext_internal_in_extern_inline) | ||||||||
179 | << /*IsVar=*/!UsedFn << D; | ||||||||
180 | |||||||||
181 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||||||
182 | |||||||||
183 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||||||
184 | << D; | ||||||||
185 | } | ||||||||
186 | |||||||||
187 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||||||
188 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||||||
189 | |||||||||
190 | // Suggest "static" on the function, if possible. | ||||||||
191 | if (!hasAnyExplicitStorageClass(First)) { | ||||||||
192 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||||||
193 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||||||
194 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||||||
195 | } | ||||||||
196 | } | ||||||||
197 | |||||||||
198 | /// Determine whether the use of this declaration is valid, and | ||||||||
199 | /// emit any corresponding diagnostics. | ||||||||
200 | /// | ||||||||
201 | /// This routine diagnoses various problems with referencing | ||||||||
202 | /// declarations that can occur when using a declaration. For example, | ||||||||
203 | /// it might warn if a deprecated or unavailable declaration is being | ||||||||
204 | /// used, or produce an error (and return true) if a C++0x deleted | ||||||||
205 | /// function is being used. | ||||||||
206 | /// | ||||||||
207 | /// \returns true if there was an error (this declaration cannot be | ||||||||
208 | /// referenced), false otherwise. | ||||||||
209 | /// | ||||||||
210 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||||||
211 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||||||
212 | bool ObjCPropertyAccess, | ||||||||
213 | bool AvoidPartialAvailabilityChecks, | ||||||||
214 | ObjCInterfaceDecl *ClassReceiver) { | ||||||||
215 | SourceLocation Loc = Locs.front(); | ||||||||
216 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||||||
217 | // If there were any diagnostics suppressed by template argument deduction, | ||||||||
218 | // emit them now. | ||||||||
219 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||||||
220 | if (Pos != SuppressedDiagnostics.end()) { | ||||||||
221 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||||||
222 | Diag(Suppressed.first, Suppressed.second); | ||||||||
223 | |||||||||
224 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||||||
225 | // them again for this specialization. However, we don't obsolete this | ||||||||
226 | // entry from the table, because we want to avoid ever emitting these | ||||||||
227 | // diagnostics again. | ||||||||
228 | Pos->second.clear(); | ||||||||
229 | } | ||||||||
230 | |||||||||
231 | // C++ [basic.start.main]p3: | ||||||||
232 | // The function 'main' shall not be used within a program. | ||||||||
233 | if (cast<FunctionDecl>(D)->isMain()) | ||||||||
234 | Diag(Loc, diag::ext_main_used); | ||||||||
235 | |||||||||
236 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||||||
237 | } | ||||||||
238 | |||||||||
239 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||||||
240 | if (ParsingInitForAutoVars.count(D)) { | ||||||||
241 | if (isa<BindingDecl>(D)) { | ||||||||
242 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||||||
243 | << D->getDeclName(); | ||||||||
244 | } else { | ||||||||
245 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||||||
246 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||||||
247 | } | ||||||||
248 | return true; | ||||||||
249 | } | ||||||||
250 | |||||||||
251 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
252 | // See if this is a deleted function. | ||||||||
253 | if (FD->isDeleted()) { | ||||||||
254 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||||||
255 | if (Ctor && Ctor->isInheritingConstructor()) | ||||||||
256 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||||||
257 | << Ctor->getParent() | ||||||||
258 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||||||
259 | else | ||||||||
260 | Diag(Loc, diag::err_deleted_function_use); | ||||||||
261 | NoteDeletedFunction(FD); | ||||||||
262 | return true; | ||||||||
263 | } | ||||||||
264 | |||||||||
265 | // [expr.prim.id]p4 | ||||||||
266 | // A program that refers explicitly or implicitly to a function with a | ||||||||
267 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||||||
268 | // other than to declare it, is ill-formed. [...] | ||||||||
269 | // | ||||||||
270 | // See if this is a function with constraints that need to be satisfied. | ||||||||
271 | // Check this before deducing the return type, as it might instantiate the | ||||||||
272 | // definition. | ||||||||
273 | if (FD->getTrailingRequiresClause()) { | ||||||||
274 | ConstraintSatisfaction Satisfaction; | ||||||||
275 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | ||||||||
276 | // A diagnostic will have already been generated (non-constant | ||||||||
277 | // constraint expression, for example) | ||||||||
278 | return true; | ||||||||
279 | if (!Satisfaction.IsSatisfied) { | ||||||||
280 | Diag(Loc, | ||||||||
281 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||||||
282 | << D; | ||||||||
283 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||||||
284 | return true; | ||||||||
285 | } | ||||||||
286 | } | ||||||||
287 | |||||||||
288 | // If the function has a deduced return type, and we can't deduce it, | ||||||||
289 | // then we can't use it either. | ||||||||
290 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||||||
291 | DeduceReturnType(FD, Loc)) | ||||||||
292 | return true; | ||||||||
293 | |||||||||
294 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||||||
295 | return true; | ||||||||
296 | |||||||||
297 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||||||
298 | return true; | ||||||||
299 | } | ||||||||
300 | |||||||||
301 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||||||
302 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||||||
303 | if (MD->getParent()->isLambda() && | ||||||||
304 | ((isa<CXXConstructorDecl>(MD) && | ||||||||
305 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||||||
306 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||||||
307 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||||||
308 | << !isa<CXXConstructorDecl>(MD); | ||||||||
309 | } | ||||||||
310 | } | ||||||||
311 | |||||||||
312 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||||||
313 | const ObjCPropertyDecl * { | ||||||||
314 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||||||
315 | return MD->findPropertyDecl(); | ||||||||
316 | return nullptr; | ||||||||
317 | }; | ||||||||
318 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||||||
319 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||||||
320 | return true; | ||||||||
321 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||||||
322 | return true; | ||||||||
323 | } | ||||||||
324 | |||||||||
325 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||||||
326 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||||||
327 | // Only the variables omp_priv and omp_orig are allowed in the | ||||||||
328 | // initializer-clause. | ||||||||
329 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||||||
330 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||||||
331 | isa<VarDecl>(D)) { | ||||||||
332 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||||||
333 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||||||
334 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
335 | return true; | ||||||||
336 | } | ||||||||
337 | |||||||||
338 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||||||
339 | // List-items in map clauses on this construct may only refer to the declared | ||||||||
340 | // variable var and entities that could be referenced by a procedure defined | ||||||||
341 | // at the same location | ||||||||
342 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||||||
343 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||||||
344 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||||||
345 | << getOpenMPDeclareMapperVarName(); | ||||||||
346 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
347 | return true; | ||||||||
348 | } | ||||||||
349 | |||||||||
350 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||||||
351 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||||||
352 | |||||||||
353 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||||||
354 | |||||||||
355 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||||||
356 | |||||||||
357 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||||||
358 | if (const auto *VD = dyn_cast<ValueDecl>(D)) | ||||||||
359 | checkDeviceDecl(VD, Loc); | ||||||||
360 | |||||||||
361 | if (!Context.getTargetInfo().isTLSSupported()) | ||||||||
362 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||||||
363 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||||||
364 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||||||
365 | } | ||||||||
366 | |||||||||
367 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||||||
368 | !isUnevaluatedContext()) { | ||||||||
369 | // C++ [expr.prim.req.nested] p3 | ||||||||
370 | // A local parameter shall only appear as an unevaluated operand | ||||||||
371 | // (Clause 8) within the constraint-expression. | ||||||||
372 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||||||
373 | << D; | ||||||||
374 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||||||
375 | return true; | ||||||||
376 | } | ||||||||
377 | |||||||||
378 | return false; | ||||||||
379 | } | ||||||||
380 | |||||||||
381 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||||||
382 | /// message-send is to a declaration with the sentinel attribute, and | ||||||||
383 | /// if so, it checks that the requirements of the sentinel are | ||||||||
384 | /// satisfied. | ||||||||
385 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||||||
386 | ArrayRef<Expr *> Args) { | ||||||||
387 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||||||
388 | if (!attr) | ||||||||
389 | return; | ||||||||
390 | |||||||||
391 | // The number of formal parameters of the declaration. | ||||||||
392 | unsigned numFormalParams; | ||||||||
393 | |||||||||
394 | // The kind of declaration. This is also an index into a %select in | ||||||||
395 | // the diagnostic. | ||||||||
396 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||||||
397 | |||||||||
398 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||||||
399 | numFormalParams = MD->param_size(); | ||||||||
400 | calleeType = CT_Method; | ||||||||
401 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
402 | numFormalParams = FD->param_size(); | ||||||||
403 | calleeType = CT_Function; | ||||||||
404 | } else if (isa<VarDecl>(D)) { | ||||||||
405 | QualType type = cast<ValueDecl>(D)->getType(); | ||||||||
406 | const FunctionType *fn = nullptr; | ||||||||
407 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||||||
408 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||||||
409 | if (!fn) return; | ||||||||
410 | calleeType = CT_Function; | ||||||||
411 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||||||
412 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||||||
413 | calleeType = CT_Block; | ||||||||
414 | } else { | ||||||||
415 | return; | ||||||||
416 | } | ||||||||
417 | |||||||||
418 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||||||
419 | numFormalParams = proto->getNumParams(); | ||||||||
420 | } else { | ||||||||
421 | numFormalParams = 0; | ||||||||
422 | } | ||||||||
423 | } else { | ||||||||
424 | return; | ||||||||
425 | } | ||||||||
426 | |||||||||
427 | // "nullPos" is the number of formal parameters at the end which | ||||||||
428 | // effectively count as part of the variadic arguments. This is | ||||||||
429 | // useful if you would prefer to not have *any* formal parameters, | ||||||||
430 | // but the language forces you to have at least one. | ||||||||
431 | unsigned nullPos = attr->getNullPos(); | ||||||||
432 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel" ) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 432, __PRETTY_FUNCTION__)); | ||||||||
433 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||||||
434 | |||||||||
435 | // The number of arguments which should follow the sentinel. | ||||||||
436 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||||||
437 | |||||||||
438 | // If there aren't enough arguments for all the formal parameters, | ||||||||
439 | // the sentinel, and the args after the sentinel, complain. | ||||||||
440 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||||||
441 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||||||
442 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||||||
443 | return; | ||||||||
444 | } | ||||||||
445 | |||||||||
446 | // Otherwise, find the sentinel expression. | ||||||||
447 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||||||
448 | if (!sentinelExpr) return; | ||||||||
449 | if (sentinelExpr->isValueDependent()) return; | ||||||||
450 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||||||
451 | |||||||||
452 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||||||
453 | // or 'NULL' if those are actually defined in the context. Only use | ||||||||
454 | // 'nil' for ObjC methods, where it's much more likely that the | ||||||||
455 | // variadic arguments form a list of object pointers. | ||||||||
456 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||||||
457 | std::string NullValue; | ||||||||
458 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||||||
459 | NullValue = "nil"; | ||||||||
460 | else if (getLangOpts().CPlusPlus11) | ||||||||
461 | NullValue = "nullptr"; | ||||||||
462 | else if (PP.isMacroDefined("NULL")) | ||||||||
463 | NullValue = "NULL"; | ||||||||
464 | else | ||||||||
465 | NullValue = "(void*) 0"; | ||||||||
466 | |||||||||
467 | if (MissingNilLoc.isInvalid()) | ||||||||
468 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||||||
469 | else | ||||||||
470 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||||||
471 | << int(calleeType) | ||||||||
472 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||||||
473 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||||||
474 | } | ||||||||
475 | |||||||||
476 | SourceRange Sema::getExprRange(Expr *E) const { | ||||||||
477 | return E ? E->getSourceRange() : SourceRange(); | ||||||||
478 | } | ||||||||
479 | |||||||||
480 | //===----------------------------------------------------------------------===// | ||||||||
481 | // Standard Promotions and Conversions | ||||||||
482 | //===----------------------------------------------------------------------===// | ||||||||
483 | |||||||||
484 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||||||
485 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||||||
486 | // Handle any placeholder expressions which made it here. | ||||||||
487 | if (E->getType()->isPlaceholderType()) { | ||||||||
488 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
489 | if (result.isInvalid()) return ExprError(); | ||||||||
490 | E = result.get(); | ||||||||
491 | } | ||||||||
492 | |||||||||
493 | QualType Ty = E->getType(); | ||||||||
494 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 494, __PRETTY_FUNCTION__)); | ||||||||
495 | |||||||||
496 | if (Ty->isFunctionType()) { | ||||||||
497 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||||||
498 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||||||
499 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||||||
500 | return ExprError(); | ||||||||
501 | |||||||||
502 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||||||
503 | CK_FunctionToPointerDecay).get(); | ||||||||
504 | } else if (Ty->isArrayType()) { | ||||||||
505 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||||||
506 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||||||
507 | // type 'array of type' is converted to an expression that has type 'pointer | ||||||||
508 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||||||
509 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||||||
510 | // (C90) to "an expression" (C99). | ||||||||
511 | // | ||||||||
512 | // C++ 4.2p1: | ||||||||
513 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||||||
514 | // T" can be converted to an rvalue of type "pointer to T". | ||||||||
515 | // | ||||||||
516 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | ||||||||
517 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||||||
518 | CK_ArrayToPointerDecay).get(); | ||||||||
519 | } | ||||||||
520 | return E; | ||||||||
521 | } | ||||||||
522 | |||||||||
523 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||||||
524 | // Check to see if we are dereferencing a null pointer. If so, | ||||||||
525 | // and if not volatile-qualified, this is undefined behavior that the | ||||||||
526 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||||||
527 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||||||
528 | // only handles the pattern "*null", which is a very syntactic check. | ||||||||
529 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||||||
530 | if (UO && UO->getOpcode() == UO_Deref && | ||||||||
531 | UO->getSubExpr()->getType()->isPointerType()) { | ||||||||
532 | const LangAS AS = | ||||||||
533 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||||||
534 | if ((!isTargetAddressSpace(AS) || | ||||||||
535 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||||||
536 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||||||
537 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||||||
538 | !UO->getType().isVolatileQualified()) { | ||||||||
539 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||
540 | S.PDiag(diag::warn_indirection_through_null) | ||||||||
541 | << UO->getSubExpr()->getSourceRange()); | ||||||||
542 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||
543 | S.PDiag(diag::note_indirection_through_null)); | ||||||||
544 | } | ||||||||
545 | } | ||||||||
546 | } | ||||||||
547 | |||||||||
548 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||||||
549 | SourceLocation AssignLoc, | ||||||||
550 | const Expr* RHS) { | ||||||||
551 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||||||
552 | if (!IV) | ||||||||
553 | return; | ||||||||
554 | |||||||||
555 | DeclarationName MemberName = IV->getDeclName(); | ||||||||
556 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||||||
557 | if (!Member || !Member->isStr("isa")) | ||||||||
558 | return; | ||||||||
559 | |||||||||
560 | const Expr *Base = OIRE->getBase(); | ||||||||
561 | QualType BaseType = Base->getType(); | ||||||||
562 | if (OIRE->isArrow()) | ||||||||
563 | BaseType = BaseType->getPointeeType(); | ||||||||
564 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||||||
565 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||||||
566 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||||||
567 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||||||
568 | if (!ClassDeclared->getSuperClass() | ||||||||
569 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||||||
570 | if (RHS) { | ||||||||
571 | NamedDecl *ObjectSetClass = | ||||||||
572 | S.LookupSingleName(S.TUScope, | ||||||||
573 | &S.Context.Idents.get("object_setClass"), | ||||||||
574 | SourceLocation(), S.LookupOrdinaryName); | ||||||||
575 | if (ObjectSetClass) { | ||||||||
576 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||||||
577 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||||||
578 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||||||
579 | "object_setClass(") | ||||||||
580 | << FixItHint::CreateReplacement( | ||||||||
581 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||||||
582 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||||||
583 | } | ||||||||
584 | else | ||||||||
585 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||||||
586 | } else { | ||||||||
587 | NamedDecl *ObjectGetClass = | ||||||||
588 | S.LookupSingleName(S.TUScope, | ||||||||
589 | &S.Context.Idents.get("object_getClass"), | ||||||||
590 | SourceLocation(), S.LookupOrdinaryName); | ||||||||
591 | if (ObjectGetClass) | ||||||||
592 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||||||
593 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||||||
594 | "object_getClass(") | ||||||||
595 | << FixItHint::CreateReplacement( | ||||||||
596 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||||||
597 | else | ||||||||
598 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||||||
599 | } | ||||||||
600 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||||||
601 | } | ||||||||
602 | } | ||||||||
603 | } | ||||||||
604 | |||||||||
605 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||||||
606 | // Handle any placeholder expressions which made it here. | ||||||||
607 | if (E->getType()->isPlaceholderType()) { | ||||||||
608 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
609 | if (result.isInvalid()) return ExprError(); | ||||||||
610 | E = result.get(); | ||||||||
611 | } | ||||||||
612 | |||||||||
613 | // C++ [conv.lval]p1: | ||||||||
614 | // A glvalue of a non-function, non-array type T can be | ||||||||
615 | // converted to a prvalue. | ||||||||
616 | if (!E->isGLValue()) return E; | ||||||||
617 | |||||||||
618 | QualType T = E->getType(); | ||||||||
619 | assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 619, __PRETTY_FUNCTION__)); | ||||||||
620 | |||||||||
621 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||||||
622 | if (T->isFunctionType() || T->isArrayType()) | ||||||||
623 | return E; | ||||||||
624 | |||||||||
625 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||||||
626 | // expressions of certain types in C++. | ||||||||
627 | if (getLangOpts().CPlusPlus && | ||||||||
628 | (E->getType() == Context.OverloadTy || | ||||||||
629 | T->isDependentType() || | ||||||||
630 | T->isRecordType())) | ||||||||
631 | return E; | ||||||||
632 | |||||||||
633 | // The C standard is actually really unclear on this point, and | ||||||||
634 | // DR106 tells us what the result should be but not why. It's | ||||||||
635 | // generally best to say that void types just doesn't undergo | ||||||||
636 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||||||
637 | // 'void' type are never l-values, but qualified void can be. | ||||||||
638 | if (T->isVoidType()) | ||||||||
639 | return E; | ||||||||
640 | |||||||||
641 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||||||
642 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | ||||||||
643 | T->isHalfType()) { | ||||||||
644 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||||||
645 | << 0 << T; | ||||||||
646 | return ExprError(); | ||||||||
647 | } | ||||||||
648 | |||||||||
649 | CheckForNullPointerDereference(*this, E); | ||||||||
650 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||||||
651 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||||||
652 | &Context.Idents.get("object_getClass"), | ||||||||
653 | SourceLocation(), LookupOrdinaryName); | ||||||||
654 | if (ObjectGetClass) | ||||||||
655 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||||||
656 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||||||
657 | << FixItHint::CreateReplacement( | ||||||||
658 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||||||
659 | else | ||||||||
660 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||||||
661 | } | ||||||||
662 | else if (const ObjCIvarRefExpr *OIRE = | ||||||||
663 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||||||
664 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||||||
665 | |||||||||
666 | // C++ [conv.lval]p1: | ||||||||
667 | // [...] If T is a non-class type, the type of the prvalue is the | ||||||||
668 | // cv-unqualified version of T. Otherwise, the type of the | ||||||||
669 | // rvalue is T. | ||||||||
670 | // | ||||||||
671 | // C99 6.3.2.1p2: | ||||||||
672 | // If the lvalue has qualified type, the value has the unqualified | ||||||||
673 | // version of the type of the lvalue; otherwise, the value has the | ||||||||
674 | // type of the lvalue. | ||||||||
675 | if (T.hasQualifiers()) | ||||||||
676 | T = T.getUnqualifiedType(); | ||||||||
677 | |||||||||
678 | // Under the MS ABI, lock down the inheritance model now. | ||||||||
679 | if (T->isMemberPointerType() && | ||||||||
680 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||||||
681 | (void)isCompleteType(E->getExprLoc(), T); | ||||||||
682 | |||||||||
683 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||||||
684 | if (Res.isInvalid()) | ||||||||
685 | return Res; | ||||||||
686 | E = Res.get(); | ||||||||
687 | |||||||||
688 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||||||
689 | // balance that. | ||||||||
690 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||||
691 | Cleanup.setExprNeedsCleanups(true); | ||||||||
692 | |||||||||
693 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
694 | Cleanup.setExprNeedsCleanups(true); | ||||||||
695 | |||||||||
696 | // C++ [conv.lval]p3: | ||||||||
697 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||||||
698 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||||||
699 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, | ||||||||
700 | FPOptionsOverride()); | ||||||||
701 | |||||||||
702 | // C11 6.3.2.1p2: | ||||||||
703 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||||||
704 | // of the type of the lvalue ... | ||||||||
705 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||||||
706 | T = Atomic->getValueType().getUnqualifiedType(); | ||||||||
707 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||||||
708 | nullptr, VK_RValue, FPOptionsOverride()); | ||||||||
709 | } | ||||||||
710 | |||||||||
711 | return Res; | ||||||||
712 | } | ||||||||
713 | |||||||||
714 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||||||
715 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||||||
716 | if (Res.isInvalid()) | ||||||||
717 | return ExprError(); | ||||||||
718 | Res = DefaultLvalueConversion(Res.get()); | ||||||||
719 | if (Res.isInvalid()) | ||||||||
720 | return ExprError(); | ||||||||
721 | return Res; | ||||||||
722 | } | ||||||||
723 | |||||||||
724 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||||||
725 | /// performed on a function designator of a call expression. | ||||||||
726 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||||||
727 | QualType Ty = E->getType(); | ||||||||
728 | ExprResult Res = E; | ||||||||
729 | // Only do implicit cast for a function type, but not for a pointer | ||||||||
730 | // to function type. | ||||||||
731 | if (Ty->isFunctionType()) { | ||||||||
732 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||||||
733 | CK_FunctionToPointerDecay); | ||||||||
734 | if (Res.isInvalid()) | ||||||||
735 | return ExprError(); | ||||||||
736 | } | ||||||||
737 | Res = DefaultLvalueConversion(Res.get()); | ||||||||
738 | if (Res.isInvalid()) | ||||||||
739 | return ExprError(); | ||||||||
740 | return Res.get(); | ||||||||
741 | } | ||||||||
742 | |||||||||
743 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||||||
744 | /// operators (C99 6.3). The conversions of array and function types are | ||||||||
745 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||||||
746 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||||||
747 | /// In these instances, this routine should *not* be called. | ||||||||
748 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||||||
749 | // First, convert to an r-value. | ||||||||
750 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||||||
751 | if (Res.isInvalid()) | ||||||||
752 | return ExprError(); | ||||||||
753 | E = Res.get(); | ||||||||
754 | |||||||||
755 | QualType Ty = E->getType(); | ||||||||
756 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 756, __PRETTY_FUNCTION__)); | ||||||||
757 | |||||||||
758 | // Half FP have to be promoted to float unless it is natively supported | ||||||||
759 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||||||
760 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||||||
761 | |||||||||
762 | // Try to perform integral promotions if the object has a theoretically | ||||||||
763 | // promotable type. | ||||||||
764 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||||||
765 | // C99 6.3.1.1p2: | ||||||||
766 | // | ||||||||
767 | // The following may be used in an expression wherever an int or | ||||||||
768 | // unsigned int may be used: | ||||||||
769 | // - an object or expression with an integer type whose integer | ||||||||
770 | // conversion rank is less than or equal to the rank of int | ||||||||
771 | // and unsigned int. | ||||||||
772 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||||||
773 | // | ||||||||
774 | // If an int can represent all values of the original type, the | ||||||||
775 | // value is converted to an int; otherwise, it is converted to an | ||||||||
776 | // unsigned int. These are called the integer promotions. All | ||||||||
777 | // other types are unchanged by the integer promotions. | ||||||||
778 | |||||||||
779 | QualType PTy = Context.isPromotableBitField(E); | ||||||||
780 | if (!PTy.isNull()) { | ||||||||
781 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||||||
782 | return E; | ||||||||
783 | } | ||||||||
784 | if (Ty->isPromotableIntegerType()) { | ||||||||
785 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||||||
786 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||||||
787 | return E; | ||||||||
788 | } | ||||||||
789 | } | ||||||||
790 | return E; | ||||||||
791 | } | ||||||||
792 | |||||||||
793 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||||||
794 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||||||
795 | /// are promoted to double. All other argument types are converted by | ||||||||
796 | /// UsualUnaryConversions(). | ||||||||
797 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||||||
798 | QualType Ty = E->getType(); | ||||||||
799 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 799, __PRETTY_FUNCTION__)); | ||||||||
800 | |||||||||
801 | ExprResult Res = UsualUnaryConversions(E); | ||||||||
802 | if (Res.isInvalid()) | ||||||||
803 | return ExprError(); | ||||||||
804 | E = Res.get(); | ||||||||
805 | |||||||||
806 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||||||
807 | // promote to double. | ||||||||
808 | // Note that default argument promotion applies only to float (and | ||||||||
809 | // half/fp16); it does not apply to _Float16. | ||||||||
810 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||||||
811 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||||||
812 | BTy->getKind() == BuiltinType::Float)) { | ||||||||
813 | if (getLangOpts().OpenCL && | ||||||||
814 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | ||||||||
815 | if (BTy->getKind() == BuiltinType::Half) { | ||||||||
816 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
817 | } | ||||||||
818 | } else { | ||||||||
819 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||||||
820 | } | ||||||||
821 | } | ||||||||
822 | |||||||||
823 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||||||
824 | // promotion, even on class types, but note: | ||||||||
825 | // C++11 [conv.lval]p2: | ||||||||
826 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||||||
827 | // operand or a subexpression thereof the value contained in the | ||||||||
828 | // referenced object is not accessed. Otherwise, if the glvalue | ||||||||
829 | // has a class type, the conversion copy-initializes a temporary | ||||||||
830 | // of type T from the glvalue and the result of the conversion | ||||||||
831 | // is a prvalue for the temporary. | ||||||||
832 | // FIXME: add some way to gate this entire thing for correctness in | ||||||||
833 | // potentially potentially evaluated contexts. | ||||||||
834 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||||||
835 | ExprResult Temp = PerformCopyInitialization( | ||||||||
836 | InitializedEntity::InitializeTemporary(E->getType()), | ||||||||
837 | E->getExprLoc(), E); | ||||||||
838 | if (Temp.isInvalid()) | ||||||||
839 | return ExprError(); | ||||||||
840 | E = Temp.get(); | ||||||||
841 | } | ||||||||
842 | |||||||||
843 | return E; | ||||||||
844 | } | ||||||||
845 | |||||||||
846 | /// Determine the degree of POD-ness for an expression. | ||||||||
847 | /// Incomplete types are considered POD, since this check can be performed | ||||||||
848 | /// when we're in an unevaluated context. | ||||||||
849 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||||||
850 | if (Ty->isIncompleteType()) { | ||||||||
851 | // C++11 [expr.call]p7: | ||||||||
852 | // After these conversions, if the argument does not have arithmetic, | ||||||||
853 | // enumeration, pointer, pointer to member, or class type, the program | ||||||||
854 | // is ill-formed. | ||||||||
855 | // | ||||||||
856 | // Since we've already performed array-to-pointer and function-to-pointer | ||||||||
857 | // decay, the only such type in C++ is cv void. This also handles | ||||||||
858 | // initializer lists as variadic arguments. | ||||||||
859 | if (Ty->isVoidType()) | ||||||||
860 | return VAK_Invalid; | ||||||||
861 | |||||||||
862 | if (Ty->isObjCObjectType()) | ||||||||
863 | return VAK_Invalid; | ||||||||
864 | return VAK_Valid; | ||||||||
865 | } | ||||||||
866 | |||||||||
867 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
868 | return VAK_Invalid; | ||||||||
869 | |||||||||
870 | if (Ty.isCXX98PODType(Context)) | ||||||||
871 | return VAK_Valid; | ||||||||
872 | |||||||||
873 | // C++11 [expr.call]p7: | ||||||||
874 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||||||
875 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||||||
876 | // or a non-trivial destructor, with no corresponding parameter, | ||||||||
877 | // is conditionally-supported with implementation-defined semantics. | ||||||||
878 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||||||
879 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||||||
880 | if (!Record->hasNonTrivialCopyConstructor() && | ||||||||
881 | !Record->hasNonTrivialMoveConstructor() && | ||||||||
882 | !Record->hasNonTrivialDestructor()) | ||||||||
883 | return VAK_ValidInCXX11; | ||||||||
884 | |||||||||
885 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||||||
886 | return VAK_Valid; | ||||||||
887 | |||||||||
888 | if (Ty->isObjCObjectType()) | ||||||||
889 | return VAK_Invalid; | ||||||||
890 | |||||||||
891 | if (getLangOpts().MSVCCompat) | ||||||||
892 | return VAK_MSVCUndefined; | ||||||||
893 | |||||||||
894 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||||||
895 | // permitted to reject them. We should consider doing so. | ||||||||
896 | return VAK_Undefined; | ||||||||
897 | } | ||||||||
898 | |||||||||
899 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||||||
900 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||||||
901 | const QualType &Ty = E->getType(); | ||||||||
902 | VarArgKind VAK = isValidVarArgType(Ty); | ||||||||
903 | |||||||||
904 | // Complain about passing non-POD types through varargs. | ||||||||
905 | switch (VAK) { | ||||||||
906 | case VAK_ValidInCXX11: | ||||||||
907 | DiagRuntimeBehavior( | ||||||||
908 | E->getBeginLoc(), nullptr, | ||||||||
909 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||||||
910 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
911 | case VAK_Valid: | ||||||||
912 | if (Ty->isRecordType()) { | ||||||||
913 | // This is unlikely to be what the user intended. If the class has a | ||||||||
914 | // 'c_str' member function, the user probably meant to call that. | ||||||||
915 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
916 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||||||
917 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||||||
918 | } | ||||||||
919 | break; | ||||||||
920 | |||||||||
921 | case VAK_Undefined: | ||||||||
922 | case VAK_MSVCUndefined: | ||||||||
923 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
924 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||||||
925 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||||||
926 | break; | ||||||||
927 | |||||||||
928 | case VAK_Invalid: | ||||||||
929 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||||
930 | Diag(E->getBeginLoc(), | ||||||||
931 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||||||
932 | << Ty << CT; | ||||||||
933 | else if (Ty->isObjCObjectType()) | ||||||||
934 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||||||
935 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||||||
936 | << Ty << CT); | ||||||||
937 | else | ||||||||
938 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||||||
939 | << isa<InitListExpr>(E) << Ty << CT; | ||||||||
940 | break; | ||||||||
941 | } | ||||||||
942 | } | ||||||||
943 | |||||||||
944 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||||||
945 | /// will create a trap if the resulting type is not a POD type. | ||||||||
946 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||||||
947 | FunctionDecl *FDecl) { | ||||||||
948 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||||||
949 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||||||
950 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||||||
951 | (CT == VariadicMethod || | ||||||||
952 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||||||
953 | E = stripARCUnbridgedCast(E); | ||||||||
954 | |||||||||
955 | // Otherwise, do normal placeholder checking. | ||||||||
956 | } else { | ||||||||
957 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||||||
958 | if (ExprRes.isInvalid()) | ||||||||
959 | return ExprError(); | ||||||||
960 | E = ExprRes.get(); | ||||||||
961 | } | ||||||||
962 | } | ||||||||
963 | |||||||||
964 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||||||
965 | if (ExprRes.isInvalid()) | ||||||||
966 | return ExprError(); | ||||||||
967 | |||||||||
968 | // Copy blocks to the heap. | ||||||||
969 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||||||
970 | maybeExtendBlockObject(ExprRes); | ||||||||
971 | |||||||||
972 | E = ExprRes.get(); | ||||||||
973 | |||||||||
974 | // Diagnostics regarding non-POD argument types are | ||||||||
975 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||||||
976 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||||||
977 | // Turn this into a trap. | ||||||||
978 | CXXScopeSpec SS; | ||||||||
979 | SourceLocation TemplateKWLoc; | ||||||||
980 | UnqualifiedId Name; | ||||||||
981 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||||||
982 | E->getBeginLoc()); | ||||||||
983 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||||||
984 | /*HasTrailingLParen=*/true, | ||||||||
985 | /*IsAddressOfOperand=*/false); | ||||||||
986 | if (TrapFn.isInvalid()) | ||||||||
987 | return ExprError(); | ||||||||
988 | |||||||||
989 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||||||
990 | None, E->getEndLoc()); | ||||||||
991 | if (Call.isInvalid()) | ||||||||
992 | return ExprError(); | ||||||||
993 | |||||||||
994 | ExprResult Comma = | ||||||||
995 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||||||
996 | if (Comma.isInvalid()) | ||||||||
997 | return ExprError(); | ||||||||
998 | return Comma.get(); | ||||||||
999 | } | ||||||||
1000 | |||||||||
1001 | if (!getLangOpts().CPlusPlus && | ||||||||
1002 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||||||
1003 | diag::err_call_incomplete_argument)) | ||||||||
1004 | return ExprError(); | ||||||||
1005 | |||||||||
1006 | return E; | ||||||||
1007 | } | ||||||||
1008 | |||||||||
1009 | /// Converts an integer to complex float type. Helper function of | ||||||||
1010 | /// UsualArithmeticConversions() | ||||||||
1011 | /// | ||||||||
1012 | /// \return false if the integer expression is an integer type and is | ||||||||
1013 | /// successfully converted to the complex type. | ||||||||
1014 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||||||
1015 | ExprResult &ComplexExpr, | ||||||||
1016 | QualType IntTy, | ||||||||
1017 | QualType ComplexTy, | ||||||||
1018 | bool SkipCast) { | ||||||||
1019 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||||||
1020 | if (SkipCast) return false; | ||||||||
1021 | if (IntTy->isIntegerType()) { | ||||||||
1022 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | ||||||||
1023 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||||||
1024 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||||||
1025 | CK_FloatingRealToComplex); | ||||||||
1026 | } else { | ||||||||
1027 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1027, __PRETTY_FUNCTION__)); | ||||||||
1028 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||||||
1029 | CK_IntegralComplexToFloatingComplex); | ||||||||
1030 | } | ||||||||
1031 | return false; | ||||||||
1032 | } | ||||||||
1033 | |||||||||
1034 | /// Handle arithmetic conversion with complex types. Helper function of | ||||||||
1035 | /// UsualArithmeticConversions() | ||||||||
1036 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | ||||||||
1037 | ExprResult &RHS, QualType LHSType, | ||||||||
1038 | QualType RHSType, | ||||||||
1039 | bool IsCompAssign) { | ||||||||
1040 | // if we have an integer operand, the result is the complex type. | ||||||||
1041 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||||||
1042 | /*skipCast*/false)) | ||||||||
1043 | return LHSType; | ||||||||
1044 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
1045 | /*skipCast*/IsCompAssign)) | ||||||||
1046 | return RHSType; | ||||||||
1047 | |||||||||
1048 | // This handles complex/complex, complex/float, or float/complex. | ||||||||
1049 | // When both operands are complex, the shorter operand is converted to the | ||||||||
1050 | // type of the longer, and that is the type of the result. This corresponds | ||||||||
1051 | // to what is done when combining two real floating-point operands. | ||||||||
1052 | // The fun begins when size promotion occur across type domains. | ||||||||
1053 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||||||
1054 | // floating-point type, the less precise type is converted, within it's | ||||||||
1055 | // real or complex domain, to the precision of the other type. For example, | ||||||||
1056 | // when combining a "long double" with a "double _Complex", the | ||||||||
1057 | // "double _Complex" is promoted to "long double _Complex". | ||||||||
1058 | |||||||||
1059 | // Compute the rank of the two types, regardless of whether they are complex. | ||||||||
1060 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||||||
1061 | |||||||||
1062 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | ||||||||
1063 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | ||||||||
1064 | QualType LHSElementType = | ||||||||
1065 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | ||||||||
1066 | QualType RHSElementType = | ||||||||
1067 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | ||||||||
1068 | |||||||||
1069 | QualType ResultType = S.Context.getComplexType(LHSElementType); | ||||||||
1070 | if (Order < 0) { | ||||||||
1071 | // Promote the precision of the LHS if not an assignment. | ||||||||
1072 | ResultType = S.Context.getComplexType(RHSElementType); | ||||||||
1073 | if (!IsCompAssign) { | ||||||||
1074 | if (LHSComplexType) | ||||||||
1075 | LHS = | ||||||||
1076 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | ||||||||
1077 | else | ||||||||
1078 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | ||||||||
1079 | } | ||||||||
1080 | } else if (Order > 0) { | ||||||||
1081 | // Promote the precision of the RHS. | ||||||||
1082 | if (RHSComplexType) | ||||||||
1083 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | ||||||||
1084 | else | ||||||||
1085 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | ||||||||
1086 | } | ||||||||
1087 | return ResultType; | ||||||||
1088 | } | ||||||||
1089 | |||||||||
1090 | /// Handle arithmetic conversion from integer to float. Helper function | ||||||||
1091 | /// of UsualArithmeticConversions() | ||||||||
1092 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||||||
1093 | ExprResult &IntExpr, | ||||||||
1094 | QualType FloatTy, QualType IntTy, | ||||||||
1095 | bool ConvertFloat, bool ConvertInt) { | ||||||||
1096 | if (IntTy->isIntegerType()) { | ||||||||
1097 | if (ConvertInt) | ||||||||
1098 | // Convert intExpr to the lhs floating point type. | ||||||||
1099 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||||||
1100 | CK_IntegralToFloating); | ||||||||
1101 | return FloatTy; | ||||||||
1102 | } | ||||||||
1103 | |||||||||
1104 | // Convert both sides to the appropriate complex float. | ||||||||
1105 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1105, __PRETTY_FUNCTION__)); | ||||||||
1106 | QualType result = S.Context.getComplexType(FloatTy); | ||||||||
1107 | |||||||||
1108 | // _Complex int -> _Complex float | ||||||||
1109 | if (ConvertInt) | ||||||||
1110 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||||||
1111 | CK_IntegralComplexToFloatingComplex); | ||||||||
1112 | |||||||||
1113 | // float -> _Complex float | ||||||||
1114 | if (ConvertFloat) | ||||||||
1115 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||||||
1116 | CK_FloatingRealToComplex); | ||||||||
1117 | |||||||||
1118 | return result; | ||||||||
1119 | } | ||||||||
1120 | |||||||||
1121 | /// Handle arithmethic conversion with floating point types. Helper | ||||||||
1122 | /// function of UsualArithmeticConversions() | ||||||||
1123 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||||||
1124 | ExprResult &RHS, QualType LHSType, | ||||||||
1125 | QualType RHSType, bool IsCompAssign) { | ||||||||
1126 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||||||
1127 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||||||
1128 | |||||||||
1129 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||||||
1130 | // operand has a fixed-point type, the fixed-point operand | ||||||||
1131 | // is converted to the floating type [...] | ||||||||
1132 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||||||
1133 | if (LHSFloat) | ||||||||
1134 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||||||
1135 | else if (!IsCompAssign) | ||||||||
1136 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||||||
1137 | return LHSFloat ? LHSType : RHSType; | ||||||||
1138 | } | ||||||||
1139 | |||||||||
1140 | // If we have two real floating types, convert the smaller operand | ||||||||
1141 | // to the bigger result. | ||||||||
1142 | if (LHSFloat && RHSFloat) { | ||||||||
1143 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||||||
1144 | if (order > 0) { | ||||||||
1145 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||||||
1146 | return LHSType; | ||||||||
1147 | } | ||||||||
1148 | |||||||||
1149 | assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast <void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1149, __PRETTY_FUNCTION__)); | ||||||||
1150 | if (!IsCompAssign) | ||||||||
1151 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||||||
1152 | return RHSType; | ||||||||
1153 | } | ||||||||
1154 | |||||||||
1155 | if (LHSFloat) { | ||||||||
1156 | // Half FP has to be promoted to float unless it is natively supported | ||||||||
1157 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||||||
1158 | LHSType = S.Context.FloatTy; | ||||||||
1159 | |||||||||
1160 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
1161 | /*ConvertFloat=*/!IsCompAssign, | ||||||||
1162 | /*ConvertInt=*/ true); | ||||||||
1163 | } | ||||||||
1164 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1164, __PRETTY_FUNCTION__)); | ||||||||
1165 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||||||
1166 | /*ConvertFloat=*/ true, | ||||||||
1167 | /*ConvertInt=*/!IsCompAssign); | ||||||||
1168 | } | ||||||||
1169 | |||||||||
1170 | /// Diagnose attempts to convert between __float128 and long double if | ||||||||
1171 | /// there is no support for such conversion. Helper function of | ||||||||
1172 | /// UsualArithmeticConversions(). | ||||||||
1173 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||||||
1174 | QualType RHSType) { | ||||||||
1175 | /* No issue converting if at least one of the types is not a floating point | ||||||||
1176 | type or the two types have the same rank. | ||||||||
1177 | */ | ||||||||
1178 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | ||||||||
1179 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | ||||||||
1180 | return false; | ||||||||
1181 | |||||||||
1182 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1183, __PRETTY_FUNCTION__)) | ||||||||
1183 | "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1183, __PRETTY_FUNCTION__)); | ||||||||
1184 | |||||||||
1185 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||||||
1186 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||||||
1187 | |||||||||
1188 | QualType LHSElemType = LHSComplex
| ||||||||
1189 | LHSComplex->getElementType() : LHSType; | ||||||||
1190 | QualType RHSElemType = RHSComplex
| ||||||||
1191 | RHSComplex->getElementType() : RHSType; | ||||||||
1192 | |||||||||
1193 | // No issue if the two types have the same representation | ||||||||
1194 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | ||||||||
1195 | &S.Context.getFloatTypeSemantics(RHSElemType)) | ||||||||
1196 | return false; | ||||||||
1197 | |||||||||
1198 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | ||||||||
1199 | RHSElemType == S.Context.LongDoubleTy); | ||||||||
1200 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | ||||||||
1201 | RHSElemType == S.Context.Float128Ty); | ||||||||
1202 | |||||||||
1203 | // We've handled the situation where __float128 and long double have the same | ||||||||
1204 | // representation. We allow all conversions for all possible long double types | ||||||||
1205 | // except PPC's double double. | ||||||||
1206 | return Float128AndLongDouble
| ||||||||
1207 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | ||||||||
1208 | &llvm::APFloat::PPCDoubleDouble()); | ||||||||
1209 | } | ||||||||
1210 | |||||||||
1211 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||||||
1212 | |||||||||
1213 | namespace { | ||||||||
1214 | /// These helper callbacks are placed in an anonymous namespace to | ||||||||
1215 | /// permit their use as function template parameters. | ||||||||
1216 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||||||
1217 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||||||
1218 | } | ||||||||
1219 | |||||||||
1220 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||||||
1221 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||||||
1222 | CK_IntegralComplexCast); | ||||||||
1223 | } | ||||||||
1224 | } | ||||||||
1225 | |||||||||
1226 | /// Handle integer arithmetic conversions. Helper function of | ||||||||
1227 | /// UsualArithmeticConversions() | ||||||||
1228 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||||||
1229 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||||||
1230 | ExprResult &RHS, QualType LHSType, | ||||||||
1231 | QualType RHSType, bool IsCompAssign) { | ||||||||
1232 | // The rules for this case are in C99 6.3.1.8 | ||||||||
1233 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||||||
1234 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||||||
1235 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||||||
1236 | if (LHSSigned == RHSSigned) { | ||||||||
1237 | // Same signedness; use the higher-ranked type | ||||||||
1238 | if (order >= 0) { | ||||||||
1239 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1240 | return LHSType; | ||||||||
1241 | } else if (!IsCompAssign) | ||||||||
1242 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1243 | return RHSType; | ||||||||
1244 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||||||
1245 | // The unsigned type has greater than or equal rank to the | ||||||||
1246 | // signed type, so use the unsigned type | ||||||||
1247 | if (RHSSigned) { | ||||||||
1248 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1249 | return LHSType; | ||||||||
1250 | } else if (!IsCompAssign) | ||||||||
1251 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1252 | return RHSType; | ||||||||
1253 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||||||
1254 | // The two types are different widths; if we are here, that | ||||||||
1255 | // means the signed type is larger than the unsigned type, so | ||||||||
1256 | // use the signed type. | ||||||||
1257 | if (LHSSigned) { | ||||||||
1258 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||||||
1259 | return LHSType; | ||||||||
1260 | } else if (!IsCompAssign) | ||||||||
1261 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||||||
1262 | return RHSType; | ||||||||
1263 | } else { | ||||||||
1264 | // The signed type is higher-ranked than the unsigned type, | ||||||||
1265 | // but isn't actually any bigger (like unsigned int and long | ||||||||
1266 | // on most 32-bit systems). Use the unsigned type corresponding | ||||||||
1267 | // to the signed type. | ||||||||
1268 | QualType result = | ||||||||
1269 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||||||
1270 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||||||
1271 | if (!IsCompAssign) | ||||||||
1272 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||||||
1273 | return result; | ||||||||
1274 | } | ||||||||
1275 | } | ||||||||
1276 | |||||||||
1277 | /// Handle conversions with GCC complex int extension. Helper function | ||||||||
1278 | /// of UsualArithmeticConversions() | ||||||||
1279 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||||||
1280 | ExprResult &RHS, QualType LHSType, | ||||||||
1281 | QualType RHSType, | ||||||||
1282 | bool IsCompAssign) { | ||||||||
1283 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||||||
1284 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||||||
1285 | |||||||||
1286 | if (LHSComplexInt && RHSComplexInt) { | ||||||||
1287 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||||||
1288 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||||||
1289 | QualType ScalarType = | ||||||||
1290 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||||||
1291 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||||||
1292 | |||||||||
1293 | return S.Context.getComplexType(ScalarType); | ||||||||
1294 | } | ||||||||
1295 | |||||||||
1296 | if (LHSComplexInt) { | ||||||||
1297 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||||||
1298 | QualType ScalarType = | ||||||||
1299 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||||||
1300 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||||||
1301 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||||||
1302 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||||||
1303 | CK_IntegralRealToComplex); | ||||||||
1304 | |||||||||
1305 | return ComplexType; | ||||||||
1306 | } | ||||||||
1307 | |||||||||
1308 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1308, __PRETTY_FUNCTION__)); | ||||||||
1309 | |||||||||
1310 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||||||
1311 | QualType ScalarType = | ||||||||
1312 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||||||
1313 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||||||
1314 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||||||
1315 | |||||||||
1316 | if (!IsCompAssign) | ||||||||
1317 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||||||
1318 | CK_IntegralRealToComplex); | ||||||||
1319 | return ComplexType; | ||||||||
1320 | } | ||||||||
1321 | |||||||||
1322 | /// Return the rank of a given fixed point or integer type. The value itself | ||||||||
1323 | /// doesn't matter, but the values must be increasing with proper increasing | ||||||||
1324 | /// rank as described in N1169 4.1.1. | ||||||||
1325 | static unsigned GetFixedPointRank(QualType Ty) { | ||||||||
1326 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||||||
1327 | assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast< void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1327, __PRETTY_FUNCTION__)); | ||||||||
1328 | |||||||||
1329 | switch (BTy->getKind()) { | ||||||||
1330 | case BuiltinType::ShortFract: | ||||||||
1331 | case BuiltinType::UShortFract: | ||||||||
1332 | case BuiltinType::SatShortFract: | ||||||||
1333 | case BuiltinType::SatUShortFract: | ||||||||
1334 | return 1; | ||||||||
1335 | case BuiltinType::Fract: | ||||||||
1336 | case BuiltinType::UFract: | ||||||||
1337 | case BuiltinType::SatFract: | ||||||||
1338 | case BuiltinType::SatUFract: | ||||||||
1339 | return 2; | ||||||||
1340 | case BuiltinType::LongFract: | ||||||||
1341 | case BuiltinType::ULongFract: | ||||||||
1342 | case BuiltinType::SatLongFract: | ||||||||
1343 | case BuiltinType::SatULongFract: | ||||||||
1344 | return 3; | ||||||||
1345 | case BuiltinType::ShortAccum: | ||||||||
1346 | case BuiltinType::UShortAccum: | ||||||||
1347 | case BuiltinType::SatShortAccum: | ||||||||
1348 | case BuiltinType::SatUShortAccum: | ||||||||
1349 | return 4; | ||||||||
1350 | case BuiltinType::Accum: | ||||||||
1351 | case BuiltinType::UAccum: | ||||||||
1352 | case BuiltinType::SatAccum: | ||||||||
1353 | case BuiltinType::SatUAccum: | ||||||||
1354 | return 5; | ||||||||
1355 | case BuiltinType::LongAccum: | ||||||||
1356 | case BuiltinType::ULongAccum: | ||||||||
1357 | case BuiltinType::SatLongAccum: | ||||||||
1358 | case BuiltinType::SatULongAccum: | ||||||||
1359 | return 6; | ||||||||
1360 | default: | ||||||||
1361 | if (BTy->isInteger()) | ||||||||
1362 | return 0; | ||||||||
1363 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1363); | ||||||||
1364 | } | ||||||||
1365 | } | ||||||||
1366 | |||||||||
1367 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||||||
1368 | /// point types and integers or other fixed point types do not fall under | ||||||||
1369 | /// usual arithmetic conversion since these conversions could result in loss | ||||||||
1370 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||||||
1371 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||||||
1372 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||||||
1373 | QualType RHSTy) { | ||||||||
1374 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1375, __PRETTY_FUNCTION__)) | ||||||||
1375 | "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1375, __PRETTY_FUNCTION__)); | ||||||||
1376 | assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)) | ||||||||
1377 | RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)) | ||||||||
1378 | "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)) | ||||||||
1379 | "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1379, __PRETTY_FUNCTION__)); | ||||||||
1380 | |||||||||
1381 | // If one operand has signed fixed-point type and the other operand has | ||||||||
1382 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||||||
1383 | // converted to its corresponding signed fixed-point type and the resulting | ||||||||
1384 | // type is the type of the converted operand. | ||||||||
1385 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||||||
1386 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||||||
1387 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||||||
1388 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||||||
1389 | |||||||||
1390 | // The result type is the type with the highest rank, whereby a fixed-point | ||||||||
1391 | // conversion rank is always greater than an integer conversion rank; if the | ||||||||
1392 | // type of either of the operands is a saturating fixedpoint type, the result | ||||||||
1393 | // type shall be the saturating fixed-point type corresponding to the type | ||||||||
1394 | // with the highest rank; the resulting value is converted (taking into | ||||||||
1395 | // account rounding and overflow) to the precision of the resulting type. | ||||||||
1396 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||||||
1397 | // types are either signed or both unsigned at this point. | ||||||||
1398 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||||||
1399 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||||||
1400 | |||||||||
1401 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||||||
1402 | |||||||||
1403 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||||||
1404 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||||||
1405 | |||||||||
1406 | return ResultTy; | ||||||||
1407 | } | ||||||||
1408 | |||||||||
1409 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||||||
1410 | /// expressions that might be of enumeration type. | ||||||||
1411 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||||||
1412 | SourceLocation Loc, | ||||||||
1413 | Sema::ArithConvKind ACK) { | ||||||||
1414 | // C++2a [expr.arith.conv]p1: | ||||||||
1415 | // If one operand is of enumeration type and the other operand is of a | ||||||||
1416 | // different enumeration type or a floating-point type, this behavior is | ||||||||
1417 | // deprecated ([depr.arith.conv.enum]). | ||||||||
1418 | // | ||||||||
1419 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||||||
1420 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||||||
1421 | QualType L = LHS->getType(), R = RHS->getType(); | ||||||||
1422 | bool LEnum = L->isUnscopedEnumerationType(), | ||||||||
1423 | REnum = R->isUnscopedEnumerationType(); | ||||||||
1424 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||||||
1425 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||||||
1426 | (REnum && L->isFloatingType())) { | ||||||||
1427 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||||||
1428 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||||||
1429 | : diag::warn_arith_conv_enum_float) | ||||||||
1430 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
1431 | << (int)ACK << LEnum << L << R; | ||||||||
1432 | } else if (!IsCompAssign && LEnum && REnum && | ||||||||
1433 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||||||
1434 | unsigned DiagID; | ||||||||
1435 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||||||
1436 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||||||
1437 | // If either enumeration type is unnamed, it's less likely that the | ||||||||
1438 | // user cares about this, but this situation is still deprecated in | ||||||||
1439 | // C++2a. Use a different warning group. | ||||||||
1440 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1441 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||||||
1442 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||||||
1443 | } else if (ACK == Sema::ACK_Conditional) { | ||||||||
1444 | // Conditional expressions are separated out because they have | ||||||||
1445 | // historically had a different warning flag. | ||||||||
1446 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1447 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||||||
1448 | : diag::warn_conditional_mixed_enum_types; | ||||||||
1449 | } else if (ACK == Sema::ACK_Comparison) { | ||||||||
1450 | // Comparison expressions are separated out because they have | ||||||||
1451 | // historically had a different warning flag. | ||||||||
1452 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1453 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||||||
1454 | : diag::warn_comparison_mixed_enum_types; | ||||||||
1455 | } else { | ||||||||
1456 | DiagID = S.getLangOpts().CPlusPlus20 | ||||||||
1457 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||||||
1458 | : diag::warn_arith_conv_mixed_enum_types; | ||||||||
1459 | } | ||||||||
1460 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
1461 | << (int)ACK << L << R; | ||||||||
1462 | } | ||||||||
1463 | } | ||||||||
1464 | |||||||||
1465 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||||||
1466 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||||||
1467 | /// routine returns the first non-arithmetic type found. The client is | ||||||||
1468 | /// responsible for emitting appropriate error diagnostics. | ||||||||
1469 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||||||
1470 | SourceLocation Loc, | ||||||||
1471 | ArithConvKind ACK) { | ||||||||
1472 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||||||
1473 | |||||||||
1474 | if (ACK != ACK_CompAssign) { | ||||||||
1475 | LHS = UsualUnaryConversions(LHS.get()); | ||||||||
1476 | if (LHS.isInvalid()) | ||||||||
1477 | return QualType(); | ||||||||
1478 | } | ||||||||
1479 | |||||||||
1480 | RHS = UsualUnaryConversions(RHS.get()); | ||||||||
1481 | if (RHS.isInvalid()) | ||||||||
1482 | return QualType(); | ||||||||
1483 | |||||||||
1484 | // For conversion purposes, we ignore any qualifiers. | ||||||||
1485 | // For example, "const float" and "float" are equivalent. | ||||||||
1486 | QualType LHSType = | ||||||||
1487 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||||||
1488 | QualType RHSType = | ||||||||
1489 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||||||
1490 | |||||||||
1491 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||||||
1492 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||||||
1493 | LHSType = AtomicLHS->getValueType(); | ||||||||
1494 | |||||||||
1495 | // If both types are identical, no conversion is needed. | ||||||||
1496 | if (LHSType == RHSType) | ||||||||
1497 | return LHSType; | ||||||||
1498 | |||||||||
1499 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||||||
1500 | // The caller can deal with this (e.g. pointer + int). | ||||||||
1501 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||||||
1502 | return QualType(); | ||||||||
1503 | |||||||||
1504 | // Apply unary and bitfield promotions to the LHS's type. | ||||||||
1505 | QualType LHSUnpromotedType = LHSType; | ||||||||
1506 | if (LHSType->isPromotableIntegerType()) | ||||||||
1507 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||||||
1508 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||||||
1509 | if (!LHSBitfieldPromoteTy.isNull()) | ||||||||
1510 | LHSType = LHSBitfieldPromoteTy; | ||||||||
1511 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||||||
1512 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||||||
1513 | |||||||||
1514 | // If both types are identical, no conversion is needed. | ||||||||
1515 | if (LHSType == RHSType) | ||||||||
1516 | return LHSType; | ||||||||
1517 | |||||||||
1518 | // ExtInt types aren't subject to conversions between them or normal integers, | ||||||||
1519 | // so this fails. | ||||||||
1520 | if(LHSType->isExtIntType() || RHSType->isExtIntType()) | ||||||||
1521 | return QualType(); | ||||||||
1522 | |||||||||
1523 | // At this point, we have two different arithmetic types. | ||||||||
1524 | |||||||||
1525 | // Diagnose attempts to convert between __float128 and long double where | ||||||||
1526 | // such conversions currently can't be handled. | ||||||||
1527 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||||||
1528 | return QualType(); | ||||||||
1529 | |||||||||
1530 | // Handle complex types first (C99 6.3.1.8p1). | ||||||||
1531 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||||||
1532 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1533 | ACK == ACK_CompAssign); | ||||||||
1534 | |||||||||
1535 | // Now handle "real" floating types (i.e. float, double, long double). | ||||||||
1536 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||||||
1537 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1538 | ACK == ACK_CompAssign); | ||||||||
1539 | |||||||||
1540 | // Handle GCC complex int extension. | ||||||||
1541 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||||||
1542 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||||||
1543 | ACK == ACK_CompAssign); | ||||||||
1544 | |||||||||
1545 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||||||
1546 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||||||
1547 | |||||||||
1548 | // Finally, we have two differing integer types. | ||||||||
1549 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||||||
1550 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||||||
1551 | } | ||||||||
1552 | |||||||||
1553 | //===----------------------------------------------------------------------===// | ||||||||
1554 | // Semantic Analysis for various Expression Types | ||||||||
1555 | //===----------------------------------------------------------------------===// | ||||||||
1556 | |||||||||
1557 | |||||||||
1558 | ExprResult | ||||||||
1559 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||||||
1560 | SourceLocation DefaultLoc, | ||||||||
1561 | SourceLocation RParenLoc, | ||||||||
1562 | Expr *ControllingExpr, | ||||||||
1563 | ArrayRef<ParsedType> ArgTypes, | ||||||||
1564 | ArrayRef<Expr *> ArgExprs) { | ||||||||
1565 | unsigned NumAssocs = ArgTypes.size(); | ||||||||
1566 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1566, __PRETTY_FUNCTION__)); | ||||||||
1567 | |||||||||
1568 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||||||
1569 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1570 | if (ArgTypes[i]) | ||||||||
1571 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||||||
1572 | else | ||||||||
1573 | Types[i] = nullptr; | ||||||||
1574 | } | ||||||||
1575 | |||||||||
1576 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||||||
1577 | ControllingExpr, | ||||||||
1578 | llvm::makeArrayRef(Types, NumAssocs), | ||||||||
1579 | ArgExprs); | ||||||||
1580 | delete [] Types; | ||||||||
1581 | return ER; | ||||||||
1582 | } | ||||||||
1583 | |||||||||
1584 | ExprResult | ||||||||
1585 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||||||
1586 | SourceLocation DefaultLoc, | ||||||||
1587 | SourceLocation RParenLoc, | ||||||||
1588 | Expr *ControllingExpr, | ||||||||
1589 | ArrayRef<TypeSourceInfo *> Types, | ||||||||
1590 | ArrayRef<Expr *> Exprs) { | ||||||||
1591 | unsigned NumAssocs = Types.size(); | ||||||||
1592 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1592, __PRETTY_FUNCTION__)); | ||||||||
1593 | |||||||||
1594 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||||||
1595 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||||||
1596 | { | ||||||||
1597 | EnterExpressionEvaluationContext Unevaluated( | ||||||||
1598 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||||||
1599 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||||||
1600 | if (R.isInvalid()) | ||||||||
1601 | return ExprError(); | ||||||||
1602 | ControllingExpr = R.get(); | ||||||||
1603 | } | ||||||||
1604 | |||||||||
1605 | // The controlling expression is an unevaluated operand, so side effects are | ||||||||
1606 | // likely unintended. | ||||||||
1607 | if (!inTemplateInstantiation() && | ||||||||
1608 | ControllingExpr->HasSideEffects(Context, false)) | ||||||||
1609 | Diag(ControllingExpr->getExprLoc(), | ||||||||
1610 | diag::warn_side_effects_unevaluated_context); | ||||||||
1611 | |||||||||
1612 | bool TypeErrorFound = false, | ||||||||
1613 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||||||
1614 | ContainsUnexpandedParameterPack | ||||||||
1615 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||||||
1616 | |||||||||
1617 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1618 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||||||
1619 | ContainsUnexpandedParameterPack = true; | ||||||||
1620 | |||||||||
1621 | if (Types[i]) { | ||||||||
1622 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||||||
1623 | ContainsUnexpandedParameterPack = true; | ||||||||
1624 | |||||||||
1625 | if (Types[i]->getType()->isDependentType()) { | ||||||||
1626 | IsResultDependent = true; | ||||||||
1627 | } else { | ||||||||
1628 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||||||
1629 | // complete object type other than a variably modified type." | ||||||||
1630 | unsigned D = 0; | ||||||||
1631 | if (Types[i]->getType()->isIncompleteType()) | ||||||||
1632 | D = diag::err_assoc_type_incomplete; | ||||||||
1633 | else if (!Types[i]->getType()->isObjectType()) | ||||||||
1634 | D = diag::err_assoc_type_nonobject; | ||||||||
1635 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||||||
1636 | D = diag::err_assoc_type_variably_modified; | ||||||||
1637 | |||||||||
1638 | if (D != 0) { | ||||||||
1639 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||||||
1640 | << Types[i]->getTypeLoc().getSourceRange() | ||||||||
1641 | << Types[i]->getType(); | ||||||||
1642 | TypeErrorFound = true; | ||||||||
1643 | } | ||||||||
1644 | |||||||||
1645 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||||||
1646 | // selection shall specify compatible types." | ||||||||
1647 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||||||
1648 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||||||
1649 | Context.typesAreCompatible(Types[i]->getType(), | ||||||||
1650 | Types[j]->getType())) { | ||||||||
1651 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||||||
1652 | diag::err_assoc_compatible_types) | ||||||||
1653 | << Types[j]->getTypeLoc().getSourceRange() | ||||||||
1654 | << Types[j]->getType() | ||||||||
1655 | << Types[i]->getType(); | ||||||||
1656 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||||||
1657 | diag::note_compat_assoc) | ||||||||
1658 | << Types[i]->getTypeLoc().getSourceRange() | ||||||||
1659 | << Types[i]->getType(); | ||||||||
1660 | TypeErrorFound = true; | ||||||||
1661 | } | ||||||||
1662 | } | ||||||||
1663 | } | ||||||||
1664 | } | ||||||||
1665 | if (TypeErrorFound) | ||||||||
1666 | return ExprError(); | ||||||||
1667 | |||||||||
1668 | // If we determined that the generic selection is result-dependent, don't | ||||||||
1669 | // try to compute the result expression. | ||||||||
1670 | if (IsResultDependent) | ||||||||
1671 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||||||
1672 | Exprs, DefaultLoc, RParenLoc, | ||||||||
1673 | ContainsUnexpandedParameterPack); | ||||||||
1674 | |||||||||
1675 | SmallVector<unsigned, 1> CompatIndices; | ||||||||
1676 | unsigned DefaultIndex = -1U; | ||||||||
1677 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||||||
1678 | if (!Types[i]) | ||||||||
1679 | DefaultIndex = i; | ||||||||
1680 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | ||||||||
1681 | Types[i]->getType())) | ||||||||
1682 | CompatIndices.push_back(i); | ||||||||
1683 | } | ||||||||
1684 | |||||||||
1685 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||||||
1686 | // type compatible with at most one of the types named in its generic | ||||||||
1687 | // association list." | ||||||||
1688 | if (CompatIndices.size() > 1) { | ||||||||
1689 | // We strip parens here because the controlling expression is typically | ||||||||
1690 | // parenthesized in macro definitions. | ||||||||
1691 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||||||
1692 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||||||
1693 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||||||
1694 | << (unsigned)CompatIndices.size(); | ||||||||
1695 | for (unsigned I : CompatIndices) { | ||||||||
1696 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||||||
1697 | diag::note_compat_assoc) | ||||||||
1698 | << Types[I]->getTypeLoc().getSourceRange() | ||||||||
1699 | << Types[I]->getType(); | ||||||||
1700 | } | ||||||||
1701 | return ExprError(); | ||||||||
1702 | } | ||||||||
1703 | |||||||||
1704 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||||||
1705 | // its controlling expression shall have type compatible with exactly one of | ||||||||
1706 | // the types named in its generic association list." | ||||||||
1707 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||||||
1708 | // We strip parens here because the controlling expression is typically | ||||||||
1709 | // parenthesized in macro definitions. | ||||||||
1710 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||||||
1711 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||||||
1712 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||||||
1713 | return ExprError(); | ||||||||
1714 | } | ||||||||
1715 | |||||||||
1716 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||||||
1717 | // type name that is compatible with the type of the controlling expression, | ||||||||
1718 | // then the result expression of the generic selection is the expression | ||||||||
1719 | // in that generic association. Otherwise, the result expression of the | ||||||||
1720 | // generic selection is the expression in the default generic association." | ||||||||
1721 | unsigned ResultIndex = | ||||||||
1722 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||||||
1723 | |||||||||
1724 | return GenericSelectionExpr::Create( | ||||||||
1725 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||||||
1726 | ContainsUnexpandedParameterPack, ResultIndex); | ||||||||
1727 | } | ||||||||
1728 | |||||||||
1729 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||||||
1730 | /// location of the token and the offset of the ud-suffix within it. | ||||||||
1731 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||||||
1732 | unsigned Offset) { | ||||||||
1733 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||||||
1734 | S.getLangOpts()); | ||||||||
1735 | } | ||||||||
1736 | |||||||||
1737 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||||||
1738 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||||||
1739 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||||||
1740 | IdentifierInfo *UDSuffix, | ||||||||
1741 | SourceLocation UDSuffixLoc, | ||||||||
1742 | ArrayRef<Expr*> Args, | ||||||||
1743 | SourceLocation LitEndLoc) { | ||||||||
1744 | assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator" ) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1744, __PRETTY_FUNCTION__)); | ||||||||
1745 | |||||||||
1746 | QualType ArgTy[2]; | ||||||||
1747 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||||||
1748 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||||||
1749 | if (ArgTy[ArgIdx]->isArrayType()) | ||||||||
1750 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||||||
1751 | } | ||||||||
1752 | |||||||||
1753 | DeclarationName OpName = | ||||||||
1754 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
1755 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
1756 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
1757 | |||||||||
1758 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||||||
1759 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||||||
1760 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||||||
1761 | /*AllowStringTemplatePack*/ false, | ||||||||
1762 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||||||
1763 | return ExprError(); | ||||||||
1764 | |||||||||
1765 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||||||
1766 | } | ||||||||
1767 | |||||||||
1768 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||||||
1769 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||||||
1770 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||||||
1771 | /// multiple tokens. However, the common case is that StringToks points to one | ||||||||
1772 | /// string. | ||||||||
1773 | /// | ||||||||
1774 | ExprResult | ||||||||
1775 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||||||
1776 | assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!" ) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1776, __PRETTY_FUNCTION__)); | ||||||||
1777 | |||||||||
1778 | StringLiteralParser Literal(StringToks, PP); | ||||||||
1779 | if (Literal.hadError) | ||||||||
1780 | return ExprError(); | ||||||||
1781 | |||||||||
1782 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||||||
1783 | for (const Token &Tok : StringToks) | ||||||||
1784 | StringTokLocs.push_back(Tok.getLocation()); | ||||||||
1785 | |||||||||
1786 | QualType CharTy = Context.CharTy; | ||||||||
1787 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | ||||||||
1788 | if (Literal.isWide()) { | ||||||||
1789 | CharTy = Context.getWideCharType(); | ||||||||
1790 | Kind = StringLiteral::Wide; | ||||||||
1791 | } else if (Literal.isUTF8()) { | ||||||||
1792 | if (getLangOpts().Char8) | ||||||||
1793 | CharTy = Context.Char8Ty; | ||||||||
1794 | Kind = StringLiteral::UTF8; | ||||||||
1795 | } else if (Literal.isUTF16()) { | ||||||||
1796 | CharTy = Context.Char16Ty; | ||||||||
1797 | Kind = StringLiteral::UTF16; | ||||||||
1798 | } else if (Literal.isUTF32()) { | ||||||||
1799 | CharTy = Context.Char32Ty; | ||||||||
1800 | Kind = StringLiteral::UTF32; | ||||||||
1801 | } else if (Literal.isPascal()) { | ||||||||
1802 | CharTy = Context.UnsignedCharTy; | ||||||||
1803 | } | ||||||||
1804 | |||||||||
1805 | // Warn on initializing an array of char from a u8 string literal; this | ||||||||
1806 | // becomes ill-formed in C++2a. | ||||||||
1807 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||||||
1808 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||||||
1809 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||||||
1810 | |||||||||
1811 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||||||
1812 | // ensures C++2a compatibility (but may change the program behavior when | ||||||||
1813 | // built by non-Clang compilers for which the execution character set is | ||||||||
1814 | // not always UTF-8). | ||||||||
1815 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||||||
1816 | SourceLocation RemovalDiagLoc; | ||||||||
1817 | for (const Token &Tok : StringToks) { | ||||||||
1818 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||||||
1819 | if (RemovalDiagLoc.isInvalid()) | ||||||||
1820 | RemovalDiagLoc = Tok.getLocation(); | ||||||||
1821 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||||||
1822 | Tok.getLocation(), | ||||||||
1823 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||||||
1824 | getSourceManager(), getLangOpts()))); | ||||||||
1825 | } | ||||||||
1826 | } | ||||||||
1827 | Diag(RemovalDiagLoc, RemovalDiag); | ||||||||
1828 | } | ||||||||
1829 | |||||||||
1830 | QualType StrTy = | ||||||||
1831 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||||||
1832 | |||||||||
1833 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||||||
1834 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||||||
1835 | Kind, Literal.Pascal, StrTy, | ||||||||
1836 | &StringTokLocs[0], | ||||||||
1837 | StringTokLocs.size()); | ||||||||
1838 | if (Literal.getUDSuffix().empty()) | ||||||||
1839 | return Lit; | ||||||||
1840 | |||||||||
1841 | // We're building a user-defined literal. | ||||||||
1842 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
1843 | SourceLocation UDSuffixLoc = | ||||||||
1844 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||||||
1845 | Literal.getUDSuffixOffset()); | ||||||||
1846 | |||||||||
1847 | // Make sure we're allowed user-defined literals here. | ||||||||
1848 | if (!UDLScope) | ||||||||
1849 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||||||
1850 | |||||||||
1851 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||||||
1852 | // operator "" X (str, len) | ||||||||
1853 | QualType SizeType = Context.getSizeType(); | ||||||||
1854 | |||||||||
1855 | DeclarationName OpName = | ||||||||
1856 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
1857 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
1858 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
1859 | |||||||||
1860 | QualType ArgTy[] = { | ||||||||
1861 | Context.getArrayDecayedType(StrTy), SizeType | ||||||||
1862 | }; | ||||||||
1863 | |||||||||
1864 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||||||
1865 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||||||
1866 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||||||
1867 | /*AllowStringTemplatePack*/ true, | ||||||||
1868 | /*DiagnoseMissing*/ true, Lit)) { | ||||||||
1869 | |||||||||
1870 | case LOLR_Cooked: { | ||||||||
1871 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||||||
1872 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||||||
1873 | StringTokLocs[0]); | ||||||||
1874 | Expr *Args[] = { Lit, LenArg }; | ||||||||
1875 | |||||||||
1876 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||||||
1877 | } | ||||||||
1878 | |||||||||
1879 | case LOLR_Template: { | ||||||||
1880 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
1881 | TemplateArgument Arg(Lit); | ||||||||
1882 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||||||
1883 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
1884 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||||||
1885 | &ExplicitArgs); | ||||||||
1886 | } | ||||||||
1887 | |||||||||
1888 | case LOLR_StringTemplatePack: { | ||||||||
1889 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
1890 | |||||||||
1891 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||||||
1892 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||||||
1893 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||||||
1894 | |||||||||
1895 | TemplateArgument TypeArg(CharTy); | ||||||||
1896 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||||||
1897 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||||||
1898 | |||||||||
1899 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||||||
1900 | Value = Lit->getCodeUnit(I); | ||||||||
1901 | TemplateArgument Arg(Context, Value, CharTy); | ||||||||
1902 | TemplateArgumentLocInfo ArgInfo; | ||||||||
1903 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
1904 | } | ||||||||
1905 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||||||
1906 | &ExplicitArgs); | ||||||||
1907 | } | ||||||||
1908 | case LOLR_Raw: | ||||||||
1909 | case LOLR_ErrorNoDiagnostic: | ||||||||
1910 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1910); | ||||||||
1911 | case LOLR_Error: | ||||||||
1912 | return ExprError(); | ||||||||
1913 | } | ||||||||
1914 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 1914); | ||||||||
1915 | } | ||||||||
1916 | |||||||||
1917 | DeclRefExpr * | ||||||||
1918 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1919 | SourceLocation Loc, | ||||||||
1920 | const CXXScopeSpec *SS) { | ||||||||
1921 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||||||
1922 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||||||
1923 | } | ||||||||
1924 | |||||||||
1925 | DeclRefExpr * | ||||||||
1926 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1927 | const DeclarationNameInfo &NameInfo, | ||||||||
1928 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||||||
1929 | SourceLocation TemplateKWLoc, | ||||||||
1930 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
1931 | NestedNameSpecifierLoc NNS = | ||||||||
1932 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||||||
1933 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||||||
1934 | TemplateArgs); | ||||||||
1935 | } | ||||||||
1936 | |||||||||
1937 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||||||
1938 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||||||
1939 | if (isUnevaluatedContext()) | ||||||||
1940 | return NOUR_Unevaluated; | ||||||||
1941 | |||||||||
1942 | // C++2a [basic.def.odr]p4: | ||||||||
1943 | // A variable x whose name appears as a potentially-evaluated expression e | ||||||||
1944 | // is odr-used by e unless [...] x is a reference that is usable in | ||||||||
1945 | // constant expressions. | ||||||||
1946 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||||
1947 | if (VD->getType()->isReferenceType() && | ||||||||
1948 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||||||
1949 | VD->isUsableInConstantExpressions(Context)) | ||||||||
1950 | return NOUR_Constant; | ||||||||
1951 | } | ||||||||
1952 | |||||||||
1953 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||||||
1954 | // need to wait and see how the expression is used. | ||||||||
1955 | return NOUR_None; | ||||||||
1956 | } | ||||||||
1957 | |||||||||
1958 | /// BuildDeclRefExpr - Build an expression that references a | ||||||||
1959 | /// declaration that does not require a closure capture. | ||||||||
1960 | DeclRefExpr * | ||||||||
1961 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||||||
1962 | const DeclarationNameInfo &NameInfo, | ||||||||
1963 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||||||
1964 | SourceLocation TemplateKWLoc, | ||||||||
1965 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
1966 | bool RefersToCapturedVariable = | ||||||||
1967 | isa<VarDecl>(D) && | ||||||||
1968 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | ||||||||
1969 | |||||||||
1970 | DeclRefExpr *E = DeclRefExpr::Create( | ||||||||
1971 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||||||
1972 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||||||
1973 | MarkDeclRefReferenced(E); | ||||||||
1974 | |||||||||
1975 | // C++ [except.spec]p17: | ||||||||
1976 | // An exception-specification is considered to be needed when: | ||||||||
1977 | // - in an expression, the function is the unique lookup result or | ||||||||
1978 | // the selected member of a set of overloaded functions. | ||||||||
1979 | // | ||||||||
1980 | // We delay doing this until after we've built the function reference and | ||||||||
1981 | // marked it as used so that: | ||||||||
1982 | // a) if the function is defaulted, we get errors from defining it before / | ||||||||
1983 | // instead of errors from computing its exception specification, and | ||||||||
1984 | // b) if the function is a defaulted comparison, we can use the body we | ||||||||
1985 | // build when defining it as input to the exception specification | ||||||||
1986 | // computation rather than computing a new body. | ||||||||
1987 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||||||
1988 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||||||
1989 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||||||
1990 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||||||
1991 | } | ||||||||
1992 | } | ||||||||
1993 | |||||||||
1994 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||||||
1995 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||||||
1996 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||||||
1997 | getCurFunction()->recordUseOfWeak(E); | ||||||||
1998 | |||||||||
1999 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||||||
2000 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||||||
2001 | FD = IFD->getAnonField(); | ||||||||
2002 | if (FD) { | ||||||||
2003 | UnusedPrivateFields.remove(FD); | ||||||||
2004 | // Just in case we're building an illegal pointer-to-member. | ||||||||
2005 | if (FD->isBitField()) | ||||||||
2006 | E->setObjectKind(OK_BitField); | ||||||||
2007 | } | ||||||||
2008 | |||||||||
2009 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||||||
2010 | // designates a bit-field. | ||||||||
2011 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||||||
2012 | if (auto *BE = BD->getBinding()) | ||||||||
2013 | E->setObjectKind(BE->getObjectKind()); | ||||||||
2014 | |||||||||
2015 | return E; | ||||||||
2016 | } | ||||||||
2017 | |||||||||
2018 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||||||
2019 | /// possibly a list of template arguments. | ||||||||
2020 | /// | ||||||||
2021 | /// If this produces template arguments, it is permitted to call | ||||||||
2022 | /// DecomposeTemplateName. | ||||||||
2023 | /// | ||||||||
2024 | /// This actually loses a lot of source location information for | ||||||||
2025 | /// non-standard name kinds; we should consider preserving that in | ||||||||
2026 | /// some way. | ||||||||
2027 | void | ||||||||
2028 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||||||
2029 | TemplateArgumentListInfo &Buffer, | ||||||||
2030 | DeclarationNameInfo &NameInfo, | ||||||||
2031 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||||||
2032 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||||
2033 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||||||
2034 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||||||
2035 | |||||||||
2036 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||||||
2037 | Id.TemplateId->NumArgs); | ||||||||
2038 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||||||
2039 | |||||||||
2040 | TemplateName TName = Id.TemplateId->Template.get(); | ||||||||
2041 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||||||
2042 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||||||
2043 | TemplateArgs = &Buffer; | ||||||||
2044 | } else { | ||||||||
2045 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||||||
2046 | TemplateArgs = nullptr; | ||||||||
2047 | } | ||||||||
2048 | } | ||||||||
2049 | |||||||||
2050 | static void emitEmptyLookupTypoDiagnostic( | ||||||||
2051 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||||||
2052 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||||||
2053 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||||||
2054 | DeclContext *Ctx = | ||||||||
2055 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||||||
2056 | if (!TC) { | ||||||||
2057 | // Emit a special diagnostic for failed member lookups. | ||||||||
2058 | // FIXME: computing the declaration context might fail here (?) | ||||||||
2059 | if (Ctx) | ||||||||
2060 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||||||
2061 | << SS.getRange(); | ||||||||
2062 | else | ||||||||
2063 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||||||
2064 | return; | ||||||||
2065 | } | ||||||||
2066 | |||||||||
2067 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||||||
2068 | bool DroppedSpecifier = | ||||||||
2069 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||||||
2070 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||||||
2071 | ? diag::note_implicit_param_decl | ||||||||
2072 | : diag::note_previous_decl; | ||||||||
2073 | if (!Ctx) | ||||||||
2074 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||||||
2075 | SemaRef.PDiag(NoteID)); | ||||||||
2076 | else | ||||||||
2077 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||||||
2078 | << Typo << Ctx << DroppedSpecifier | ||||||||
2079 | << SS.getRange(), | ||||||||
2080 | SemaRef.PDiag(NoteID)); | ||||||||
2081 | } | ||||||||
2082 | |||||||||
2083 | /// Diagnose an empty lookup. | ||||||||
2084 | /// | ||||||||
2085 | /// \return false if new lookup candidates were found | ||||||||
2086 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||||||
2087 | CorrectionCandidateCallback &CCC, | ||||||||
2088 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||||||
2089 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||||||
2090 | DeclarationName Name = R.getLookupName(); | ||||||||
2091 | |||||||||
2092 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||||||
2093 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||||||
2094 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||||||
2095 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||||||
2096 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||||||
2097 | diagnostic = diag::err_undeclared_use; | ||||||||
2098 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||||||
2099 | } | ||||||||
2100 | |||||||||
2101 | // If the original lookup was an unqualified lookup, fake an | ||||||||
2102 | // unqualified lookup. This is useful when (for example) the | ||||||||
2103 | // original lookup would not have found something because it was a | ||||||||
2104 | // dependent name. | ||||||||
2105 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||||||
2106 | while (DC) { | ||||||||
2107 | if (isa<CXXRecordDecl>(DC)) { | ||||||||
2108 | LookupQualifiedName(R, DC); | ||||||||
2109 | |||||||||
2110 | if (!R.empty()) { | ||||||||
2111 | // Don't give errors about ambiguities in this lookup. | ||||||||
2112 | R.suppressDiagnostics(); | ||||||||
2113 | |||||||||
2114 | // During a default argument instantiation the CurContext points | ||||||||
2115 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||||||
2116 | // function parameter list, hence add an explicit check. | ||||||||
2117 | bool isDefaultArgument = | ||||||||
2118 | !CodeSynthesisContexts.empty() && | ||||||||
2119 | CodeSynthesisContexts.back().Kind == | ||||||||
2120 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||||||
2121 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||||||
2122 | bool isInstance = CurMethod && | ||||||||
2123 | CurMethod->isInstance() && | ||||||||
2124 | DC == CurMethod->getParent() && !isDefaultArgument; | ||||||||
2125 | |||||||||
2126 | // Give a code modification hint to insert 'this->'. | ||||||||
2127 | // TODO: fixit for inserting 'Base<T>::' in the other cases. | ||||||||
2128 | // Actually quite difficult! | ||||||||
2129 | if (getLangOpts().MSVCCompat) | ||||||||
2130 | diagnostic = diag::ext_found_via_dependent_bases_lookup; | ||||||||
2131 | if (isInstance) { | ||||||||
2132 | Diag(R.getNameLoc(), diagnostic) << Name | ||||||||
2133 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||||||
2134 | CheckCXXThisCapture(R.getNameLoc()); | ||||||||
2135 | } else { | ||||||||
2136 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||||||
2137 | } | ||||||||
2138 | |||||||||
2139 | // Do we really want to note all of these? | ||||||||
2140 | for (NamedDecl *D : R) | ||||||||
2141 | Diag(D->getLocation(), diag::note_dependent_var_use); | ||||||||
2142 | |||||||||
2143 | // Return true if we are inside a default argument instantiation | ||||||||
2144 | // and the found name refers to an instance member function, otherwise | ||||||||
2145 | // the function calling DiagnoseEmptyLookup will try to create an | ||||||||
2146 | // implicit member call and this is wrong for default argument. | ||||||||
2147 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||||||
2148 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||||||
2149 | return true; | ||||||||
2150 | } | ||||||||
2151 | |||||||||
2152 | // Tell the callee to try to recover. | ||||||||
2153 | return false; | ||||||||
2154 | } | ||||||||
2155 | |||||||||
2156 | R.clear(); | ||||||||
2157 | } | ||||||||
2158 | |||||||||
2159 | DC = DC->getLookupParent(); | ||||||||
2160 | } | ||||||||
2161 | |||||||||
2162 | // We didn't find anything, so try to correct for a typo. | ||||||||
2163 | TypoCorrection Corrected; | ||||||||
2164 | if (S && Out) { | ||||||||
2165 | SourceLocation TypoLoc = R.getNameLoc(); | ||||||||
2166 | assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2167, __PRETTY_FUNCTION__)) | ||||||||
2167 | "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2167, __PRETTY_FUNCTION__)); | ||||||||
2168 | *Out = CorrectTypoDelayed( | ||||||||
2169 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||||||
2170 | [=](const TypoCorrection &TC) { | ||||||||
2171 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||||||
2172 | diagnostic, diagnostic_suggest); | ||||||||
2173 | }, | ||||||||
2174 | nullptr, CTK_ErrorRecovery); | ||||||||
2175 | if (*Out) | ||||||||
2176 | return true; | ||||||||
2177 | } else if (S && | ||||||||
2178 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||||||
2179 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||||||
2180 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||||
2181 | bool DroppedSpecifier = | ||||||||
2182 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||||||
2183 | R.setLookupName(Corrected.getCorrection()); | ||||||||
2184 | |||||||||
2185 | bool AcceptableWithRecovery = false; | ||||||||
2186 | bool AcceptableWithoutRecovery = false; | ||||||||
2187 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||||||
2188 | if (ND) { | ||||||||
2189 | if (Corrected.isOverloaded()) { | ||||||||
2190 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||||||
2191 | OverloadCandidateSet::CSK_Normal); | ||||||||
2192 | OverloadCandidateSet::iterator Best; | ||||||||
2193 | for (NamedDecl *CD : Corrected) { | ||||||||
2194 | if (FunctionTemplateDecl *FTD = | ||||||||
2195 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||||||
2196 | AddTemplateOverloadCandidate( | ||||||||
2197 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||||||
2198 | Args, OCS); | ||||||||
2199 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||||||
2200 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||||||
2201 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||||||
2202 | Args, OCS); | ||||||||
2203 | } | ||||||||
2204 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||||||
2205 | case OR_Success: | ||||||||
2206 | ND = Best->FoundDecl; | ||||||||
2207 | Corrected.setCorrectionDecl(ND); | ||||||||
2208 | break; | ||||||||
2209 | default: | ||||||||
2210 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||||||
2211 | Corrected.setCorrectionDecl(ND); | ||||||||
2212 | break; | ||||||||
2213 | } | ||||||||
2214 | } | ||||||||
2215 | R.addDecl(ND); | ||||||||
2216 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||||||
2217 | CXXRecordDecl *Record = nullptr; | ||||||||
2218 | if (Corrected.getCorrectionSpecifier()) { | ||||||||
2219 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||||||
2220 | Record = Ty->getAsCXXRecordDecl(); | ||||||||
2221 | } | ||||||||
2222 | if (!Record) | ||||||||
2223 | Record = cast<CXXRecordDecl>( | ||||||||
2224 | ND->getDeclContext()->getRedeclContext()); | ||||||||
2225 | R.setNamingClass(Record); | ||||||||
2226 | } | ||||||||
2227 | |||||||||
2228 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||||||
2229 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||||||
2230 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||||||
2231 | // FIXME: If we ended up with a typo for a type name or | ||||||||
2232 | // Objective-C class name, we're in trouble because the parser | ||||||||
2233 | // is in the wrong place to recover. Suggest the typo | ||||||||
2234 | // correction, but don't make it a fix-it since we're not going | ||||||||
2235 | // to recover well anyway. | ||||||||
2236 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||||||
2237 | getAsTypeTemplateDecl(UnderlyingND) || | ||||||||
2238 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||||||
2239 | } else { | ||||||||
2240 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||||||
2241 | // because we aren't able to recover. | ||||||||
2242 | AcceptableWithoutRecovery = true; | ||||||||
2243 | } | ||||||||
2244 | |||||||||
2245 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||||||
2246 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||||||
2247 | ? diag::note_implicit_param_decl | ||||||||
2248 | : diag::note_previous_decl; | ||||||||
2249 | if (SS.isEmpty()) | ||||||||
2250 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||||||
2251 | PDiag(NoteID), AcceptableWithRecovery); | ||||||||
2252 | else | ||||||||
2253 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||||||
2254 | << Name << computeDeclContext(SS, false) | ||||||||
2255 | << DroppedSpecifier << SS.getRange(), | ||||||||
2256 | PDiag(NoteID), AcceptableWithRecovery); | ||||||||
2257 | |||||||||
2258 | // Tell the callee whether to try to recover. | ||||||||
2259 | return !AcceptableWithRecovery; | ||||||||
2260 | } | ||||||||
2261 | } | ||||||||
2262 | R.clear(); | ||||||||
2263 | |||||||||
2264 | // Emit a special diagnostic for failed member lookups. | ||||||||
2265 | // FIXME: computing the declaration context might fail here (?) | ||||||||
2266 | if (!SS.isEmpty()) { | ||||||||
2267 | Diag(R.getNameLoc(), diag::err_no_member) | ||||||||
2268 | << Name << computeDeclContext(SS, false) | ||||||||
2269 | << SS.getRange(); | ||||||||
2270 | return true; | ||||||||
2271 | } | ||||||||
2272 | |||||||||
2273 | // Give up, we can't recover. | ||||||||
2274 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||||||
2275 | return true; | ||||||||
2276 | } | ||||||||
2277 | |||||||||
2278 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||||||
2279 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||||||
2280 | /// assume the identifier is a member of a dependent base class. We can only | ||||||||
2281 | /// recover successfully in static methods, instance methods, and other contexts | ||||||||
2282 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||||||
2283 | /// instantiation model, but it's close enough. | ||||||||
2284 | static Expr * | ||||||||
2285 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||||||
2286 | DeclarationNameInfo &NameInfo, | ||||||||
2287 | SourceLocation TemplateKWLoc, | ||||||||
2288 | const TemplateArgumentListInfo *TemplateArgs) { | ||||||||
2289 | // Only try to recover from lookup into dependent bases in static methods or | ||||||||
2290 | // contexts where 'this' is available. | ||||||||
2291 | QualType ThisType = S.getCurrentThisType(); | ||||||||
2292 | const CXXRecordDecl *RD = nullptr; | ||||||||
2293 | if (!ThisType.isNull()) | ||||||||
2294 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||||||
2295 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||||||
2296 | RD = MD->getParent(); | ||||||||
2297 | if (!RD || !RD->hasAnyDependentBases()) | ||||||||
2298 | return nullptr; | ||||||||
2299 | |||||||||
2300 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||||||
2301 | // is available, suggest inserting 'this->' as a fixit. | ||||||||
2302 | SourceLocation Loc = NameInfo.getLoc(); | ||||||||
2303 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||||||
2304 | DB << NameInfo.getName() << RD; | ||||||||
2305 | |||||||||
2306 | if (!ThisType.isNull()) { | ||||||||
2307 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||||||
2308 | return CXXDependentScopeMemberExpr::Create( | ||||||||
2309 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||||||
2310 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||||||
2311 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||||||
2312 | } | ||||||||
2313 | |||||||||
2314 | // Synthesize a fake NNS that points to the derived class. This will | ||||||||
2315 | // perform name lookup during template instantiation. | ||||||||
2316 | CXXScopeSpec SS; | ||||||||
2317 | auto *NNS = | ||||||||
2318 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||||||
2319 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||||||
2320 | return DependentScopeDeclRefExpr::Create( | ||||||||
2321 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||||||
2322 | TemplateArgs); | ||||||||
2323 | } | ||||||||
2324 | |||||||||
2325 | ExprResult | ||||||||
2326 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||||||
2327 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||||||
2328 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||||||
2329 | CorrectionCandidateCallback *CCC, | ||||||||
2330 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||||||
2331 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2332, __PRETTY_FUNCTION__)) | ||||||||
2332 | "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2332, __PRETTY_FUNCTION__)); | ||||||||
2333 | if (SS.isInvalid()) | ||||||||
2334 | return ExprError(); | ||||||||
2335 | |||||||||
2336 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||||||
2337 | |||||||||
2338 | // Decompose the UnqualifiedId into the following data. | ||||||||
2339 | DeclarationNameInfo NameInfo; | ||||||||
2340 | const TemplateArgumentListInfo *TemplateArgs; | ||||||||
2341 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||||||
2342 | |||||||||
2343 | DeclarationName Name = NameInfo.getName(); | ||||||||
2344 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||||
2345 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||||||
2346 | |||||||||
2347 | if (II && II->isEditorPlaceholder()) { | ||||||||
2348 | // FIXME: When typed placeholders are supported we can create a typed | ||||||||
2349 | // placeholder expression node. | ||||||||
2350 | return ExprError(); | ||||||||
2351 | } | ||||||||
2352 | |||||||||
2353 | // C++ [temp.dep.expr]p3: | ||||||||
2354 | // An id-expression is type-dependent if it contains: | ||||||||
2355 | // -- an identifier that was declared with a dependent type, | ||||||||
2356 | // (note: handled after lookup) | ||||||||
2357 | // -- a template-id that is dependent, | ||||||||
2358 | // (note: handled in BuildTemplateIdExpr) | ||||||||
2359 | // -- a conversion-function-id that specifies a dependent type, | ||||||||
2360 | // -- a nested-name-specifier that contains a class-name that | ||||||||
2361 | // names a dependent type. | ||||||||
2362 | // Determine whether this is a member of an unknown specialization; | ||||||||
2363 | // we need to handle these differently. | ||||||||
2364 | bool DependentID = false; | ||||||||
2365 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||||||
2366 | Name.getCXXNameType()->isDependentType()) { | ||||||||
2367 | DependentID = true; | ||||||||
2368 | } else if (SS.isSet()) { | ||||||||
2369 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||||||
2370 | if (RequireCompleteDeclContext(SS, DC)) | ||||||||
2371 | return ExprError(); | ||||||||
2372 | } else { | ||||||||
2373 | DependentID = true; | ||||||||
2374 | } | ||||||||
2375 | } | ||||||||
2376 | |||||||||
2377 | if (DependentID) | ||||||||
2378 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2379 | IsAddressOfOperand, TemplateArgs); | ||||||||
2380 | |||||||||
2381 | // Perform the required lookup. | ||||||||
2382 | LookupResult R(*this, NameInfo, | ||||||||
2383 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||||||
2384 | ? LookupObjCImplicitSelfParam | ||||||||
2385 | : LookupOrdinaryName); | ||||||||
2386 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||||||
2387 | // Lookup the template name again to correctly establish the context in | ||||||||
2388 | // which it was found. This is really unfortunate as we already did the | ||||||||
2389 | // lookup to determine that it was a template name in the first place. If | ||||||||
2390 | // this becomes a performance hit, we can work harder to preserve those | ||||||||
2391 | // results until we get here but it's likely not worth it. | ||||||||
2392 | bool MemberOfUnknownSpecialization; | ||||||||
2393 | AssumedTemplateKind AssumedTemplate; | ||||||||
2394 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||||||
2395 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||||||
2396 | &AssumedTemplate)) | ||||||||
2397 | return ExprError(); | ||||||||
2398 | |||||||||
2399 | if (MemberOfUnknownSpecialization || | ||||||||
2400 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||||||
2401 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2402 | IsAddressOfOperand, TemplateArgs); | ||||||||
2403 | } else { | ||||||||
2404 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||||||
2405 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||||||
2406 | |||||||||
2407 | // If the result might be in a dependent base class, this is a dependent | ||||||||
2408 | // id-expression. | ||||||||
2409 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||||||
2410 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||||||
2411 | IsAddressOfOperand, TemplateArgs); | ||||||||
2412 | |||||||||
2413 | // If this reference is in an Objective-C method, then we need to do | ||||||||
2414 | // some special Objective-C lookup, too. | ||||||||
2415 | if (IvarLookupFollowUp) { | ||||||||
2416 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||||||
2417 | if (E.isInvalid()) | ||||||||
2418 | return ExprError(); | ||||||||
2419 | |||||||||
2420 | if (Expr *Ex = E.getAs<Expr>()) | ||||||||
2421 | return Ex; | ||||||||
2422 | } | ||||||||
2423 | } | ||||||||
2424 | |||||||||
2425 | if (R.isAmbiguous()) | ||||||||
2426 | return ExprError(); | ||||||||
2427 | |||||||||
2428 | // This could be an implicitly declared function reference (legal in C90, | ||||||||
2429 | // extension in C99, forbidden in C++). | ||||||||
2430 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | ||||||||
2431 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||||||
2432 | if (D) R.addDecl(D); | ||||||||
2433 | } | ||||||||
2434 | |||||||||
2435 | // Determine whether this name might be a candidate for | ||||||||
2436 | // argument-dependent lookup. | ||||||||
2437 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||||||
2438 | |||||||||
2439 | if (R.empty() && !ADL) { | ||||||||
2440 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||||||
2441 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||||||
2442 | TemplateKWLoc, TemplateArgs)) | ||||||||
2443 | return E; | ||||||||
2444 | } | ||||||||
2445 | |||||||||
2446 | // Don't diagnose an empty lookup for inline assembly. | ||||||||
2447 | if (IsInlineAsmIdentifier) | ||||||||
2448 | return ExprError(); | ||||||||
2449 | |||||||||
2450 | // If this name wasn't predeclared and if this is not a function | ||||||||
2451 | // call, diagnose the problem. | ||||||||
2452 | TypoExpr *TE = nullptr; | ||||||||
2453 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||||||
2454 | : nullptr); | ||||||||
2455 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||||||
2456 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2457, __PRETTY_FUNCTION__)) | ||||||||
2457 | "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2457, __PRETTY_FUNCTION__)); | ||||||||
2458 | if (CCC) { | ||||||||
2459 | // Make sure the callback knows what the typo being diagnosed is. | ||||||||
2460 | CCC->setTypoName(II); | ||||||||
2461 | if (SS.isValid()) | ||||||||
2462 | CCC->setTypoNNS(SS.getScopeRep()); | ||||||||
2463 | } | ||||||||
2464 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||||||
2465 | // a template name, but we happen to have always already looked up the name | ||||||||
2466 | // before we get here if it must be a template name. | ||||||||
2467 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||||||
2468 | None, &TE)) { | ||||||||
2469 | if (TE && KeywordReplacement) { | ||||||||
2470 | auto &State = getTypoExprState(TE); | ||||||||
2471 | auto BestTC = State.Consumer->getNextCorrection(); | ||||||||
2472 | if (BestTC.isKeyword()) { | ||||||||
2473 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||||||
2474 | if (State.DiagHandler) | ||||||||
2475 | State.DiagHandler(BestTC); | ||||||||
2476 | KeywordReplacement->startToken(); | ||||||||
2477 | KeywordReplacement->setKind(II->getTokenID()); | ||||||||
2478 | KeywordReplacement->setIdentifierInfo(II); | ||||||||
2479 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||||||
2480 | // Clean up the state associated with the TypoExpr, since it has | ||||||||
2481 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||||||
2482 | clearDelayedTypo(TE); | ||||||||
2483 | // Signal that a correction to a keyword was performed by returning a | ||||||||
2484 | // valid-but-null ExprResult. | ||||||||
2485 | return (Expr*)nullptr; | ||||||||
2486 | } | ||||||||
2487 | State.Consumer->resetCorrectionStream(); | ||||||||
2488 | } | ||||||||
2489 | return TE ? TE : ExprError(); | ||||||||
2490 | } | ||||||||
2491 | |||||||||
2492 | assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2493, __PRETTY_FUNCTION__)) | ||||||||
2493 | "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2493, __PRETTY_FUNCTION__)); | ||||||||
2494 | |||||||||
2495 | // If we found an Objective-C instance variable, let | ||||||||
2496 | // LookupInObjCMethod build the appropriate expression to | ||||||||
2497 | // reference the ivar. | ||||||||
2498 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||||||
2499 | R.clear(); | ||||||||
2500 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||||||
2501 | // In a hopelessly buggy code, Objective-C instance variable | ||||||||
2502 | // lookup fails and no expression will be built to reference it. | ||||||||
2503 | if (!E.isInvalid() && !E.get()) | ||||||||
2504 | return ExprError(); | ||||||||
2505 | return E; | ||||||||
2506 | } | ||||||||
2507 | } | ||||||||
2508 | |||||||||
2509 | // This is guaranteed from this point on. | ||||||||
2510 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2510, __PRETTY_FUNCTION__)); | ||||||||
2511 | |||||||||
2512 | // Check whether this might be a C++ implicit instance member access. | ||||||||
2513 | // C++ [class.mfct.non-static]p3: | ||||||||
2514 | // When an id-expression that is not part of a class member access | ||||||||
2515 | // syntax and not used to form a pointer to member is used in the | ||||||||
2516 | // body of a non-static member function of class X, if name lookup | ||||||||
2517 | // resolves the name in the id-expression to a non-static non-type | ||||||||
2518 | // member of some class C, the id-expression is transformed into a | ||||||||
2519 | // class member access expression using (*this) as the | ||||||||
2520 | // postfix-expression to the left of the . operator. | ||||||||
2521 | // | ||||||||
2522 | // But we don't actually need to do this for '&' operands if R | ||||||||
2523 | // resolved to a function or overloaded function set, because the | ||||||||
2524 | // expression is ill-formed if it actually works out to be a | ||||||||
2525 | // non-static member function: | ||||||||
2526 | // | ||||||||
2527 | // C++ [expr.ref]p4: | ||||||||
2528 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||||||
2529 | // [t]he expression can be used only as the left-hand operand of a | ||||||||
2530 | // member function call. | ||||||||
2531 | // | ||||||||
2532 | // There are other safeguards against such uses, but it's important | ||||||||
2533 | // to get this right here so that we don't end up making a | ||||||||
2534 | // spuriously dependent expression if we're inside a dependent | ||||||||
2535 | // instance method. | ||||||||
2536 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||||||
2537 | bool MightBeImplicitMember; | ||||||||
2538 | if (!IsAddressOfOperand) | ||||||||
2539 | MightBeImplicitMember = true; | ||||||||
2540 | else if (!SS.isEmpty()) | ||||||||
2541 | MightBeImplicitMember = false; | ||||||||
2542 | else if (R.isOverloadedResult()) | ||||||||
2543 | MightBeImplicitMember = false; | ||||||||
2544 | else if (R.isUnresolvableResult()) | ||||||||
2545 | MightBeImplicitMember = true; | ||||||||
2546 | else | ||||||||
2547 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||||||
2548 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||||||
2549 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||||||
2550 | |||||||||
2551 | if (MightBeImplicitMember) | ||||||||
2552 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||||||
2553 | R, TemplateArgs, S); | ||||||||
2554 | } | ||||||||
2555 | |||||||||
2556 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||||||
2557 | |||||||||
2558 | // In C++1y, if this is a variable template id, then check it | ||||||||
2559 | // in BuildTemplateIdExpr(). | ||||||||
2560 | // The single lookup result must be a variable template declaration. | ||||||||
2561 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||||||
2562 | Id.TemplateId->Kind == TNK_Var_template) { | ||||||||
2563 | assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2564, __PRETTY_FUNCTION__)) | ||||||||
2564 | "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2564, __PRETTY_FUNCTION__)); | ||||||||
2565 | } | ||||||||
2566 | |||||||||
2567 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||||||
2568 | } | ||||||||
2569 | |||||||||
2570 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||||||
2571 | } | ||||||||
2572 | |||||||||
2573 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||||||
2574 | /// declaration name, generally during template instantiation. | ||||||||
2575 | /// There's a large number of things which don't need to be done along | ||||||||
2576 | /// this path. | ||||||||
2577 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||||||
2578 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||||||
2579 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||||||
2580 | DeclContext *DC = computeDeclContext(SS, false); | ||||||||
2581 | if (!DC) | ||||||||
2582 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2583 | NameInfo, /*TemplateArgs=*/nullptr); | ||||||||
2584 | |||||||||
2585 | if (RequireCompleteDeclContext(SS, DC)) | ||||||||
2586 | return ExprError(); | ||||||||
2587 | |||||||||
2588 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||||||
2589 | LookupQualifiedName(R, DC); | ||||||||
2590 | |||||||||
2591 | if (R.isAmbiguous()) | ||||||||
2592 | return ExprError(); | ||||||||
2593 | |||||||||
2594 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||||||
2595 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2596 | NameInfo, /*TemplateArgs=*/nullptr); | ||||||||
2597 | |||||||||
2598 | if (R.empty()) { | ||||||||
2599 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||||||
2600 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||||||
2601 | // is invalid because it's derived from an invalid base class, then missing | ||||||||
2602 | // members were likely supposed to be inherited. | ||||||||
2603 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||||||
2604 | if (CD->isInvalidDecl()) | ||||||||
2605 | return ExprError(); | ||||||||
2606 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||||||
2607 | << NameInfo.getName() << DC << SS.getRange(); | ||||||||
2608 | return ExprError(); | ||||||||
2609 | } | ||||||||
2610 | |||||||||
2611 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||||||
2612 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||||||
2613 | // a dependent context. If we can recover with a type, downgrade this to | ||||||||
2614 | // a warning in Microsoft compatibility mode. | ||||||||
2615 | unsigned DiagID = diag::err_typename_missing; | ||||||||
2616 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||||||
2617 | DiagID = diag::ext_typename_missing; | ||||||||
2618 | SourceLocation Loc = SS.getBeginLoc(); | ||||||||
2619 | auto D = Diag(Loc, DiagID); | ||||||||
2620 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||||||
2621 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||||||
2622 | |||||||||
2623 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||||||
2624 | // context. | ||||||||
2625 | if (!RecoveryTSI) | ||||||||
2626 | return ExprError(); | ||||||||
2627 | |||||||||
2628 | // Only issue the fixit if we're prepared to recover. | ||||||||
2629 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||||||
2630 | |||||||||
2631 | // Recover by pretending this was an elaborated type. | ||||||||
2632 | QualType Ty = Context.getTypeDeclType(TD); | ||||||||
2633 | TypeLocBuilder TLB; | ||||||||
2634 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||||||
2635 | |||||||||
2636 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||||||
2637 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||||||
2638 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||||
2639 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||||
2640 | |||||||||
2641 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||||||
2642 | |||||||||
2643 | return ExprEmpty(); | ||||||||
2644 | } | ||||||||
2645 | |||||||||
2646 | // Defend against this resolving to an implicit member access. We usually | ||||||||
2647 | // won't get here if this might be a legitimate a class member (we end up in | ||||||||
2648 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||||||
2649 | // a pointer-to-member or in an unevaluated context in C++11. | ||||||||
2650 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||||||
2651 | return BuildPossibleImplicitMemberExpr(SS, | ||||||||
2652 | /*TemplateKWLoc=*/SourceLocation(), | ||||||||
2653 | R, /*TemplateArgs=*/nullptr, S); | ||||||||
2654 | |||||||||
2655 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||||||
2656 | } | ||||||||
2657 | |||||||||
2658 | /// The parser has read a name in, and Sema has detected that we're currently | ||||||||
2659 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||||||
2660 | /// should form a reference to an ivar. | ||||||||
2661 | /// | ||||||||
2662 | /// Ideally, most of this would be done by lookup, but there's | ||||||||
2663 | /// actually quite a lot of extra work involved. | ||||||||
2664 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||||||
2665 | IdentifierInfo *II) { | ||||||||
2666 | SourceLocation Loc = Lookup.getNameLoc(); | ||||||||
2667 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||||
2668 | |||||||||
2669 | // Check for error condition which is already reported. | ||||||||
2670 | if (!CurMethod) | ||||||||
2671 | return DeclResult(true); | ||||||||
2672 | |||||||||
2673 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||||||
2674 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||||||
2675 | // found a decl, but that decl is outside the current instance method (i.e. | ||||||||
2676 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||||||
2677 | // this name, if the lookup sucedes, we replace it our current decl. | ||||||||
2678 | |||||||||
2679 | // If we're in a class method, we don't normally want to look for | ||||||||
2680 | // ivars. But if we don't find anything else, and there's an | ||||||||
2681 | // ivar, that's an error. | ||||||||
2682 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||||||
2683 | |||||||||
2684 | bool LookForIvars; | ||||||||
2685 | if (Lookup.empty()) | ||||||||
2686 | LookForIvars = true; | ||||||||
2687 | else if (IsClassMethod) | ||||||||
2688 | LookForIvars = false; | ||||||||
2689 | else | ||||||||
2690 | LookForIvars = (Lookup.isSingleResult() && | ||||||||
2691 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||||||
2692 | ObjCInterfaceDecl *IFace = nullptr; | ||||||||
2693 | if (LookForIvars) { | ||||||||
2694 | IFace = CurMethod->getClassInterface(); | ||||||||
2695 | ObjCInterfaceDecl *ClassDeclared; | ||||||||
2696 | ObjCIvarDecl *IV = nullptr; | ||||||||
2697 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||||||
2698 | // Diagnose using an ivar in a class method. | ||||||||
2699 | if (IsClassMethod) { | ||||||||
2700 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||||||
2701 | return DeclResult(true); | ||||||||
2702 | } | ||||||||
2703 | |||||||||
2704 | // Diagnose the use of an ivar outside of the declaring class. | ||||||||
2705 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||||||
2706 | !declaresSameEntity(ClassDeclared, IFace) && | ||||||||
2707 | !getLangOpts().DebuggerSupport) | ||||||||
2708 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||||||
2709 | |||||||||
2710 | // Success. | ||||||||
2711 | return IV; | ||||||||
2712 | } | ||||||||
2713 | } else if (CurMethod->isInstanceMethod()) { | ||||||||
2714 | // We should warn if a local variable hides an ivar. | ||||||||
2715 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||||||
2716 | ObjCInterfaceDecl *ClassDeclared; | ||||||||
2717 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||||||
2718 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||||||
2719 | declaresSameEntity(IFace, ClassDeclared)) | ||||||||
2720 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||||||
2721 | } | ||||||||
2722 | } | ||||||||
2723 | } else if (Lookup.isSingleResult() && | ||||||||
2724 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||||||
2725 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||||||
2726 | if (const ObjCIvarDecl *IV = | ||||||||
2727 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||||||
2728 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||||||
2729 | return DeclResult(true); | ||||||||
2730 | } | ||||||||
2731 | } | ||||||||
2732 | |||||||||
2733 | // Didn't encounter an error, didn't find an ivar. | ||||||||
2734 | return DeclResult(false); | ||||||||
2735 | } | ||||||||
2736 | |||||||||
2737 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||||||
2738 | ObjCIvarDecl *IV) { | ||||||||
2739 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||||
2740 | assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2741, __PRETTY_FUNCTION__)) | ||||||||
2741 | "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2741, __PRETTY_FUNCTION__)); | ||||||||
2742 | |||||||||
2743 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||||||
2744 | assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context" ) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2744, __PRETTY_FUNCTION__)); | ||||||||
2745 | |||||||||
2746 | // If we're referencing an invalid decl, just return this as a silent | ||||||||
2747 | // error node. The error diagnostic was already emitted on the decl. | ||||||||
2748 | if (IV->isInvalidDecl()) | ||||||||
2749 | return ExprError(); | ||||||||
2750 | |||||||||
2751 | // Check if referencing a field with __attribute__((deprecated)). | ||||||||
2752 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||||||
2753 | return ExprError(); | ||||||||
2754 | |||||||||
2755 | // FIXME: This should use a new expr for a direct reference, don't | ||||||||
2756 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||||||
2757 | IdentifierInfo &II = Context.Idents.get("self"); | ||||||||
2758 | UnqualifiedId SelfName; | ||||||||
2759 | SelfName.setIdentifier(&II, SourceLocation()); | ||||||||
2760 | SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); | ||||||||
2761 | CXXScopeSpec SelfScopeSpec; | ||||||||
2762 | SourceLocation TemplateKWLoc; | ||||||||
2763 | ExprResult SelfExpr = | ||||||||
2764 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||||||
2765 | /*HasTrailingLParen=*/false, | ||||||||
2766 | /*IsAddressOfOperand=*/false); | ||||||||
2767 | if (SelfExpr.isInvalid()) | ||||||||
2768 | return ExprError(); | ||||||||
2769 | |||||||||
2770 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||||||
2771 | if (SelfExpr.isInvalid()) | ||||||||
2772 | return ExprError(); | ||||||||
2773 | |||||||||
2774 | MarkAnyDeclReferenced(Loc, IV, true); | ||||||||
2775 | |||||||||
2776 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||||||
2777 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||||||
2778 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||||||
2779 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||||||
2780 | |||||||||
2781 | ObjCIvarRefExpr *Result = new (Context) | ||||||||
2782 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||||||
2783 | IV->getLocation(), SelfExpr.get(), true, true); | ||||||||
2784 | |||||||||
2785 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||||||
2786 | if (!isUnevaluatedContext() && | ||||||||
2787 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||||||
2788 | getCurFunction()->recordUseOfWeak(Result); | ||||||||
2789 | } | ||||||||
2790 | if (getLangOpts().ObjCAutoRefCount) | ||||||||
2791 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||||||
2792 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||||||
2793 | |||||||||
2794 | return Result; | ||||||||
2795 | } | ||||||||
2796 | |||||||||
2797 | /// The parser has read a name in, and Sema has detected that we're currently | ||||||||
2798 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||||||
2799 | /// should form a reference to an ivar. If so, build an expression referencing | ||||||||
2800 | /// that ivar. | ||||||||
2801 | ExprResult | ||||||||
2802 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||||||
2803 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||||||
2804 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||||||
2805 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||||||
2806 | if (Ivar.isInvalid()) | ||||||||
2807 | return ExprError(); | ||||||||
2808 | if (Ivar.isUsable()) | ||||||||
2809 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||||||
2810 | cast<ObjCIvarDecl>(Ivar.get())); | ||||||||
2811 | |||||||||
2812 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||||||
2813 | LookupBuiltin(Lookup); | ||||||||
2814 | |||||||||
2815 | // Sentinel value saying that we didn't do anything special. | ||||||||
2816 | return ExprResult(false); | ||||||||
2817 | } | ||||||||
2818 | |||||||||
2819 | /// Cast a base object to a member's actual type. | ||||||||
2820 | /// | ||||||||
2821 | /// Logically this happens in three phases: | ||||||||
2822 | /// | ||||||||
2823 | /// * First we cast from the base type to the naming class. | ||||||||
2824 | /// The naming class is the class into which we were looking | ||||||||
2825 | /// when we found the member; it's the qualifier type if a | ||||||||
2826 | /// qualifier was provided, and otherwise it's the base type. | ||||||||
2827 | /// | ||||||||
2828 | /// * Next we cast from the naming class to the declaring class. | ||||||||
2829 | /// If the member we found was brought into a class's scope by | ||||||||
2830 | /// a using declaration, this is that class; otherwise it's | ||||||||
2831 | /// the class declaring the member. | ||||||||
2832 | /// | ||||||||
2833 | /// * Finally we cast from the declaring class to the "true" | ||||||||
2834 | /// declaring class of the member. This conversion does not | ||||||||
2835 | /// obey access control. | ||||||||
2836 | ExprResult | ||||||||
2837 | Sema::PerformObjectMemberConversion(Expr *From, | ||||||||
2838 | NestedNameSpecifier *Qualifier, | ||||||||
2839 | NamedDecl *FoundDecl, | ||||||||
2840 | NamedDecl *Member) { | ||||||||
2841 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||||||
2842 | if (!RD) | ||||||||
2843 | return From; | ||||||||
2844 | |||||||||
2845 | QualType DestRecordType; | ||||||||
2846 | QualType DestType; | ||||||||
2847 | QualType FromRecordType; | ||||||||
2848 | QualType FromType = From->getType(); | ||||||||
2849 | bool PointerConversions = false; | ||||||||
2850 | if (isa<FieldDecl>(Member)) { | ||||||||
2851 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||||||
2852 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||||||
2853 | DestRecordType = Context.getAddrSpaceQualType( | ||||||||
2854 | DestRecordType, FromPtrType | ||||||||
2855 | ? FromType->getPointeeType().getAddressSpace() | ||||||||
2856 | : FromType.getAddressSpace()); | ||||||||
2857 | |||||||||
2858 | if (FromPtrType) { | ||||||||
2859 | DestType = Context.getPointerType(DestRecordType); | ||||||||
2860 | FromRecordType = FromPtrType->getPointeeType(); | ||||||||
2861 | PointerConversions = true; | ||||||||
2862 | } else { | ||||||||
2863 | DestType = DestRecordType; | ||||||||
2864 | FromRecordType = FromType; | ||||||||
2865 | } | ||||||||
2866 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||||||
2867 | if (Method->isStatic()) | ||||||||
2868 | return From; | ||||||||
2869 | |||||||||
2870 | DestType = Method->getThisType(); | ||||||||
2871 | DestRecordType = DestType->getPointeeType(); | ||||||||
2872 | |||||||||
2873 | if (FromType->getAs<PointerType>()) { | ||||||||
2874 | FromRecordType = FromType->getPointeeType(); | ||||||||
2875 | PointerConversions = true; | ||||||||
2876 | } else { | ||||||||
2877 | FromRecordType = FromType; | ||||||||
2878 | DestType = DestRecordType; | ||||||||
2879 | } | ||||||||
2880 | |||||||||
2881 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||||||
2882 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||||||
2883 | if (FromAS != DestAS) { | ||||||||
2884 | QualType FromRecordTypeWithoutAS = | ||||||||
2885 | Context.removeAddrSpaceQualType(FromRecordType); | ||||||||
2886 | QualType FromTypeWithDestAS = | ||||||||
2887 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||||||
2888 | if (PointerConversions) | ||||||||
2889 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||||||
2890 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||||||
2891 | CK_AddressSpaceConversion, From->getValueKind()) | ||||||||
2892 | .get(); | ||||||||
2893 | } | ||||||||
2894 | } else { | ||||||||
2895 | // No conversion necessary. | ||||||||
2896 | return From; | ||||||||
2897 | } | ||||||||
2898 | |||||||||
2899 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||||||
2900 | return From; | ||||||||
2901 | |||||||||
2902 | // If the unqualified types are the same, no conversion is necessary. | ||||||||
2903 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||||||
2904 | return From; | ||||||||
2905 | |||||||||
2906 | SourceRange FromRange = From->getSourceRange(); | ||||||||
2907 | SourceLocation FromLoc = FromRange.getBegin(); | ||||||||
2908 | |||||||||
2909 | ExprValueKind VK = From->getValueKind(); | ||||||||
2910 | |||||||||
2911 | // C++ [class.member.lookup]p8: | ||||||||
2912 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||||||
2913 | // class name. | ||||||||
2914 | // | ||||||||
2915 | // If the member was a qualified name and the qualified referred to a | ||||||||
2916 | // specific base subobject type, we'll cast to that intermediate type | ||||||||
2917 | // first and then to the object in which the member is declared. That allows | ||||||||
2918 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||||||
2919 | // | ||||||||
2920 | // class Base { public: int x; }; | ||||||||
2921 | // class Derived1 : public Base { }; | ||||||||
2922 | // class Derived2 : public Base { }; | ||||||||
2923 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||||||
2924 | // | ||||||||
2925 | // void VeryDerived::f() { | ||||||||
2926 | // x = 17; // error: ambiguous base subobjects | ||||||||
2927 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||||||
2928 | // } | ||||||||
2929 | if (Qualifier && Qualifier->getAsType()) { | ||||||||
2930 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||||||
2931 | assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type" ) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2931, __PRETTY_FUNCTION__)); | ||||||||
2932 | |||||||||
2933 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | ||||||||
2934 | |||||||||
2935 | // In C++98, the qualifier type doesn't actually have to be a base | ||||||||
2936 | // type of the object type, in which case we just ignore it. | ||||||||
2937 | // Otherwise build the appropriate casts. | ||||||||
2938 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||||||
2939 | CXXCastPath BasePath; | ||||||||
2940 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||||||
2941 | FromLoc, FromRange, &BasePath)) | ||||||||
2942 | return ExprError(); | ||||||||
2943 | |||||||||
2944 | if (PointerConversions) | ||||||||
2945 | QType = Context.getPointerType(QType); | ||||||||
2946 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||||||
2947 | VK, &BasePath).get(); | ||||||||
2948 | |||||||||
2949 | FromType = QType; | ||||||||
2950 | FromRecordType = QRecordType; | ||||||||
2951 | |||||||||
2952 | // If the qualifier type was the same as the destination type, | ||||||||
2953 | // we're done. | ||||||||
2954 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||||||
2955 | return From; | ||||||||
2956 | } | ||||||||
2957 | } | ||||||||
2958 | |||||||||
2959 | bool IgnoreAccess = false; | ||||||||
2960 | |||||||||
2961 | // If we actually found the member through a using declaration, cast | ||||||||
2962 | // down to the using declaration's type. | ||||||||
2963 | // | ||||||||
2964 | // Pointer equality is fine here because only one declaration of a | ||||||||
2965 | // class ever has member declarations. | ||||||||
2966 | if (FoundDecl->getDeclContext() != Member->getDeclContext()) { | ||||||||
2967 | assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void > (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2967, __PRETTY_FUNCTION__)); | ||||||||
2968 | QualType URecordType = Context.getTypeDeclType( | ||||||||
2969 | cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | ||||||||
2970 | |||||||||
2971 | // We only need to do this if the naming-class to declaring-class | ||||||||
2972 | // conversion is non-trivial. | ||||||||
2973 | if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { | ||||||||
2974 | assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast <void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 2974, __PRETTY_FUNCTION__)); | ||||||||
2975 | CXXCastPath BasePath; | ||||||||
2976 | if (CheckDerivedToBaseConversion(FromRecordType, URecordType, | ||||||||
2977 | FromLoc, FromRange, &BasePath)) | ||||||||
2978 | return ExprError(); | ||||||||
2979 | |||||||||
2980 | QualType UType = URecordType; | ||||||||
2981 | if (PointerConversions) | ||||||||
2982 | UType = Context.getPointerType(UType); | ||||||||
2983 | From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, | ||||||||
2984 | VK, &BasePath).get(); | ||||||||
2985 | FromType = UType; | ||||||||
2986 | FromRecordType = URecordType; | ||||||||
2987 | } | ||||||||
2988 | |||||||||
2989 | // We don't do access control for the conversion from the | ||||||||
2990 | // declaring class to the true declaring class. | ||||||||
2991 | IgnoreAccess = true; | ||||||||
2992 | } | ||||||||
2993 | |||||||||
2994 | CXXCastPath BasePath; | ||||||||
2995 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||||||
2996 | FromLoc, FromRange, &BasePath, | ||||||||
2997 | IgnoreAccess)) | ||||||||
2998 | return ExprError(); | ||||||||
2999 | |||||||||
3000 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||||||
3001 | VK, &BasePath); | ||||||||
3002 | } | ||||||||
3003 | |||||||||
3004 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||||||
3005 | const LookupResult &R, | ||||||||
3006 | bool HasTrailingLParen) { | ||||||||
3007 | // Only when used directly as the postfix-expression of a call. | ||||||||
3008 | if (!HasTrailingLParen) | ||||||||
3009 | return false; | ||||||||
3010 | |||||||||
3011 | // Never if a scope specifier was provided. | ||||||||
3012 | if (SS.isSet()) | ||||||||
3013 | return false; | ||||||||
3014 | |||||||||
3015 | // Only in C++ or ObjC++. | ||||||||
3016 | if (!getLangOpts().CPlusPlus) | ||||||||
3017 | return false; | ||||||||
3018 | |||||||||
3019 | // Turn off ADL when we find certain kinds of declarations during | ||||||||
3020 | // normal lookup: | ||||||||
3021 | for (NamedDecl *D : R) { | ||||||||
3022 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3023 | // -- a declaration of a class member | ||||||||
3024 | // Since using decls preserve this property, we check this on the | ||||||||
3025 | // original decl. | ||||||||
3026 | if (D->isCXXClassMember()) | ||||||||
3027 | return false; | ||||||||
3028 | |||||||||
3029 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3030 | // -- a block-scope function declaration that is not a | ||||||||
3031 | // using-declaration | ||||||||
3032 | // NOTE: we also trigger this for function templates (in fact, we | ||||||||
3033 | // don't check the decl type at all, since all other decl types | ||||||||
3034 | // turn off ADL anyway). | ||||||||
3035 | if (isa<UsingShadowDecl>(D)) | ||||||||
3036 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||||||
3037 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||||
3038 | return false; | ||||||||
3039 | |||||||||
3040 | // C++0x [basic.lookup.argdep]p3: | ||||||||
3041 | // -- a declaration that is neither a function or a function | ||||||||
3042 | // template | ||||||||
3043 | // And also for builtin functions. | ||||||||
3044 | if (isa<FunctionDecl>(D)) { | ||||||||
3045 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||||||
3046 | |||||||||
3047 | // But also builtin functions. | ||||||||
3048 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||||||
3049 | return false; | ||||||||
3050 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||||||
3051 | return false; | ||||||||
3052 | } | ||||||||
3053 | |||||||||
3054 | return true; | ||||||||
3055 | } | ||||||||
3056 | |||||||||
3057 | |||||||||
3058 | /// Diagnoses obvious problems with the use of the given declaration | ||||||||
3059 | /// as an expression. This is only actually called for lookups that | ||||||||
3060 | /// were not overloaded, and it doesn't promise that the declaration | ||||||||
3061 | /// will in fact be used. | ||||||||
3062 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | ||||||||
3063 | if (D->isInvalidDecl()) | ||||||||
3064 | return true; | ||||||||
3065 | |||||||||
3066 | if (isa<TypedefNameDecl>(D)) { | ||||||||
3067 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||||||
3068 | return true; | ||||||||
3069 | } | ||||||||
3070 | |||||||||
3071 | if (isa<ObjCInterfaceDecl>(D)) { | ||||||||
3072 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||||||
3073 | return true; | ||||||||
3074 | } | ||||||||
3075 | |||||||||
3076 | if (isa<NamespaceDecl>(D)) { | ||||||||
3077 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||||||
3078 | return true; | ||||||||
3079 | } | ||||||||
3080 | |||||||||
3081 | return false; | ||||||||
3082 | } | ||||||||
3083 | |||||||||
3084 | // Certain multiversion types should be treated as overloaded even when there is | ||||||||
3085 | // only one result. | ||||||||
3086 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||||||
3087 | assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result" ) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3087, __PRETTY_FUNCTION__)); | ||||||||
3088 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||||||
3089 | return FD && | ||||||||
3090 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||||||
3091 | } | ||||||||
3092 | |||||||||
3093 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||||||
3094 | LookupResult &R, bool NeedsADL, | ||||||||
3095 | bool AcceptInvalidDecl) { | ||||||||
3096 | // If this is a single, fully-resolved result and we don't need ADL, | ||||||||
3097 | // just build an ordinary singleton decl ref. | ||||||||
3098 | if (!NeedsADL && R.isSingleResult() && | ||||||||
3099 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||||||
3100 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||||||
3101 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||||||
3102 | R.getRepresentativeDecl(), nullptr, | ||||||||
3103 | AcceptInvalidDecl); | ||||||||
3104 | |||||||||
3105 | // We only need to check the declaration if there's exactly one | ||||||||
3106 | // result, because in the overloaded case the results can only be | ||||||||
3107 | // functions and function templates. | ||||||||
3108 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||||||
3109 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | ||||||||
3110 | return ExprError(); | ||||||||
3111 | |||||||||
3112 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||||||
3113 | // any lookup-related diagnostics; we'll hash these out later, when | ||||||||
3114 | // we've picked a target. | ||||||||
3115 | R.suppressDiagnostics(); | ||||||||
3116 | |||||||||
3117 | UnresolvedLookupExpr *ULE | ||||||||
3118 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||||||
3119 | SS.getWithLocInContext(Context), | ||||||||
3120 | R.getLookupNameInfo(), | ||||||||
3121 | NeedsADL, R.isOverloadedResult(), | ||||||||
3122 | R.begin(), R.end()); | ||||||||
3123 | |||||||||
3124 | return ULE; | ||||||||
3125 | } | ||||||||
3126 | |||||||||
3127 | static void | ||||||||
3128 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||||||
3129 | ValueDecl *var, DeclContext *DC); | ||||||||
3130 | |||||||||
3131 | /// Complete semantic analysis for a reference to the given declaration. | ||||||||
3132 | ExprResult Sema::BuildDeclarationNameExpr( | ||||||||
3133 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||||||
3134 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||||||
3135 | bool AcceptInvalidDecl) { | ||||||||
3136 | assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast <void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3136, __PRETTY_FUNCTION__)); | ||||||||
3137 | assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3138, __PRETTY_FUNCTION__)) | ||||||||
3138 | "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3138, __PRETTY_FUNCTION__)); | ||||||||
3139 | |||||||||
3140 | SourceLocation Loc = NameInfo.getLoc(); | ||||||||
3141 | if (CheckDeclInExpr(*this, Loc, D)) | ||||||||
3142 | return ExprError(); | ||||||||
3143 | |||||||||
3144 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||||||
3145 | // Specifically diagnose references to class templates that are missing | ||||||||
3146 | // a template argument list. | ||||||||
3147 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||||||
3148 | return ExprError(); | ||||||||
3149 | } | ||||||||
3150 | |||||||||
3151 | // Make sure that we're referring to a value. | ||||||||
3152 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | ||||||||
3153 | if (!VD) { | ||||||||
3154 | Diag(Loc, diag::err_ref_non_value) | ||||||||
3155 | << D << SS.getRange(); | ||||||||
3156 | Diag(D->getLocation(), diag::note_declared_at); | ||||||||
3157 | return ExprError(); | ||||||||
3158 | } | ||||||||
3159 | |||||||||
3160 | // Check whether this declaration can be used. Note that we suppress | ||||||||
3161 | // this check when we're going to perform argument-dependent lookup | ||||||||
3162 | // on this function name, because this might not be the function | ||||||||
3163 | // that overload resolution actually selects. | ||||||||
3164 | if (DiagnoseUseOfDecl(VD, Loc)) | ||||||||
3165 | return ExprError(); | ||||||||
3166 | |||||||||
3167 | // Only create DeclRefExpr's for valid Decl's. | ||||||||
3168 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||||||
3169 | return ExprError(); | ||||||||
3170 | |||||||||
3171 | // Handle members of anonymous structs and unions. If we got here, | ||||||||
3172 | // and the reference is to a class member indirect field, then this | ||||||||
3173 | // must be the subject of a pointer-to-member expression. | ||||||||
3174 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||||||
3175 | if (!indirectField->isCXXClassMember()) | ||||||||
3176 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||||||
3177 | indirectField); | ||||||||
3178 | |||||||||
3179 | { | ||||||||
3180 | QualType type = VD->getType(); | ||||||||
3181 | if (type.isNull()) | ||||||||
3182 | return ExprError(); | ||||||||
3183 | ExprValueKind valueKind = VK_RValue; | ||||||||
3184 | |||||||||
3185 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||||||
3186 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||||||
3187 | // is expanded by some outer '...' in the context of the use. | ||||||||
3188 | type = type.getNonPackExpansionType(); | ||||||||
3189 | |||||||||
3190 | switch (D->getKind()) { | ||||||||
3191 | // Ignore all the non-ValueDecl kinds. | ||||||||
3192 | #define ABSTRACT_DECL(kind) | ||||||||
3193 | #define VALUE(type, base) | ||||||||
3194 | #define DECL(type, base) \ | ||||||||
3195 | case Decl::type: | ||||||||
3196 | #include "clang/AST/DeclNodes.inc" | ||||||||
3197 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3197); | ||||||||
3198 | |||||||||
3199 | // These shouldn't make it here. | ||||||||
3200 | case Decl::ObjCAtDefsField: | ||||||||
3201 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3201); | ||||||||
3202 | |||||||||
3203 | // Enum constants are always r-values and never references. | ||||||||
3204 | // Unresolved using declarations are dependent. | ||||||||
3205 | case Decl::EnumConstant: | ||||||||
3206 | case Decl::UnresolvedUsingValue: | ||||||||
3207 | case Decl::OMPDeclareReduction: | ||||||||
3208 | case Decl::OMPDeclareMapper: | ||||||||
3209 | valueKind = VK_RValue; | ||||||||
3210 | break; | ||||||||
3211 | |||||||||
3212 | // Fields and indirect fields that got here must be for | ||||||||
3213 | // pointer-to-member expressions; we just call them l-values for | ||||||||
3214 | // internal consistency, because this subexpression doesn't really | ||||||||
3215 | // exist in the high-level semantics. | ||||||||
3216 | case Decl::Field: | ||||||||
3217 | case Decl::IndirectField: | ||||||||
3218 | case Decl::ObjCIvar: | ||||||||
3219 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3220, __PRETTY_FUNCTION__)) | ||||||||
3220 | "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3220, __PRETTY_FUNCTION__)); | ||||||||
3221 | |||||||||
3222 | // These can't have reference type in well-formed programs, but | ||||||||
3223 | // for internal consistency we do this anyway. | ||||||||
3224 | type = type.getNonReferenceType(); | ||||||||
3225 | valueKind = VK_LValue; | ||||||||
3226 | break; | ||||||||
3227 | |||||||||
3228 | // Non-type template parameters are either l-values or r-values | ||||||||
3229 | // depending on the type. | ||||||||
3230 | case Decl::NonTypeTemplateParm: { | ||||||||
3231 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||||||
3232 | type = reftype->getPointeeType(); | ||||||||
3233 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||||||
3234 | break; | ||||||||
3235 | } | ||||||||
3236 | |||||||||
3237 | // [expr.prim.id.unqual]p2: | ||||||||
3238 | // If the entity is a template parameter object for a template | ||||||||
3239 | // parameter of type T, the type of the expression is const T. | ||||||||
3240 | // [...] The expression is an lvalue if the entity is a [...] template | ||||||||
3241 | // parameter object. | ||||||||
3242 | if (type->isRecordType()) { | ||||||||
3243 | type = type.getUnqualifiedType().withConst(); | ||||||||
3244 | valueKind = VK_LValue; | ||||||||
3245 | break; | ||||||||
3246 | } | ||||||||
3247 | |||||||||
3248 | // For non-references, we need to strip qualifiers just in case | ||||||||
3249 | // the template parameter was declared as 'const int' or whatever. | ||||||||
3250 | valueKind = VK_RValue; | ||||||||
3251 | type = type.getUnqualifiedType(); | ||||||||
3252 | break; | ||||||||
3253 | } | ||||||||
3254 | |||||||||
3255 | case Decl::Var: | ||||||||
3256 | case Decl::VarTemplateSpecialization: | ||||||||
3257 | case Decl::VarTemplatePartialSpecialization: | ||||||||
3258 | case Decl::Decomposition: | ||||||||
3259 | case Decl::OMPCapturedExpr: | ||||||||
3260 | // In C, "extern void blah;" is valid and is an r-value. | ||||||||
3261 | if (!getLangOpts().CPlusPlus && | ||||||||
3262 | !type.hasQualifiers() && | ||||||||
3263 | type->isVoidType()) { | ||||||||
3264 | valueKind = VK_RValue; | ||||||||
3265 | break; | ||||||||
3266 | } | ||||||||
3267 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
3268 | |||||||||
3269 | case Decl::ImplicitParam: | ||||||||
3270 | case Decl::ParmVar: { | ||||||||
3271 | // These are always l-values. | ||||||||
3272 | valueKind = VK_LValue; | ||||||||
3273 | type = type.getNonReferenceType(); | ||||||||
3274 | |||||||||
3275 | // FIXME: Does the addition of const really only apply in | ||||||||
3276 | // potentially-evaluated contexts? Since the variable isn't actually | ||||||||
3277 | // captured in an unevaluated context, it seems that the answer is no. | ||||||||
3278 | if (!isUnevaluatedContext()) { | ||||||||
3279 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||||||
3280 | if (!CapturedType.isNull()) | ||||||||
3281 | type = CapturedType; | ||||||||
3282 | } | ||||||||
3283 | |||||||||
3284 | break; | ||||||||
3285 | } | ||||||||
3286 | |||||||||
3287 | case Decl::Binding: { | ||||||||
3288 | // These are always lvalues. | ||||||||
3289 | valueKind = VK_LValue; | ||||||||
3290 | type = type.getNonReferenceType(); | ||||||||
3291 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | ||||||||
3292 | // decides how that's supposed to work. | ||||||||
3293 | auto *BD = cast<BindingDecl>(VD); | ||||||||
3294 | if (BD->getDeclContext() != CurContext) { | ||||||||
3295 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | ||||||||
3296 | if (DD && DD->hasLocalStorage()) | ||||||||
3297 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | ||||||||
3298 | } | ||||||||
3299 | break; | ||||||||
3300 | } | ||||||||
3301 | |||||||||
3302 | case Decl::Function: { | ||||||||
3303 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||||||
3304 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | ||||||||
3305 | type = Context.BuiltinFnTy; | ||||||||
3306 | valueKind = VK_RValue; | ||||||||
3307 | break; | ||||||||
3308 | } | ||||||||
3309 | } | ||||||||
3310 | |||||||||
3311 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||||||
3312 | |||||||||
3313 | // If we're referring to a function with an __unknown_anytype | ||||||||
3314 | // result type, make the entire expression __unknown_anytype. | ||||||||
3315 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||||||
3316 | type = Context.UnknownAnyTy; | ||||||||
3317 | valueKind = VK_RValue; | ||||||||
3318 | break; | ||||||||
3319 | } | ||||||||
3320 | |||||||||
3321 | // Functions are l-values in C++. | ||||||||
3322 | if (getLangOpts().CPlusPlus) { | ||||||||
3323 | valueKind = VK_LValue; | ||||||||
3324 | break; | ||||||||
3325 | } | ||||||||
3326 | |||||||||
3327 | // C99 DR 316 says that, if a function type comes from a | ||||||||
3328 | // function definition (without a prototype), that type is only | ||||||||
3329 | // used for checking compatibility. Therefore, when referencing | ||||||||
3330 | // the function, we pretend that we don't have the full function | ||||||||
3331 | // type. | ||||||||
3332 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | ||||||||
3333 | isa<FunctionProtoType>(fty)) | ||||||||
3334 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||||||
3335 | fty->getExtInfo()); | ||||||||
3336 | |||||||||
3337 | // Functions are r-values in C. | ||||||||
3338 | valueKind = VK_RValue; | ||||||||
3339 | break; | ||||||||
3340 | } | ||||||||
3341 | |||||||||
3342 | case Decl::CXXDeductionGuide: | ||||||||
3343 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3343); | ||||||||
3344 | |||||||||
3345 | case Decl::MSProperty: | ||||||||
3346 | case Decl::MSGuid: | ||||||||
3347 | case Decl::TemplateParamObject: | ||||||||
3348 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||||||
3349 | // capture in OpenMP, or duplicated between host and device? | ||||||||
3350 | valueKind = VK_LValue; | ||||||||
3351 | break; | ||||||||
3352 | |||||||||
3353 | case Decl::CXXMethod: | ||||||||
3354 | // If we're referring to a method with an __unknown_anytype | ||||||||
3355 | // result type, make the entire expression __unknown_anytype. | ||||||||
3356 | // This should only be possible with a type written directly. | ||||||||
3357 | if (const FunctionProtoType *proto | ||||||||
3358 | = dyn_cast<FunctionProtoType>(VD->getType())) | ||||||||
3359 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||||||
3360 | type = Context.UnknownAnyTy; | ||||||||
3361 | valueKind = VK_RValue; | ||||||||
3362 | break; | ||||||||
3363 | } | ||||||||
3364 | |||||||||
3365 | // C++ methods are l-values if static, r-values if non-static. | ||||||||
3366 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||||||
3367 | valueKind = VK_LValue; | ||||||||
3368 | break; | ||||||||
3369 | } | ||||||||
3370 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
3371 | |||||||||
3372 | case Decl::CXXConversion: | ||||||||
3373 | case Decl::CXXDestructor: | ||||||||
3374 | case Decl::CXXConstructor: | ||||||||
3375 | valueKind = VK_RValue; | ||||||||
3376 | break; | ||||||||
3377 | } | ||||||||
3378 | |||||||||
3379 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||||||
3380 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | ||||||||
3381 | TemplateArgs); | ||||||||
3382 | } | ||||||||
3383 | } | ||||||||
3384 | |||||||||
3385 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||||||
3386 | SmallString<32> &Target) { | ||||||||
3387 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||||||
3388 | char *ResultPtr = &Target[0]; | ||||||||
3389 | const llvm::UTF8 *ErrorPtr; | ||||||||
3390 | bool success = | ||||||||
3391 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||||||
3392 | (void)success; | ||||||||
3393 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3393, __PRETTY_FUNCTION__)); | ||||||||
3394 | Target.resize(ResultPtr - &Target[0]); | ||||||||
3395 | } | ||||||||
3396 | |||||||||
3397 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||||||
3398 | PredefinedExpr::IdentKind IK) { | ||||||||
3399 | // Pick the current block, lambda, captured statement or function. | ||||||||
3400 | Decl *currentDecl = nullptr; | ||||||||
3401 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||||||
3402 | currentDecl = BSI->TheDecl; | ||||||||
3403 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||||||
3404 | currentDecl = LSI->CallOperator; | ||||||||
3405 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||||||
3406 | currentDecl = CSI->TheCapturedDecl; | ||||||||
3407 | else | ||||||||
3408 | currentDecl = getCurFunctionOrMethodDecl(); | ||||||||
3409 | |||||||||
3410 | if (!currentDecl) { | ||||||||
3411 | Diag(Loc, diag::ext_predef_outside_function); | ||||||||
3412 | currentDecl = Context.getTranslationUnitDecl(); | ||||||||
3413 | } | ||||||||
3414 | |||||||||
3415 | QualType ResTy; | ||||||||
3416 | StringLiteral *SL = nullptr; | ||||||||
3417 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||||||
3418 | ResTy = Context.DependentTy; | ||||||||
3419 | else { | ||||||||
3420 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||||||
3421 | // the string. | ||||||||
3422 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||||||
3423 | unsigned Length = Str.length(); | ||||||||
3424 | |||||||||
3425 | llvm::APInt LengthI(32, Length + 1); | ||||||||
3426 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||||||
3427 | ResTy = | ||||||||
3428 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||||||
3429 | SmallString<32> RawChars; | ||||||||
3430 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||||||
3431 | Str, RawChars); | ||||||||
3432 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||||||
3433 | ArrayType::Normal, | ||||||||
3434 | /*IndexTypeQuals*/ 0); | ||||||||
3435 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||||||
3436 | /*Pascal*/ false, ResTy, Loc); | ||||||||
3437 | } else { | ||||||||
3438 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||||||
3439 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||||||
3440 | ArrayType::Normal, | ||||||||
3441 | /*IndexTypeQuals*/ 0); | ||||||||
3442 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | ||||||||
3443 | /*Pascal*/ false, ResTy, Loc); | ||||||||
3444 | } | ||||||||
3445 | } | ||||||||
3446 | |||||||||
3447 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||||||
3448 | } | ||||||||
3449 | |||||||||
3450 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||||||
3451 | PredefinedExpr::IdentKind IK; | ||||||||
3452 | |||||||||
3453 | switch (Kind) { | ||||||||
3454 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3454); | ||||||||
3455 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||||||
3456 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||||||
3457 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||||||
3458 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||||||
3459 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||||||
3460 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||||||
3461 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||||||
3462 | } | ||||||||
3463 | |||||||||
3464 | return BuildPredefinedExpr(Loc, IK); | ||||||||
3465 | } | ||||||||
3466 | |||||||||
3467 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||||||
3468 | SmallString<16> CharBuffer; | ||||||||
3469 | bool Invalid = false; | ||||||||
3470 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||||||
3471 | if (Invalid) | ||||||||
3472 | return ExprError(); | ||||||||
3473 | |||||||||
3474 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||||||
3475 | PP, Tok.getKind()); | ||||||||
3476 | if (Literal.hadError()) | ||||||||
3477 | return ExprError(); | ||||||||
3478 | |||||||||
3479 | QualType Ty; | ||||||||
3480 | if (Literal.isWide()) | ||||||||
3481 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||||||
3482 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||||||
3483 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||||||
3484 | else if (Literal.isUTF16()) | ||||||||
3485 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||||||
3486 | else if (Literal.isUTF32()) | ||||||||
3487 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||||||
3488 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||||||
3489 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||||||
3490 | else | ||||||||
3491 | Ty = Context.CharTy; // 'x' -> char in C++ | ||||||||
3492 | |||||||||
3493 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||||||
3494 | if (Literal.isWide()) | ||||||||
3495 | Kind = CharacterLiteral::Wide; | ||||||||
3496 | else if (Literal.isUTF16()) | ||||||||
3497 | Kind = CharacterLiteral::UTF16; | ||||||||
3498 | else if (Literal.isUTF32()) | ||||||||
3499 | Kind = CharacterLiteral::UTF32; | ||||||||
3500 | else if (Literal.isUTF8()) | ||||||||
3501 | Kind = CharacterLiteral::UTF8; | ||||||||
3502 | |||||||||
3503 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||||||
3504 | Tok.getLocation()); | ||||||||
3505 | |||||||||
3506 | if (Literal.getUDSuffix().empty()) | ||||||||
3507 | return Lit; | ||||||||
3508 | |||||||||
3509 | // We're building a user-defined literal. | ||||||||
3510 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
3511 | SourceLocation UDSuffixLoc = | ||||||||
3512 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||||||
3513 | |||||||||
3514 | // Make sure we're allowed user-defined literals here. | ||||||||
3515 | if (!UDLScope) | ||||||||
3516 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||||||
3517 | |||||||||
3518 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||||||
3519 | // operator "" X (ch) | ||||||||
3520 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||||||
3521 | Lit, Tok.getLocation()); | ||||||||
3522 | } | ||||||||
3523 | |||||||||
3524 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||||||
3525 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||||||
3526 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||||||
3527 | Context.IntTy, Loc); | ||||||||
3528 | } | ||||||||
3529 | |||||||||
3530 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||||||
3531 | QualType Ty, SourceLocation Loc) { | ||||||||
3532 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||||||
3533 | |||||||||
3534 | using llvm::APFloat; | ||||||||
3535 | APFloat Val(Format); | ||||||||
3536 | |||||||||
3537 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||||||
3538 | |||||||||
3539 | // Overflow is always an error, but underflow is only an error if | ||||||||
3540 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||||||
3541 | if ((result & APFloat::opOverflow) || | ||||||||
3542 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||||||
3543 | unsigned diagnostic; | ||||||||
3544 | SmallString<20> buffer; | ||||||||
3545 | if (result & APFloat::opOverflow) { | ||||||||
3546 | diagnostic = diag::warn_float_overflow; | ||||||||
3547 | APFloat::getLargest(Format).toString(buffer); | ||||||||
3548 | } else { | ||||||||
3549 | diagnostic = diag::warn_float_underflow; | ||||||||
3550 | APFloat::getSmallest(Format).toString(buffer); | ||||||||
3551 | } | ||||||||
3552 | |||||||||
3553 | S.Diag(Loc, diagnostic) | ||||||||
3554 | << Ty | ||||||||
3555 | << StringRef(buffer.data(), buffer.size()); | ||||||||
3556 | } | ||||||||
3557 | |||||||||
3558 | bool isExact = (result == APFloat::opOK); | ||||||||
3559 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||||||
3560 | } | ||||||||
3561 | |||||||||
3562 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||||||
3563 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3563, __PRETTY_FUNCTION__)); | ||||||||
3564 | |||||||||
3565 | if (E->isValueDependent()) | ||||||||
3566 | return false; | ||||||||
3567 | |||||||||
3568 | QualType QT = E->getType(); | ||||||||
3569 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||||||
3570 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||||||
3571 | return true; | ||||||||
3572 | } | ||||||||
3573 | |||||||||
3574 | llvm::APSInt ValueAPS; | ||||||||
3575 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||||||
3576 | |||||||||
3577 | if (R.isInvalid()) | ||||||||
3578 | return true; | ||||||||
3579 | |||||||||
3580 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||||||
3581 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||||||
3582 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||||||
3583 | << ValueAPS.toString(10) << ValueIsPositive; | ||||||||
3584 | return true; | ||||||||
3585 | } | ||||||||
3586 | |||||||||
3587 | return false; | ||||||||
3588 | } | ||||||||
3589 | |||||||||
3590 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||||||
3591 | // Fast path for a single digit (which is quite common). A single digit | ||||||||
3592 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||||||
3593 | if (Tok.getLength() == 1) { | ||||||||
3594 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||||||
3595 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||||||
3596 | } | ||||||||
3597 | |||||||||
3598 | SmallString<128> SpellingBuffer; | ||||||||
3599 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||||||
3600 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||||||
3601 | // returns a StringRef to the memory buffer, it should have a null char at | ||||||||
3602 | // the EOF, so it is also safe. | ||||||||
3603 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||||||
3604 | |||||||||
3605 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||||||
3606 | bool Invalid = false; | ||||||||
3607 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||||||
3608 | if (Invalid) | ||||||||
3609 | return ExprError(); | ||||||||
3610 | |||||||||
3611 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||||||
3612 | PP.getSourceManager(), PP.getLangOpts(), | ||||||||
3613 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||||||
3614 | if (Literal.hadError) | ||||||||
3615 | return ExprError(); | ||||||||
3616 | |||||||||
3617 | if (Literal.hasUDSuffix()) { | ||||||||
3618 | // We're building a user-defined literal. | ||||||||
3619 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||||||
3620 | SourceLocation UDSuffixLoc = | ||||||||
3621 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||||||
3622 | |||||||||
3623 | // Make sure we're allowed user-defined literals here. | ||||||||
3624 | if (!UDLScope) | ||||||||
3625 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||||||
3626 | |||||||||
3627 | QualType CookedTy; | ||||||||
3628 | if (Literal.isFloatingLiteral()) { | ||||||||
3629 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||||||
3630 | // long double, the literal is treated as a call of the form | ||||||||
3631 | // operator "" X (f L) | ||||||||
3632 | CookedTy = Context.LongDoubleTy; | ||||||||
3633 | } else { | ||||||||
3634 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||||||
3635 | // unsigned long long, the literal is treated as a call of the form | ||||||||
3636 | // operator "" X (n ULL) | ||||||||
3637 | CookedTy = Context.UnsignedLongLongTy; | ||||||||
3638 | } | ||||||||
3639 | |||||||||
3640 | DeclarationName OpName = | ||||||||
3641 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||||||
3642 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||||||
3643 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||||||
3644 | |||||||||
3645 | SourceLocation TokLoc = Tok.getLocation(); | ||||||||
3646 | |||||||||
3647 | // Perform literal operator lookup to determine if we're building a raw | ||||||||
3648 | // literal or a cooked one. | ||||||||
3649 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||||||
3650 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||||||
3651 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||||||
3652 | /*AllowStringTemplatePack*/ false, | ||||||||
3653 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||||||
3654 | case LOLR_ErrorNoDiagnostic: | ||||||||
3655 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||||||
3656 | // GNU extension producing _Complex types. | ||||||||
3657 | break; | ||||||||
3658 | case LOLR_Error: | ||||||||
3659 | return ExprError(); | ||||||||
3660 | case LOLR_Cooked: { | ||||||||
3661 | Expr *Lit; | ||||||||
3662 | if (Literal.isFloatingLiteral()) { | ||||||||
3663 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||||||
3664 | } else { | ||||||||
3665 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||||||
3666 | if (Literal.GetIntegerValue(ResultVal)) | ||||||||
3667 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||||||
3668 | << /* Unsigned */ 1; | ||||||||
3669 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||||||
3670 | Tok.getLocation()); | ||||||||
3671 | } | ||||||||
3672 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||||||
3673 | } | ||||||||
3674 | |||||||||
3675 | case LOLR_Raw: { | ||||||||
3676 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||||||
3677 | // literal is treated as a call of the form | ||||||||
3678 | // operator "" X ("n") | ||||||||
3679 | unsigned Length = Literal.getUDSuffixOffset(); | ||||||||
3680 | QualType StrTy = Context.getConstantArrayType( | ||||||||
3681 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||||||
3682 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||||||
3683 | Expr *Lit = StringLiteral::Create( | ||||||||
3684 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | ||||||||
3685 | /*Pascal*/false, StrTy, &TokLoc, 1); | ||||||||
3686 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||||||
3687 | } | ||||||||
3688 | |||||||||
3689 | case LOLR_Template: { | ||||||||
3690 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||||||
3691 | // template), L is treated as a call fo the form | ||||||||
3692 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||||||
3693 | // where n is the source character sequence c1 c2 ... ck. | ||||||||
3694 | TemplateArgumentListInfo ExplicitArgs; | ||||||||
3695 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||||||
3696 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||||||
3697 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||||||
3698 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||||||
3699 | Value = TokSpelling[I]; | ||||||||
3700 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||||||
3701 | TemplateArgumentLocInfo ArgInfo; | ||||||||
3702 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||||||
3703 | } | ||||||||
3704 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||||||
3705 | &ExplicitArgs); | ||||||||
3706 | } | ||||||||
3707 | case LOLR_StringTemplatePack: | ||||||||
3708 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3708); | ||||||||
3709 | } | ||||||||
3710 | } | ||||||||
3711 | |||||||||
3712 | Expr *Res; | ||||||||
3713 | |||||||||
3714 | if (Literal.isFixedPointLiteral()) { | ||||||||
3715 | QualType Ty; | ||||||||
3716 | |||||||||
3717 | if (Literal.isAccum) { | ||||||||
3718 | if (Literal.isHalf) { | ||||||||
3719 | Ty = Context.ShortAccumTy; | ||||||||
3720 | } else if (Literal.isLong) { | ||||||||
3721 | Ty = Context.LongAccumTy; | ||||||||
3722 | } else { | ||||||||
3723 | Ty = Context.AccumTy; | ||||||||
3724 | } | ||||||||
3725 | } else if (Literal.isFract) { | ||||||||
3726 | if (Literal.isHalf) { | ||||||||
3727 | Ty = Context.ShortFractTy; | ||||||||
3728 | } else if (Literal.isLong) { | ||||||||
3729 | Ty = Context.LongFractTy; | ||||||||
3730 | } else { | ||||||||
3731 | Ty = Context.FractTy; | ||||||||
3732 | } | ||||||||
3733 | } | ||||||||
3734 | |||||||||
3735 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||||||
3736 | |||||||||
3737 | bool isSigned = !Literal.isUnsigned; | ||||||||
3738 | unsigned scale = Context.getFixedPointScale(Ty); | ||||||||
3739 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||||||
3740 | |||||||||
3741 | llvm::APInt Val(bit_width, 0, isSigned); | ||||||||
3742 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||||||
3743 | bool ValIsZero = Val.isNullValue() && !Overflowed; | ||||||||
3744 | |||||||||
3745 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||||||
3746 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||||||
3747 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||||||
3748 | // representable values for its type, with exception for constants of a | ||||||||
3749 | // fract type with a value of exactly 1; such a constant shall denote | ||||||||
3750 | // the maximal value for the type. | ||||||||
3751 | --Val; | ||||||||
3752 | else if (Val.ugt(MaxVal) || Overflowed) | ||||||||
3753 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||||||
3754 | |||||||||
3755 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||||||
3756 | Tok.getLocation(), scale); | ||||||||
3757 | } else if (Literal.isFloatingLiteral()) { | ||||||||
3758 | QualType Ty; | ||||||||
3759 | if (Literal.isHalf){ | ||||||||
3760 | if (getOpenCLOptions().isEnabled("cl_khr_fp16")) | ||||||||
3761 | Ty = Context.HalfTy; | ||||||||
3762 | else { | ||||||||
3763 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||||||
3764 | return ExprError(); | ||||||||
3765 | } | ||||||||
3766 | } else if (Literal.isFloat) | ||||||||
3767 | Ty = Context.FloatTy; | ||||||||
3768 | else if (Literal.isLong) | ||||||||
3769 | Ty = Context.LongDoubleTy; | ||||||||
3770 | else if (Literal.isFloat16) | ||||||||
3771 | Ty = Context.Float16Ty; | ||||||||
3772 | else if (Literal.isFloat128) | ||||||||
3773 | Ty = Context.Float128Ty; | ||||||||
3774 | else | ||||||||
3775 | Ty = Context.DoubleTy; | ||||||||
3776 | |||||||||
3777 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||||||
3778 | |||||||||
3779 | if (Ty == Context.DoubleTy) { | ||||||||
3780 | if (getLangOpts().SinglePrecisionConstants) { | ||||||||
3781 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||||||
3782 | if (BTy->getKind() != BuiltinType::Float) { | ||||||||
3783 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
3784 | } | ||||||||
3785 | } else if (getLangOpts().OpenCL && | ||||||||
3786 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | ||||||||
3787 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||||||
3788 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | ||||||||
3789 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||||||
3790 | } | ||||||||
3791 | } | ||||||||
3792 | } else if (!Literal.isIntegerLiteral()) { | ||||||||
3793 | return ExprError(); | ||||||||
3794 | } else { | ||||||||
3795 | QualType Ty; | ||||||||
3796 | |||||||||
3797 | // 'long long' is a C99 or C++11 feature. | ||||||||
3798 | if (!getLangOpts().C99 && Literal.isLongLong) { | ||||||||
3799 | if (getLangOpts().CPlusPlus) | ||||||||
3800 | Diag(Tok.getLocation(), | ||||||||
3801 | getLangOpts().CPlusPlus11 ? | ||||||||
3802 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||||||
3803 | else | ||||||||
3804 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||||||
3805 | } | ||||||||
3806 | |||||||||
3807 | // Get the value in the widest-possible width. | ||||||||
3808 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | ||||||||
3809 | llvm::APInt ResultVal(MaxWidth, 0); | ||||||||
3810 | |||||||||
3811 | if (Literal.GetIntegerValue(ResultVal)) { | ||||||||
3812 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||||||
3813 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||||||
3814 | << /* Unsigned */ 1; | ||||||||
3815 | Ty = Context.UnsignedLongLongTy; | ||||||||
3816 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3817, __PRETTY_FUNCTION__)) | ||||||||
3817 | "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3817, __PRETTY_FUNCTION__)); | ||||||||
3818 | } else { | ||||||||
3819 | // If this value fits into a ULL, try to figure out what else it fits into | ||||||||
3820 | // according to the rules of C99 6.4.4.1p5. | ||||||||
3821 | |||||||||
3822 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||||||
3823 | // be an unsigned int. | ||||||||
3824 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||||||
3825 | |||||||||
3826 | // Check from smallest to largest, picking the smallest type we can. | ||||||||
3827 | unsigned Width = 0; | ||||||||
3828 | |||||||||
3829 | // Microsoft specific integer suffixes are explicitly sized. | ||||||||
3830 | if (Literal.MicrosoftInteger) { | ||||||||
3831 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||||||
3832 | Width = 8; | ||||||||
3833 | Ty = Context.CharTy; | ||||||||
3834 | } else { | ||||||||
3835 | Width = Literal.MicrosoftInteger; | ||||||||
3836 | Ty = Context.getIntTypeForBitwidth(Width, | ||||||||
3837 | /*Signed=*/!Literal.isUnsigned); | ||||||||
3838 | } | ||||||||
3839 | } | ||||||||
3840 | |||||||||
3841 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { | ||||||||
3842 | // Are int/unsigned possibilities? | ||||||||
3843 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||||||
3844 | |||||||||
3845 | // Does it fit in a unsigned int? | ||||||||
3846 | if (ResultVal.isIntN(IntSize)) { | ||||||||
3847 | // Does it fit in a signed int? | ||||||||
3848 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||||||
3849 | Ty = Context.IntTy; | ||||||||
3850 | else if (AllowUnsigned) | ||||||||
3851 | Ty = Context.UnsignedIntTy; | ||||||||
3852 | Width = IntSize; | ||||||||
3853 | } | ||||||||
3854 | } | ||||||||
3855 | |||||||||
3856 | // Are long/unsigned long possibilities? | ||||||||
3857 | if (Ty.isNull() && !Literal.isLongLong) { | ||||||||
3858 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||||||
3859 | |||||||||
3860 | // Does it fit in a unsigned long? | ||||||||
3861 | if (ResultVal.isIntN(LongSize)) { | ||||||||
3862 | // Does it fit in a signed long? | ||||||||
3863 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||||||
3864 | Ty = Context.LongTy; | ||||||||
3865 | else if (AllowUnsigned) | ||||||||
3866 | Ty = Context.UnsignedLongTy; | ||||||||
3867 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||||||
3868 | // is compatible. | ||||||||
3869 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||||||
3870 | const unsigned LongLongSize = | ||||||||
3871 | Context.getTargetInfo().getLongLongWidth(); | ||||||||
3872 | Diag(Tok.getLocation(), | ||||||||
3873 | getLangOpts().CPlusPlus | ||||||||
3874 | ? Literal.isLong | ||||||||
3875 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||||||
3876 | : /*C++98 UB*/ diag:: | ||||||||
3877 | ext_old_implicitly_unsigned_long_cxx | ||||||||
3878 | : diag::warn_old_implicitly_unsigned_long) | ||||||||
3879 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||||||
3880 | : /*will be ill-formed*/ 1); | ||||||||
3881 | Ty = Context.UnsignedLongTy; | ||||||||
3882 | } | ||||||||
3883 | Width = LongSize; | ||||||||
3884 | } | ||||||||
3885 | } | ||||||||
3886 | |||||||||
3887 | // Check long long if needed. | ||||||||
3888 | if (Ty.isNull()) { | ||||||||
3889 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||||||
3890 | |||||||||
3891 | // Does it fit in a unsigned long long? | ||||||||
3892 | if (ResultVal.isIntN(LongLongSize)) { | ||||||||
3893 | // Does it fit in a signed long long? | ||||||||
3894 | // To be compatible with MSVC, hex integer literals ending with the | ||||||||
3895 | // LL or i64 suffix are always signed in Microsoft mode. | ||||||||
3896 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||||||
3897 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||||||
3898 | Ty = Context.LongLongTy; | ||||||||
3899 | else if (AllowUnsigned) | ||||||||
3900 | Ty = Context.UnsignedLongLongTy; | ||||||||
3901 | Width = LongLongSize; | ||||||||
3902 | } | ||||||||
3903 | } | ||||||||
3904 | |||||||||
3905 | // If we still couldn't decide a type, we probably have something that | ||||||||
3906 | // does not fit in a signed long long, but has no U suffix. | ||||||||
3907 | if (Ty.isNull()) { | ||||||||
3908 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); | ||||||||
3909 | Ty = Context.UnsignedLongLongTy; | ||||||||
3910 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||||||
3911 | } | ||||||||
3912 | |||||||||
3913 | if (ResultVal.getBitWidth() != Width) | ||||||||
3914 | ResultVal = ResultVal.trunc(Width); | ||||||||
3915 | } | ||||||||
3916 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||||||
3917 | } | ||||||||
3918 | |||||||||
3919 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||||||
3920 | if (Literal.isImaginary) { | ||||||||
3921 | Res = new (Context) ImaginaryLiteral(Res, | ||||||||
3922 | Context.getComplexType(Res->getType())); | ||||||||
3923 | |||||||||
3924 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||||||
3925 | } | ||||||||
3926 | return Res; | ||||||||
3927 | } | ||||||||
3928 | |||||||||
3929 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||||||
3930 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3930, __PRETTY_FUNCTION__)); | ||||||||
3931 | return new (Context) ParenExpr(L, R, E); | ||||||||
3932 | } | ||||||||
3933 | |||||||||
3934 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||||||
3935 | SourceLocation Loc, | ||||||||
3936 | SourceRange ArgRange) { | ||||||||
3937 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||||||
3938 | // scalar or vector data type argument..." | ||||||||
3939 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||||||
3940 | // type (C99 6.2.5p18) or void. | ||||||||
3941 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||||||
3942 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||||||
3943 | << T << ArgRange; | ||||||||
3944 | return true; | ||||||||
3945 | } | ||||||||
3946 | |||||||||
3947 | assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3948, __PRETTY_FUNCTION__)) | ||||||||
3948 | "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 3948, __PRETTY_FUNCTION__)); | ||||||||
3949 | return false; | ||||||||
3950 | } | ||||||||
3951 | |||||||||
3952 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||||||
3953 | SourceLocation Loc, | ||||||||
3954 | SourceRange ArgRange, | ||||||||
3955 | UnaryExprOrTypeTrait TraitKind) { | ||||||||
3956 | // Invalid types must be hard errors for SFINAE in C++. | ||||||||
3957 | if (S.LangOpts.CPlusPlus) | ||||||||
3958 | return true; | ||||||||
3959 | |||||||||
3960 | // C99 6.5.3.4p1: | ||||||||
3961 | if (T->isFunctionType() && | ||||||||
3962 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||||||
3963 | TraitKind == UETT_PreferredAlignOf)) { | ||||||||
3964 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||||||
3965 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||||||
3966 | << getTraitSpelling(TraitKind) << ArgRange; | ||||||||
3967 | return false; | ||||||||
3968 | } | ||||||||
3969 | |||||||||
3970 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||||||
3971 | // this is an error (OpenCL v1.1 s6.3.k) | ||||||||
3972 | if (T->isVoidType()) { | ||||||||
3973 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||||||
3974 | : diag::ext_sizeof_alignof_void_type; | ||||||||
3975 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||||||
3976 | return false; | ||||||||
3977 | } | ||||||||
3978 | |||||||||
3979 | return true; | ||||||||
3980 | } | ||||||||
3981 | |||||||||
3982 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||||||
3983 | SourceLocation Loc, | ||||||||
3984 | SourceRange ArgRange, | ||||||||
3985 | UnaryExprOrTypeTrait TraitKind) { | ||||||||
3986 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||||||
3987 | // runtime doesn't allow it. | ||||||||
3988 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||||||
3989 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||||||
3990 | << T << (TraitKind == UETT_SizeOf) | ||||||||
3991 | << ArgRange; | ||||||||
3992 | return true; | ||||||||
3993 | } | ||||||||
3994 | |||||||||
3995 | return false; | ||||||||
3996 | } | ||||||||
3997 | |||||||||
3998 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||||||
3999 | /// pointer type is equal to T) and emit a warning if it is. | ||||||||
4000 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||||||
4001 | Expr *E) { | ||||||||
4002 | // Don't warn if the operation changed the type. | ||||||||
4003 | if (T != E->getType()) | ||||||||
4004 | return; | ||||||||
4005 | |||||||||
4006 | // Now look for array decays. | ||||||||
4007 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||||||
4008 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||||||
4009 | return; | ||||||||
4010 | |||||||||
4011 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||||||
4012 | << ICE->getType() | ||||||||
4013 | << ICE->getSubExpr()->getType(); | ||||||||
4014 | } | ||||||||
4015 | |||||||||
4016 | /// Check the constraints on expression operands to unary type expression | ||||||||
4017 | /// and type traits. | ||||||||
4018 | /// | ||||||||
4019 | /// Completes any types necessary and validates the constraints on the operand | ||||||||
4020 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||||||
4021 | /// the expression as it completes the type for that expression through template | ||||||||
4022 | /// instantiation, etc. | ||||||||
4023 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||||||
4024 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4025 | QualType ExprTy = E->getType(); | ||||||||
4026 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4026, __PRETTY_FUNCTION__)); | ||||||||
4027 | |||||||||
4028 | bool IsUnevaluatedOperand = | ||||||||
4029 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||||||
4030 | ExprKind == UETT_PreferredAlignOf); | ||||||||
4031 | if (IsUnevaluatedOperand) { | ||||||||
4032 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||||||
4033 | if (Result.isInvalid()) | ||||||||
4034 | return true; | ||||||||
4035 | E = Result.get(); | ||||||||
4036 | } | ||||||||
4037 | |||||||||
4038 | if (ExprKind == UETT_VecStep) | ||||||||
4039 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||||||
4040 | E->getSourceRange()); | ||||||||
4041 | |||||||||
4042 | // Explicitly list some types as extensions. | ||||||||
4043 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||||||
4044 | E->getSourceRange(), ExprKind)) | ||||||||
4045 | return false; | ||||||||
4046 | |||||||||
4047 | // 'alignof' applied to an expression only requires the base element type of | ||||||||
4048 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||||||
4049 | // be complete (and will attempt to complete it if it's an array of unknown | ||||||||
4050 | // bound). | ||||||||
4051 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||||||
4052 | if (RequireCompleteSizedType( | ||||||||
4053 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||||||
4054 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4055 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||||||
4056 | return true; | ||||||||
4057 | } else { | ||||||||
4058 | if (RequireCompleteSizedExprType( | ||||||||
4059 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4060 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||||||
4061 | return true; | ||||||||
4062 | } | ||||||||
4063 | |||||||||
4064 | // Completing the expression's type may have changed it. | ||||||||
4065 | ExprTy = E->getType(); | ||||||||
4066 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4066, __PRETTY_FUNCTION__)); | ||||||||
4067 | |||||||||
4068 | if (ExprTy->isFunctionType()) { | ||||||||
4069 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||||||
4070 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||||||
4071 | return true; | ||||||||
4072 | } | ||||||||
4073 | |||||||||
4074 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||||||
4075 | // so side effects could result in unintended consequences. | ||||||||
4076 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||||||
4077 | E->HasSideEffects(Context, false)) | ||||||||
4078 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||||||
4079 | |||||||||
4080 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||||||
4081 | E->getSourceRange(), ExprKind)) | ||||||||
4082 | return true; | ||||||||
4083 | |||||||||
4084 | if (ExprKind == UETT_SizeOf) { | ||||||||
4085 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||||||
4086 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||||||
4087 | QualType OType = PVD->getOriginalType(); | ||||||||
4088 | QualType Type = PVD->getType(); | ||||||||
4089 | if (Type->isPointerType() && OType->isArrayType()) { | ||||||||
4090 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||||||
4091 | << Type << OType; | ||||||||
4092 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||||||
4093 | } | ||||||||
4094 | } | ||||||||
4095 | } | ||||||||
4096 | |||||||||
4097 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||||||
4098 | // decays into a pointer and returns an unintended result. This is most | ||||||||
4099 | // likely a typo for "sizeof(array) op x". | ||||||||
4100 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||||||
4101 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||||||
4102 | BO->getLHS()); | ||||||||
4103 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||||||
4104 | BO->getRHS()); | ||||||||
4105 | } | ||||||||
4106 | } | ||||||||
4107 | |||||||||
4108 | return false; | ||||||||
4109 | } | ||||||||
4110 | |||||||||
4111 | /// Check the constraints on operands to unary expression and type | ||||||||
4112 | /// traits. | ||||||||
4113 | /// | ||||||||
4114 | /// This will complete any types necessary, and validate the various constraints | ||||||||
4115 | /// on those operands. | ||||||||
4116 | /// | ||||||||
4117 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||||||
4118 | /// C99 6.3.2.1p[2-4] all state: | ||||||||
4119 | /// Except when it is the operand of the sizeof operator ... | ||||||||
4120 | /// | ||||||||
4121 | /// C++ [expr.sizeof]p4 | ||||||||
4122 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||||||
4123 | /// standard conversions are not applied to the operand of sizeof. | ||||||||
4124 | /// | ||||||||
4125 | /// This policy is followed for all of the unary trait expressions. | ||||||||
4126 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||||||
4127 | SourceLocation OpLoc, | ||||||||
4128 | SourceRange ExprRange, | ||||||||
4129 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4130 | if (ExprType->isDependentType()) | ||||||||
4131 | return false; | ||||||||
4132 | |||||||||
4133 | // C++ [expr.sizeof]p2: | ||||||||
4134 | // When applied to a reference or a reference type, the result | ||||||||
4135 | // is the size of the referenced type. | ||||||||
4136 | // C++11 [expr.alignof]p3: | ||||||||
4137 | // When alignof is applied to a reference type, the result | ||||||||
4138 | // shall be the alignment of the referenced type. | ||||||||
4139 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||||||
4140 | ExprType = Ref->getPointeeType(); | ||||||||
4141 | |||||||||
4142 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||||||
4143 | // When alignof or _Alignof is applied to an array type, the result | ||||||||
4144 | // is the alignment of the element type. | ||||||||
4145 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||||||
4146 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||||||
4147 | ExprType = Context.getBaseElementType(ExprType); | ||||||||
4148 | |||||||||
4149 | if (ExprKind == UETT_VecStep) | ||||||||
4150 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||||||
4151 | |||||||||
4152 | // Explicitly list some types as extensions. | ||||||||
4153 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||||||
4154 | ExprKind)) | ||||||||
4155 | return false; | ||||||||
4156 | |||||||||
4157 | if (RequireCompleteSizedType( | ||||||||
4158 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||||||
4159 | getTraitSpelling(ExprKind), ExprRange)) | ||||||||
4160 | return true; | ||||||||
4161 | |||||||||
4162 | if (ExprType->isFunctionType()) { | ||||||||
4163 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||||||
4164 | << getTraitSpelling(ExprKind) << ExprRange; | ||||||||
4165 | return true; | ||||||||
4166 | } | ||||||||
4167 | |||||||||
4168 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||||||
4169 | ExprKind)) | ||||||||
4170 | return true; | ||||||||
4171 | |||||||||
4172 | return false; | ||||||||
4173 | } | ||||||||
4174 | |||||||||
4175 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||||||
4176 | // Cannot know anything else if the expression is dependent. | ||||||||
4177 | if (E->isTypeDependent()) | ||||||||
4178 | return false; | ||||||||
4179 | |||||||||
4180 | if (E->getObjectKind() == OK_BitField) { | ||||||||
4181 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||||||
4182 | << 1 << E->getSourceRange(); | ||||||||
4183 | return true; | ||||||||
4184 | } | ||||||||
4185 | |||||||||
4186 | ValueDecl *D = nullptr; | ||||||||
4187 | Expr *Inner = E->IgnoreParens(); | ||||||||
4188 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||||||
4189 | D = DRE->getDecl(); | ||||||||
4190 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||||||
4191 | D = ME->getMemberDecl(); | ||||||||
4192 | } | ||||||||
4193 | |||||||||
4194 | // If it's a field, require the containing struct to have a | ||||||||
4195 | // complete definition so that we can compute the layout. | ||||||||
4196 | // | ||||||||
4197 | // This can happen in C++11 onwards, either by naming the member | ||||||||
4198 | // in a way that is not transformed into a member access expression | ||||||||
4199 | // (in an unevaluated operand, for instance), or by naming the member | ||||||||
4200 | // in a trailing-return-type. | ||||||||
4201 | // | ||||||||
4202 | // For the record, since __alignof__ on expressions is a GCC | ||||||||
4203 | // extension, GCC seems to permit this but always gives the | ||||||||
4204 | // nonsensical answer 0. | ||||||||
4205 | // | ||||||||
4206 | // We don't really need the layout here --- we could instead just | ||||||||
4207 | // directly check for all the appropriate alignment-lowing | ||||||||
4208 | // attributes --- but that would require duplicating a lot of | ||||||||
4209 | // logic that just isn't worth duplicating for such a marginal | ||||||||
4210 | // use-case. | ||||||||
4211 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||||||
4212 | // Fast path this check, since we at least know the record has a | ||||||||
4213 | // definition if we can find a member of it. | ||||||||
4214 | if (!FD->getParent()->isCompleteDefinition()) { | ||||||||
4215 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||||||
4216 | << E->getSourceRange(); | ||||||||
4217 | return true; | ||||||||
4218 | } | ||||||||
4219 | |||||||||
4220 | // Otherwise, if it's a field, and the field doesn't have | ||||||||
4221 | // reference type, then it must have a complete type (or be a | ||||||||
4222 | // flexible array member, which we explicitly want to | ||||||||
4223 | // white-list anyway), which makes the following checks trivial. | ||||||||
4224 | if (!FD->getType()->isReferenceType()) | ||||||||
4225 | return false; | ||||||||
4226 | } | ||||||||
4227 | |||||||||
4228 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||||||
4229 | } | ||||||||
4230 | |||||||||
4231 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||||||
4232 | E = E->IgnoreParens(); | ||||||||
4233 | |||||||||
4234 | // Cannot know anything else if the expression is dependent. | ||||||||
4235 | if (E->isTypeDependent()) | ||||||||
4236 | return false; | ||||||||
4237 | |||||||||
4238 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||||||
4239 | } | ||||||||
4240 | |||||||||
4241 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||||||
4242 | CapturingScopeInfo *CSI) { | ||||||||
4243 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4243, __PRETTY_FUNCTION__)); | ||||||||
4244 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4244, __PRETTY_FUNCTION__)); | ||||||||
4245 | |||||||||
4246 | // We're going to walk down into the type and look for VLA expressions. | ||||||||
4247 | do { | ||||||||
4248 | const Type *Ty = T.getTypePtr(); | ||||||||
4249 | switch (Ty->getTypeClass()) { | ||||||||
4250 | #define TYPE(Class, Base) | ||||||||
4251 | #define ABSTRACT_TYPE(Class, Base) | ||||||||
4252 | #define NON_CANONICAL_TYPE(Class, Base) | ||||||||
4253 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||||||
4254 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||||||
4255 | #include "clang/AST/TypeNodes.inc" | ||||||||
4256 | T = QualType(); | ||||||||
4257 | break; | ||||||||
4258 | // These types are never variably-modified. | ||||||||
4259 | case Type::Builtin: | ||||||||
4260 | case Type::Complex: | ||||||||
4261 | case Type::Vector: | ||||||||
4262 | case Type::ExtVector: | ||||||||
4263 | case Type::ConstantMatrix: | ||||||||
4264 | case Type::Record: | ||||||||
4265 | case Type::Enum: | ||||||||
4266 | case Type::Elaborated: | ||||||||
4267 | case Type::TemplateSpecialization: | ||||||||
4268 | case Type::ObjCObject: | ||||||||
4269 | case Type::ObjCInterface: | ||||||||
4270 | case Type::ObjCObjectPointer: | ||||||||
4271 | case Type::ObjCTypeParam: | ||||||||
4272 | case Type::Pipe: | ||||||||
4273 | case Type::ExtInt: | ||||||||
4274 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4274); | ||||||||
4275 | case Type::Adjusted: | ||||||||
4276 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||||||
4277 | break; | ||||||||
4278 | case Type::Decayed: | ||||||||
4279 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||||||
4280 | break; | ||||||||
4281 | case Type::Pointer: | ||||||||
4282 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||||||
4283 | break; | ||||||||
4284 | case Type::BlockPointer: | ||||||||
4285 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||||||
4286 | break; | ||||||||
4287 | case Type::LValueReference: | ||||||||
4288 | case Type::RValueReference: | ||||||||
4289 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||||||
4290 | break; | ||||||||
4291 | case Type::MemberPointer: | ||||||||
4292 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||||||
4293 | break; | ||||||||
4294 | case Type::ConstantArray: | ||||||||
4295 | case Type::IncompleteArray: | ||||||||
4296 | // Losing element qualification here is fine. | ||||||||
4297 | T = cast<ArrayType>(Ty)->getElementType(); | ||||||||
4298 | break; | ||||||||
4299 | case Type::VariableArray: { | ||||||||
4300 | // Losing element qualification here is fine. | ||||||||
4301 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||||||
4302 | |||||||||
4303 | // Unknown size indication requires no size computation. | ||||||||
4304 | // Otherwise, evaluate and record it. | ||||||||
4305 | auto Size = VAT->getSizeExpr(); | ||||||||
4306 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||||||
4307 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||||||
4308 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||||||
4309 | |||||||||
4310 | T = VAT->getElementType(); | ||||||||
4311 | break; | ||||||||
4312 | } | ||||||||
4313 | case Type::FunctionProto: | ||||||||
4314 | case Type::FunctionNoProto: | ||||||||
4315 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||||||
4316 | break; | ||||||||
4317 | case Type::Paren: | ||||||||
4318 | case Type::TypeOf: | ||||||||
4319 | case Type::UnaryTransform: | ||||||||
4320 | case Type::Attributed: | ||||||||
4321 | case Type::SubstTemplateTypeParm: | ||||||||
4322 | case Type::MacroQualified: | ||||||||
4323 | // Keep walking after single level desugaring. | ||||||||
4324 | T = T.getSingleStepDesugaredType(Context); | ||||||||
4325 | break; | ||||||||
4326 | case Type::Typedef: | ||||||||
4327 | T = cast<TypedefType>(Ty)->desugar(); | ||||||||
4328 | break; | ||||||||
4329 | case Type::Decltype: | ||||||||
4330 | T = cast<DecltypeType>(Ty)->desugar(); | ||||||||
4331 | break; | ||||||||
4332 | case Type::Auto: | ||||||||
4333 | case Type::DeducedTemplateSpecialization: | ||||||||
4334 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||||||
4335 | break; | ||||||||
4336 | case Type::TypeOfExpr: | ||||||||
4337 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||||||
4338 | break; | ||||||||
4339 | case Type::Atomic: | ||||||||
4340 | T = cast<AtomicType>(Ty)->getValueType(); | ||||||||
4341 | break; | ||||||||
4342 | } | ||||||||
4343 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||||||
4344 | } | ||||||||
4345 | |||||||||
4346 | /// Build a sizeof or alignof expression given a type operand. | ||||||||
4347 | ExprResult | ||||||||
4348 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||||||
4349 | SourceLocation OpLoc, | ||||||||
4350 | UnaryExprOrTypeTrait ExprKind, | ||||||||
4351 | SourceRange R) { | ||||||||
4352 | if (!TInfo) | ||||||||
4353 | return ExprError(); | ||||||||
4354 | |||||||||
4355 | QualType T = TInfo->getType(); | ||||||||
4356 | |||||||||
4357 | if (!T->isDependentType() && | ||||||||
4358 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||||||
4359 | return ExprError(); | ||||||||
4360 | |||||||||
4361 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||||||
4362 | if (auto *TT = T->getAs<TypedefType>()) { | ||||||||
4363 | for (auto I = FunctionScopes.rbegin(), | ||||||||
4364 | E = std::prev(FunctionScopes.rend()); | ||||||||
4365 | I != E; ++I) { | ||||||||
4366 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||||||
4367 | if (CSI == nullptr) | ||||||||
4368 | break; | ||||||||
4369 | DeclContext *DC = nullptr; | ||||||||
4370 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||||||
4371 | DC = LSI->CallOperator; | ||||||||
4372 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||||||
4373 | DC = CRSI->TheCapturedDecl; | ||||||||
4374 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||||||
4375 | DC = BSI->TheDecl; | ||||||||
4376 | if (DC) { | ||||||||
4377 | if (DC->containsDecl(TT->getDecl())) | ||||||||
4378 | break; | ||||||||
4379 | captureVariablyModifiedType(Context, T, CSI); | ||||||||
4380 | } | ||||||||
4381 | } | ||||||||
4382 | } | ||||||||
4383 | } | ||||||||
4384 | |||||||||
4385 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||||||
4386 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||||||
4387 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||||||
4388 | } | ||||||||
4389 | |||||||||
4390 | /// Build a sizeof or alignof expression given an expression | ||||||||
4391 | /// operand. | ||||||||
4392 | ExprResult | ||||||||
4393 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||||||
4394 | UnaryExprOrTypeTrait ExprKind) { | ||||||||
4395 | ExprResult PE = CheckPlaceholderExpr(E); | ||||||||
4396 | if (PE.isInvalid()) | ||||||||
4397 | return ExprError(); | ||||||||
4398 | |||||||||
4399 | E = PE.get(); | ||||||||
4400 | |||||||||
4401 | // Verify that the operand is valid. | ||||||||
4402 | bool isInvalid = false; | ||||||||
4403 | if (E->isTypeDependent()) { | ||||||||
4404 | // Delay type-checking for type-dependent expressions. | ||||||||
4405 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||||||
4406 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||||||
4407 | } else if (ExprKind == UETT_VecStep) { | ||||||||
4408 | isInvalid = CheckVecStepExpr(E); | ||||||||
4409 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||||||
4410 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||||||
4411 | isInvalid = true; | ||||||||
4412 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||||||
4413 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||||||
4414 | isInvalid = true; | ||||||||
4415 | } else { | ||||||||
4416 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||||||
4417 | } | ||||||||
4418 | |||||||||
4419 | if (isInvalid) | ||||||||
4420 | return ExprError(); | ||||||||
4421 | |||||||||
4422 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||||||
4423 | PE = TransformToPotentiallyEvaluated(E); | ||||||||
4424 | if (PE.isInvalid()) return ExprError(); | ||||||||
4425 | E = PE.get(); | ||||||||
4426 | } | ||||||||
4427 | |||||||||
4428 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||||||
4429 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||||||
4430 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||||||
4431 | } | ||||||||
4432 | |||||||||
4433 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||||||
4434 | /// expr and the same for @c alignof and @c __alignof | ||||||||
4435 | /// Note that the ArgRange is invalid if isType is false. | ||||||||
4436 | ExprResult | ||||||||
4437 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||||||
4438 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||||||
4439 | void *TyOrEx, SourceRange ArgRange) { | ||||||||
4440 | // If error parsing type, ignore. | ||||||||
4441 | if (!TyOrEx) return ExprError(); | ||||||||
4442 | |||||||||
4443 | if (IsType) { | ||||||||
4444 | TypeSourceInfo *TInfo; | ||||||||
4445 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||||||
4446 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||||||
4447 | } | ||||||||
4448 | |||||||||
4449 | Expr *ArgEx = (Expr *)TyOrEx; | ||||||||
4450 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||||||
4451 | return Result; | ||||||||
4452 | } | ||||||||
4453 | |||||||||
4454 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||||||
4455 | bool IsReal) { | ||||||||
4456 | if (V.get()->isTypeDependent()) | ||||||||
4457 | return S.Context.DependentTy; | ||||||||
4458 | |||||||||
4459 | // _Real and _Imag are only l-values for normal l-values. | ||||||||
4460 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||||||
4461 | V = S.DefaultLvalueConversion(V.get()); | ||||||||
4462 | if (V.isInvalid()) | ||||||||
4463 | return QualType(); | ||||||||
4464 | } | ||||||||
4465 | |||||||||
4466 | // These operators return the element type of a complex type. | ||||||||
4467 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||||||
4468 | return CT->getElementType(); | ||||||||
4469 | |||||||||
4470 | // Otherwise they pass through real integer and floating point types here. | ||||||||
4471 | if (V.get()->getType()->isArithmeticType()) | ||||||||
4472 | return V.get()->getType(); | ||||||||
4473 | |||||||||
4474 | // Test for placeholders. | ||||||||
4475 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||||||
4476 | if (PR.isInvalid()) return QualType(); | ||||||||
4477 | if (PR.get() != V.get()) { | ||||||||
4478 | V = PR; | ||||||||
4479 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||||||
4480 | } | ||||||||
4481 | |||||||||
4482 | // Reject anything else. | ||||||||
4483 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||||||
4484 | << (IsReal ? "__real" : "__imag"); | ||||||||
4485 | return QualType(); | ||||||||
4486 | } | ||||||||
4487 | |||||||||
4488 | |||||||||
4489 | |||||||||
4490 | ExprResult | ||||||||
4491 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||||||
4492 | tok::TokenKind Kind, Expr *Input) { | ||||||||
4493 | UnaryOperatorKind Opc; | ||||||||
4494 | switch (Kind) { | ||||||||
4495 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4495); | ||||||||
4496 | case tok::plusplus: Opc = UO_PostInc; break; | ||||||||
4497 | case tok::minusminus: Opc = UO_PostDec; break; | ||||||||
4498 | } | ||||||||
4499 | |||||||||
4500 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||||||
4501 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||||||
4502 | if (Result.isInvalid()) return ExprError(); | ||||||||
4503 | Input = Result.get(); | ||||||||
4504 | |||||||||
4505 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||||||
4506 | } | ||||||||
4507 | |||||||||
4508 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||||||
4509 | /// | ||||||||
4510 | /// \return true on error | ||||||||
4511 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||||||
4512 | SourceLocation opLoc, | ||||||||
4513 | Expr *op) { | ||||||||
4514 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4514, __PRETTY_FUNCTION__)); | ||||||||
4515 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||||||
4516 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||||||
4517 | return false; | ||||||||
4518 | |||||||||
4519 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||||||
4520 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||||||
4521 | << op->getSourceRange(); | ||||||||
4522 | return true; | ||||||||
4523 | } | ||||||||
4524 | |||||||||
4525 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||||||
4526 | auto *BaseNoParens = Base->IgnoreParens(); | ||||||||
4527 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||||||
4528 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||||||
4529 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||||||
4530 | } | ||||||||
4531 | |||||||||
4532 | ExprResult | ||||||||
4533 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | ||||||||
4534 | Expr *idx, SourceLocation rbLoc) { | ||||||||
4535 | if (base && !base->getType().isNull() && | ||||||||
4536 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | ||||||||
4537 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | ||||||||
4538 | SourceLocation(), /*Length*/ nullptr, | ||||||||
4539 | /*Stride=*/nullptr, rbLoc); | ||||||||
4540 | |||||||||
4541 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||||||
4542 | if (isa<ParenListExpr>(base)) { | ||||||||
4543 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||||||
4544 | if (result.isInvalid()) return ExprError(); | ||||||||
4545 | base = result.get(); | ||||||||
4546 | } | ||||||||
4547 | |||||||||
4548 | // Check if base and idx form a MatrixSubscriptExpr. | ||||||||
4549 | // | ||||||||
4550 | // Helper to check for comma expressions, which are not allowed as indices for | ||||||||
4551 | // matrix subscript expressions. | ||||||||
4552 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||||||
4553 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||||||
4554 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||||||
4555 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4556 | return true; | ||||||||
4557 | } | ||||||||
4558 | return false; | ||||||||
4559 | }; | ||||||||
4560 | // The matrix subscript operator ([][])is considered a single operator. | ||||||||
4561 | // Separating the index expressions by parenthesis is not allowed. | ||||||||
4562 | if (base->getType()->isSpecificPlaceholderType( | ||||||||
4563 | BuiltinType::IncompleteMatrixIdx) && | ||||||||
4564 | !isa<MatrixSubscriptExpr>(base)) { | ||||||||
4565 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||||||
4566 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4567 | return ExprError(); | ||||||||
4568 | } | ||||||||
4569 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||||||
4570 | // MatrixSubscriptExpr. | ||||||||
4571 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||||||
4572 | if (matSubscriptE) { | ||||||||
4573 | if (CheckAndReportCommaError(idx)) | ||||||||
4574 | return ExprError(); | ||||||||
4575 | |||||||||
4576 | assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4577, __PRETTY_FUNCTION__)) | ||||||||
4577 | "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4577, __PRETTY_FUNCTION__)); | ||||||||
4578 | return CreateBuiltinMatrixSubscriptExpr( | ||||||||
4579 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | ||||||||
4580 | } | ||||||||
4581 | |||||||||
4582 | // Handle any non-overload placeholder types in the base and index | ||||||||
4583 | // expressions. We can't handle overloads here because the other | ||||||||
4584 | // operand might be an overloadable type, in which case the overload | ||||||||
4585 | // resolution for the operator overload should get the first crack | ||||||||
4586 | // at the overload. | ||||||||
4587 | bool IsMSPropertySubscript = false; | ||||||||
4588 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4589 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||||||
4590 | if (!IsMSPropertySubscript) { | ||||||||
4591 | ExprResult result = CheckPlaceholderExpr(base); | ||||||||
4592 | if (result.isInvalid()) | ||||||||
4593 | return ExprError(); | ||||||||
4594 | base = result.get(); | ||||||||
4595 | } | ||||||||
4596 | } | ||||||||
4597 | |||||||||
4598 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||||||
4599 | if (base->getType()->isMatrixType()) { | ||||||||
4600 | if (CheckAndReportCommaError(idx)) | ||||||||
4601 | return ExprError(); | ||||||||
4602 | |||||||||
4603 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | ||||||||
4604 | } | ||||||||
4605 | |||||||||
4606 | // A comma-expression as the index is deprecated in C++2a onwards. | ||||||||
4607 | if (getLangOpts().CPlusPlus20 && | ||||||||
4608 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||||||
4609 | (isa<CXXOperatorCallExpr>(idx) && | ||||||||
4610 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | ||||||||
4611 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||||||
4612 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||||||
4613 | } | ||||||||
4614 | |||||||||
4615 | if (idx->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4616 | ExprResult result = CheckPlaceholderExpr(idx); | ||||||||
4617 | if (result.isInvalid()) return ExprError(); | ||||||||
4618 | idx = result.get(); | ||||||||
4619 | } | ||||||||
4620 | |||||||||
4621 | // Build an unanalyzed expression if either operand is type-dependent. | ||||||||
4622 | if (getLangOpts().CPlusPlus && | ||||||||
4623 | (base->isTypeDependent() || idx->isTypeDependent())) { | ||||||||
4624 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | ||||||||
4625 | VK_LValue, OK_Ordinary, rbLoc); | ||||||||
4626 | } | ||||||||
4627 | |||||||||
4628 | // MSDN, property (C++) | ||||||||
4629 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||||||
4630 | // This attribute can also be used in the declaration of an empty array in a | ||||||||
4631 | // class or structure definition. For example: | ||||||||
4632 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||||||
4633 | // The above statement indicates that x[] can be used with one or more array | ||||||||
4634 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||||||
4635 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||||||
4636 | if (IsMSPropertySubscript) { | ||||||||
4637 | // Build MS property subscript expression if base is MS property reference | ||||||||
4638 | // or MS property subscript. | ||||||||
4639 | return new (Context) MSPropertySubscriptExpr( | ||||||||
4640 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | ||||||||
4641 | } | ||||||||
4642 | |||||||||
4643 | // Use C++ overloaded-operator rules if either operand has record | ||||||||
4644 | // type. The spec says to do this if either type is *overloadable*, | ||||||||
4645 | // but enum types can't declare subscript operators or conversion | ||||||||
4646 | // operators, so there's nothing interesting for overload resolution | ||||||||
4647 | // to do if there aren't any record types involved. | ||||||||
4648 | // | ||||||||
4649 | // ObjC pointers have their own subscripting logic that is not tied | ||||||||
4650 | // to overload resolution and so should not take this path. | ||||||||
4651 | if (getLangOpts().CPlusPlus && | ||||||||
4652 | (base->getType()->isRecordType() || | ||||||||
4653 | (!base->getType()->isObjCObjectPointerType() && | ||||||||
4654 | idx->getType()->isRecordType()))) { | ||||||||
4655 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | ||||||||
4656 | } | ||||||||
4657 | |||||||||
4658 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | ||||||||
4659 | |||||||||
4660 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||||||
4661 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||||||
4662 | |||||||||
4663 | return Res; | ||||||||
4664 | } | ||||||||
4665 | |||||||||
4666 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||||||
4667 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||||||
4668 | InitializationKind Kind = | ||||||||
4669 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||||||
4670 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||||||
4671 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||||||
4672 | } | ||||||||
4673 | |||||||||
4674 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||||||
4675 | Expr *ColumnIdx, | ||||||||
4676 | SourceLocation RBLoc) { | ||||||||
4677 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||||||
4678 | if (BaseR.isInvalid()) | ||||||||
4679 | return BaseR; | ||||||||
4680 | Base = BaseR.get(); | ||||||||
4681 | |||||||||
4682 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||||||
4683 | if (RowR.isInvalid()) | ||||||||
4684 | return RowR; | ||||||||
4685 | RowIdx = RowR.get(); | ||||||||
4686 | |||||||||
4687 | if (!ColumnIdx) | ||||||||
4688 | return new (Context) MatrixSubscriptExpr( | ||||||||
4689 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||||||
4690 | |||||||||
4691 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||||||
4692 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||||||
4693 | ColumnIdx->isTypeDependent()) | ||||||||
4694 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||||||
4695 | Context.DependentTy, RBLoc); | ||||||||
4696 | |||||||||
4697 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||||||
4698 | if (ColumnR.isInvalid()) | ||||||||
4699 | return ColumnR; | ||||||||
4700 | ColumnIdx = ColumnR.get(); | ||||||||
4701 | |||||||||
4702 | // Check that IndexExpr is an integer expression. If it is a constant | ||||||||
4703 | // expression, check that it is less than Dim (= the number of elements in the | ||||||||
4704 | // corresponding dimension). | ||||||||
4705 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||||||
4706 | bool IsColumnIdx) -> Expr * { | ||||||||
4707 | if (!IndexExpr->getType()->isIntegerType() && | ||||||||
4708 | !IndexExpr->isTypeDependent()) { | ||||||||
4709 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||||||
4710 | << IsColumnIdx; | ||||||||
4711 | return nullptr; | ||||||||
4712 | } | ||||||||
4713 | |||||||||
4714 | if (Optional<llvm::APSInt> Idx = | ||||||||
4715 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||||||
4716 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||||||
4717 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||||||
4718 | << IsColumnIdx << Dim; | ||||||||
4719 | return nullptr; | ||||||||
4720 | } | ||||||||
4721 | } | ||||||||
4722 | |||||||||
4723 | ExprResult ConvExpr = | ||||||||
4724 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||||||
4725 | assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4726, __PRETTY_FUNCTION__)) | ||||||||
4726 | "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 4726, __PRETTY_FUNCTION__)); | ||||||||
4727 | return ConvExpr.get(); | ||||||||
4728 | }; | ||||||||
4729 | |||||||||
4730 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||||||
4731 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||||||
4732 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||||||
4733 | if (!RowIdx || !ColumnIdx) | ||||||||
4734 | return ExprError(); | ||||||||
4735 | |||||||||
4736 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||||||
4737 | MTy->getElementType(), RBLoc); | ||||||||
4738 | } | ||||||||
4739 | |||||||||
4740 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||||||
4741 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||||||
4742 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||||||
4743 | |||||||||
4744 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||||||
4745 | // checked. | ||||||||
4746 | const MemberExpr *Member = nullptr; | ||||||||
4747 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||||||
4748 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||||||
4749 | |||||||||
4750 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||||||
4751 | } | ||||||||
4752 | |||||||||
4753 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||||||
4754 | QualType ResultTy = E->getType(); | ||||||||
4755 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||||||
4756 | |||||||||
4757 | // Bail if the element is an array since it is not memory access. | ||||||||
4758 | if (isa<ArrayType>(ResultTy)) | ||||||||
4759 | return; | ||||||||
4760 | |||||||||
4761 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||||||
4762 | LastRecord.PossibleDerefs.insert(E); | ||||||||
4763 | return; | ||||||||
4764 | } | ||||||||
4765 | |||||||||
4766 | // Check if the base type is a pointer to a member access of a struct | ||||||||
4767 | // marked with noderef. | ||||||||
4768 | const Expr *Base = E->getBase(); | ||||||||
4769 | QualType BaseTy = Base->getType(); | ||||||||
4770 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||||||
4771 | // Not a pointer access | ||||||||
4772 | return; | ||||||||
4773 | |||||||||
4774 | const MemberExpr *Member = nullptr; | ||||||||
4775 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||||||
4776 | Member->isArrow()) | ||||||||
4777 | Base = Member->getBase(); | ||||||||
4778 | |||||||||
4779 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||||||
4780 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||||||
4781 | LastRecord.PossibleDerefs.insert(E); | ||||||||
4782 | } | ||||||||
4783 | } | ||||||||
4784 | |||||||||
4785 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||||||
4786 | Expr *LowerBound, | ||||||||
4787 | SourceLocation ColonLocFirst, | ||||||||
4788 | SourceLocation ColonLocSecond, | ||||||||
4789 | Expr *Length, Expr *Stride, | ||||||||
4790 | SourceLocation RBLoc) { | ||||||||
4791 | if (Base->getType()->isPlaceholderType() && | ||||||||
4792 | !Base->getType()->isSpecificPlaceholderType( | ||||||||
4793 | BuiltinType::OMPArraySection)) { | ||||||||
4794 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||||||
4795 | if (Result.isInvalid()) | ||||||||
4796 | return ExprError(); | ||||||||
4797 | Base = Result.get(); | ||||||||
4798 | } | ||||||||
4799 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4800 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||||||
4801 | if (Result.isInvalid()) | ||||||||
4802 | return ExprError(); | ||||||||
4803 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4804 | if (Result.isInvalid()) | ||||||||
4805 | return ExprError(); | ||||||||
4806 | LowerBound = Result.get(); | ||||||||
4807 | } | ||||||||
4808 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4809 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||||||
4810 | if (Result.isInvalid()) | ||||||||
4811 | return ExprError(); | ||||||||
4812 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4813 | if (Result.isInvalid()) | ||||||||
4814 | return ExprError(); | ||||||||
4815 | Length = Result.get(); | ||||||||
4816 | } | ||||||||
4817 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||||||
4818 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||||||
4819 | if (Result.isInvalid()) | ||||||||
4820 | return ExprError(); | ||||||||
4821 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4822 | if (Result.isInvalid()) | ||||||||
4823 | return ExprError(); | ||||||||
4824 | Stride = Result.get(); | ||||||||
4825 | } | ||||||||
4826 | |||||||||
4827 | // Build an unanalyzed expression if either operand is type-dependent. | ||||||||
4828 | if (Base->isTypeDependent() || | ||||||||
4829 | (LowerBound && | ||||||||
4830 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||||||
4831 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||||||
4832 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||||||
4833 | return new (Context) OMPArraySectionExpr( | ||||||||
4834 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||||||
4835 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||||||
4836 | } | ||||||||
4837 | |||||||||
4838 | // Perform default conversions. | ||||||||
4839 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||||||
4840 | QualType ResultTy; | ||||||||
4841 | if (OriginalTy->isAnyPointerType()) { | ||||||||
4842 | ResultTy = OriginalTy->getPointeeType(); | ||||||||
4843 | } else if (OriginalTy->isArrayType()) { | ||||||||
4844 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||||||
4845 | } else { | ||||||||
4846 | return ExprError( | ||||||||
4847 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||||||
4848 | << Base->getSourceRange()); | ||||||||
4849 | } | ||||||||
4850 | // C99 6.5.2.1p1 | ||||||||
4851 | if (LowerBound) { | ||||||||
4852 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||||||
4853 | LowerBound); | ||||||||
4854 | if (Res.isInvalid()) | ||||||||
4855 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||||||
4856 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4857 | << 0 << LowerBound->getSourceRange()); | ||||||||
4858 | LowerBound = Res.get(); | ||||||||
4859 | |||||||||
4860 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4861 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4862 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4863 | << 0 << LowerBound->getSourceRange(); | ||||||||
4864 | } | ||||||||
4865 | if (Length) { | ||||||||
4866 | auto Res = | ||||||||
4867 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||||||
4868 | if (Res.isInvalid()) | ||||||||
4869 | return ExprError(Diag(Length->getExprLoc(), | ||||||||
4870 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4871 | << 1 << Length->getSourceRange()); | ||||||||
4872 | Length = Res.get(); | ||||||||
4873 | |||||||||
4874 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4875 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4876 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4877 | << 1 << Length->getSourceRange(); | ||||||||
4878 | } | ||||||||
4879 | if (Stride) { | ||||||||
4880 | ExprResult Res = | ||||||||
4881 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||||||
4882 | if (Res.isInvalid()) | ||||||||
4883 | return ExprError(Diag(Stride->getExprLoc(), | ||||||||
4884 | diag::err_omp_typecheck_section_not_integer) | ||||||||
4885 | << 1 << Stride->getSourceRange()); | ||||||||
4886 | Stride = Res.get(); | ||||||||
4887 | |||||||||
4888 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
4889 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
4890 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||||||
4891 | << 1 << Stride->getSourceRange(); | ||||||||
4892 | } | ||||||||
4893 | |||||||||
4894 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||||||
4895 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||||||
4896 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||||||
4897 | // incomplete types are not object types. | ||||||||
4898 | if (ResultTy->isFunctionType()) { | ||||||||
4899 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||||||
4900 | << ResultTy << Base->getSourceRange(); | ||||||||
4901 | return ExprError(); | ||||||||
4902 | } | ||||||||
4903 | |||||||||
4904 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||||||
4905 | diag::err_omp_section_incomplete_type, Base)) | ||||||||
4906 | return ExprError(); | ||||||||
4907 | |||||||||
4908 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||||||
4909 | Expr::EvalResult Result; | ||||||||
4910 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||||||
4911 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
4912 | // The array section must be a subset of the original array. | ||||||||
4913 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||||||
4914 | if (LowerBoundValue.isNegative()) { | ||||||||
4915 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||||||
4916 | << LowerBound->getSourceRange(); | ||||||||
4917 | return ExprError(); | ||||||||
4918 | } | ||||||||
4919 | } | ||||||||
4920 | } | ||||||||
4921 | |||||||||
4922 | if (Length) { | ||||||||
4923 | Expr::EvalResult Result; | ||||||||
4924 | if (Length->EvaluateAsInt(Result, Context)) { | ||||||||
4925 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
4926 | // The length must evaluate to non-negative integers. | ||||||||
4927 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||||||
4928 | if (LengthValue.isNegative()) { | ||||||||
4929 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||||||
4930 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
4931 | << Length->getSourceRange(); | ||||||||
4932 | return ExprError(); | ||||||||
4933 | } | ||||||||
4934 | } | ||||||||
4935 | } else if (ColonLocFirst.isValid() && | ||||||||
4936 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||||||
4937 | !OriginalTy->isVariableArrayType()))) { | ||||||||
4938 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
4939 | // When the size of the array dimension is not known, the length must be | ||||||||
4940 | // specified explicitly. | ||||||||
4941 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||||||
4942 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||||||
4943 | return ExprError(); | ||||||||
4944 | } | ||||||||
4945 | |||||||||
4946 | if (Stride) { | ||||||||
4947 | Expr::EvalResult Result; | ||||||||
4948 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||||||
4949 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||||||
4950 | // The stride must evaluate to a positive integer. | ||||||||
4951 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||||||
4952 | if (!StrideValue.isStrictlyPositive()) { | ||||||||
4953 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||||||
4954 | << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
4955 | << Stride->getSourceRange(); | ||||||||
4956 | return ExprError(); | ||||||||
4957 | } | ||||||||
4958 | } | ||||||||
4959 | } | ||||||||
4960 | |||||||||
4961 | if (!Base->getType()->isSpecificPlaceholderType( | ||||||||
4962 | BuiltinType::OMPArraySection)) { | ||||||||
4963 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||||||
4964 | if (Result.isInvalid()) | ||||||||
4965 | return ExprError(); | ||||||||
4966 | Base = Result.get(); | ||||||||
4967 | } | ||||||||
4968 | return new (Context) OMPArraySectionExpr( | ||||||||
4969 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||||||
4970 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||||||
4971 | } | ||||||||
4972 | |||||||||
4973 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||||||
4974 | SourceLocation RParenLoc, | ||||||||
4975 | ArrayRef<Expr *> Dims, | ||||||||
4976 | ArrayRef<SourceRange> Brackets) { | ||||||||
4977 | if (Base->getType()->isPlaceholderType()) { | ||||||||
4978 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||||||
4979 | if (Result.isInvalid()) | ||||||||
4980 | return ExprError(); | ||||||||
4981 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
4982 | if (Result.isInvalid()) | ||||||||
4983 | return ExprError(); | ||||||||
4984 | Base = Result.get(); | ||||||||
4985 | } | ||||||||
4986 | QualType BaseTy = Base->getType(); | ||||||||
4987 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||||||
4988 | // required. | ||||||||
4989 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||||||
4990 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||||||
4991 | LParenLoc, RParenLoc, Dims, Brackets); | ||||||||
4992 | if (!BaseTy->isPointerType() || | ||||||||
4993 | (!Base->isTypeDependent() && | ||||||||
4994 | BaseTy->getPointeeType()->isIncompleteType())) | ||||||||
4995 | return ExprError(Diag(Base->getExprLoc(), | ||||||||
4996 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||||||
4997 | << Base->getSourceRange()); | ||||||||
4998 | |||||||||
4999 | SmallVector<Expr *, 4> NewDims; | ||||||||
5000 | bool ErrorFound = false; | ||||||||
5001 | for (Expr *Dim : Dims) { | ||||||||
5002 | if (Dim->getType()->isPlaceholderType()) { | ||||||||
5003 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||||||
5004 | if (Result.isInvalid()) { | ||||||||
5005 | ErrorFound = true; | ||||||||
5006 | continue; | ||||||||
5007 | } | ||||||||
5008 | Result = DefaultLvalueConversion(Result.get()); | ||||||||
5009 | if (Result.isInvalid()) { | ||||||||
5010 | ErrorFound = true; | ||||||||
5011 | continue; | ||||||||
5012 | } | ||||||||
5013 | Dim = Result.get(); | ||||||||
5014 | } | ||||||||
5015 | if (!Dim->isTypeDependent()) { | ||||||||
5016 | ExprResult Result = | ||||||||
5017 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||||||
5018 | if (Result.isInvalid()) { | ||||||||
5019 | ErrorFound = true; | ||||||||
5020 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||||||
5021 | << Dim->getSourceRange(); | ||||||||
5022 | continue; | ||||||||
5023 | } | ||||||||
5024 | Dim = Result.get(); | ||||||||
5025 | Expr::EvalResult EvResult; | ||||||||
5026 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||||||
5027 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||||||
5028 | // Each si is an integral type expression that must evaluate to a | ||||||||
5029 | // positive integer. | ||||||||
5030 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||||||
5031 | if (!Value.isStrictlyPositive()) { | ||||||||
5032 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||||||
5033 | << Value.toString(/*Radix=*/10, /*Signed=*/true) | ||||||||
5034 | << Dim->getSourceRange(); | ||||||||
5035 | ErrorFound = true; | ||||||||
5036 | continue; | ||||||||
5037 | } | ||||||||
5038 | } | ||||||||
5039 | } | ||||||||
5040 | NewDims.push_back(Dim); | ||||||||
5041 | } | ||||||||
5042 | if (ErrorFound) | ||||||||
5043 | return ExprError(); | ||||||||
5044 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||||||
5045 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||||||
5046 | } | ||||||||
5047 | |||||||||
5048 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||||||
5049 | SourceLocation LLoc, SourceLocation RLoc, | ||||||||
5050 | ArrayRef<OMPIteratorData> Data) { | ||||||||
5051 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||||||
5052 | bool IsCorrect = true; | ||||||||
5053 | for (const OMPIteratorData &D : Data) { | ||||||||
5054 | TypeSourceInfo *TInfo = nullptr; | ||||||||
5055 | SourceLocation StartLoc; | ||||||||
5056 | QualType DeclTy; | ||||||||
5057 | if (!D.Type.getAsOpaquePtr()) { | ||||||||
5058 | // OpenMP 5.0, 2.1.6 Iterators | ||||||||
5059 | // In an iterator-specifier, if the iterator-type is not specified then | ||||||||
5060 | // the type of that iterator is of int type. | ||||||||
5061 | DeclTy = Context.IntTy; | ||||||||
5062 | StartLoc = D.DeclIdentLoc; | ||||||||
5063 | } else { | ||||||||
5064 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||||||
5065 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||||||
5066 | } | ||||||||
5067 | |||||||||
5068 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||||||
5069 | DeclTy->containsUnexpandedParameterPack() || | ||||||||
5070 | DeclTy->isInstantiationDependentType(); | ||||||||
5071 | if (!IsDeclTyDependent) { | ||||||||
5072 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||||||
5073 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||||||
5074 | // The iterator-type must be an integral or pointer type. | ||||||||
5075 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||||||
5076 | << DeclTy; | ||||||||
5077 | IsCorrect = false; | ||||||||
5078 | continue; | ||||||||
5079 | } | ||||||||
5080 | if (DeclTy.isConstant(Context)) { | ||||||||
5081 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||||||
5082 | // The iterator-type must not be const qualified. | ||||||||
5083 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||||||
5084 | << DeclTy; | ||||||||
5085 | IsCorrect = false; | ||||||||
5086 | continue; | ||||||||
5087 | } | ||||||||
5088 | } | ||||||||
5089 | |||||||||
5090 | // Iterator declaration. | ||||||||
5091 | assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast <void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5091, __PRETTY_FUNCTION__)); | ||||||||
5092 | // Always try to create iterator declarator to avoid extra error messages | ||||||||
5093 | // about unknown declarations use. | ||||||||
5094 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||||||
5095 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||||||
5096 | VD->setImplicit(); | ||||||||
5097 | if (S) { | ||||||||
5098 | // Check for conflicting previous declaration. | ||||||||
5099 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||||||
5100 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||||||
5101 | ForVisibleRedeclaration); | ||||||||
5102 | Previous.suppressDiagnostics(); | ||||||||
5103 | LookupName(Previous, S); | ||||||||
5104 | |||||||||
5105 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||||||
5106 | /*AllowInlineNamespace=*/false); | ||||||||
5107 | if (!Previous.empty()) { | ||||||||
5108 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||||||
5109 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||||||
5110 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||||||
5111 | } else { | ||||||||
5112 | PushOnScopeChains(VD, S); | ||||||||
5113 | } | ||||||||
5114 | } else { | ||||||||
5115 | CurContext->addDecl(VD); | ||||||||
5116 | } | ||||||||
5117 | Expr *Begin = D.Range.Begin; | ||||||||
5118 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||||||
5119 | ExprResult BeginRes = | ||||||||
5120 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||||||
5121 | Begin = BeginRes.get(); | ||||||||
5122 | } | ||||||||
5123 | Expr *End = D.Range.End; | ||||||||
5124 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||||||
5125 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||||||
5126 | End = EndRes.get(); | ||||||||
5127 | } | ||||||||
5128 | Expr *Step = D.Range.Step; | ||||||||
5129 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||||||
5130 | if (!Step->getType()->isIntegralType(Context)) { | ||||||||
5131 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||||||
5132 | << Step << Step->getSourceRange(); | ||||||||
5133 | IsCorrect = false; | ||||||||
5134 | continue; | ||||||||
5135 | } | ||||||||
5136 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||||||
5137 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||||||
5138 | // If the step expression of a range-specification equals zero, the | ||||||||
5139 | // behavior is unspecified. | ||||||||
5140 | if (Result && Result->isNullValue()) { | ||||||||
5141 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||||||
5142 | << Step << Step->getSourceRange(); | ||||||||
5143 | IsCorrect = false; | ||||||||
5144 | continue; | ||||||||
5145 | } | ||||||||
5146 | } | ||||||||
5147 | if (!Begin || !End || !IsCorrect) { | ||||||||
5148 | IsCorrect = false; | ||||||||
5149 | continue; | ||||||||
5150 | } | ||||||||
5151 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||||||
5152 | IDElem.IteratorDecl = VD; | ||||||||
5153 | IDElem.AssignmentLoc = D.AssignLoc; | ||||||||
5154 | IDElem.Range.Begin = Begin; | ||||||||
5155 | IDElem.Range.End = End; | ||||||||
5156 | IDElem.Range.Step = Step; | ||||||||
5157 | IDElem.ColonLoc = D.ColonLoc; | ||||||||
5158 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||||||
5159 | } | ||||||||
5160 | if (!IsCorrect) { | ||||||||
5161 | // Invalidate all created iterator declarations if error is found. | ||||||||
5162 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5163 | if (Decl *ID = D.IteratorDecl) | ||||||||
5164 | ID->setInvalidDecl(); | ||||||||
5165 | } | ||||||||
5166 | return ExprError(); | ||||||||
5167 | } | ||||||||
5168 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||||||
5169 | if (!CurContext->isDependentContext()) { | ||||||||
5170 | // Build number of ityeration for each iteration range. | ||||||||
5171 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||||||
5172 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||||||
5173 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5174 | // (Endi - Begini) | ||||||||
5175 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||||||
5176 | D.Range.Begin); | ||||||||
5177 | if(!Res.isUsable()) { | ||||||||
5178 | IsCorrect = false; | ||||||||
5179 | continue; | ||||||||
5180 | } | ||||||||
5181 | ExprResult St, St1; | ||||||||
5182 | if (D.Range.Step) { | ||||||||
5183 | St = D.Range.Step; | ||||||||
5184 | // (Endi - Begini) + Stepi | ||||||||
5185 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||||||
5186 | if (!Res.isUsable()) { | ||||||||
5187 | IsCorrect = false; | ||||||||
5188 | continue; | ||||||||
5189 | } | ||||||||
5190 | // (Endi - Begini) + Stepi - 1 | ||||||||
5191 | Res = | ||||||||
5192 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||||||
5193 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||||||
5194 | if (!Res.isUsable()) { | ||||||||
5195 | IsCorrect = false; | ||||||||
5196 | continue; | ||||||||
5197 | } | ||||||||
5198 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||||||
5199 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||||||
5200 | if (!Res.isUsable()) { | ||||||||
5201 | IsCorrect = false; | ||||||||
5202 | continue; | ||||||||
5203 | } | ||||||||
5204 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||||||
5205 | // (Begini - Endi) | ||||||||
5206 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||||||
5207 | D.Range.Begin, D.Range.End); | ||||||||
5208 | if (!Res1.isUsable()) { | ||||||||
5209 | IsCorrect = false; | ||||||||
5210 | continue; | ||||||||
5211 | } | ||||||||
5212 | // (Begini - Endi) - Stepi | ||||||||
5213 | Res1 = | ||||||||
5214 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||||||
5215 | if (!Res1.isUsable()) { | ||||||||
5216 | IsCorrect = false; | ||||||||
5217 | continue; | ||||||||
5218 | } | ||||||||
5219 | // (Begini - Endi) - Stepi - 1 | ||||||||
5220 | Res1 = | ||||||||
5221 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||||||
5222 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||||||
5223 | if (!Res1.isUsable()) { | ||||||||
5224 | IsCorrect = false; | ||||||||
5225 | continue; | ||||||||
5226 | } | ||||||||
5227 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||||||
5228 | Res1 = | ||||||||
5229 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||||||
5230 | if (!Res1.isUsable()) { | ||||||||
5231 | IsCorrect = false; | ||||||||
5232 | continue; | ||||||||
5233 | } | ||||||||
5234 | // Stepi > 0. | ||||||||
5235 | ExprResult CmpRes = | ||||||||
5236 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||||||
5237 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||||||
5238 | if (!CmpRes.isUsable()) { | ||||||||
5239 | IsCorrect = false; | ||||||||
5240 | continue; | ||||||||
5241 | } | ||||||||
5242 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||||||
5243 | Res.get(), Res1.get()); | ||||||||
5244 | if (!Res.isUsable()) { | ||||||||
5245 | IsCorrect = false; | ||||||||
5246 | continue; | ||||||||
5247 | } | ||||||||
5248 | } | ||||||||
5249 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||||||
5250 | if (!Res.isUsable()) { | ||||||||
5251 | IsCorrect = false; | ||||||||
5252 | continue; | ||||||||
5253 | } | ||||||||
5254 | |||||||||
5255 | // Build counter update. | ||||||||
5256 | // Build counter. | ||||||||
5257 | auto *CounterVD = | ||||||||
5258 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||||||
5259 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||||||
5260 | Res.get()->getType(), nullptr, SC_None); | ||||||||
5261 | CounterVD->setImplicit(); | ||||||||
5262 | ExprResult RefRes = | ||||||||
5263 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||||||
5264 | D.IteratorDecl->getBeginLoc()); | ||||||||
5265 | // Build counter update. | ||||||||
5266 | // I = Begini + counter * Stepi; | ||||||||
5267 | ExprResult UpdateRes; | ||||||||
5268 | if (D.Range.Step) { | ||||||||
5269 | UpdateRes = CreateBuiltinBinOp( | ||||||||
5270 | D.AssignmentLoc, BO_Mul, | ||||||||
5271 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||||||
5272 | } else { | ||||||||
5273 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||||||
5274 | } | ||||||||
5275 | if (!UpdateRes.isUsable()) { | ||||||||
5276 | IsCorrect = false; | ||||||||
5277 | continue; | ||||||||
5278 | } | ||||||||
5279 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||||||
5280 | UpdateRes.get()); | ||||||||
5281 | if (!UpdateRes.isUsable()) { | ||||||||
5282 | IsCorrect = false; | ||||||||
5283 | continue; | ||||||||
5284 | } | ||||||||
5285 | ExprResult VDRes = | ||||||||
5286 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||||||
5287 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||||||
5288 | D.IteratorDecl->getBeginLoc()); | ||||||||
5289 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||||||
5290 | UpdateRes.get()); | ||||||||
5291 | if (!UpdateRes.isUsable()) { | ||||||||
5292 | IsCorrect = false; | ||||||||
5293 | continue; | ||||||||
5294 | } | ||||||||
5295 | UpdateRes = | ||||||||
5296 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||||||
5297 | if (!UpdateRes.isUsable()) { | ||||||||
5298 | IsCorrect = false; | ||||||||
5299 | continue; | ||||||||
5300 | } | ||||||||
5301 | ExprResult CounterUpdateRes = | ||||||||
5302 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||||||
5303 | if (!CounterUpdateRes.isUsable()) { | ||||||||
5304 | IsCorrect = false; | ||||||||
5305 | continue; | ||||||||
5306 | } | ||||||||
5307 | CounterUpdateRes = | ||||||||
5308 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||||||
5309 | if (!CounterUpdateRes.isUsable()) { | ||||||||
5310 | IsCorrect = false; | ||||||||
5311 | continue; | ||||||||
5312 | } | ||||||||
5313 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||||||
5314 | HD.CounterVD = CounterVD; | ||||||||
5315 | HD.Upper = Res.get(); | ||||||||
5316 | HD.Update = UpdateRes.get(); | ||||||||
5317 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||||||
5318 | } | ||||||||
5319 | } else { | ||||||||
5320 | Helpers.assign(ID.size(), {}); | ||||||||
5321 | } | ||||||||
5322 | if (!IsCorrect) { | ||||||||
5323 | // Invalidate all created iterator declarations if error is found. | ||||||||
5324 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||||||
5325 | if (Decl *ID = D.IteratorDecl) | ||||||||
5326 | ID->setInvalidDecl(); | ||||||||
5327 | } | ||||||||
5328 | return ExprError(); | ||||||||
5329 | } | ||||||||
5330 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||||||
5331 | LLoc, RLoc, ID, Helpers); | ||||||||
5332 | } | ||||||||
5333 | |||||||||
5334 | ExprResult | ||||||||
5335 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||||||
5336 | Expr *Idx, SourceLocation RLoc) { | ||||||||
5337 | Expr *LHSExp = Base; | ||||||||
5338 | Expr *RHSExp = Idx; | ||||||||
5339 | |||||||||
5340 | ExprValueKind VK = VK_LValue; | ||||||||
5341 | ExprObjectKind OK = OK_Ordinary; | ||||||||
5342 | |||||||||
5343 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||||||
5344 | // a non-lvalue array, and an lvalue otherwise. | ||||||||
5345 | if (getLangOpts().CPlusPlus11) { | ||||||||
5346 | for (auto *Op : {LHSExp, RHSExp}) { | ||||||||
5347 | Op = Op->IgnoreImplicit(); | ||||||||
5348 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||||||
5349 | VK = VK_XValue; | ||||||||
5350 | } | ||||||||
5351 | } | ||||||||
5352 | |||||||||
5353 | // Perform default conversions. | ||||||||
5354 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||||||
5355 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||||||
5356 | if (Result.isInvalid()) | ||||||||
5357 | return ExprError(); | ||||||||
5358 | LHSExp = Result.get(); | ||||||||
5359 | } | ||||||||
5360 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||||||
5361 | if (Result.isInvalid()) | ||||||||
5362 | return ExprError(); | ||||||||
5363 | RHSExp = Result.get(); | ||||||||
5364 | |||||||||
5365 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||||||
5366 | |||||||||
5367 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||||||
5368 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||||||
5369 | // in the subscript position. As a result, we need to derive the array base | ||||||||
5370 | // and index from the expression types. | ||||||||
5371 | Expr *BaseExpr, *IndexExpr; | ||||||||
5372 | QualType ResultType; | ||||||||
5373 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||||||
5374 | BaseExpr = LHSExp; | ||||||||
5375 | IndexExpr = RHSExp; | ||||||||
5376 | ResultType = Context.DependentTy; | ||||||||
5377 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||||||
5378 | BaseExpr = LHSExp; | ||||||||
5379 | IndexExpr = RHSExp; | ||||||||
5380 | ResultType = PTy->getPointeeType(); | ||||||||
5381 | } else if (const ObjCObjectPointerType *PTy = | ||||||||
5382 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||||||
5383 | BaseExpr = LHSExp; | ||||||||
5384 | IndexExpr = RHSExp; | ||||||||
5385 | |||||||||
5386 | // Use custom logic if this should be the pseudo-object subscript | ||||||||
5387 | // expression. | ||||||||
5388 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||||||
5389 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||||||
5390 | nullptr); | ||||||||
5391 | |||||||||
5392 | ResultType = PTy->getPointeeType(); | ||||||||
5393 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||||||
5394 | // Handle the uncommon case of "123[Ptr]". | ||||||||
5395 | BaseExpr = RHSExp; | ||||||||
5396 | IndexExpr = LHSExp; | ||||||||
5397 | ResultType = PTy->getPointeeType(); | ||||||||
5398 | } else if (const ObjCObjectPointerType *PTy = | ||||||||
5399 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||||||
5400 | // Handle the uncommon case of "123[Ptr]". | ||||||||
5401 | BaseExpr = RHSExp; | ||||||||
5402 | IndexExpr = LHSExp; | ||||||||
5403 | ResultType = PTy->getPointeeType(); | ||||||||
5404 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||||||
5405 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||||||
5406 | << ResultType << BaseExpr->getSourceRange(); | ||||||||
5407 | return ExprError(); | ||||||||
5408 | } | ||||||||
5409 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||||||
5410 | BaseExpr = LHSExp; // vectors: V[123] | ||||||||
5411 | IndexExpr = RHSExp; | ||||||||
5412 | // We apply C++ DR1213 to vector subscripting too. | ||||||||
5413 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | ||||||||
5414 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||||||
5415 | if (Materialized.isInvalid()) | ||||||||
5416 | return ExprError(); | ||||||||
5417 | LHSExp = Materialized.get(); | ||||||||
5418 | } | ||||||||
5419 | VK = LHSExp->getValueKind(); | ||||||||
5420 | if (VK != VK_RValue) | ||||||||
5421 | OK = OK_VectorComponent; | ||||||||
5422 | |||||||||
5423 | ResultType = VTy->getElementType(); | ||||||||
5424 | QualType BaseType = BaseExpr->getType(); | ||||||||
5425 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||||||
5426 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||||||
5427 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||||||
5428 | if (Combined != MemberQuals) | ||||||||
5429 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||||||
5430 | } else if (LHSTy->isArrayType()) { | ||||||||
5431 | // If we see an array that wasn't promoted by | ||||||||
5432 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||||||
5433 | // wasn't promoted because of the C90 rule that doesn't | ||||||||
5434 | // allow promoting non-lvalue arrays. Warn, then | ||||||||
5435 | // force the promotion here. | ||||||||
5436 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||||||
5437 | << LHSExp->getSourceRange(); | ||||||||
5438 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||||||
5439 | CK_ArrayToPointerDecay).get(); | ||||||||
5440 | LHSTy = LHSExp->getType(); | ||||||||
5441 | |||||||||
5442 | BaseExpr = LHSExp; | ||||||||
5443 | IndexExpr = RHSExp; | ||||||||
5444 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | ||||||||
5445 | } else if (RHSTy->isArrayType()) { | ||||||||
5446 | // Same as previous, except for 123[f().a] case | ||||||||
5447 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||||||
5448 | << RHSExp->getSourceRange(); | ||||||||
5449 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||||||
5450 | CK_ArrayToPointerDecay).get(); | ||||||||
5451 | RHSTy = RHSExp->getType(); | ||||||||
5452 | |||||||||
5453 | BaseExpr = RHSExp; | ||||||||
5454 | IndexExpr = LHSExp; | ||||||||
5455 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | ||||||||
5456 | } else { | ||||||||
5457 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||||||
5458 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||||||
5459 | } | ||||||||
5460 | // C99 6.5.2.1p1 | ||||||||
5461 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||||||
5462 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||||||
5463 | << IndexExpr->getSourceRange()); | ||||||||
5464 | |||||||||
5465 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||||||
5466 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||||||
5467 | && !IndexExpr->isTypeDependent()) | ||||||||
5468 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||||||
5469 | |||||||||
5470 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||||||
5471 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||||||
5472 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||||||
5473 | // incomplete types are not object types. | ||||||||
5474 | if (ResultType->isFunctionType()) { | ||||||||
5475 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||||||
5476 | << ResultType << BaseExpr->getSourceRange(); | ||||||||
5477 | return ExprError(); | ||||||||
5478 | } | ||||||||
5479 | |||||||||
5480 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||||||
5481 | // GNU extension: subscripting on pointer to void | ||||||||
5482 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||||||
5483 | << BaseExpr->getSourceRange(); | ||||||||
5484 | |||||||||
5485 | // C forbids expressions of unqualified void type from being l-values. | ||||||||
5486 | // See IsCForbiddenLValueType. | ||||||||
5487 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | ||||||||
5488 | } else if (!ResultType->isDependentType() && | ||||||||
5489 | RequireCompleteSizedType( | ||||||||
5490 | LLoc, ResultType, | ||||||||
5491 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||||||
5492 | return ExprError(); | ||||||||
5493 | |||||||||
5494 | assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5495, __PRETTY_FUNCTION__)) | ||||||||
5495 | !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5495, __PRETTY_FUNCTION__)); | ||||||||
5496 | |||||||||
5497 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||||||
5498 | FunctionScopes.size() > 1) { | ||||||||
5499 | if (auto *TT = | ||||||||
5500 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||||||
5501 | for (auto I = FunctionScopes.rbegin(), | ||||||||
5502 | E = std::prev(FunctionScopes.rend()); | ||||||||
5503 | I != E; ++I) { | ||||||||
5504 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||||||
5505 | if (CSI == nullptr) | ||||||||
5506 | break; | ||||||||
5507 | DeclContext *DC = nullptr; | ||||||||
5508 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||||||
5509 | DC = LSI->CallOperator; | ||||||||
5510 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||||||
5511 | DC = CRSI->TheCapturedDecl; | ||||||||
5512 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||||||
5513 | DC = BSI->TheDecl; | ||||||||
5514 | if (DC) { | ||||||||
5515 | if (DC->containsDecl(TT->getDecl())) | ||||||||
5516 | break; | ||||||||
5517 | captureVariablyModifiedType( | ||||||||
5518 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||||||
5519 | } | ||||||||
5520 | } | ||||||||
5521 | } | ||||||||
5522 | } | ||||||||
5523 | |||||||||
5524 | return new (Context) | ||||||||
5525 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||||||
5526 | } | ||||||||
5527 | |||||||||
5528 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||||||
5529 | ParmVarDecl *Param) { | ||||||||
5530 | if (Param->hasUnparsedDefaultArg()) { | ||||||||
5531 | // If we've already cleared out the location for the default argument, | ||||||||
5532 | // that means we're parsing it right now. | ||||||||
5533 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||||||
5534 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||||||
5535 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||||||
5536 | Param->setInvalidDecl(); | ||||||||
5537 | return true; | ||||||||
5538 | } | ||||||||
5539 | |||||||||
5540 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||||||
5541 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||||||
5542 | Diag(UnparsedDefaultArgLocs[Param], | ||||||||
5543 | diag::note_default_argument_declared_here); | ||||||||
5544 | return true; | ||||||||
5545 | } | ||||||||
5546 | |||||||||
5547 | if (Param->hasUninstantiatedDefaultArg() && | ||||||||
5548 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||||||
5549 | return true; | ||||||||
5550 | |||||||||
5551 | assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?" ) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5551, __PRETTY_FUNCTION__)); | ||||||||
5552 | |||||||||
5553 | // If the default expression creates temporaries, we need to | ||||||||
5554 | // push them to the current stack of expression temporaries so they'll | ||||||||
5555 | // be properly destroyed. | ||||||||
5556 | // FIXME: We should really be rebuilding the default argument with new | ||||||||
5557 | // bound temporaries; see the comment in PR5810. | ||||||||
5558 | // We don't need to do that with block decls, though, because | ||||||||
5559 | // blocks in default argument expression can never capture anything. | ||||||||
5560 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||||||
5561 | // Set the "needs cleanups" bit regardless of whether there are | ||||||||
5562 | // any explicit objects. | ||||||||
5563 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||||||
5564 | |||||||||
5565 | // Append all the objects to the cleanup list. Right now, this | ||||||||
5566 | // should always be a no-op, because blocks in default argument | ||||||||
5567 | // expressions should never be able to capture anything. | ||||||||
5568 | assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5569, __PRETTY_FUNCTION__)) | ||||||||
5569 | "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5569, __PRETTY_FUNCTION__)); | ||||||||
5570 | } | ||||||||
5571 | |||||||||
5572 | // We already type-checked the argument, so we know it works. | ||||||||
5573 | // Just mark all of the declarations in this potentially-evaluated expression | ||||||||
5574 | // as being "referenced". | ||||||||
5575 | EnterExpressionEvaluationContext EvalContext( | ||||||||
5576 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||||||
5577 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||||||
5578 | /*SkipLocalVariables=*/true); | ||||||||
5579 | return false; | ||||||||
5580 | } | ||||||||
5581 | |||||||||
5582 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||||||
5583 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||||||
5584 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg" ) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5584, __PRETTY_FUNCTION__)); | ||||||||
5585 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||||||
5586 | return ExprError(); | ||||||||
5587 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||||||
5588 | } | ||||||||
5589 | |||||||||
5590 | Sema::VariadicCallType | ||||||||
5591 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||||||
5592 | Expr *Fn) { | ||||||||
5593 | if (Proto && Proto->isVariadic()) { | ||||||||
5594 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | ||||||||
5595 | return VariadicConstructor; | ||||||||
5596 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||||||
5597 | return VariadicBlock; | ||||||||
5598 | else if (FDecl) { | ||||||||
5599 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||||||
5600 | if (Method->isInstance()) | ||||||||
5601 | return VariadicMethod; | ||||||||
5602 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||||||
5603 | return VariadicMethod; | ||||||||
5604 | return VariadicFunction; | ||||||||
5605 | } | ||||||||
5606 | return VariadicDoesNotApply; | ||||||||
5607 | } | ||||||||
5608 | |||||||||
5609 | namespace { | ||||||||
5610 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||||||
5611 | public: | ||||||||
5612 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||||||
5613 | unsigned NumArgs, MemberExpr *ME) | ||||||||
5614 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||||||
5615 | FunctionName(FuncName) {} | ||||||||
5616 | |||||||||
5617 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||||
5618 | if (!candidate.getCorrectionSpecifier() || | ||||||||
5619 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||||||
5620 | return false; | ||||||||
5621 | } | ||||||||
5622 | |||||||||
5623 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||||||
5624 | } | ||||||||
5625 | |||||||||
5626 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||||
5627 | return std::make_unique<FunctionCallCCC>(*this); | ||||||||
5628 | } | ||||||||
5629 | |||||||||
5630 | private: | ||||||||
5631 | const IdentifierInfo *const FunctionName; | ||||||||
5632 | }; | ||||||||
5633 | } | ||||||||
5634 | |||||||||
5635 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||||||
5636 | FunctionDecl *FDecl, | ||||||||
5637 | ArrayRef<Expr *> Args) { | ||||||||
5638 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||||||
5639 | DeclarationName FuncName = FDecl->getDeclName(); | ||||||||
5640 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||||||
5641 | |||||||||
5642 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||||||
5643 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||||||
5644 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||||||
5645 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||||||
5646 | Sema::CTK_ErrorRecovery)) { | ||||||||
5647 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||||||
5648 | if (Corrected.isOverloaded()) { | ||||||||
5649 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||||||
5650 | OverloadCandidateSet::iterator Best; | ||||||||
5651 | for (NamedDecl *CD : Corrected) { | ||||||||
5652 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||||||
5653 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||||||
5654 | OCS); | ||||||||
5655 | } | ||||||||
5656 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||||||
5657 | case OR_Success: | ||||||||
5658 | ND = Best->FoundDecl; | ||||||||
5659 | Corrected.setCorrectionDecl(ND); | ||||||||
5660 | break; | ||||||||
5661 | default: | ||||||||
5662 | break; | ||||||||
5663 | } | ||||||||
5664 | } | ||||||||
5665 | ND = ND->getUnderlyingDecl(); | ||||||||
5666 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||||||
5667 | return Corrected; | ||||||||
5668 | } | ||||||||
5669 | } | ||||||||
5670 | return TypoCorrection(); | ||||||||
5671 | } | ||||||||
5672 | |||||||||
5673 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||||||
5674 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||||||
5675 | /// function prototype Proto. Call is the call expression itself, and | ||||||||
5676 | /// Fn is the function expression. For a C++ member function, this | ||||||||
5677 | /// routine does not attempt to convert the object argument. Returns | ||||||||
5678 | /// true if the call is ill-formed. | ||||||||
5679 | bool | ||||||||
5680 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||||||
5681 | FunctionDecl *FDecl, | ||||||||
5682 | const FunctionProtoType *Proto, | ||||||||
5683 | ArrayRef<Expr *> Args, | ||||||||
5684 | SourceLocation RParenLoc, | ||||||||
5685 | bool IsExecConfig) { | ||||||||
5686 | // Bail out early if calling a builtin with custom typechecking. | ||||||||
5687 | if (FDecl) | ||||||||
5688 | if (unsigned ID = FDecl->getBuiltinID()) | ||||||||
5689 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||||||
5690 | return false; | ||||||||
5691 | |||||||||
5692 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||||||
5693 | // assignment, to the types of the corresponding parameter, ... | ||||||||
5694 | unsigned NumParams = Proto->getNumParams(); | ||||||||
5695 | bool Invalid = false; | ||||||||
5696 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||||||
5697 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||||||
5698 | ? 1 /* block */ | ||||||||
5699 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||||||
5700 | : 0 /* function */); | ||||||||
5701 | |||||||||
5702 | // If too few arguments are available (and we don't have default | ||||||||
5703 | // arguments for the remaining parameters), don't make the call. | ||||||||
5704 | if (Args.size() < NumParams) { | ||||||||
5705 | if (Args.size() < MinArgs) { | ||||||||
5706 | TypoCorrection TC; | ||||||||
5707 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||||||
5708 | unsigned diag_id = | ||||||||
5709 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5710 | ? diag::err_typecheck_call_too_few_args_suggest | ||||||||
5711 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||||||
5712 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||||||
5713 | << static_cast<unsigned>(Args.size()) | ||||||||
5714 | << TC.getCorrectionRange()); | ||||||||
5715 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||||||
5716 | Diag(RParenLoc, | ||||||||
5717 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5718 | ? diag::err_typecheck_call_too_few_args_one | ||||||||
5719 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||||||
5720 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||||||
5721 | else | ||||||||
5722 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5723 | ? diag::err_typecheck_call_too_few_args | ||||||||
5724 | : diag::err_typecheck_call_too_few_args_at_least) | ||||||||
5725 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||||||
5726 | << Fn->getSourceRange(); | ||||||||
5727 | |||||||||
5728 | // Emit the location of the prototype. | ||||||||
5729 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||||||
5730 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||||||
5731 | |||||||||
5732 | return true; | ||||||||
5733 | } | ||||||||
5734 | // We reserve space for the default arguments when we create | ||||||||
5735 | // the call expression, before calling ConvertArgumentsForCall. | ||||||||
5736 | assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5737, __PRETTY_FUNCTION__)) | ||||||||
5737 | "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5737, __PRETTY_FUNCTION__)); | ||||||||
5738 | } | ||||||||
5739 | |||||||||
5740 | // If too many are passed and not variadic, error on the extras and drop | ||||||||
5741 | // them. | ||||||||
5742 | if (Args.size() > NumParams) { | ||||||||
5743 | if (!Proto->isVariadic()) { | ||||||||
5744 | TypoCorrection TC; | ||||||||
5745 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||||||
5746 | unsigned diag_id = | ||||||||
5747 | MinArgs == NumParams && !Proto->isVariadic() | ||||||||
5748 | ? diag::err_typecheck_call_too_many_args_suggest | ||||||||
5749 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||||||
5750 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||||||
5751 | << static_cast<unsigned>(Args.size()) | ||||||||
5752 | << TC.getCorrectionRange()); | ||||||||
5753 | } else if (NumParams == 1 && FDecl && | ||||||||
5754 | FDecl->getParamDecl(0)->getDeclName()) | ||||||||
5755 | Diag(Args[NumParams]->getBeginLoc(), | ||||||||
5756 | MinArgs == NumParams | ||||||||
5757 | ? diag::err_typecheck_call_too_many_args_one | ||||||||
5758 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||||||
5759 | << FnKind << FDecl->getParamDecl(0) | ||||||||
5760 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||||||
5761 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||||||
5762 | Args.back()->getEndLoc()); | ||||||||
5763 | else | ||||||||
5764 | Diag(Args[NumParams]->getBeginLoc(), | ||||||||
5765 | MinArgs == NumParams | ||||||||
5766 | ? diag::err_typecheck_call_too_many_args | ||||||||
5767 | : diag::err_typecheck_call_too_many_args_at_most) | ||||||||
5768 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||||||
5769 | << Fn->getSourceRange() | ||||||||
5770 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||||||
5771 | Args.back()->getEndLoc()); | ||||||||
5772 | |||||||||
5773 | // Emit the location of the prototype. | ||||||||
5774 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||||||
5775 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||||||
5776 | |||||||||
5777 | // This deletes the extra arguments. | ||||||||
5778 | Call->shrinkNumArgs(NumParams); | ||||||||
5779 | return true; | ||||||||
5780 | } | ||||||||
5781 | } | ||||||||
5782 | SmallVector<Expr *, 8> AllArgs; | ||||||||
5783 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||||||
5784 | |||||||||
5785 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||||||
5786 | AllArgs, CallType); | ||||||||
5787 | if (Invalid) | ||||||||
5788 | return true; | ||||||||
5789 | unsigned TotalNumArgs = AllArgs.size(); | ||||||||
5790 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||||||
5791 | Call->setArg(i, AllArgs[i]); | ||||||||
5792 | |||||||||
5793 | return false; | ||||||||
5794 | } | ||||||||
5795 | |||||||||
5796 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||||||
5797 | const FunctionProtoType *Proto, | ||||||||
5798 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||||||
5799 | SmallVectorImpl<Expr *> &AllArgs, | ||||||||
5800 | VariadicCallType CallType, bool AllowExplicit, | ||||||||
5801 | bool IsListInitialization) { | ||||||||
5802 | unsigned NumParams = Proto->getNumParams(); | ||||||||
5803 | bool Invalid = false; | ||||||||
5804 | size_t ArgIx = 0; | ||||||||
5805 | // Continue to check argument types (even if we have too few/many args). | ||||||||
5806 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||||||
5807 | QualType ProtoArgType = Proto->getParamType(i); | ||||||||
5808 | |||||||||
5809 | Expr *Arg; | ||||||||
5810 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||||||
5811 | if (ArgIx < Args.size()) { | ||||||||
5812 | Arg = Args[ArgIx++]; | ||||||||
5813 | |||||||||
5814 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||||||
5815 | diag::err_call_incomplete_argument, Arg)) | ||||||||
5816 | return true; | ||||||||
5817 | |||||||||
5818 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||||||
5819 | bool CFAudited = false; | ||||||||
5820 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||||||
5821 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||||||
5822 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||||||
5823 | Arg = stripARCUnbridgedCast(Arg); | ||||||||
5824 | else if (getLangOpts().ObjCAutoRefCount && | ||||||||
5825 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||||||
5826 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||||||
5827 | CFAudited = true; | ||||||||
5828 | |||||||||
5829 | if (Proto->getExtParameterInfo(i).isNoEscape()) | ||||||||
5830 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||||||
5831 | BE->getBlockDecl()->setDoesNotEscape(); | ||||||||
5832 | |||||||||
5833 | InitializedEntity Entity = | ||||||||
5834 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||||||
5835 | ProtoArgType) | ||||||||
5836 | : InitializedEntity::InitializeParameter( | ||||||||
5837 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||||||
5838 | |||||||||
5839 | // Remember that parameter belongs to a CF audited API. | ||||||||
5840 | if (CFAudited) | ||||||||
5841 | Entity.setParameterCFAudited(); | ||||||||
5842 | |||||||||
5843 | ExprResult ArgE = PerformCopyInitialization( | ||||||||
5844 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||||||
5845 | if (ArgE.isInvalid()) | ||||||||
5846 | return true; | ||||||||
5847 | |||||||||
5848 | Arg = ArgE.getAs<Expr>(); | ||||||||
5849 | } else { | ||||||||
5850 | assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee" ) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 5850, __PRETTY_FUNCTION__)); | ||||||||
5851 | |||||||||
5852 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||||||
5853 | if (ArgExpr.isInvalid()) | ||||||||
5854 | return true; | ||||||||
5855 | |||||||||
5856 | Arg = ArgExpr.getAs<Expr>(); | ||||||||
5857 | } | ||||||||
5858 | |||||||||
5859 | // Check for array bounds violations for each argument to the call. This | ||||||||
5860 | // check only triggers warnings when the argument isn't a more complex Expr | ||||||||
5861 | // with its own checking, such as a BinaryOperator. | ||||||||
5862 | CheckArrayAccess(Arg); | ||||||||
5863 | |||||||||
5864 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||||||
5865 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||||||
5866 | |||||||||
5867 | AllArgs.push_back(Arg); | ||||||||
5868 | } | ||||||||
5869 | |||||||||
5870 | // If this is a variadic call, handle args passed through "...". | ||||||||
5871 | if (CallType != VariadicDoesNotApply) { | ||||||||
5872 | // Assume that extern "C" functions with variadic arguments that | ||||||||
5873 | // return __unknown_anytype aren't *really* variadic. | ||||||||
5874 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||||||
5875 | FDecl->isExternC()) { | ||||||||
5876 | for (Expr *A : Args.slice(ArgIx)) { | ||||||||
5877 | QualType paramType; // ignored | ||||||||
5878 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | ||||||||
5879 | Invalid |= arg.isInvalid(); | ||||||||
5880 | AllArgs.push_back(arg.get()); | ||||||||
5881 | } | ||||||||
5882 | |||||||||
5883 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | ||||||||
5884 | } else { | ||||||||
5885 | for (Expr *A : Args.slice(ArgIx)) { | ||||||||
5886 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | ||||||||
5887 | Invalid |= Arg.isInvalid(); | ||||||||
5888 | AllArgs.push_back(Arg.get()); | ||||||||
5889 | } | ||||||||
5890 | } | ||||||||
5891 | |||||||||
5892 | // Check for array bounds violations. | ||||||||
5893 | for (Expr *A : Args.slice(ArgIx)) | ||||||||
5894 | CheckArrayAccess(A); | ||||||||
5895 | } | ||||||||
5896 | return Invalid; | ||||||||
5897 | } | ||||||||
5898 | |||||||||
5899 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | ||||||||
5900 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | ||||||||
5901 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | ||||||||
5902 | TL = DTL.getOriginalLoc(); | ||||||||
5903 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | ||||||||
5904 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | ||||||||
5905 | << ATL.getLocalSourceRange(); | ||||||||
5906 | } | ||||||||
5907 | |||||||||
5908 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | ||||||||
5909 | /// array parameter, check that it is non-null, and that if it is formed by | ||||||||
5910 | /// array-to-pointer decay, the underlying array is sufficiently large. | ||||||||
5911 | /// | ||||||||
5912 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | ||||||||
5913 | /// array type derivation, then for each call to the function, the value of the | ||||||||
5914 | /// corresponding actual argument shall provide access to the first element of | ||||||||
5915 | /// an array with at least as many elements as specified by the size expression. | ||||||||
5916 | void | ||||||||
5917 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | ||||||||
5918 | ParmVarDecl *Param, | ||||||||
5919 | const Expr *ArgExpr) { | ||||||||
5920 | // Static array parameters are not supported in C++. | ||||||||
5921 | if (!Param || getLangOpts().CPlusPlus) | ||||||||
5922 | return; | ||||||||
5923 | |||||||||
5924 | QualType OrigTy = Param->getOriginalType(); | ||||||||
5925 | |||||||||
5926 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | ||||||||
5927 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | ||||||||
5928 | return; | ||||||||
5929 | |||||||||
5930 | if (ArgExpr->isNullPointerConstant(Context, | ||||||||
5931 | Expr::NPC_NeverValueDependent)) { | ||||||||
5932 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | ||||||||
5933 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||||||
5934 | return; | ||||||||
5935 | } | ||||||||
5936 | |||||||||
5937 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | ||||||||
5938 | if (!CAT) | ||||||||
5939 | return; | ||||||||
5940 | |||||||||
5941 | const ConstantArrayType *ArgCAT = | ||||||||
5942 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | ||||||||
5943 | if (!ArgCAT) | ||||||||
5944 | return; | ||||||||
5945 | |||||||||
5946 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | ||||||||
5947 | ArgCAT->getElementType())) { | ||||||||
5948 | if (ArgCAT->getSize().ult(CAT->getSize())) { | ||||||||
5949 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||||||
5950 | << ArgExpr->getSourceRange() | ||||||||
5951 | << (unsigned)ArgCAT->getSize().getZExtValue() | ||||||||
5952 | << (unsigned)CAT->getSize().getZExtValue() << 0; | ||||||||
5953 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||||||
5954 | } | ||||||||
5955 | return; | ||||||||
5956 | } | ||||||||
5957 | |||||||||
5958 | Optional<CharUnits> ArgSize = | ||||||||
5959 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | ||||||||
5960 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | ||||||||
5961 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | ||||||||
5962 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||||||
5963 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | ||||||||
5964 | << (unsigned)ParmSize->getQuantity() << 1; | ||||||||
5965 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||||||
5966 | } | ||||||||
5967 | } | ||||||||
5968 | |||||||||
5969 | /// Given a function expression of unknown-any type, try to rebuild it | ||||||||
5970 | /// to have a function type. | ||||||||
5971 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | ||||||||
5972 | |||||||||
5973 | /// Is the given type a placeholder that we need to lower out | ||||||||
5974 | /// immediately during argument processing? | ||||||||
5975 | static bool isPlaceholderToRemoveAsArg(QualType type) { | ||||||||
5976 | // Placeholders are never sugared. | ||||||||
5977 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | ||||||||
5978 | if (!placeholder) return false; | ||||||||
5979 | |||||||||
5980 | switch (placeholder->getKind()) { | ||||||||
5981 | // Ignore all the non-placeholder types. | ||||||||
5982 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||||||
5983 | case BuiltinType::Id: | ||||||||
5984 | #include "clang/Basic/OpenCLImageTypes.def" | ||||||||
5985 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||||||
5986 | case BuiltinType::Id: | ||||||||
5987 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||||||
5988 | // In practice we'll never use this, since all SVE types are sugared | ||||||||
5989 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | ||||||||
5990 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||||||
5991 | case BuiltinType::Id: | ||||||||
5992 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||||||
5993 | #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ | ||||||||
5994 | case BuiltinType::Id: | ||||||||
5995 | #include "clang/Basic/PPCTypes.def" | ||||||||
5996 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | ||||||||
5997 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | ||||||||
5998 | #include "clang/AST/BuiltinTypes.def" | ||||||||
5999 | return false; | ||||||||
6000 | |||||||||
6001 | // We cannot lower out overload sets; they might validly be resolved | ||||||||
6002 | // by the call machinery. | ||||||||
6003 | case BuiltinType::Overload: | ||||||||
6004 | return false; | ||||||||
6005 | |||||||||
6006 | // Unbridged casts in ARC can be handled in some call positions and | ||||||||
6007 | // should be left in place. | ||||||||
6008 | case BuiltinType::ARCUnbridgedCast: | ||||||||
6009 | return false; | ||||||||
6010 | |||||||||
6011 | // Pseudo-objects should be converted as soon as possible. | ||||||||
6012 | case BuiltinType::PseudoObject: | ||||||||
6013 | return true; | ||||||||
6014 | |||||||||
6015 | // The debugger mode could theoretically but currently does not try | ||||||||
6016 | // to resolve unknown-typed arguments based on known parameter types. | ||||||||
6017 | case BuiltinType::UnknownAny: | ||||||||
6018 | return true; | ||||||||
6019 | |||||||||
6020 | // These are always invalid as call arguments and should be reported. | ||||||||
6021 | case BuiltinType::BoundMember: | ||||||||
6022 | case BuiltinType::BuiltinFn: | ||||||||
6023 | case BuiltinType::IncompleteMatrixIdx: | ||||||||
6024 | case BuiltinType::OMPArraySection: | ||||||||
6025 | case BuiltinType::OMPArrayShaping: | ||||||||
6026 | case BuiltinType::OMPIterator: | ||||||||
6027 | return true; | ||||||||
6028 | |||||||||
6029 | } | ||||||||
6030 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6030); | ||||||||
6031 | } | ||||||||
6032 | |||||||||
6033 | /// Check an argument list for placeholders that we won't try to | ||||||||
6034 | /// handle later. | ||||||||
6035 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | ||||||||
6036 | // Apply this processing to all the arguments at once instead of | ||||||||
6037 | // dying at the first failure. | ||||||||
6038 | bool hasInvalid = false; | ||||||||
6039 | for (size_t i = 0, e = args.size(); i != e; i++) { | ||||||||
6040 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | ||||||||
6041 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | ||||||||
6042 | if (result.isInvalid()) hasInvalid = true; | ||||||||
6043 | else args[i] = result.get(); | ||||||||
6044 | } | ||||||||
6045 | } | ||||||||
6046 | return hasInvalid; | ||||||||
6047 | } | ||||||||
6048 | |||||||||
6049 | /// If a builtin function has a pointer argument with no explicit address | ||||||||
6050 | /// space, then it should be able to accept a pointer to any address | ||||||||
6051 | /// space as input. In order to do this, we need to replace the | ||||||||
6052 | /// standard builtin declaration with one that uses the same address space | ||||||||
6053 | /// as the call. | ||||||||
6054 | /// | ||||||||
6055 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | ||||||||
6056 | /// it does not contain any pointer arguments without | ||||||||
6057 | /// an address space qualifer. Otherwise the rewritten | ||||||||
6058 | /// FunctionDecl is returned. | ||||||||
6059 | /// TODO: Handle pointer return types. | ||||||||
6060 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | ||||||||
6061 | FunctionDecl *FDecl, | ||||||||
6062 | MultiExprArg ArgExprs) { | ||||||||
6063 | |||||||||
6064 | QualType DeclType = FDecl->getType(); | ||||||||
6065 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | ||||||||
6066 | |||||||||
6067 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | ||||||||
6068 | ArgExprs.size() < FT->getNumParams()) | ||||||||
6069 | return nullptr; | ||||||||
6070 | |||||||||
6071 | bool NeedsNewDecl = false; | ||||||||
6072 | unsigned i = 0; | ||||||||
6073 | SmallVector<QualType, 8> OverloadParams; | ||||||||
6074 | |||||||||
6075 | for (QualType ParamType : FT->param_types()) { | ||||||||
6076 | |||||||||
6077 | // Convert array arguments to pointer to simplify type lookup. | ||||||||
6078 | ExprResult ArgRes = | ||||||||
6079 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | ||||||||
6080 | if (ArgRes.isInvalid()) | ||||||||
6081 | return nullptr; | ||||||||
6082 | Expr *Arg = ArgRes.get(); | ||||||||
6083 | QualType ArgType = Arg->getType(); | ||||||||
6084 | if (!ParamType->isPointerType() || | ||||||||
6085 | ParamType.hasAddressSpace() || | ||||||||
6086 | !ArgType->isPointerType() || | ||||||||
6087 | !ArgType->getPointeeType().hasAddressSpace()) { | ||||||||
6088 | OverloadParams.push_back(ParamType); | ||||||||
6089 | continue; | ||||||||
6090 | } | ||||||||
6091 | |||||||||
6092 | QualType PointeeType = ParamType->getPointeeType(); | ||||||||
6093 | if (PointeeType.hasAddressSpace()) | ||||||||
6094 | continue; | ||||||||
6095 | |||||||||
6096 | NeedsNewDecl = true; | ||||||||
6097 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | ||||||||
6098 | |||||||||
6099 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | ||||||||
6100 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | ||||||||
6101 | } | ||||||||
6102 | |||||||||
6103 | if (!NeedsNewDecl) | ||||||||
6104 | return nullptr; | ||||||||
6105 | |||||||||
6106 | FunctionProtoType::ExtProtoInfo EPI; | ||||||||
6107 | EPI.Variadic = FT->isVariadic(); | ||||||||
6108 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | ||||||||
6109 | OverloadParams, EPI); | ||||||||
6110 | DeclContext *Parent = FDecl->getParent(); | ||||||||
6111 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, | ||||||||
6112 | FDecl->getLocation(), | ||||||||
6113 | FDecl->getLocation(), | ||||||||
6114 | FDecl->getIdentifier(), | ||||||||
6115 | OverloadTy, | ||||||||
6116 | /*TInfo=*/nullptr, | ||||||||
6117 | SC_Extern, false, | ||||||||
6118 | /*hasPrototype=*/true); | ||||||||
6119 | SmallVector<ParmVarDecl*, 16> Params; | ||||||||
6120 | FT = cast<FunctionProtoType>(OverloadTy); | ||||||||
6121 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||||||
6122 | QualType ParamType = FT->getParamType(i); | ||||||||
6123 | ParmVarDecl *Parm = | ||||||||
6124 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | ||||||||
6125 | SourceLocation(), nullptr, ParamType, | ||||||||
6126 | /*TInfo=*/nullptr, SC_None, nullptr); | ||||||||
6127 | Parm->setScopeInfo(0, i); | ||||||||
6128 | Params.push_back(Parm); | ||||||||
6129 | } | ||||||||
6130 | OverloadDecl->setParams(Params); | ||||||||
6131 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | ||||||||
6132 | return OverloadDecl; | ||||||||
6133 | } | ||||||||
6134 | |||||||||
6135 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | ||||||||
6136 | FunctionDecl *Callee, | ||||||||
6137 | MultiExprArg ArgExprs) { | ||||||||
6138 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | ||||||||
6139 | // similar attributes) really don't like it when functions are called with an | ||||||||
6140 | // invalid number of args. | ||||||||
6141 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | ||||||||
6142 | /*PartialOverloading=*/false) && | ||||||||
6143 | !Callee->isVariadic()) | ||||||||
6144 | return; | ||||||||
6145 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | ||||||||
6146 | return; | ||||||||
6147 | |||||||||
6148 | if (const EnableIfAttr *Attr = | ||||||||
6149 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | ||||||||
6150 | S.Diag(Fn->getBeginLoc(), | ||||||||
6151 | isa<CXXMethodDecl>(Callee) | ||||||||
6152 | ? diag::err_ovl_no_viable_member_function_in_call | ||||||||
6153 | : diag::err_ovl_no_viable_function_in_call) | ||||||||
6154 | << Callee << Callee->getSourceRange(); | ||||||||
6155 | S.Diag(Callee->getLocation(), | ||||||||
6156 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | ||||||||
6157 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | ||||||||
6158 | return; | ||||||||
6159 | } | ||||||||
6160 | } | ||||||||
6161 | |||||||||
6162 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | ||||||||
6163 | const UnresolvedMemberExpr *const UME, Sema &S) { | ||||||||
6164 | |||||||||
6165 | const auto GetFunctionLevelDCIfCXXClass = | ||||||||
6166 | [](Sema &S) -> const CXXRecordDecl * { | ||||||||
6167 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | ||||||||
6168 | if (!DC || !DC->getParent()) | ||||||||
6169 | return nullptr; | ||||||||
6170 | |||||||||
6171 | // If the call to some member function was made from within a member | ||||||||
6172 | // function body 'M' return return 'M's parent. | ||||||||
6173 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||||||
6174 | return MD->getParent()->getCanonicalDecl(); | ||||||||
6175 | // else the call was made from within a default member initializer of a | ||||||||
6176 | // class, so return the class. | ||||||||
6177 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||||||
6178 | return RD->getCanonicalDecl(); | ||||||||
6179 | return nullptr; | ||||||||
6180 | }; | ||||||||
6181 | // If our DeclContext is neither a member function nor a class (in the | ||||||||
6182 | // case of a lambda in a default member initializer), we can't have an | ||||||||
6183 | // enclosing 'this'. | ||||||||
6184 | |||||||||
6185 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | ||||||||
6186 | if (!CurParentClass) | ||||||||
6187 | return false; | ||||||||
6188 | |||||||||
6189 | // The naming class for implicit member functions call is the class in which | ||||||||
6190 | // name lookup starts. | ||||||||
6191 | const CXXRecordDecl *const NamingClass = | ||||||||
6192 | UME->getNamingClass()->getCanonicalDecl(); | ||||||||
6193 | assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access" ) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6193, __PRETTY_FUNCTION__)); | ||||||||
6194 | |||||||||
6195 | // If the unresolved member functions were found in a 'naming class' that is | ||||||||
6196 | // related (either the same or derived from) to the class that contains the | ||||||||
6197 | // member function that itself contained the implicit member access. | ||||||||
6198 | |||||||||
6199 | return CurParentClass == NamingClass || | ||||||||
6200 | CurParentClass->isDerivedFrom(NamingClass); | ||||||||
6201 | } | ||||||||
6202 | |||||||||
6203 | static void | ||||||||
6204 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||||||
6205 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | ||||||||
6206 | |||||||||
6207 | if (!UME) | ||||||||
6208 | return; | ||||||||
6209 | |||||||||
6210 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | ||||||||
6211 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | ||||||||
6212 | // already been captured, or if this is an implicit member function call (if | ||||||||
6213 | // it isn't, an attempt to capture 'this' should already have been made). | ||||||||
6214 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | ||||||||
6215 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | ||||||||
6216 | return; | ||||||||
6217 | |||||||||
6218 | // Check if the naming class in which the unresolved members were found is | ||||||||
6219 | // related (same as or is a base of) to the enclosing class. | ||||||||
6220 | |||||||||
6221 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | ||||||||
6222 | return; | ||||||||
6223 | |||||||||
6224 | |||||||||
6225 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | ||||||||
6226 | // If the enclosing function is not dependent, then this lambda is | ||||||||
6227 | // capture ready, so if we can capture this, do so. | ||||||||
6228 | if (!EnclosingFunctionCtx->isDependentContext()) { | ||||||||
6229 | // If the current lambda and all enclosing lambdas can capture 'this' - | ||||||||
6230 | // then go ahead and capture 'this' (since our unresolved overload set | ||||||||
6231 | // contains at least one non-static member function). | ||||||||
6232 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | ||||||||
6233 | S.CheckCXXThisCapture(CallLoc); | ||||||||
6234 | } else if (S.CurContext->isDependentContext()) { | ||||||||
6235 | // ... since this is an implicit member reference, that might potentially | ||||||||
6236 | // involve a 'this' capture, mark 'this' for potential capture in | ||||||||
6237 | // enclosing lambdas. | ||||||||
6238 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | ||||||||
6239 | CurLSI->addPotentialThisCapture(CallLoc); | ||||||||
6240 | } | ||||||||
6241 | } | ||||||||
6242 | |||||||||
6243 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||||||
6244 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||||||
6245 | Expr *ExecConfig) { | ||||||||
6246 | ExprResult Call = | ||||||||
6247 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); | ||||||||
6248 | if (Call.isInvalid()) | ||||||||
6249 | return Call; | ||||||||
6250 | |||||||||
6251 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | ||||||||
6252 | // language modes. | ||||||||
6253 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | ||||||||
6254 | if (ULE->hasExplicitTemplateArgs() && | ||||||||
6255 | ULE->decls_begin() == ULE->decls_end()) { | ||||||||
6256 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | ||||||||
6257 | ? diag::warn_cxx17_compat_adl_only_template_id | ||||||||
6258 | : diag::ext_adl_only_template_id) | ||||||||
6259 | << ULE->getName(); | ||||||||
6260 | } | ||||||||
6261 | } | ||||||||
6262 | |||||||||
6263 | if (LangOpts.OpenMP) | ||||||||
6264 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | ||||||||
6265 | ExecConfig); | ||||||||
6266 | |||||||||
6267 | return Call; | ||||||||
6268 | } | ||||||||
6269 | |||||||||
6270 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | ||||||||
6271 | /// This provides the location of the left/right parens and a list of comma | ||||||||
6272 | /// locations. | ||||||||
6273 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||||||
6274 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||||||
6275 | Expr *ExecConfig, bool IsExecConfig) { | ||||||||
6276 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||||||
6277 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | ||||||||
6278 | if (Result.isInvalid()) return ExprError(); | ||||||||
6279 | Fn = Result.get(); | ||||||||
6280 | |||||||||
6281 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||||||
6282 | return ExprError(); | ||||||||
6283 | |||||||||
6284 | if (getLangOpts().CPlusPlus) { | ||||||||
6285 | // If this is a pseudo-destructor expression, build the call immediately. | ||||||||
6286 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | ||||||||
6287 | if (!ArgExprs.empty()) { | ||||||||
6288 | // Pseudo-destructor calls should not have any arguments. | ||||||||
6289 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | ||||||||
6290 | << FixItHint::CreateRemoval( | ||||||||
6291 | SourceRange(ArgExprs.front()->getBeginLoc(), | ||||||||
6292 | ArgExprs.back()->getEndLoc())); | ||||||||
6293 | } | ||||||||
6294 | |||||||||
6295 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | ||||||||
6296 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||||||
6297 | } | ||||||||
6298 | if (Fn->getType() == Context.PseudoObjectTy) { | ||||||||
6299 | ExprResult result = CheckPlaceholderExpr(Fn); | ||||||||
6300 | if (result.isInvalid()) return ExprError(); | ||||||||
6301 | Fn = result.get(); | ||||||||
6302 | } | ||||||||
6303 | |||||||||
6304 | // Determine whether this is a dependent call inside a C++ template, | ||||||||
6305 | // in which case we won't do any semantic analysis now. | ||||||||
6306 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | ||||||||
6307 | if (ExecConfig) { | ||||||||
6308 | return CUDAKernelCallExpr::Create( | ||||||||
6309 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, | ||||||||
6310 | Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||||||
6311 | } else { | ||||||||
6312 | |||||||||
6313 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||||||
6314 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | ||||||||
6315 | Fn->getBeginLoc()); | ||||||||
6316 | |||||||||
6317 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||||||
6318 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||||||
6319 | } | ||||||||
6320 | } | ||||||||
6321 | |||||||||
6322 | // Determine whether this is a call to an object (C++ [over.call.object]). | ||||||||
6323 | if (Fn->getType()->isRecordType()) | ||||||||
6324 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | ||||||||
6325 | RParenLoc); | ||||||||
6326 | |||||||||
6327 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||||||
6328 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||||||
6329 | if (result.isInvalid()) return ExprError(); | ||||||||
6330 | Fn = result.get(); | ||||||||
6331 | } | ||||||||
6332 | |||||||||
6333 | if (Fn->getType() == Context.BoundMemberTy) { | ||||||||
6334 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||||||
6335 | RParenLoc); | ||||||||
6336 | } | ||||||||
6337 | } | ||||||||
6338 | |||||||||
6339 | // Check for overloaded calls. This can happen even in C due to extensions. | ||||||||
6340 | if (Fn->getType() == Context.OverloadTy) { | ||||||||
6341 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | ||||||||
6342 | |||||||||
6343 | // We aren't supposed to apply this logic if there's an '&' involved. | ||||||||
6344 | if (!find.HasFormOfMemberPointer) { | ||||||||
6345 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | ||||||||
6346 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||||||
6347 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||||||
6348 | OverloadExpr *ovl = find.Expression; | ||||||||
6349 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | ||||||||
6350 | return BuildOverloadedCallExpr( | ||||||||
6351 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||||||
6352 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | ||||||||
6353 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||||||
6354 | RParenLoc); | ||||||||
6355 | } | ||||||||
6356 | } | ||||||||
6357 | |||||||||
6358 | // If we're directly calling a function, get the appropriate declaration. | ||||||||
6359 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||||||
6360 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||||||
6361 | if (result.isInvalid()) return ExprError(); | ||||||||
6362 | Fn = result.get(); | ||||||||
6363 | } | ||||||||
6364 | |||||||||
6365 | Expr *NakedFn = Fn->IgnoreParens(); | ||||||||
6366 | |||||||||
6367 | bool CallingNDeclIndirectly = false; | ||||||||
6368 | NamedDecl *NDecl = nullptr; | ||||||||
6369 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | ||||||||
6370 | if (UnOp->getOpcode() == UO_AddrOf) { | ||||||||
6371 | CallingNDeclIndirectly = true; | ||||||||
6372 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | ||||||||
6373 | } | ||||||||
6374 | } | ||||||||
6375 | |||||||||
6376 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | ||||||||
6377 | NDecl = DRE->getDecl(); | ||||||||
6378 | |||||||||
6379 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | ||||||||
6380 | if (FDecl && FDecl->getBuiltinID()) { | ||||||||
6381 | // Rewrite the function decl for this builtin by replacing parameters | ||||||||
6382 | // with no explicit address space with the address space of the arguments | ||||||||
6383 | // in ArgExprs. | ||||||||
6384 | if ((FDecl = | ||||||||
6385 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | ||||||||
6386 | NDecl = FDecl; | ||||||||
6387 | Fn = DeclRefExpr::Create( | ||||||||
6388 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | ||||||||
6389 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | ||||||||
6390 | nullptr, DRE->isNonOdrUse()); | ||||||||
6391 | } | ||||||||
6392 | } | ||||||||
6393 | } else if (isa<MemberExpr>(NakedFn)) | ||||||||
6394 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | ||||||||
6395 | |||||||||
6396 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | ||||||||
6397 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | ||||||||
6398 | FD, /*Complain=*/true, Fn->getBeginLoc())) | ||||||||
6399 | return ExprError(); | ||||||||
6400 | |||||||||
6401 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) | ||||||||
6402 | return ExprError(); | ||||||||
6403 | |||||||||
6404 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | ||||||||
6405 | } | ||||||||
6406 | |||||||||
6407 | if (Context.isDependenceAllowed() && | ||||||||
6408 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||||||
6409 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6409, __PRETTY_FUNCTION__)); | ||||||||
6410 | assert((Fn->containsErrors() ||(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6413, __PRETTY_FUNCTION__)) | ||||||||
6411 | llvm::any_of(ArgExprs,(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6413, __PRETTY_FUNCTION__)) | ||||||||
6412 | [](clang::Expr *E) { return E->containsErrors(); })) &&(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6413, __PRETTY_FUNCTION__)) | ||||||||
6413 | "should only occur in error-recovery path.")(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6413, __PRETTY_FUNCTION__)); | ||||||||
6414 | QualType ReturnType = | ||||||||
6415 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | ||||||||
6416 | ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType() | ||||||||
6417 | : Context.DependentTy; | ||||||||
6418 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | ||||||||
6419 | Expr::getValueKindForType(ReturnType), RParenLoc, | ||||||||
6420 | CurFPFeatureOverrides()); | ||||||||
6421 | } | ||||||||
6422 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | ||||||||
6423 | ExecConfig, IsExecConfig); | ||||||||
6424 | } | ||||||||
6425 | |||||||||
6426 | /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. | ||||||||
6427 | /// | ||||||||
6428 | /// __builtin_astype( value, dst type ) | ||||||||
6429 | /// | ||||||||
6430 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | ||||||||
6431 | SourceLocation BuiltinLoc, | ||||||||
6432 | SourceLocation RParenLoc) { | ||||||||
6433 | ExprValueKind VK = VK_RValue; | ||||||||
6434 | ExprObjectKind OK = OK_Ordinary; | ||||||||
6435 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | ||||||||
6436 | QualType SrcTy = E->getType(); | ||||||||
6437 | if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) | ||||||||
6438 | return ExprError(Diag(BuiltinLoc, | ||||||||
6439 | diag::err_invalid_astype_of_different_size) | ||||||||
6440 | << DstTy | ||||||||
6441 | << SrcTy | ||||||||
6442 | << E->getSourceRange()); | ||||||||
6443 | return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); | ||||||||
6444 | } | ||||||||
6445 | |||||||||
6446 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | ||||||||
6447 | /// provided arguments. | ||||||||
6448 | /// | ||||||||
6449 | /// __builtin_convertvector( value, dst type ) | ||||||||
6450 | /// | ||||||||
6451 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | ||||||||
6452 | SourceLocation BuiltinLoc, | ||||||||
6453 | SourceLocation RParenLoc) { | ||||||||
6454 | TypeSourceInfo *TInfo; | ||||||||
6455 | GetTypeFromParser(ParsedDestTy, &TInfo); | ||||||||
6456 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | ||||||||
6457 | } | ||||||||
6458 | |||||||||
6459 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | ||||||||
6460 | /// i.e. an expression not of \p OverloadTy. The expression should | ||||||||
6461 | /// unary-convert to an expression of function-pointer or | ||||||||
6462 | /// block-pointer type. | ||||||||
6463 | /// | ||||||||
6464 | /// \param NDecl the declaration being called, if available | ||||||||
6465 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | ||||||||
6466 | SourceLocation LParenLoc, | ||||||||
6467 | ArrayRef<Expr *> Args, | ||||||||
6468 | SourceLocation RParenLoc, Expr *Config, | ||||||||
6469 | bool IsExecConfig, ADLCallKind UsesADL) { | ||||||||
6470 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | ||||||||
6471 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); | ||||||||
6472 | |||||||||
6473 | // Functions with 'interrupt' attribute cannot be called directly. | ||||||||
6474 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { | ||||||||
6475 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | ||||||||
6476 | return ExprError(); | ||||||||
6477 | } | ||||||||
6478 | |||||||||
6479 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | ||||||||
6480 | // so there's some risk when calling out to non-interrupt handler functions | ||||||||
6481 | // that the callee might not preserve them. This is easy to diagnose here, | ||||||||
6482 | // but can be very challenging to debug. | ||||||||
6483 | if (auto *Caller = getCurFunctionDecl()) | ||||||||
6484 | if (Caller->hasAttr<ARMInterruptAttr>()) { | ||||||||
6485 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | ||||||||
6486 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) | ||||||||
6487 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | ||||||||
6488 | } | ||||||||
6489 | |||||||||
6490 | // Promote the function operand. | ||||||||
6491 | // We special-case function promotion here because we only allow promoting | ||||||||
6492 | // builtin functions to function pointers in the callee of a call. | ||||||||
6493 | ExprResult Result; | ||||||||
6494 | QualType ResultTy; | ||||||||
6495 | if (BuiltinID && | ||||||||
6496 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | ||||||||
6497 | // Extract the return type from the (builtin) function pointer type. | ||||||||
6498 | // FIXME Several builtins still have setType in | ||||||||
6499 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | ||||||||
6500 | // Builtins.def to ensure they are correct before removing setType calls. | ||||||||
6501 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | ||||||||
6502 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | ||||||||
6503 | ResultTy = FDecl->getCallResultType(); | ||||||||
6504 | } else { | ||||||||
6505 | Result = CallExprUnaryConversions(Fn); | ||||||||
6506 | ResultTy = Context.BoolTy; | ||||||||
6507 | } | ||||||||
6508 | if (Result.isInvalid()) | ||||||||
6509 | return ExprError(); | ||||||||
6510 | Fn = Result.get(); | ||||||||
6511 | |||||||||
6512 | // Check for a valid function type, but only if it is not a builtin which | ||||||||
6513 | // requires custom type checking. These will be handled by | ||||||||
6514 | // CheckBuiltinFunctionCall below just after creation of the call expression. | ||||||||
6515 | const FunctionType *FuncT = nullptr; | ||||||||
6516 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | ||||||||
6517 | retry: | ||||||||
6518 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { | ||||||||
6519 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | ||||||||
6520 | // have type pointer to function". | ||||||||
6521 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | ||||||||
6522 | if (!FuncT) | ||||||||
6523 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||||||
6524 | << Fn->getType() << Fn->getSourceRange()); | ||||||||
6525 | } else if (const BlockPointerType *BPT = | ||||||||
6526 | Fn->getType()->getAs<BlockPointerType>()) { | ||||||||
6527 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | ||||||||
6528 | } else { | ||||||||
6529 | // Handle calls to expressions of unknown-any type. | ||||||||
6530 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||||||
6531 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | ||||||||
6532 | if (rewrite.isInvalid()) | ||||||||
6533 | return ExprError(); | ||||||||
6534 | Fn = rewrite.get(); | ||||||||
6535 | goto retry; | ||||||||
6536 | } | ||||||||
6537 | |||||||||
6538 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||||||
6539 | << Fn->getType() << Fn->getSourceRange()); | ||||||||
6540 | } | ||||||||
6541 | } | ||||||||
6542 | |||||||||
6543 | // Get the number of parameters in the function prototype, if any. | ||||||||
6544 | // We will allocate space for max(Args.size(), NumParams) arguments | ||||||||
6545 | // in the call expression. | ||||||||
6546 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | ||||||||
6547 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; | ||||||||
6548 | |||||||||
6549 | CallExpr *TheCall; | ||||||||
6550 | if (Config) { | ||||||||
6551 | assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6552, __PRETTY_FUNCTION__)) | ||||||||
6552 | "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6552, __PRETTY_FUNCTION__)); | ||||||||
6553 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | ||||||||
6554 | Args, ResultTy, VK_RValue, RParenLoc, | ||||||||
6555 | CurFPFeatureOverrides(), NumParams); | ||||||||
6556 | } else { | ||||||||
6557 | TheCall = | ||||||||
6558 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | ||||||||
6559 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||||||
6560 | } | ||||||||
6561 | |||||||||
6562 | if (!Context.isDependenceAllowed()) { | ||||||||
6563 | // Forget about the nulled arguments since typo correction | ||||||||
6564 | // do not handle them well. | ||||||||
6565 | TheCall->shrinkNumArgs(Args.size()); | ||||||||
6566 | // C cannot always handle TypoExpr nodes in builtin calls and direct | ||||||||
6567 | // function calls as their argument checking don't necessarily handle | ||||||||
6568 | // dependent types properly, so make sure any TypoExprs have been | ||||||||
6569 | // dealt with. | ||||||||
6570 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | ||||||||
6571 | if (!Result.isUsable()) return ExprError(); | ||||||||
6572 | CallExpr *TheOldCall = TheCall; | ||||||||
6573 | TheCall = dyn_cast<CallExpr>(Result.get()); | ||||||||
6574 | bool CorrectedTypos = TheCall != TheOldCall; | ||||||||
6575 | if (!TheCall) return Result; | ||||||||
6576 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | ||||||||
6577 | |||||||||
6578 | // A new call expression node was created if some typos were corrected. | ||||||||
6579 | // However it may not have been constructed with enough storage. In this | ||||||||
6580 | // case, rebuild the node with enough storage. The waste of space is | ||||||||
6581 | // immaterial since this only happens when some typos were corrected. | ||||||||
6582 | if (CorrectedTypos && Args.size() < NumParams) { | ||||||||
6583 | if (Config) | ||||||||
6584 | TheCall = CUDAKernelCallExpr::Create( | ||||||||
6585 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, | ||||||||
6586 | RParenLoc, CurFPFeatureOverrides(), NumParams); | ||||||||
6587 | else | ||||||||
6588 | TheCall = | ||||||||
6589 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | ||||||||
6590 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||||||
6591 | } | ||||||||
6592 | // We can now handle the nulled arguments for the default arguments. | ||||||||
6593 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | ||||||||
6594 | } | ||||||||
6595 | |||||||||
6596 | // Bail out early if calling a builtin with custom type checking. | ||||||||
6597 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) | ||||||||
6598 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||||||
6599 | |||||||||
6600 | if (getLangOpts().CUDA) { | ||||||||
6601 | if (Config) { | ||||||||
6602 | // CUDA: Kernel calls must be to global functions | ||||||||
6603 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | ||||||||
6604 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | ||||||||
6605 | << FDecl << Fn->getSourceRange()); | ||||||||
6606 | |||||||||
6607 | // CUDA: Kernel function must have 'void' return type | ||||||||
6608 | if (!FuncT->getReturnType()->isVoidType() && | ||||||||
6609 | !FuncT->getReturnType()->getAs<AutoType>() && | ||||||||
6610 | !FuncT->getReturnType()->isInstantiationDependentType()) | ||||||||
6611 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | ||||||||
6612 | << Fn->getType() << Fn->getSourceRange()); | ||||||||
6613 | } else { | ||||||||
6614 | // CUDA: Calls to global functions must be configured | ||||||||
6615 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | ||||||||
6616 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | ||||||||
6617 | << FDecl << Fn->getSourceRange()); | ||||||||
6618 | } | ||||||||
6619 | } | ||||||||
6620 | |||||||||
6621 | // Check for a valid return type | ||||||||
6622 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | ||||||||
6623 | FDecl)) | ||||||||
6624 | return ExprError(); | ||||||||
6625 | |||||||||
6626 | // We know the result type of the call, set it. | ||||||||
6627 | TheCall->setType(FuncT->getCallResultType(Context)); | ||||||||
6628 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | ||||||||
6629 | |||||||||
6630 | if (Proto) { | ||||||||
6631 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | ||||||||
6632 | IsExecConfig)) | ||||||||
6633 | return ExprError(); | ||||||||
6634 | } else { | ||||||||
6635 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6635, __PRETTY_FUNCTION__)); | ||||||||
6636 | |||||||||
6637 | if (FDecl) { | ||||||||
6638 | // Check if we have too few/too many template arguments, based | ||||||||
6639 | // on our knowledge of the function definition. | ||||||||
6640 | const FunctionDecl *Def = nullptr; | ||||||||
6641 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | ||||||||
6642 | Proto = Def->getType()->getAs<FunctionProtoType>(); | ||||||||
6643 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | ||||||||
6644 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | ||||||||
6645 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | ||||||||
6646 | } | ||||||||
6647 | |||||||||
6648 | // If the function we're calling isn't a function prototype, but we have | ||||||||
6649 | // a function prototype from a prior declaratiom, use that prototype. | ||||||||
6650 | if (!FDecl->hasPrototype()) | ||||||||
6651 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | ||||||||
6652 | } | ||||||||
6653 | |||||||||
6654 | // Promote the arguments (C99 6.5.2.2p6). | ||||||||
6655 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||||||
6656 | Expr *Arg = Args[i]; | ||||||||
6657 | |||||||||
6658 | if (Proto && i < Proto->getNumParams()) { | ||||||||
6659 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||||||
6660 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | ||||||||
6661 | ExprResult ArgE = | ||||||||
6662 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | ||||||||
6663 | if (ArgE.isInvalid()) | ||||||||
6664 | return true; | ||||||||
6665 | |||||||||
6666 | Arg = ArgE.getAs<Expr>(); | ||||||||
6667 | |||||||||
6668 | } else { | ||||||||
6669 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | ||||||||
6670 | |||||||||
6671 | if (ArgE.isInvalid()) | ||||||||
6672 | return true; | ||||||||
6673 | |||||||||
6674 | Arg = ArgE.getAs<Expr>(); | ||||||||
6675 | } | ||||||||
6676 | |||||||||
6677 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | ||||||||
6678 | diag::err_call_incomplete_argument, Arg)) | ||||||||
6679 | return ExprError(); | ||||||||
6680 | |||||||||
6681 | TheCall->setArg(i, Arg); | ||||||||
6682 | } | ||||||||
6683 | } | ||||||||
6684 | |||||||||
6685 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||||||
6686 | if (!Method->isStatic()) | ||||||||
6687 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | ||||||||
6688 | << Fn->getSourceRange()); | ||||||||
6689 | |||||||||
6690 | // Check for sentinels | ||||||||
6691 | if (NDecl) | ||||||||
6692 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | ||||||||
6693 | |||||||||
6694 | // Warn for unions passing across security boundary (CMSE). | ||||||||
6695 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | ||||||||
6696 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||||||
6697 | if (const auto *RT = | ||||||||
6698 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | ||||||||
6699 | if (RT->getDecl()->isOrContainsUnion()) | ||||||||
6700 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | ||||||||
6701 | << 0 << i; | ||||||||
6702 | } | ||||||||
6703 | } | ||||||||
6704 | } | ||||||||
6705 | |||||||||
6706 | // Do special checking on direct calls to functions. | ||||||||
6707 | if (FDecl) { | ||||||||
6708 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | ||||||||
6709 | return ExprError(); | ||||||||
6710 | |||||||||
6711 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | ||||||||
6712 | |||||||||
6713 | if (BuiltinID) | ||||||||
6714 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||||||
6715 | } else if (NDecl) { | ||||||||
6716 | if (CheckPointerCall(NDecl, TheCall, Proto)) | ||||||||
6717 | return ExprError(); | ||||||||
6718 | } else { | ||||||||
6719 | if (CheckOtherCall(TheCall, Proto)) | ||||||||
6720 | return ExprError(); | ||||||||
6721 | } | ||||||||
6722 | |||||||||
6723 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | ||||||||
6724 | } | ||||||||
6725 | |||||||||
6726 | ExprResult | ||||||||
6727 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | ||||||||
6728 | SourceLocation RParenLoc, Expr *InitExpr) { | ||||||||
6729 | assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast <void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6729, __PRETTY_FUNCTION__)); | ||||||||
6730 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6730, __PRETTY_FUNCTION__)); | ||||||||
6731 | |||||||||
6732 | TypeSourceInfo *TInfo; | ||||||||
6733 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | ||||||||
6734 | if (!TInfo) | ||||||||
6735 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | ||||||||
6736 | |||||||||
6737 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | ||||||||
6738 | } | ||||||||
6739 | |||||||||
6740 | ExprResult | ||||||||
6741 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | ||||||||
6742 | SourceLocation RParenLoc, Expr *LiteralExpr) { | ||||||||
6743 | QualType literalType = TInfo->getType(); | ||||||||
6744 | |||||||||
6745 | if (literalType->isArrayType()) { | ||||||||
6746 | if (RequireCompleteSizedType( | ||||||||
6747 | LParenLoc, Context.getBaseElementType(literalType), | ||||||||
6748 | diag::err_array_incomplete_or_sizeless_type, | ||||||||
6749 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||||||
6750 | return ExprError(); | ||||||||
6751 | if (literalType->isVariableArrayType()) | ||||||||
6752 | return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) | ||||||||
6753 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); | ||||||||
6754 | } else if (!literalType->isDependentType() && | ||||||||
6755 | RequireCompleteType(LParenLoc, literalType, | ||||||||
6756 | diag::err_typecheck_decl_incomplete_type, | ||||||||
6757 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||||||
6758 | return ExprError(); | ||||||||
6759 | |||||||||
6760 | InitializedEntity Entity | ||||||||
6761 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | ||||||||
6762 | InitializationKind Kind | ||||||||
6763 | = InitializationKind::CreateCStyleCast(LParenLoc, | ||||||||
6764 | SourceRange(LParenLoc, RParenLoc), | ||||||||
6765 | /*InitList=*/true); | ||||||||
6766 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | ||||||||
6767 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | ||||||||
6768 | &literalType); | ||||||||
6769 | if (Result.isInvalid()) | ||||||||
6770 | return ExprError(); | ||||||||
6771 | LiteralExpr = Result.get(); | ||||||||
6772 | |||||||||
6773 | bool isFileScope = !CurContext->isFunctionOrMethod(); | ||||||||
6774 | |||||||||
6775 | // In C, compound literals are l-values for some reason. | ||||||||
6776 | // For GCC compatibility, in C++, file-scope array compound literals with | ||||||||
6777 | // constant initializers are also l-values, and compound literals are | ||||||||
6778 | // otherwise prvalues. | ||||||||
6779 | // | ||||||||
6780 | // (GCC also treats C++ list-initialized file-scope array prvalues with | ||||||||
6781 | // constant initializers as l-values, but that's non-conforming, so we don't | ||||||||
6782 | // follow it there.) | ||||||||
6783 | // | ||||||||
6784 | // FIXME: It would be better to handle the lvalue cases as materializing and | ||||||||
6785 | // lifetime-extending a temporary object, but our materialized temporaries | ||||||||
6786 | // representation only supports lifetime extension from a variable, not "out | ||||||||
6787 | // of thin air". | ||||||||
6788 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | ||||||||
6789 | // is bound to the result of applying array-to-pointer decay to the compound | ||||||||
6790 | // literal. | ||||||||
6791 | // FIXME: GCC supports compound literals of reference type, which should | ||||||||
6792 | // obviously have a value kind derived from the kind of reference involved. | ||||||||
6793 | ExprValueKind VK = | ||||||||
6794 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | ||||||||
6795 | ? VK_RValue | ||||||||
6796 | : VK_LValue; | ||||||||
6797 | |||||||||
6798 | if (isFileScope) | ||||||||
6799 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | ||||||||
6800 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | ||||||||
6801 | Expr *Init = ILE->getInit(i); | ||||||||
6802 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | ||||||||
6803 | } | ||||||||
6804 | |||||||||
6805 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | ||||||||
6806 | VK, LiteralExpr, isFileScope); | ||||||||
6807 | if (isFileScope) { | ||||||||
6808 | if (!LiteralExpr->isTypeDependent() && | ||||||||
6809 | !LiteralExpr->isValueDependent() && | ||||||||
6810 | !literalType->isDependentType()) // C99 6.5.2.5p3 | ||||||||
6811 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | ||||||||
6812 | return ExprError(); | ||||||||
6813 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | ||||||||
6814 | literalType.getAddressSpace() != LangAS::Default) { | ||||||||
6815 | // Embedded-C extensions to C99 6.5.2.5: | ||||||||
6816 | // "If the compound literal occurs inside the body of a function, the | ||||||||
6817 | // type name shall not be qualified by an address-space qualifier." | ||||||||
6818 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | ||||||||
6819 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | ||||||||
6820 | return ExprError(); | ||||||||
6821 | } | ||||||||
6822 | |||||||||
6823 | if (!isFileScope && !getLangOpts().CPlusPlus) { | ||||||||
6824 | // Compound literals that have automatic storage duration are destroyed at | ||||||||
6825 | // the end of the scope in C; in C++, they're just temporaries. | ||||||||
6826 | |||||||||
6827 | // Emit diagnostics if it is or contains a C union type that is non-trivial | ||||||||
6828 | // to destruct. | ||||||||
6829 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | ||||||||
6830 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||||||
6831 | NTCUC_CompoundLiteral, NTCUK_Destruct); | ||||||||
6832 | |||||||||
6833 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | ||||||||
6834 | if (literalType.isDestructedType()) { | ||||||||
6835 | Cleanup.setExprNeedsCleanups(true); | ||||||||
6836 | ExprCleanupObjects.push_back(E); | ||||||||
6837 | getCurFunction()->setHasBranchProtectedScope(); | ||||||||
6838 | } | ||||||||
6839 | } | ||||||||
6840 | |||||||||
6841 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||||
6842 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||||
6843 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | ||||||||
6844 | E->getInitializer()->getExprLoc()); | ||||||||
6845 | |||||||||
6846 | return MaybeBindToTemporary(E); | ||||||||
6847 | } | ||||||||
6848 | |||||||||
6849 | ExprResult | ||||||||
6850 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||||||
6851 | SourceLocation RBraceLoc) { | ||||||||
6852 | // Only produce each kind of designated initialization diagnostic once. | ||||||||
6853 | SourceLocation FirstDesignator; | ||||||||
6854 | bool DiagnosedArrayDesignator = false; | ||||||||
6855 | bool DiagnosedNestedDesignator = false; | ||||||||
6856 | bool DiagnosedMixedDesignator = false; | ||||||||
6857 | |||||||||
6858 | // Check that any designated initializers are syntactically valid in the | ||||||||
6859 | // current language mode. | ||||||||
6860 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||||||
6861 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | ||||||||
6862 | if (FirstDesignator.isInvalid()) | ||||||||
6863 | FirstDesignator = DIE->getBeginLoc(); | ||||||||
6864 | |||||||||
6865 | if (!getLangOpts().CPlusPlus) | ||||||||
6866 | break; | ||||||||
6867 | |||||||||
6868 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | ||||||||
6869 | DiagnosedNestedDesignator = true; | ||||||||
6870 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | ||||||||
6871 | << DIE->getDesignatorsSourceRange(); | ||||||||
6872 | } | ||||||||
6873 | |||||||||
6874 | for (auto &Desig : DIE->designators()) { | ||||||||
6875 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | ||||||||
6876 | DiagnosedArrayDesignator = true; | ||||||||
6877 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | ||||||||
6878 | << Desig.getSourceRange(); | ||||||||
6879 | } | ||||||||
6880 | } | ||||||||
6881 | |||||||||
6882 | if (!DiagnosedMixedDesignator && | ||||||||
6883 | !isa<DesignatedInitExpr>(InitArgList[0])) { | ||||||||
6884 | DiagnosedMixedDesignator = true; | ||||||||
6885 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||||||
6886 | << DIE->getSourceRange(); | ||||||||
6887 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | ||||||||
6888 | << InitArgList[0]->getSourceRange(); | ||||||||
6889 | } | ||||||||
6890 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | ||||||||
6891 | isa<DesignatedInitExpr>(InitArgList[0])) { | ||||||||
6892 | DiagnosedMixedDesignator = true; | ||||||||
6893 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | ||||||||
6894 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||||||
6895 | << DIE->getSourceRange(); | ||||||||
6896 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | ||||||||
6897 | << InitArgList[I]->getSourceRange(); | ||||||||
6898 | } | ||||||||
6899 | } | ||||||||
6900 | |||||||||
6901 | if (FirstDesignator.isValid()) { | ||||||||
6902 | // Only diagnose designated initiaization as a C++20 extension if we didn't | ||||||||
6903 | // already diagnose use of (non-C++20) C99 designator syntax. | ||||||||
6904 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | ||||||||
6905 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | ||||||||
6906 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | ||||||||
6907 | ? diag::warn_cxx17_compat_designated_init | ||||||||
6908 | : diag::ext_cxx_designated_init); | ||||||||
6909 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | ||||||||
6910 | Diag(FirstDesignator, diag::ext_designated_init); | ||||||||
6911 | } | ||||||||
6912 | } | ||||||||
6913 | |||||||||
6914 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | ||||||||
6915 | } | ||||||||
6916 | |||||||||
6917 | ExprResult | ||||||||
6918 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||||||
6919 | SourceLocation RBraceLoc) { | ||||||||
6920 | // Semantic analysis for initializers is done by ActOnDeclarator() and | ||||||||
6921 | // CheckInitializer() - it requires knowledge of the object being initialized. | ||||||||
6922 | |||||||||
6923 | // Immediately handle non-overload placeholders. Overloads can be | ||||||||
6924 | // resolved contextually, but everything else here can't. | ||||||||
6925 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||||||
6926 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | ||||||||
6927 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | ||||||||
6928 | |||||||||
6929 | // Ignore failures; dropping the entire initializer list because | ||||||||
6930 | // of one failure would be terrible for indexing/etc. | ||||||||
6931 | if (result.isInvalid()) continue; | ||||||||
6932 | |||||||||
6933 | InitArgList[I] = result.get(); | ||||||||
6934 | } | ||||||||
6935 | } | ||||||||
6936 | |||||||||
6937 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | ||||||||
6938 | RBraceLoc); | ||||||||
6939 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | ||||||||
6940 | return E; | ||||||||
6941 | } | ||||||||
6942 | |||||||||
6943 | /// Do an explicit extend of the given block pointer if we're in ARC. | ||||||||
6944 | void Sema::maybeExtendBlockObject(ExprResult &E) { | ||||||||
6945 | assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast <void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6945, __PRETTY_FUNCTION__)); | ||||||||
6946 | assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail ("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6946, __PRETTY_FUNCTION__)); | ||||||||
6947 | |||||||||
6948 | // Only do this in an r-value context. | ||||||||
6949 | if (!getLangOpts().ObjCAutoRefCount) return; | ||||||||
6950 | |||||||||
6951 | E = ImplicitCastExpr::Create( | ||||||||
6952 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | ||||||||
6953 | /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); | ||||||||
6954 | Cleanup.setExprNeedsCleanups(true); | ||||||||
6955 | } | ||||||||
6956 | |||||||||
6957 | /// Prepare a conversion of the given expression to an ObjC object | ||||||||
6958 | /// pointer type. | ||||||||
6959 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | ||||||||
6960 | QualType type = E.get()->getType(); | ||||||||
6961 | if (type->isObjCObjectPointerType()) { | ||||||||
6962 | return CK_BitCast; | ||||||||
6963 | } else if (type->isBlockPointerType()) { | ||||||||
6964 | maybeExtendBlockObject(E); | ||||||||
6965 | return CK_BlockPointerToObjCPointerCast; | ||||||||
6966 | } else { | ||||||||
6967 | assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail ("type->isPointerType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6967, __PRETTY_FUNCTION__)); | ||||||||
6968 | return CK_CPointerToObjCPointerCast; | ||||||||
6969 | } | ||||||||
6970 | } | ||||||||
6971 | |||||||||
6972 | /// Prepares for a scalar cast, performing all the necessary stages | ||||||||
6973 | /// except the final cast and returning the kind required. | ||||||||
6974 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | ||||||||
6975 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | ||||||||
6976 | // Also, callers should have filtered out the invalid cases with | ||||||||
6977 | // pointers. Everything else should be possible. | ||||||||
6978 | |||||||||
6979 | QualType SrcTy = Src.get()->getType(); | ||||||||
6980 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | ||||||||
6981 | return CK_NoOp; | ||||||||
6982 | |||||||||
6983 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | ||||||||
6984 | case Type::STK_MemberPointer: | ||||||||
6985 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 6985); | ||||||||
6986 | |||||||||
6987 | case Type::STK_CPointer: | ||||||||
6988 | case Type::STK_BlockPointer: | ||||||||
6989 | case Type::STK_ObjCObjectPointer: | ||||||||
6990 | switch (DestTy->getScalarTypeKind()) { | ||||||||
6991 | case Type::STK_CPointer: { | ||||||||
6992 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | ||||||||
6993 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | ||||||||
6994 | if (SrcAS != DestAS) | ||||||||
6995 | return CK_AddressSpaceConversion; | ||||||||
6996 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | ||||||||
6997 | return CK_NoOp; | ||||||||
6998 | return CK_BitCast; | ||||||||
6999 | } | ||||||||
7000 | case Type::STK_BlockPointer: | ||||||||
7001 | return (SrcKind == Type::STK_BlockPointer | ||||||||
7002 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | ||||||||
7003 | case Type::STK_ObjCObjectPointer: | ||||||||
7004 | if (SrcKind == Type::STK_ObjCObjectPointer) | ||||||||
7005 | return CK_BitCast; | ||||||||
7006 | if (SrcKind == Type::STK_CPointer) | ||||||||
7007 | return CK_CPointerToObjCPointerCast; | ||||||||
7008 | maybeExtendBlockObject(Src); | ||||||||
7009 | return CK_BlockPointerToObjCPointerCast; | ||||||||
7010 | case Type::STK_Bool: | ||||||||
7011 | return CK_PointerToBoolean; | ||||||||
7012 | case Type::STK_Integral: | ||||||||
7013 | return CK_PointerToIntegral; | ||||||||
7014 | case Type::STK_Floating: | ||||||||
7015 | case Type::STK_FloatingComplex: | ||||||||
7016 | case Type::STK_IntegralComplex: | ||||||||
7017 | case Type::STK_MemberPointer: | ||||||||
7018 | case Type::STK_FixedPoint: | ||||||||
7019 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7019); | ||||||||
7020 | } | ||||||||
7021 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7021); | ||||||||
7022 | |||||||||
7023 | case Type::STK_FixedPoint: | ||||||||
7024 | switch (DestTy->getScalarTypeKind()) { | ||||||||
7025 | case Type::STK_FixedPoint: | ||||||||
7026 | return CK_FixedPointCast; | ||||||||
7027 | case Type::STK_Bool: | ||||||||
7028 | return CK_FixedPointToBoolean; | ||||||||
7029 | case Type::STK_Integral: | ||||||||
7030 | return CK_FixedPointToIntegral; | ||||||||
7031 | case Type::STK_Floating: | ||||||||
7032 | return CK_FixedPointToFloating; | ||||||||
7033 | case Type::STK_IntegralComplex: | ||||||||
7034 | case Type::STK_FloatingComplex: | ||||||||
7035 | Diag(Src.get()->getExprLoc(), | ||||||||
7036 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||||||
7037 | << DestTy; | ||||||||
7038 | return CK_IntegralCast; | ||||||||
7039 | case Type::STK_CPointer: | ||||||||
7040 | case Type::STK_ObjCObjectPointer: | ||||||||
7041 | case Type::STK_BlockPointer: | ||||||||
7042 | case Type::STK_MemberPointer: | ||||||||
7043 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7043); | ||||||||
7044 | } | ||||||||
7045 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7045); | ||||||||
7046 | |||||||||
7047 | case Type::STK_Bool: // casting from bool is like casting from an integer | ||||||||
7048 | case Type::STK_Integral: | ||||||||
7049 | switch (DestTy->getScalarTypeKind()) { | ||||||||
7050 | case Type::STK_CPointer: | ||||||||
7051 | case Type::STK_ObjCObjectPointer: | ||||||||
7052 | case Type::STK_BlockPointer: | ||||||||
7053 | if (Src.get()->isNullPointerConstant(Context, | ||||||||
7054 | Expr::NPC_ValueDependentIsNull)) | ||||||||
7055 | return CK_NullToPointer; | ||||||||
7056 | return CK_IntegralToPointer; | ||||||||
7057 | case Type::STK_Bool: | ||||||||
7058 | return CK_IntegralToBoolean; | ||||||||
7059 | case Type::STK_Integral: | ||||||||
7060 | return CK_IntegralCast; | ||||||||
7061 | case Type::STK_Floating: | ||||||||
7062 | return CK_IntegralToFloating; | ||||||||
7063 | case Type::STK_IntegralComplex: | ||||||||
7064 | Src = ImpCastExprToType(Src.get(), | ||||||||
7065 | DestTy->castAs<ComplexType>()->getElementType(), | ||||||||
7066 | CK_IntegralCast); | ||||||||
7067 | return CK_IntegralRealToComplex; | ||||||||
7068 | case Type::STK_FloatingComplex: | ||||||||
7069 | Src = ImpCastExprToType(Src.get(), | ||||||||
7070 | DestTy->castAs<ComplexType>()->getElementType(), | ||||||||
7071 | CK_IntegralToFloating); | ||||||||
7072 | return CK_FloatingRealToComplex; | ||||||||
7073 | case Type::STK_MemberPointer: | ||||||||
7074 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7074); | ||||||||
7075 | case Type::STK_FixedPoint: | ||||||||
7076 | return CK_IntegralToFixedPoint; | ||||||||
7077 | } | ||||||||
7078 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7078); | ||||||||
7079 | |||||||||
7080 | case Type::STK_Floating: | ||||||||
7081 | switch (DestTy->getScalarTypeKind()) { | ||||||||
7082 | case Type::STK_Floating: | ||||||||
7083 | return CK_FloatingCast; | ||||||||
7084 | case Type::STK_Bool: | ||||||||
7085 | return CK_FloatingToBoolean; | ||||||||
7086 | case Type::STK_Integral: | ||||||||
7087 | return CK_FloatingToIntegral; | ||||||||
7088 | case Type::STK_FloatingComplex: | ||||||||
7089 | Src = ImpCastExprToType(Src.get(), | ||||||||
7090 | DestTy->castAs<ComplexType>()->getElementType(), | ||||||||
7091 | CK_FloatingCast); | ||||||||
7092 | return CK_FloatingRealToComplex; | ||||||||
7093 | case Type::STK_IntegralComplex: | ||||||||
7094 | Src = ImpCastExprToType(Src.get(), | ||||||||
7095 | DestTy->castAs<ComplexType>()->getElementType(), | ||||||||
7096 | CK_FloatingToIntegral); | ||||||||
7097 | return CK_IntegralRealToComplex; | ||||||||
7098 | case Type::STK_CPointer: | ||||||||
7099 | case Type::STK_ObjCObjectPointer: | ||||||||
7100 | case Type::STK_BlockPointer: | ||||||||
7101 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7101); | ||||||||
7102 | case Type::STK_MemberPointer: | ||||||||
7103 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7103); | ||||||||
7104 | case Type::STK_FixedPoint: | ||||||||
7105 | return CK_FloatingToFixedPoint; | ||||||||
7106 | } | ||||||||
7107 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7107); | ||||||||
7108 | |||||||||
7109 | case Type::STK_FloatingComplex: | ||||||||
7110 | switch (DestTy->getScalarTypeKind()) { | ||||||||
7111 | case Type::STK_FloatingComplex: | ||||||||
7112 | return CK_FloatingComplexCast; | ||||||||
7113 | case Type::STK_IntegralComplex: | ||||||||
7114 | return CK_FloatingComplexToIntegralComplex; | ||||||||
7115 | case Type::STK_Floating: { | ||||||||
7116 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||||||
7117 | if (Context.hasSameType(ET, DestTy)) | ||||||||
7118 | return CK_FloatingComplexToReal; | ||||||||
7119 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | ||||||||
7120 | return CK_FloatingCast; | ||||||||
7121 | } | ||||||||
7122 | case Type::STK_Bool: | ||||||||
7123 | return CK_FloatingComplexToBoolean; | ||||||||
7124 | case Type::STK_Integral: | ||||||||
7125 | Src = ImpCastExprToType(Src.get(), | ||||||||
7126 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||||||
7127 | CK_FloatingComplexToReal); | ||||||||
7128 | return CK_FloatingToIntegral; | ||||||||
7129 | case Type::STK_CPointer: | ||||||||
7130 | case Type::STK_ObjCObjectPointer: | ||||||||
7131 | case Type::STK_BlockPointer: | ||||||||
7132 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7132); | ||||||||
7133 | case Type::STK_MemberPointer: | ||||||||
7134 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7134); | ||||||||
7135 | case Type::STK_FixedPoint: | ||||||||
7136 | Diag(Src.get()->getExprLoc(), | ||||||||
7137 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||||||
7138 | << SrcTy; | ||||||||
7139 | return CK_IntegralCast; | ||||||||
7140 | } | ||||||||
7141 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7141); | ||||||||
7142 | |||||||||
7143 | case Type::STK_IntegralComplex: | ||||||||
7144 | switch (DestTy->getScalarTypeKind()) { | ||||||||
7145 | case Type::STK_FloatingComplex: | ||||||||
7146 | return CK_IntegralComplexToFloatingComplex; | ||||||||
7147 | case Type::STK_IntegralComplex: | ||||||||
7148 | return CK_IntegralComplexCast; | ||||||||
7149 | case Type::STK_Integral: { | ||||||||
7150 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||||||
7151 | if (Context.hasSameType(ET, DestTy)) | ||||||||
7152 | return CK_IntegralComplexToReal; | ||||||||
7153 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | ||||||||
7154 | return CK_IntegralCast; | ||||||||
7155 | } | ||||||||
7156 | case Type::STK_Bool: | ||||||||
7157 | return CK_IntegralComplexToBoolean; | ||||||||
7158 | case Type::STK_Floating: | ||||||||
7159 | Src = ImpCastExprToType(Src.get(), | ||||||||
7160 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||||||
7161 | CK_IntegralComplexToReal); | ||||||||
7162 | return CK_IntegralToFloating; | ||||||||
7163 | case Type::STK_CPointer: | ||||||||
7164 | case Type::STK_ObjCObjectPointer: | ||||||||
7165 | case Type::STK_BlockPointer: | ||||||||
7166 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7166); | ||||||||
7167 | case Type::STK_MemberPointer: | ||||||||
7168 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7168); | ||||||||
7169 | case Type::STK_FixedPoint: | ||||||||
7170 | Diag(Src.get()->getExprLoc(), | ||||||||
7171 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||||||
7172 | << SrcTy; | ||||||||
7173 | return CK_IntegralCast; | ||||||||
7174 | } | ||||||||
7175 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7175); | ||||||||
7176 | } | ||||||||
7177 | |||||||||
7178 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7178); | ||||||||
7179 | } | ||||||||
7180 | |||||||||
7181 | static bool breakDownVectorType(QualType type, uint64_t &len, | ||||||||
7182 | QualType &eltType) { | ||||||||
7183 | // Vectors are simple. | ||||||||
7184 | if (const VectorType *vecType = type->getAs<VectorType>()) { | ||||||||
7185 | len = vecType->getNumElements(); | ||||||||
7186 | eltType = vecType->getElementType(); | ||||||||
7187 | assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) : __assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7187, __PRETTY_FUNCTION__)); | ||||||||
7188 | return true; | ||||||||
7189 | } | ||||||||
7190 | |||||||||
7191 | // We allow lax conversion to and from non-vector types, but only if | ||||||||
7192 | // they're real types (i.e. non-complex, non-pointer scalar types). | ||||||||
7193 | if (!type->isRealType()) return false; | ||||||||
7194 | |||||||||
7195 | len = 1; | ||||||||
7196 | eltType = type; | ||||||||
7197 | return true; | ||||||||
7198 | } | ||||||||
7199 | |||||||||
7200 | /// Are the two types lax-compatible vector types? That is, given | ||||||||
7201 | /// that one of them is a vector, do they have equal storage sizes, | ||||||||
7202 | /// where the storage size is the number of elements times the element | ||||||||
7203 | /// size? | ||||||||
7204 | /// | ||||||||
7205 | /// This will also return false if either of the types is neither a | ||||||||
7206 | /// vector nor a real type. | ||||||||
7207 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | ||||||||
7208 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7208, __PRETTY_FUNCTION__)); | ||||||||
7209 | |||||||||
7210 | // Disallow lax conversions between scalars and ExtVectors (these | ||||||||
7211 | // conversions are allowed for other vector types because common headers | ||||||||
7212 | // depend on them). Most scalar OP ExtVector cases are handled by the | ||||||||
7213 | // splat path anyway, which does what we want (convert, not bitcast). | ||||||||
7214 | // What this rules out for ExtVectors is crazy things like char4*float. | ||||||||
7215 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | ||||||||
7216 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | ||||||||
7217 | |||||||||
7218 | uint64_t srcLen, destLen; | ||||||||
7219 | QualType srcEltTy, destEltTy; | ||||||||
7220 | if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; | ||||||||
7221 | if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; | ||||||||
7222 | |||||||||
7223 | // ASTContext::getTypeSize will return the size rounded up to a | ||||||||
7224 | // power of 2, so instead of using that, we need to use the raw | ||||||||
7225 | // element size multiplied by the element count. | ||||||||
7226 | uint64_t srcEltSize = Context.getTypeSize(srcEltTy); | ||||||||
7227 | uint64_t destEltSize = Context.getTypeSize(destEltTy); | ||||||||
7228 | |||||||||
7229 | return (srcLen * srcEltSize == destLen * destEltSize); | ||||||||
7230 | } | ||||||||
7231 | |||||||||
7232 | /// Is this a legal conversion between two types, one of which is | ||||||||
7233 | /// known to be a vector type? | ||||||||
7234 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | ||||||||
7235 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7235, __PRETTY_FUNCTION__)); | ||||||||
7236 | |||||||||
7237 | switch (Context.getLangOpts().getLaxVectorConversions()) { | ||||||||
7238 | case LangOptions::LaxVectorConversionKind::None: | ||||||||
7239 | return false; | ||||||||
7240 | |||||||||
7241 | case LangOptions::LaxVectorConversionKind::Integer: | ||||||||
7242 | if (!srcTy->isIntegralOrEnumerationType()) { | ||||||||
7243 | auto *Vec = srcTy->getAs<VectorType>(); | ||||||||
7244 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||||||
7245 | return false; | ||||||||
7246 | } | ||||||||
7247 | if (!destTy->isIntegralOrEnumerationType()) { | ||||||||
7248 | auto *Vec = destTy->getAs<VectorType>(); | ||||||||
7249 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||||||
7250 | return false; | ||||||||
7251 | } | ||||||||
7252 | // OK, integer (vector) -> integer (vector) bitcast. | ||||||||
7253 | break; | ||||||||
7254 | |||||||||
7255 | case LangOptions::LaxVectorConversionKind::All: | ||||||||
7256 | break; | ||||||||
7257 | } | ||||||||
7258 | |||||||||
7259 | return areLaxCompatibleVectorTypes(srcTy, destTy); | ||||||||
7260 | } | ||||||||
7261 | |||||||||
7262 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | ||||||||
7263 | CastKind &Kind) { | ||||||||
7264 | assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!" ) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7264, __PRETTY_FUNCTION__)); | ||||||||
7265 | |||||||||
7266 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | ||||||||
7267 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | ||||||||
7268 | return Diag(R.getBegin(), | ||||||||
7269 | Ty->isVectorType() ? | ||||||||
7270 | diag::err_invalid_conversion_between_vectors : | ||||||||
7271 | diag::err_invalid_conversion_between_vector_and_integer) | ||||||||
7272 | << VectorTy << Ty << R; | ||||||||
7273 | } else | ||||||||
7274 | return Diag(R.getBegin(), | ||||||||
7275 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||||||
7276 | << VectorTy << Ty << R; | ||||||||
7277 | |||||||||
7278 | Kind = CK_BitCast; | ||||||||
7279 | return false; | ||||||||
7280 | } | ||||||||
7281 | |||||||||
7282 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | ||||||||
7283 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | ||||||||
7284 | |||||||||
7285 | if (DestElemTy == SplattedExpr->getType()) | ||||||||
7286 | return SplattedExpr; | ||||||||
7287 | |||||||||
7288 | assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7289, __PRETTY_FUNCTION__)) | ||||||||
7289 | DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7289, __PRETTY_FUNCTION__)); | ||||||||
7290 | |||||||||
7291 | CastKind CK; | ||||||||
7292 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | ||||||||
7293 | // OpenCL requires that we convert `true` boolean expressions to -1, but | ||||||||
7294 | // only when splatting vectors. | ||||||||
7295 | if (DestElemTy->isFloatingType()) { | ||||||||
7296 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | ||||||||
7297 | // in two steps: boolean to signed integral, then to floating. | ||||||||
7298 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | ||||||||
7299 | CK_BooleanToSignedIntegral); | ||||||||
7300 | SplattedExpr = CastExprRes.get(); | ||||||||
7301 | CK = CK_IntegralToFloating; | ||||||||
7302 | } else { | ||||||||
7303 | CK = CK_BooleanToSignedIntegral; | ||||||||
7304 | } | ||||||||
7305 | } else { | ||||||||
7306 | ExprResult CastExprRes = SplattedExpr; | ||||||||
7307 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | ||||||||
7308 | if (CastExprRes.isInvalid()) | ||||||||
7309 | return ExprError(); | ||||||||
7310 | SplattedExpr = CastExprRes.get(); | ||||||||
7311 | } | ||||||||
7312 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | ||||||||
7313 | } | ||||||||
7314 | |||||||||
7315 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | ||||||||
7316 | Expr *CastExpr, CastKind &Kind) { | ||||||||
7317 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!" ) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7317, __PRETTY_FUNCTION__)); | ||||||||
7318 | |||||||||
7319 | QualType SrcTy = CastExpr->getType(); | ||||||||
7320 | |||||||||
7321 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | ||||||||
7322 | // an ExtVectorType. | ||||||||
7323 | // In OpenCL, casts between vectors of different types are not allowed. | ||||||||
7324 | // (See OpenCL 6.2). | ||||||||
7325 | if (SrcTy->isVectorType()) { | ||||||||
7326 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | ||||||||
7327 | (getLangOpts().OpenCL && | ||||||||
7328 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | ||||||||
7329 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | ||||||||
7330 | << DestTy << SrcTy << R; | ||||||||
7331 | return ExprError(); | ||||||||
7332 | } | ||||||||
7333 | Kind = CK_BitCast; | ||||||||
7334 | return CastExpr; | ||||||||
7335 | } | ||||||||
7336 | |||||||||
7337 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | ||||||||
7338 | // conversion will take place first from scalar to elt type, and then | ||||||||
7339 | // splat from elt type to vector. | ||||||||
7340 | if (SrcTy->isPointerType()) | ||||||||
7341 | return Diag(R.getBegin(), | ||||||||
7342 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||||||
7343 | << DestTy << SrcTy << R; | ||||||||
7344 | |||||||||
7345 | Kind = CK_VectorSplat; | ||||||||
7346 | return prepareVectorSplat(DestTy, CastExpr); | ||||||||
7347 | } | ||||||||
7348 | |||||||||
7349 | ExprResult | ||||||||
7350 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | ||||||||
7351 | Declarator &D, ParsedType &Ty, | ||||||||
7352 | SourceLocation RParenLoc, Expr *CastExpr) { | ||||||||
7353 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7354, __PRETTY_FUNCTION__)) | ||||||||
7354 | "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7354, __PRETTY_FUNCTION__)); | ||||||||
7355 | |||||||||
7356 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | ||||||||
7357 | if (D.isInvalidType()) | ||||||||
7358 | return ExprError(); | ||||||||
7359 | |||||||||
7360 | if (getLangOpts().CPlusPlus) { | ||||||||
7361 | // Check that there are no default arguments (C++ only). | ||||||||
7362 | CheckExtraCXXDefaultArguments(D); | ||||||||
7363 | } else { | ||||||||
7364 | // Make sure any TypoExprs have been dealt with. | ||||||||
7365 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | ||||||||
7366 | if (!Res.isUsable()) | ||||||||
7367 | return ExprError(); | ||||||||
7368 | CastExpr = Res.get(); | ||||||||
7369 | } | ||||||||
7370 | |||||||||
7371 | checkUnusedDeclAttributes(D); | ||||||||
7372 | |||||||||
7373 | QualType castType = castTInfo->getType(); | ||||||||
7374 | Ty = CreateParsedType(castType, castTInfo); | ||||||||
7375 | |||||||||
7376 | bool isVectorLiteral = false; | ||||||||
7377 | |||||||||
7378 | // Check for an altivec or OpenCL literal, | ||||||||
7379 | // i.e. all the elements are integer constants. | ||||||||
7380 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | ||||||||
7381 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | ||||||||
7382 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | ||||||||
7383 | && castType->isVectorType() && (PE || PLE)) { | ||||||||
7384 | if (PLE && PLE->getNumExprs() == 0) { | ||||||||
7385 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | ||||||||
7386 | return ExprError(); | ||||||||
7387 | } | ||||||||
7388 | if (PE || PLE->getNumExprs() == 1) { | ||||||||
7389 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | ||||||||
7390 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | ||||||||
7391 | isVectorLiteral = true; | ||||||||
7392 | } | ||||||||
7393 | else | ||||||||
7394 | isVectorLiteral = true; | ||||||||
7395 | } | ||||||||
7396 | |||||||||
7397 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | ||||||||
7398 | // then handle it as such. | ||||||||
7399 | if (isVectorLiteral) | ||||||||
7400 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | ||||||||
7401 | |||||||||
7402 | // If the Expr being casted is a ParenListExpr, handle it specially. | ||||||||
7403 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | ||||||||
7404 | // sequence of BinOp comma operators. | ||||||||
7405 | if (isa<ParenListExpr>(CastExpr)) { | ||||||||
7406 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | ||||||||
7407 | if (Result.isInvalid()) return ExprError(); | ||||||||
7408 | CastExpr = Result.get(); | ||||||||
7409 | } | ||||||||
7410 | |||||||||
7411 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && | ||||||||
7412 | !getSourceManager().isInSystemMacro(LParenLoc)) | ||||||||
7413 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | ||||||||
7414 | |||||||||
7415 | CheckTollFreeBridgeCast(castType, CastExpr); | ||||||||
7416 | |||||||||
7417 | CheckObjCBridgeRelatedCast(castType, CastExpr); | ||||||||
7418 | |||||||||
7419 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | ||||||||
7420 | |||||||||
7421 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | ||||||||
7422 | } | ||||||||
7423 | |||||||||
7424 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | ||||||||
7425 | SourceLocation RParenLoc, Expr *E, | ||||||||
7426 | TypeSourceInfo *TInfo) { | ||||||||
7427 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7428, __PRETTY_FUNCTION__)) | ||||||||
7428 | "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7428, __PRETTY_FUNCTION__)); | ||||||||
7429 | |||||||||
7430 | Expr **exprs; | ||||||||
7431 | unsigned numExprs; | ||||||||
7432 | Expr *subExpr; | ||||||||
7433 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | ||||||||
7434 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | ||||||||
7435 | LiteralLParenLoc = PE->getLParenLoc(); | ||||||||
7436 | LiteralRParenLoc = PE->getRParenLoc(); | ||||||||
7437 | exprs = PE->getExprs(); | ||||||||
7438 | numExprs = PE->getNumExprs(); | ||||||||
7439 | } else { // isa<ParenExpr> by assertion at function entrance | ||||||||
7440 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | ||||||||
7441 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | ||||||||
7442 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | ||||||||
7443 | exprs = &subExpr; | ||||||||
7444 | numExprs = 1; | ||||||||
7445 | } | ||||||||
7446 | |||||||||
7447 | QualType Ty = TInfo->getType(); | ||||||||
7448 | assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast <void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7448, __PRETTY_FUNCTION__)); | ||||||||
7449 | |||||||||
7450 | SmallVector<Expr *, 8> initExprs; | ||||||||
7451 | const VectorType *VTy = Ty->castAs<VectorType>(); | ||||||||
7452 | unsigned numElems = VTy->getNumElements(); | ||||||||
7453 | |||||||||
7454 | // '(...)' form of vector initialization in AltiVec: the number of | ||||||||
7455 | // initializers must be one or must match the size of the vector. | ||||||||
7456 | // If a single value is specified in the initializer then it will be | ||||||||
7457 | // replicated to all the components of the vector | ||||||||
7458 | if (VTy->getVectorKind() == VectorType::AltiVecVector) { | ||||||||
7459 | // The number of initializers must be one or must match the size of the | ||||||||
7460 | // vector. If a single value is specified in the initializer then it will | ||||||||
7461 | // be replicated to all the components of the vector | ||||||||
7462 | if (numExprs == 1) { | ||||||||
7463 | QualType ElemTy = VTy->getElementType(); | ||||||||
7464 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||||||
7465 | if (Literal.isInvalid()) | ||||||||
7466 | return ExprError(); | ||||||||
7467 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||||||
7468 | PrepareScalarCast(Literal, ElemTy)); | ||||||||
7469 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||||||
7470 | } | ||||||||
7471 | else if (numExprs < numElems) { | ||||||||
7472 | Diag(E->getExprLoc(), | ||||||||
7473 | diag::err_incorrect_number_of_vector_initializers); | ||||||||
7474 | return ExprError(); | ||||||||
7475 | } | ||||||||
7476 | else | ||||||||
7477 | initExprs.append(exprs, exprs + numExprs); | ||||||||
7478 | } | ||||||||
7479 | else { | ||||||||
7480 | // For OpenCL, when the number of initializers is a single value, | ||||||||
7481 | // it will be replicated to all components of the vector. | ||||||||
7482 | if (getLangOpts().OpenCL && | ||||||||
7483 | VTy->getVectorKind() == VectorType::GenericVector && | ||||||||
7484 | numExprs == 1) { | ||||||||
7485 | QualType ElemTy = VTy->getElementType(); | ||||||||
7486 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||||||
7487 | if (Literal.isInvalid()) | ||||||||
7488 | return ExprError(); | ||||||||
7489 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||||||
7490 | PrepareScalarCast(Literal, ElemTy)); | ||||||||
7491 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||||||
7492 | } | ||||||||
7493 | |||||||||
7494 | initExprs.append(exprs, exprs + numExprs); | ||||||||
7495 | } | ||||||||
7496 | // FIXME: This means that pretty-printing the final AST will produce curly | ||||||||
7497 | // braces instead of the original commas. | ||||||||
7498 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | ||||||||
7499 | initExprs, LiteralRParenLoc); | ||||||||
7500 | initE->setType(Ty); | ||||||||
7501 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | ||||||||
7502 | } | ||||||||
7503 | |||||||||
7504 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | ||||||||
7505 | /// the ParenListExpr into a sequence of comma binary operators. | ||||||||
7506 | ExprResult | ||||||||
7507 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | ||||||||
7508 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | ||||||||
7509 | if (!E) | ||||||||
7510 | return OrigExpr; | ||||||||
7511 | |||||||||
7512 | ExprResult Result(E->getExpr(0)); | ||||||||
7513 | |||||||||
7514 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | ||||||||
7515 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | ||||||||
7516 | E->getExpr(i)); | ||||||||
7517 | |||||||||
7518 | if (Result.isInvalid()) return ExprError(); | ||||||||
7519 | |||||||||
7520 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | ||||||||
7521 | } | ||||||||
7522 | |||||||||
7523 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | ||||||||
7524 | SourceLocation R, | ||||||||
7525 | MultiExprArg Val) { | ||||||||
7526 | return ParenListExpr::Create(Context, L, Val, R); | ||||||||
7527 | } | ||||||||
7528 | |||||||||
7529 | /// Emit a specialized diagnostic when one expression is a null pointer | ||||||||
7530 | /// constant and the other is not a pointer. Returns true if a diagnostic is | ||||||||
7531 | /// emitted. | ||||||||
7532 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | ||||||||
7533 | SourceLocation QuestionLoc) { | ||||||||
7534 | Expr *NullExpr = LHSExpr; | ||||||||
7535 | Expr *NonPointerExpr = RHSExpr; | ||||||||
7536 | Expr::NullPointerConstantKind NullKind = | ||||||||
7537 | NullExpr->isNullPointerConstant(Context, | ||||||||
7538 | Expr::NPC_ValueDependentIsNotNull); | ||||||||
7539 | |||||||||
7540 | if (NullKind == Expr::NPCK_NotNull) { | ||||||||
7541 | NullExpr = RHSExpr; | ||||||||
7542 | NonPointerExpr = LHSExpr; | ||||||||
7543 | NullKind = | ||||||||
7544 | NullExpr->isNullPointerConstant(Context, | ||||||||
7545 | Expr::NPC_ValueDependentIsNotNull); | ||||||||
7546 | } | ||||||||
7547 | |||||||||
7548 | if (NullKind == Expr::NPCK_NotNull) | ||||||||
7549 | return false; | ||||||||
7550 | |||||||||
7551 | if (NullKind == Expr::NPCK_ZeroExpression) | ||||||||
7552 | return false; | ||||||||
7553 | |||||||||
7554 | if (NullKind == Expr::NPCK_ZeroLiteral) { | ||||||||
7555 | // In this case, check to make sure that we got here from a "NULL" | ||||||||
7556 | // string in the source code. | ||||||||
7557 | NullExpr = NullExpr->IgnoreParenImpCasts(); | ||||||||
7558 | SourceLocation loc = NullExpr->getExprLoc(); | ||||||||
7559 | if (!findMacroSpelling(loc, "NULL")) | ||||||||
7560 | return false; | ||||||||
7561 | } | ||||||||
7562 | |||||||||
7563 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | ||||||||
7564 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | ||||||||
7565 | << NonPointerExpr->getType() << DiagType | ||||||||
7566 | << NonPointerExpr->getSourceRange(); | ||||||||
7567 | return true; | ||||||||
7568 | } | ||||||||
7569 | |||||||||
7570 | /// Return false if the condition expression is valid, true otherwise. | ||||||||
7571 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | ||||||||
7572 | QualType CondTy = Cond->getType(); | ||||||||
7573 | |||||||||
7574 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | ||||||||
7575 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | ||||||||
7576 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||||||
7577 | << CondTy << Cond->getSourceRange(); | ||||||||
7578 | return true; | ||||||||
7579 | } | ||||||||
7580 | |||||||||
7581 | // C99 6.5.15p2 | ||||||||
7582 | if (CondTy->isScalarType()) return false; | ||||||||
7583 | |||||||||
7584 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | ||||||||
7585 | << CondTy << Cond->getSourceRange(); | ||||||||
7586 | return true; | ||||||||
7587 | } | ||||||||
7588 | |||||||||
7589 | /// Handle when one or both operands are void type. | ||||||||
7590 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | ||||||||
7591 | ExprResult &RHS) { | ||||||||
7592 | Expr *LHSExpr = LHS.get(); | ||||||||
7593 | Expr *RHSExpr = RHS.get(); | ||||||||
7594 | |||||||||
7595 | if (!LHSExpr->getType()->isVoidType()) | ||||||||
7596 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||||||
7597 | << RHSExpr->getSourceRange(); | ||||||||
7598 | if (!RHSExpr->getType()->isVoidType()) | ||||||||
7599 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||||||
7600 | << LHSExpr->getSourceRange(); | ||||||||
7601 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||||||
7602 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||||||
7603 | return S.Context.VoidTy; | ||||||||
7604 | } | ||||||||
7605 | |||||||||
7606 | /// Return false if the NullExpr can be promoted to PointerTy, | ||||||||
7607 | /// true otherwise. | ||||||||
7608 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | ||||||||
7609 | QualType PointerTy) { | ||||||||
7610 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | ||||||||
7611 | !NullExpr.get()->isNullPointerConstant(S.Context, | ||||||||
7612 | Expr::NPC_ValueDependentIsNull)) | ||||||||
7613 | return true; | ||||||||
7614 | |||||||||
7615 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | ||||||||
7616 | return false; | ||||||||
7617 | } | ||||||||
7618 | |||||||||
7619 | /// Checks compatibility between two pointers and return the resulting | ||||||||
7620 | /// type. | ||||||||
7621 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | ||||||||
7622 | ExprResult &RHS, | ||||||||
7623 | SourceLocation Loc) { | ||||||||
7624 | QualType LHSTy = LHS.get()->getType(); | ||||||||
7625 | QualType RHSTy = RHS.get()->getType(); | ||||||||
7626 | |||||||||
7627 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | ||||||||
7628 | // Two identical pointers types are always compatible. | ||||||||
7629 | return LHSTy; | ||||||||
7630 | } | ||||||||
7631 | |||||||||
7632 | QualType lhptee, rhptee; | ||||||||
7633 | |||||||||
7634 | // Get the pointee types. | ||||||||
7635 | bool IsBlockPointer = false; | ||||||||
7636 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | ||||||||
7637 | lhptee = LHSBTy->getPointeeType(); | ||||||||
7638 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | ||||||||
7639 | IsBlockPointer = true; | ||||||||
7640 | } else { | ||||||||
7641 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
7642 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
7643 | } | ||||||||
7644 | |||||||||
7645 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | ||||||||
7646 | // differently qualified versions of compatible types, the result type is | ||||||||
7647 | // a pointer to an appropriately qualified version of the composite | ||||||||
7648 | // type. | ||||||||
7649 | |||||||||
7650 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | ||||||||
7651 | // clause doesn't make sense for our extensions. E.g. address space 2 should | ||||||||
7652 | // be incompatible with address space 3: they may live on different devices or | ||||||||
7653 | // anything. | ||||||||
7654 | Qualifiers lhQual = lhptee.getQualifiers(); | ||||||||
7655 | Qualifiers rhQual = rhptee.getQualifiers(); | ||||||||
7656 | |||||||||
7657 | LangAS ResultAddrSpace = LangAS::Default; | ||||||||
7658 | LangAS LAddrSpace = lhQual.getAddressSpace(); | ||||||||
7659 | LangAS RAddrSpace = rhQual.getAddressSpace(); | ||||||||
7660 | |||||||||
7661 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | ||||||||
7662 | // spaces is disallowed. | ||||||||
7663 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | ||||||||
7664 | ResultAddrSpace = LAddrSpace; | ||||||||
7665 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | ||||||||
7666 | ResultAddrSpace = RAddrSpace; | ||||||||
7667 | else { | ||||||||
7668 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||||||
7669 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | ||||||||
7670 | << RHS.get()->getSourceRange(); | ||||||||
7671 | return QualType(); | ||||||||
7672 | } | ||||||||
7673 | |||||||||
7674 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | ||||||||
7675 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | ||||||||
7676 | lhQual.removeCVRQualifiers(); | ||||||||
7677 | rhQual.removeCVRQualifiers(); | ||||||||
7678 | |||||||||
7679 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | ||||||||
7680 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | ||||||||
7681 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | ||||||||
7682 | // qual types are compatible iff | ||||||||
7683 | // * corresponded types are compatible | ||||||||
7684 | // * CVR qualifiers are equal | ||||||||
7685 | // * address spaces are equal | ||||||||
7686 | // Thus for conditional operator we merge CVR and address space unqualified | ||||||||
7687 | // pointees and if there is a composite type we return a pointer to it with | ||||||||
7688 | // merged qualifiers. | ||||||||
7689 | LHSCastKind = | ||||||||
7690 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||||||
7691 | RHSCastKind = | ||||||||
7692 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||||||
7693 | lhQual.removeAddressSpace(); | ||||||||
7694 | rhQual.removeAddressSpace(); | ||||||||
7695 | |||||||||
7696 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | ||||||||
7697 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | ||||||||
7698 | |||||||||
7699 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | ||||||||
7700 | |||||||||
7701 | if (CompositeTy.isNull()) { | ||||||||
7702 | // In this situation, we assume void* type. No especially good | ||||||||
7703 | // reason, but this is what gcc does, and we do have to pick | ||||||||
7704 | // to get a consistent AST. | ||||||||
7705 | QualType incompatTy; | ||||||||
7706 | incompatTy = S.Context.getPointerType( | ||||||||
7707 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | ||||||||
7708 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | ||||||||
7709 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | ||||||||
7710 | |||||||||
7711 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | ||||||||
7712 | // for casts between types with incompatible address space qualifiers. | ||||||||
7713 | // For the following code the compiler produces casts between global and | ||||||||
7714 | // local address spaces of the corresponded innermost pointees: | ||||||||
7715 | // local int *global *a; | ||||||||
7716 | // global int *global *b; | ||||||||
7717 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | ||||||||
7718 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | ||||||||
7719 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||||||
7720 | << RHS.get()->getSourceRange(); | ||||||||
7721 | |||||||||
7722 | return incompatTy; | ||||||||
7723 | } | ||||||||
7724 | |||||||||
7725 | // The pointer types are compatible. | ||||||||
7726 | // In case of OpenCL ResultTy should have the address space qualifier | ||||||||
7727 | // which is a superset of address spaces of both the 2nd and the 3rd | ||||||||
7728 | // operands of the conditional operator. | ||||||||
7729 | QualType ResultTy = [&, ResultAddrSpace]() { | ||||||||
7730 | if (S.getLangOpts().OpenCL) { | ||||||||
7731 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | ||||||||
7732 | CompositeQuals.setAddressSpace(ResultAddrSpace); | ||||||||
7733 | return S.Context | ||||||||
7734 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | ||||||||
7735 | .withCVRQualifiers(MergedCVRQual); | ||||||||
7736 | } | ||||||||
7737 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | ||||||||
7738 | }(); | ||||||||
7739 | if (IsBlockPointer) | ||||||||
7740 | ResultTy = S.Context.getBlockPointerType(ResultTy); | ||||||||
7741 | else | ||||||||
7742 | ResultTy = S.Context.getPointerType(ResultTy); | ||||||||
7743 | |||||||||
7744 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | ||||||||
7745 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | ||||||||
7746 | return ResultTy; | ||||||||
7747 | } | ||||||||
7748 | |||||||||
7749 | /// Return the resulting type when the operands are both block pointers. | ||||||||
7750 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | ||||||||
7751 | ExprResult &LHS, | ||||||||
7752 | ExprResult &RHS, | ||||||||
7753 | SourceLocation Loc) { | ||||||||
7754 | QualType LHSTy = LHS.get()->getType(); | ||||||||
7755 | QualType RHSTy = RHS.get()->getType(); | ||||||||
7756 | |||||||||
7757 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | ||||||||
7758 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | ||||||||
7759 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | ||||||||
7760 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||||||
7761 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||||||
7762 | return destType; | ||||||||
7763 | } | ||||||||
7764 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | ||||||||
7765 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||||||
7766 | << RHS.get()->getSourceRange(); | ||||||||
7767 | return QualType(); | ||||||||
7768 | } | ||||||||
7769 | |||||||||
7770 | // We have 2 block pointer types. | ||||||||
7771 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||||||
7772 | } | ||||||||
7773 | |||||||||
7774 | /// Return the resulting type when the operands are both pointers. | ||||||||
7775 | static QualType | ||||||||
7776 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | ||||||||
7777 | ExprResult &RHS, | ||||||||
7778 | SourceLocation Loc) { | ||||||||
7779 | // get the pointer types | ||||||||
7780 | QualType LHSTy = LHS.get()->getType(); | ||||||||
7781 | QualType RHSTy = RHS.get()->getType(); | ||||||||
7782 | |||||||||
7783 | // get the "pointed to" types | ||||||||
7784 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
7785 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
7786 | |||||||||
7787 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | ||||||||
7788 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | ||||||||
7789 | // Figure out necessary qualifiers (C99 6.5.15p6) | ||||||||
7790 | QualType destPointee | ||||||||
7791 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||||||
7792 | QualType destType = S.Context.getPointerType(destPointee); | ||||||||
7793 | // Add qualifiers if necessary. | ||||||||
7794 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||||||
7795 | // Promote to void*. | ||||||||
7796 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||||||
7797 | return destType; | ||||||||
7798 | } | ||||||||
7799 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | ||||||||
7800 | QualType destPointee | ||||||||
7801 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||||||
7802 | QualType destType = S.Context.getPointerType(destPointee); | ||||||||
7803 | // Add qualifiers if necessary. | ||||||||
7804 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||||||
7805 | // Promote to void*. | ||||||||
7806 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||||||
7807 | return destType; | ||||||||
7808 | } | ||||||||
7809 | |||||||||
7810 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||||||
7811 | } | ||||||||
7812 | |||||||||
7813 | /// Return false if the first expression is not an integer and the second | ||||||||
7814 | /// expression is not a pointer, true otherwise. | ||||||||
7815 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | ||||||||
7816 | Expr* PointerExpr, SourceLocation Loc, | ||||||||
7817 | bool IsIntFirstExpr) { | ||||||||
7818 | if (!PointerExpr->getType()->isPointerType() || | ||||||||
7819 | !Int.get()->getType()->isIntegerType()) | ||||||||
7820 | return false; | ||||||||
7821 | |||||||||
7822 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | ||||||||
7823 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | ||||||||
7824 | |||||||||
7825 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | ||||||||
7826 | << Expr1->getType() << Expr2->getType() | ||||||||
7827 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | ||||||||
7828 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | ||||||||
7829 | CK_IntegralToPointer); | ||||||||
7830 | return true; | ||||||||
7831 | } | ||||||||
7832 | |||||||||
7833 | /// Simple conversion between integer and floating point types. | ||||||||
7834 | /// | ||||||||
7835 | /// Used when handling the OpenCL conditional operator where the | ||||||||
7836 | /// condition is a vector while the other operands are scalar. | ||||||||
7837 | /// | ||||||||
7838 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | ||||||||
7839 | /// types are either integer or floating type. Between the two | ||||||||
7840 | /// operands, the type with the higher rank is defined as the "result | ||||||||
7841 | /// type". The other operand needs to be promoted to the same type. No | ||||||||
7842 | /// other type promotion is allowed. We cannot use | ||||||||
7843 | /// UsualArithmeticConversions() for this purpose, since it always | ||||||||
7844 | /// promotes promotable types. | ||||||||
7845 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | ||||||||
7846 | ExprResult &RHS, | ||||||||
7847 | SourceLocation QuestionLoc) { | ||||||||
7848 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||||||
7849 | if (LHS.isInvalid()) | ||||||||
7850 | return QualType(); | ||||||||
7851 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||||||
7852 | if (RHS.isInvalid()) | ||||||||
7853 | return QualType(); | ||||||||
7854 | |||||||||
7855 | // For conversion purposes, we ignore any qualifiers. | ||||||||
7856 | // For example, "const float" and "float" are equivalent. | ||||||||
7857 | QualType LHSType = | ||||||||
7858 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||||||
7859 | QualType RHSType = | ||||||||
7860 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||||||
7861 | |||||||||
7862 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | ||||||||
7863 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||||||
7864 | << LHSType << LHS.get()->getSourceRange(); | ||||||||
7865 | return QualType(); | ||||||||
7866 | } | ||||||||
7867 | |||||||||
7868 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | ||||||||
7869 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||||||
7870 | << RHSType << RHS.get()->getSourceRange(); | ||||||||
7871 | return QualType(); | ||||||||
7872 | } | ||||||||
7873 | |||||||||
7874 | // If both types are identical, no conversion is needed. | ||||||||
7875 | if (LHSType == RHSType) | ||||||||
7876 | return LHSType; | ||||||||
7877 | |||||||||
7878 | // Now handle "real" floating types (i.e. float, double, long double). | ||||||||
7879 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||||||
7880 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||||||
7881 | /*IsCompAssign = */ false); | ||||||||
7882 | |||||||||
7883 | // Finally, we have two differing integer types. | ||||||||
7884 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||||||
7885 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | ||||||||
7886 | } | ||||||||
7887 | |||||||||
7888 | /// Convert scalar operands to a vector that matches the | ||||||||
7889 | /// condition in length. | ||||||||
7890 | /// | ||||||||
7891 | /// Used when handling the OpenCL conditional operator where the | ||||||||
7892 | /// condition is a vector while the other operands are scalar. | ||||||||
7893 | /// | ||||||||
7894 | /// We first compute the "result type" for the scalar operands | ||||||||
7895 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | ||||||||
7896 | /// into a vector of that type where the length matches the condition | ||||||||
7897 | /// vector type. s6.11.6 requires that the element types of the result | ||||||||
7898 | /// and the condition must have the same number of bits. | ||||||||
7899 | static QualType | ||||||||
7900 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||||||
7901 | QualType CondTy, SourceLocation QuestionLoc) { | ||||||||
7902 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | ||||||||
7903 | if (ResTy.isNull()) return QualType(); | ||||||||
7904 | |||||||||
7905 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||||||
7906 | assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7906, __PRETTY_FUNCTION__)); | ||||||||
7907 | |||||||||
7908 | // Determine the vector result type | ||||||||
7909 | unsigned NumElements = CV->getNumElements(); | ||||||||
7910 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | ||||||||
7911 | |||||||||
7912 | // Ensure that all types have the same number of bits | ||||||||
7913 | if (S.Context.getTypeSize(CV->getElementType()) | ||||||||
7914 | != S.Context.getTypeSize(ResTy)) { | ||||||||
7915 | // Since VectorTy is created internally, it does not pretty print | ||||||||
7916 | // with an OpenCL name. Instead, we just print a description. | ||||||||
7917 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | ||||||||
7918 | SmallString<64> Str; | ||||||||
7919 | llvm::raw_svector_ostream OS(Str); | ||||||||
7920 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | ||||||||
7921 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||||||
7922 | << CondTy << OS.str(); | ||||||||
7923 | return QualType(); | ||||||||
7924 | } | ||||||||
7925 | |||||||||
7926 | // Convert operands to the vector result type | ||||||||
7927 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | ||||||||
7928 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | ||||||||
7929 | |||||||||
7930 | return VectorTy; | ||||||||
7931 | } | ||||||||
7932 | |||||||||
7933 | /// Return false if this is a valid OpenCL condition vector | ||||||||
7934 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | ||||||||
7935 | SourceLocation QuestionLoc) { | ||||||||
7936 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | ||||||||
7937 | // integral type. | ||||||||
7938 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | ||||||||
7939 | assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7939, __PRETTY_FUNCTION__)); | ||||||||
7940 | QualType EleTy = CondTy->getElementType(); | ||||||||
7941 | if (EleTy->isIntegerType()) return false; | ||||||||
7942 | |||||||||
7943 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||||||
7944 | << Cond->getType() << Cond->getSourceRange(); | ||||||||
7945 | return true; | ||||||||
7946 | } | ||||||||
7947 | |||||||||
7948 | /// Return false if the vector condition type and the vector | ||||||||
7949 | /// result type are compatible. | ||||||||
7950 | /// | ||||||||
7951 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | ||||||||
7952 | /// number of elements, and their element types have the same number | ||||||||
7953 | /// of bits. | ||||||||
7954 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | ||||||||
7955 | SourceLocation QuestionLoc) { | ||||||||
7956 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||||||
7957 | const VectorType *RV = VecResTy->getAs<VectorType>(); | ||||||||
7958 | assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail ("CV && RV", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 7958, __PRETTY_FUNCTION__)); | ||||||||
7959 | |||||||||
7960 | if (CV->getNumElements() != RV->getNumElements()) { | ||||||||
7961 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | ||||||||
7962 | << CondTy << VecResTy; | ||||||||
7963 | return true; | ||||||||
7964 | } | ||||||||
7965 | |||||||||
7966 | QualType CVE = CV->getElementType(); | ||||||||
7967 | QualType RVE = RV->getElementType(); | ||||||||
7968 | |||||||||
7969 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | ||||||||
7970 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||||||
7971 | << CondTy << VecResTy; | ||||||||
7972 | return true; | ||||||||
7973 | } | ||||||||
7974 | |||||||||
7975 | return false; | ||||||||
7976 | } | ||||||||
7977 | |||||||||
7978 | /// Return the resulting type for the conditional operator in | ||||||||
7979 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | ||||||||
7980 | /// s6.3.i) when the condition is a vector type. | ||||||||
7981 | static QualType | ||||||||
7982 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | ||||||||
7983 | ExprResult &LHS, ExprResult &RHS, | ||||||||
7984 | SourceLocation QuestionLoc) { | ||||||||
7985 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | ||||||||
7986 | if (Cond.isInvalid()) | ||||||||
7987 | return QualType(); | ||||||||
7988 | QualType CondTy = Cond.get()->getType(); | ||||||||
7989 | |||||||||
7990 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | ||||||||
7991 | return QualType(); | ||||||||
7992 | |||||||||
7993 | // If either operand is a vector then find the vector type of the | ||||||||
7994 | // result as specified in OpenCL v1.1 s6.3.i. | ||||||||
7995 | if (LHS.get()->getType()->isVectorType() || | ||||||||
7996 | RHS.get()->getType()->isVectorType()) { | ||||||||
7997 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | ||||||||
7998 | /*isCompAssign*/false, | ||||||||
7999 | /*AllowBothBool*/true, | ||||||||
8000 | /*AllowBoolConversions*/false); | ||||||||
8001 | if (VecResTy.isNull()) return QualType(); | ||||||||
8002 | // The result type must match the condition type as specified in | ||||||||
8003 | // OpenCL v1.1 s6.11.6. | ||||||||
8004 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | ||||||||
8005 | return QualType(); | ||||||||
8006 | return VecResTy; | ||||||||
8007 | } | ||||||||
8008 | |||||||||
8009 | // Both operands are scalar. | ||||||||
8010 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | ||||||||
8011 | } | ||||||||
8012 | |||||||||
8013 | /// Return true if the Expr is block type | ||||||||
8014 | static bool checkBlockType(Sema &S, const Expr *E) { | ||||||||
8015 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||||||
8016 | QualType Ty = CE->getCallee()->getType(); | ||||||||
8017 | if (Ty->isBlockPointerType()) { | ||||||||
8018 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | ||||||||
8019 | return true; | ||||||||
8020 | } | ||||||||
8021 | } | ||||||||
8022 | return false; | ||||||||
8023 | } | ||||||||
8024 | |||||||||
8025 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | ||||||||
8026 | /// In that case, LHS = cond. | ||||||||
8027 | /// C99 6.5.15 | ||||||||
8028 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | ||||||||
8029 | ExprResult &RHS, ExprValueKind &VK, | ||||||||
8030 | ExprObjectKind &OK, | ||||||||
8031 | SourceLocation QuestionLoc) { | ||||||||
8032 | |||||||||
8033 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | ||||||||
8034 | if (!LHSResult.isUsable()) return QualType(); | ||||||||
8035 | LHS = LHSResult; | ||||||||
8036 | |||||||||
8037 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | ||||||||
8038 | if (!RHSResult.isUsable()) return QualType(); | ||||||||
8039 | RHS = RHSResult; | ||||||||
8040 | |||||||||
8041 | // C++ is sufficiently different to merit its own checker. | ||||||||
8042 | if (getLangOpts().CPlusPlus) | ||||||||
8043 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | ||||||||
8044 | |||||||||
8045 | VK = VK_RValue; | ||||||||
8046 | OK = OK_Ordinary; | ||||||||
8047 | |||||||||
8048 | if (Context.isDependenceAllowed() && | ||||||||
8049 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | ||||||||
8050 | RHS.get()->isTypeDependent())) { | ||||||||
8051 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8051, __PRETTY_FUNCTION__)); | ||||||||
8052 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8054, __PRETTY_FUNCTION__)) | ||||||||
8053 | RHS.get()->containsErrors()) &&(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8054, __PRETTY_FUNCTION__)) | ||||||||
8054 | "should only occur in error-recovery path.")(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8054, __PRETTY_FUNCTION__)); | ||||||||
8055 | return Context.DependentTy; | ||||||||
8056 | } | ||||||||
8057 | |||||||||
8058 | // The OpenCL operator with a vector condition is sufficiently | ||||||||
8059 | // different to merit its own checker. | ||||||||
8060 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | ||||||||
8061 | Cond.get()->getType()->isExtVectorType()) | ||||||||
8062 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | ||||||||
8063 | |||||||||
8064 | // First, check the condition. | ||||||||
8065 | Cond = UsualUnaryConversions(Cond.get()); | ||||||||
8066 | if (Cond.isInvalid()) | ||||||||
8067 | return QualType(); | ||||||||
8068 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | ||||||||
8069 | return QualType(); | ||||||||
8070 | |||||||||
8071 | // Now check the two expressions. | ||||||||
8072 | if (LHS.get()->getType()->isVectorType() || | ||||||||
8073 | RHS.get()->getType()->isVectorType()) | ||||||||
8074 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | ||||||||
8075 | /*AllowBothBool*/true, | ||||||||
8076 | /*AllowBoolConversions*/false); | ||||||||
8077 | |||||||||
8078 | QualType ResTy = | ||||||||
8079 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | ||||||||
8080 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
8081 | return QualType(); | ||||||||
8082 | |||||||||
8083 | QualType LHSTy = LHS.get()->getType(); | ||||||||
8084 | QualType RHSTy = RHS.get()->getType(); | ||||||||
8085 | |||||||||
8086 | // Diagnose attempts to convert between __float128 and long double where | ||||||||
8087 | // such conversions currently can't be handled. | ||||||||
8088 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | ||||||||
8089 | Diag(QuestionLoc, | ||||||||
8090 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | ||||||||
8091 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
8092 | return QualType(); | ||||||||
8093 | } | ||||||||
8094 | |||||||||
8095 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | ||||||||
8096 | // selection operator (?:). | ||||||||
8097 | if (getLangOpts().OpenCL && | ||||||||
8098 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { | ||||||||
8099 | return QualType(); | ||||||||
8100 | } | ||||||||
8101 | |||||||||
8102 | // If both operands have arithmetic type, do the usual arithmetic conversions | ||||||||
8103 | // to find a common type: C99 6.5.15p3,5. | ||||||||
8104 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | ||||||||
8105 | // Disallow invalid arithmetic conversions, such as those between ExtInts of | ||||||||
8106 | // different sizes, or between ExtInts and other types. | ||||||||
8107 | if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { | ||||||||
8108 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||||||
8109 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||||||
8110 | << RHS.get()->getSourceRange(); | ||||||||
8111 | return QualType(); | ||||||||
8112 | } | ||||||||
8113 | |||||||||
8114 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | ||||||||
8115 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | ||||||||
8116 | |||||||||
8117 | return ResTy; | ||||||||
8118 | } | ||||||||
8119 | |||||||||
8120 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | ||||||||
8121 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | ||||||||
8122 | return LHSTy; | ||||||||
8123 | } | ||||||||
8124 | |||||||||
8125 | // If both operands are the same structure or union type, the result is that | ||||||||
8126 | // type. | ||||||||
8127 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | ||||||||
8128 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | ||||||||
8129 | if (LHSRT->getDecl() == RHSRT->getDecl()) | ||||||||
8130 | // "If both the operands have structure or union type, the result has | ||||||||
8131 | // that type." This implies that CV qualifiers are dropped. | ||||||||
8132 | return LHSTy.getUnqualifiedType(); | ||||||||
8133 | // FIXME: Type of conditional expression must be complete in C mode. | ||||||||
8134 | } | ||||||||
8135 | |||||||||
8136 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | ||||||||
8137 | // The following || allows only one side to be void (a GCC-ism). | ||||||||
8138 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | ||||||||
8139 | return checkConditionalVoidType(*this, LHS, RHS); | ||||||||
8140 | } | ||||||||
8141 | |||||||||
8142 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | ||||||||
8143 | // the type of the other operand." | ||||||||
8144 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | ||||||||
8145 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | ||||||||
8146 | |||||||||
8147 | // All objective-c pointer type analysis is done here. | ||||||||
8148 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | ||||||||
8149 | QuestionLoc); | ||||||||
8150 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
8151 | return QualType(); | ||||||||
8152 | if (!compositeType.isNull()) | ||||||||
8153 | return compositeType; | ||||||||
8154 | |||||||||
8155 | |||||||||
8156 | // Handle block pointer types. | ||||||||
8157 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | ||||||||
8158 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | ||||||||
8159 | QuestionLoc); | ||||||||
8160 | |||||||||
8161 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | ||||||||
8162 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | ||||||||
8163 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | ||||||||
8164 | QuestionLoc); | ||||||||
8165 | |||||||||
8166 | // GCC compatibility: soften pointer/integer mismatch. Note that | ||||||||
8167 | // null pointers have been filtered out by this point. | ||||||||
8168 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | ||||||||
8169 | /*IsIntFirstExpr=*/true)) | ||||||||
8170 | return RHSTy; | ||||||||
8171 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | ||||||||
8172 | /*IsIntFirstExpr=*/false)) | ||||||||
8173 | return LHSTy; | ||||||||
8174 | |||||||||
8175 | // Allow ?: operations in which both operands have the same | ||||||||
8176 | // built-in sizeless type. | ||||||||
8177 | if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) | ||||||||
8178 | return LHSTy; | ||||||||
8179 | |||||||||
8180 | // Emit a better diagnostic if one of the expressions is a null pointer | ||||||||
8181 | // constant and the other is not a pointer type. In this case, the user most | ||||||||
8182 | // likely forgot to take the address of the other expression. | ||||||||
8183 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | ||||||||
8184 | return QualType(); | ||||||||
8185 | |||||||||
8186 | // Otherwise, the operands are not compatible. | ||||||||
8187 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||||||
8188 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||||||
8189 | << RHS.get()->getSourceRange(); | ||||||||
8190 | return QualType(); | ||||||||
8191 | } | ||||||||
8192 | |||||||||
8193 | /// FindCompositeObjCPointerType - Helper method to find composite type of | ||||||||
8194 | /// two objective-c pointer types of the two input expressions. | ||||||||
8195 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | ||||||||
8196 | SourceLocation QuestionLoc) { | ||||||||
8197 | QualType LHSTy = LHS.get()->getType(); | ||||||||
8198 | QualType RHSTy = RHS.get()->getType(); | ||||||||
8199 | |||||||||
8200 | // Handle things like Class and struct objc_class*. Here we case the result | ||||||||
8201 | // to the pseudo-builtin, because that will be implicitly cast back to the | ||||||||
8202 | // redefinition type if an attempt is made to access its fields. | ||||||||
8203 | if (LHSTy->isObjCClassType() && | ||||||||
8204 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | ||||||||
8205 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||||||
8206 | return LHSTy; | ||||||||
8207 | } | ||||||||
8208 | if (RHSTy->isObjCClassType() && | ||||||||
8209 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | ||||||||
8210 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||||||
8211 | return RHSTy; | ||||||||
8212 | } | ||||||||
8213 | // And the same for struct objc_object* / id | ||||||||
8214 | if (LHSTy->isObjCIdType() && | ||||||||
8215 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | ||||||||
8216 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||||||
8217 | return LHSTy; | ||||||||
8218 | } | ||||||||
8219 | if (RHSTy->isObjCIdType() && | ||||||||
8220 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | ||||||||
8221 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||||||
8222 | return RHSTy; | ||||||||
8223 | } | ||||||||
8224 | // And the same for struct objc_selector* / SEL | ||||||||
8225 | if (Context.isObjCSelType(LHSTy) && | ||||||||
8226 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | ||||||||
8227 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | ||||||||
8228 | return LHSTy; | ||||||||
8229 | } | ||||||||
8230 | if (Context.isObjCSelType(RHSTy) && | ||||||||
8231 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | ||||||||
8232 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | ||||||||
8233 | return RHSTy; | ||||||||
8234 | } | ||||||||
8235 | // Check constraints for Objective-C object pointers types. | ||||||||
8236 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||||||
8237 | |||||||||
8238 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | ||||||||
8239 | // Two identical object pointer types are always compatible. | ||||||||
8240 | return LHSTy; | ||||||||
8241 | } | ||||||||
8242 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | ||||||||
8243 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | ||||||||
8244 | QualType compositeType = LHSTy; | ||||||||
8245 | |||||||||
8246 | // If both operands are interfaces and either operand can be | ||||||||
8247 | // assigned to the other, use that type as the composite | ||||||||
8248 | // type. This allows | ||||||||
8249 | // xxx ? (A*) a : (B*) b | ||||||||
8250 | // where B is a subclass of A. | ||||||||
8251 | // | ||||||||
8252 | // Additionally, as for assignment, if either type is 'id' | ||||||||
8253 | // allow silent coercion. Finally, if the types are | ||||||||
8254 | // incompatible then make sure to use 'id' as the composite | ||||||||
8255 | // type so the result is acceptable for sending messages to. | ||||||||
8256 | |||||||||
8257 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | ||||||||
8258 | // It could return the composite type. | ||||||||
8259 | if (!(compositeType = | ||||||||
8260 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | ||||||||
8261 | // Nothing more to do. | ||||||||
8262 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | ||||||||
8263 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | ||||||||
8264 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | ||||||||
8265 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | ||||||||
8266 | } else if ((LHSOPT->isObjCQualifiedIdType() || | ||||||||
8267 | RHSOPT->isObjCQualifiedIdType()) && | ||||||||
8268 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | ||||||||
8269 | true)) { | ||||||||
8270 | // Need to handle "id<xx>" explicitly. | ||||||||
8271 | // GCC allows qualified id and any Objective-C type to devolve to | ||||||||
8272 | // id. Currently localizing to here until clear this should be | ||||||||
8273 | // part of ObjCQualifiedIdTypesAreCompatible. | ||||||||
8274 | compositeType = Context.getObjCIdType(); | ||||||||
8275 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | ||||||||
8276 | compositeType = Context.getObjCIdType(); | ||||||||
8277 | } else { | ||||||||
8278 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | ||||||||
8279 | << LHSTy << RHSTy | ||||||||
8280 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
8281 | QualType incompatTy = Context.getObjCIdType(); | ||||||||
8282 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | ||||||||
8283 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | ||||||||
8284 | return incompatTy; | ||||||||
8285 | } | ||||||||
8286 | // The object pointer types are compatible. | ||||||||
8287 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | ||||||||
8288 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | ||||||||
8289 | return compositeType; | ||||||||
8290 | } | ||||||||
8291 | // Check Objective-C object pointer types and 'void *' | ||||||||
8292 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||||||
8293 | if (getLangOpts().ObjCAutoRefCount) { | ||||||||
8294 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||||||
8295 | // so these types are not compatible. | ||||||||
8296 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||||||
8297 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
8298 | LHS = RHS = true; | ||||||||
8299 | return QualType(); | ||||||||
8300 | } | ||||||||
8301 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
8302 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||||||
8303 | QualType destPointee | ||||||||
8304 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||||||
8305 | QualType destType = Context.getPointerType(destPointee); | ||||||||
8306 | // Add qualifiers if necessary. | ||||||||
8307 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||||||
8308 | // Promote to void*. | ||||||||
8309 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||||||
8310 | return destType; | ||||||||
8311 | } | ||||||||
8312 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | ||||||||
8313 | if (getLangOpts().ObjCAutoRefCount) { | ||||||||
8314 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||||||
8315 | // so these types are not compatible. | ||||||||
8316 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||||||
8317 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
8318 | LHS = RHS = true; | ||||||||
8319 | return QualType(); | ||||||||
8320 | } | ||||||||
8321 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||||||
8322 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||||||
8323 | QualType destPointee | ||||||||
8324 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||||||
8325 | QualType destType = Context.getPointerType(destPointee); | ||||||||
8326 | // Add qualifiers if necessary. | ||||||||
8327 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||||||
8328 | // Promote to void*. | ||||||||
8329 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||||||
8330 | return destType; | ||||||||
8331 | } | ||||||||
8332 | return QualType(); | ||||||||
8333 | } | ||||||||
8334 | |||||||||
8335 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | ||||||||
8336 | /// ParenRange in parentheses. | ||||||||
8337 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | ||||||||
8338 | const PartialDiagnostic &Note, | ||||||||
8339 | SourceRange ParenRange) { | ||||||||
8340 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | ||||||||
8341 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | ||||||||
8342 | EndLoc.isValid()) { | ||||||||
8343 | Self.Diag(Loc, Note) | ||||||||
8344 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | ||||||||
8345 | << FixItHint::CreateInsertion(EndLoc, ")"); | ||||||||
8346 | } else { | ||||||||
8347 | // We can't display the parentheses, so just show the bare note. | ||||||||
8348 | Self.Diag(Loc, Note) << ParenRange; | ||||||||
8349 | } | ||||||||
8350 | } | ||||||||
8351 | |||||||||
8352 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | ||||||||
8353 | return BinaryOperator::isAdditiveOp(Opc) || | ||||||||
8354 | BinaryOperator::isMultiplicativeOp(Opc) || | ||||||||
8355 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | ||||||||
8356 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | ||||||||
8357 | // not any of the logical operators. Bitwise-xor is commonly used as a | ||||||||
8358 | // logical-xor because there is no logical-xor operator. The logical | ||||||||
8359 | // operators, including uses of xor, have a high false positive rate for | ||||||||
8360 | // precedence warnings. | ||||||||
8361 | } | ||||||||
8362 | |||||||||
8363 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | ||||||||
8364 | /// expression, either using a built-in or overloaded operator, | ||||||||
8365 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | ||||||||
8366 | /// expression. | ||||||||
8367 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | ||||||||
8368 | Expr **RHSExprs) { | ||||||||
8369 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | ||||||||
8370 | E = E->IgnoreImpCasts(); | ||||||||
8371 | E = E->IgnoreConversionOperatorSingleStep(); | ||||||||
8372 | E = E->IgnoreImpCasts(); | ||||||||
8373 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | ||||||||
8374 | E = MTE->getSubExpr(); | ||||||||
8375 | E = E->IgnoreImpCasts(); | ||||||||
8376 | } | ||||||||
8377 | |||||||||
8378 | // Built-in binary operator. | ||||||||
8379 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | ||||||||
8380 | if (IsArithmeticOp(OP->getOpcode())) { | ||||||||
8381 | *Opcode = OP->getOpcode(); | ||||||||
8382 | *RHSExprs = OP->getRHS(); | ||||||||
8383 | return true; | ||||||||
8384 | } | ||||||||
8385 | } | ||||||||
8386 | |||||||||
8387 | // Overloaded operator. | ||||||||
8388 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||||||
8389 | if (Call->getNumArgs() != 2) | ||||||||
8390 | return false; | ||||||||
8391 | |||||||||
8392 | // Make sure this is really a binary operator that is safe to pass into | ||||||||
8393 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | ||||||||
8394 | OverloadedOperatorKind OO = Call->getOperator(); | ||||||||
8395 | if (OO < OO_Plus || OO > OO_Arrow || | ||||||||
8396 | OO == OO_PlusPlus || OO == OO_MinusMinus) | ||||||||
8397 | return false; | ||||||||
8398 | |||||||||
8399 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | ||||||||
8400 | if (IsArithmeticOp(OpKind)) { | ||||||||
8401 | *Opcode = OpKind; | ||||||||
8402 | *RHSExprs = Call->getArg(1); | ||||||||
8403 | return true; | ||||||||
8404 | } | ||||||||
8405 | } | ||||||||
8406 | |||||||||
8407 | return false; | ||||||||
8408 | } | ||||||||
8409 | |||||||||
8410 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | ||||||||
8411 | /// or is a logical expression such as (x==y) which has int type, but is | ||||||||
8412 | /// commonly interpreted as boolean. | ||||||||
8413 | static bool ExprLooksBoolean(Expr *E) { | ||||||||
8414 | E = E->IgnoreParenImpCasts(); | ||||||||
8415 | |||||||||
8416 | if (E->getType()->isBooleanType()) | ||||||||
8417 | return true; | ||||||||
8418 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | ||||||||
8419 | return OP->isComparisonOp() || OP->isLogicalOp(); | ||||||||
8420 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | ||||||||
8421 | return OP->getOpcode() == UO_LNot; | ||||||||
8422 | if (E->getType()->isPointerType()) | ||||||||
8423 | return true; | ||||||||
8424 | // FIXME: What about overloaded operator calls returning "unspecified boolean | ||||||||
8425 | // type"s (commonly pointer-to-members)? | ||||||||
8426 | |||||||||
8427 | return false; | ||||||||
8428 | } | ||||||||
8429 | |||||||||
8430 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | ||||||||
8431 | /// and binary operator are mixed in a way that suggests the programmer assumed | ||||||||
8432 | /// the conditional operator has higher precedence, for example: | ||||||||
8433 | /// "int x = a + someBinaryCondition ? 1 : 2". | ||||||||
8434 | static void DiagnoseConditionalPrecedence(Sema &Self, | ||||||||
8435 | SourceLocation OpLoc, | ||||||||
8436 | Expr *Condition, | ||||||||
8437 | Expr *LHSExpr, | ||||||||
8438 | Expr *RHSExpr) { | ||||||||
8439 | BinaryOperatorKind CondOpcode; | ||||||||
8440 | Expr *CondRHS; | ||||||||
8441 | |||||||||
8442 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | ||||||||
8443 | return; | ||||||||
8444 | if (!ExprLooksBoolean(CondRHS)) | ||||||||
8445 | return; | ||||||||
8446 | |||||||||
8447 | // The condition is an arithmetic binary expression, with a right- | ||||||||
8448 | // hand side that looks boolean, so warn. | ||||||||
8449 | |||||||||
8450 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | ||||||||
8451 | ? diag::warn_precedence_bitwise_conditional | ||||||||
8452 | : diag::warn_precedence_conditional; | ||||||||
8453 | |||||||||
8454 | Self.Diag(OpLoc, DiagID) | ||||||||
8455 | << Condition->getSourceRange() | ||||||||
8456 | << BinaryOperator::getOpcodeStr(CondOpcode); | ||||||||
8457 | |||||||||
8458 | SuggestParentheses( | ||||||||
8459 | Self, OpLoc, | ||||||||
8460 | Self.PDiag(diag::note_precedence_silence) | ||||||||
8461 | << BinaryOperator::getOpcodeStr(CondOpcode), | ||||||||
8462 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | ||||||||
8463 | |||||||||
8464 | SuggestParentheses(Self, OpLoc, | ||||||||
8465 | Self.PDiag(diag::note_precedence_conditional_first), | ||||||||
8466 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | ||||||||
8467 | } | ||||||||
8468 | |||||||||
8469 | /// Compute the nullability of a conditional expression. | ||||||||
8470 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | ||||||||
8471 | QualType LHSTy, QualType RHSTy, | ||||||||
8472 | ASTContext &Ctx) { | ||||||||
8473 | if (!ResTy->isAnyPointerType()) | ||||||||
8474 | return ResTy; | ||||||||
8475 | |||||||||
8476 | auto GetNullability = [&Ctx](QualType Ty) { | ||||||||
8477 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | ||||||||
8478 | if (Kind) | ||||||||
8479 | return *Kind; | ||||||||
8480 | return NullabilityKind::Unspecified; | ||||||||
8481 | }; | ||||||||
8482 | |||||||||
8483 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | ||||||||
8484 | NullabilityKind MergedKind; | ||||||||
8485 | |||||||||
8486 | // Compute nullability of a binary conditional expression. | ||||||||
8487 | if (IsBin) { | ||||||||
8488 | if (LHSKind == NullabilityKind::NonNull) | ||||||||
8489 | MergedKind = NullabilityKind::NonNull; | ||||||||
8490 | else | ||||||||
8491 | MergedKind = RHSKind; | ||||||||
8492 | // Compute nullability of a normal conditional expression. | ||||||||
8493 | } else { | ||||||||
8494 | if (LHSKind == NullabilityKind::Nullable || | ||||||||
8495 | RHSKind == NullabilityKind::Nullable) | ||||||||
8496 | MergedKind = NullabilityKind::Nullable; | ||||||||
8497 | else if (LHSKind == NullabilityKind::NonNull) | ||||||||
8498 | MergedKind = RHSKind; | ||||||||
8499 | else if (RHSKind == NullabilityKind::NonNull) | ||||||||
8500 | MergedKind = LHSKind; | ||||||||
8501 | else | ||||||||
8502 | MergedKind = NullabilityKind::Unspecified; | ||||||||
8503 | } | ||||||||
8504 | |||||||||
8505 | // Return if ResTy already has the correct nullability. | ||||||||
8506 | if (GetNullability(ResTy) == MergedKind) | ||||||||
8507 | return ResTy; | ||||||||
8508 | |||||||||
8509 | // Strip all nullability from ResTy. | ||||||||
8510 | while (ResTy->getNullability(Ctx)) | ||||||||
8511 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | ||||||||
8512 | |||||||||
8513 | // Create a new AttributedType with the new nullability kind. | ||||||||
8514 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | ||||||||
8515 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | ||||||||
8516 | } | ||||||||
8517 | |||||||||
8518 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | ||||||||
8519 | /// in the case of a the GNU conditional expr extension. | ||||||||
8520 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | ||||||||
8521 | SourceLocation ColonLoc, | ||||||||
8522 | Expr *CondExpr, Expr *LHSExpr, | ||||||||
8523 | Expr *RHSExpr) { | ||||||||
8524 | if (!Context.isDependenceAllowed()) { | ||||||||
8525 | // C cannot handle TypoExpr nodes in the condition because it | ||||||||
8526 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||||||
8527 | // been dealt with before checking the operands. | ||||||||
8528 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | ||||||||
8529 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | ||||||||
8530 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | ||||||||
8531 | |||||||||
8532 | if (!CondResult.isUsable()) | ||||||||
8533 | return ExprError(); | ||||||||
8534 | |||||||||
8535 | if (LHSExpr) { | ||||||||
8536 | if (!LHSResult.isUsable()) | ||||||||
8537 | return ExprError(); | ||||||||
8538 | } | ||||||||
8539 | |||||||||
8540 | if (!RHSResult.isUsable()) | ||||||||
8541 | return ExprError(); | ||||||||
8542 | |||||||||
8543 | CondExpr = CondResult.get(); | ||||||||
8544 | LHSExpr = LHSResult.get(); | ||||||||
8545 | RHSExpr = RHSResult.get(); | ||||||||
8546 | } | ||||||||
8547 | |||||||||
8548 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | ||||||||
8549 | // was the condition. | ||||||||
8550 | OpaqueValueExpr *opaqueValue = nullptr; | ||||||||
8551 | Expr *commonExpr = nullptr; | ||||||||
8552 | if (!LHSExpr) { | ||||||||
8553 | commonExpr = CondExpr; | ||||||||
8554 | // Lower out placeholder types first. This is important so that we don't | ||||||||
8555 | // try to capture a placeholder. This happens in few cases in C++; such | ||||||||
8556 | // as Objective-C++'s dictionary subscripting syntax. | ||||||||
8557 | if (commonExpr->hasPlaceholderType()) { | ||||||||
8558 | ExprResult result = CheckPlaceholderExpr(commonExpr); | ||||||||
8559 | if (!result.isUsable()) return ExprError(); | ||||||||
8560 | commonExpr = result.get(); | ||||||||
8561 | } | ||||||||
8562 | // We usually want to apply unary conversions *before* saving, except | ||||||||
8563 | // in the special case of a C++ l-value conditional. | ||||||||
8564 | if (!(getLangOpts().CPlusPlus | ||||||||
8565 | && !commonExpr->isTypeDependent() | ||||||||
8566 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | ||||||||
8567 | && commonExpr->isGLValue() | ||||||||
8568 | && commonExpr->isOrdinaryOrBitFieldObject() | ||||||||
8569 | && RHSExpr->isOrdinaryOrBitFieldObject() | ||||||||
8570 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | ||||||||
8571 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | ||||||||
8572 | if (commonRes.isInvalid()) | ||||||||
8573 | return ExprError(); | ||||||||
8574 | commonExpr = commonRes.get(); | ||||||||
8575 | } | ||||||||
8576 | |||||||||
8577 | // If the common expression is a class or array prvalue, materialize it | ||||||||
8578 | // so that we can safely refer to it multiple times. | ||||||||
8579 | if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || | ||||||||
8580 | commonExpr->getType()->isArrayType())) { | ||||||||
8581 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | ||||||||
8582 | if (MatExpr.isInvalid()) | ||||||||
8583 | return ExprError(); | ||||||||
8584 | commonExpr = MatExpr.get(); | ||||||||
8585 | } | ||||||||
8586 | |||||||||
8587 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | ||||||||
8588 | commonExpr->getType(), | ||||||||
8589 | commonExpr->getValueKind(), | ||||||||
8590 | commonExpr->getObjectKind(), | ||||||||
8591 | commonExpr); | ||||||||
8592 | LHSExpr = CondExpr = opaqueValue; | ||||||||
8593 | } | ||||||||
8594 | |||||||||
8595 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | ||||||||
8596 | ExprValueKind VK = VK_RValue; | ||||||||
8597 | ExprObjectKind OK = OK_Ordinary; | ||||||||
8598 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | ||||||||
8599 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | ||||||||
8600 | VK, OK, QuestionLoc); | ||||||||
8601 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | ||||||||
8602 | RHS.isInvalid()) | ||||||||
8603 | return ExprError(); | ||||||||
8604 | |||||||||
8605 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | ||||||||
8606 | RHS.get()); | ||||||||
8607 | |||||||||
8608 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | ||||||||
8609 | |||||||||
8610 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | ||||||||
8611 | Context); | ||||||||
8612 | |||||||||
8613 | if (!commonExpr) | ||||||||
8614 | return new (Context) | ||||||||
8615 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | ||||||||
8616 | RHS.get(), result, VK, OK); | ||||||||
8617 | |||||||||
8618 | return new (Context) BinaryConditionalOperator( | ||||||||
8619 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | ||||||||
8620 | ColonLoc, result, VK, OK); | ||||||||
8621 | } | ||||||||
8622 | |||||||||
8623 | // Check if we have a conversion between incompatible cmse function pointer | ||||||||
8624 | // types, that is, a conversion between a function pointer with the | ||||||||
8625 | // cmse_nonsecure_call attribute and one without. | ||||||||
8626 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | ||||||||
8627 | QualType ToType) { | ||||||||
8628 | if (const auto *ToFn = | ||||||||
8629 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | ||||||||
8630 | if (const auto *FromFn = | ||||||||
8631 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | ||||||||
8632 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | ||||||||
8633 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | ||||||||
8634 | |||||||||
8635 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | ||||||||
8636 | } | ||||||||
8637 | } | ||||||||
8638 | return false; | ||||||||
8639 | } | ||||||||
8640 | |||||||||
8641 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | ||||||||
8642 | // being closely modeled after the C99 spec:-). The odd characteristic of this | ||||||||
8643 | // routine is it effectively iqnores the qualifiers on the top level pointee. | ||||||||
8644 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | ||||||||
8645 | // FIXME: add a couple examples in this comment. | ||||||||
8646 | static Sema::AssignConvertType | ||||||||
8647 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | ||||||||
8648 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8648, __PRETTY_FUNCTION__)); | ||||||||
8649 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8649, __PRETTY_FUNCTION__)); | ||||||||
8650 | |||||||||
8651 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||||||
8652 | const Type *lhptee, *rhptee; | ||||||||
8653 | Qualifiers lhq, rhq; | ||||||||
8654 | std::tie(lhptee, lhq) = | ||||||||
8655 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | ||||||||
8656 | std::tie(rhptee, rhq) = | ||||||||
8657 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | ||||||||
8658 | |||||||||
8659 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||||||
8660 | |||||||||
8661 | // C99 6.5.16.1p1: This following citation is common to constraints | ||||||||
8662 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | ||||||||
8663 | // qualifiers of the type *pointed to* by the right; | ||||||||
8664 | |||||||||
8665 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | ||||||||
8666 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | ||||||||
8667 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | ||||||||
8668 | // Ignore lifetime for further calculation. | ||||||||
8669 | lhq.removeObjCLifetime(); | ||||||||
8670 | rhq.removeObjCLifetime(); | ||||||||
8671 | } | ||||||||
8672 | |||||||||
8673 | if (!lhq.compatiblyIncludes(rhq)) { | ||||||||
8674 | // Treat address-space mismatches as fatal. | ||||||||
8675 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | ||||||||
8676 | return Sema::IncompatiblePointerDiscardsQualifiers; | ||||||||
8677 | |||||||||
8678 | // It's okay to add or remove GC or lifetime qualifiers when converting to | ||||||||
8679 | // and from void*. | ||||||||
8680 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | ||||||||
8681 | .compatiblyIncludes( | ||||||||
8682 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | ||||||||
8683 | && (lhptee->isVoidType() || rhptee->isVoidType())) | ||||||||
8684 | ; // keep old | ||||||||
8685 | |||||||||
8686 | // Treat lifetime mismatches as fatal. | ||||||||
8687 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | ||||||||
8688 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | ||||||||
8689 | |||||||||
8690 | // For GCC/MS compatibility, other qualifier mismatches are treated | ||||||||
8691 | // as still compatible in C. | ||||||||
8692 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||||||
8693 | } | ||||||||
8694 | |||||||||
8695 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | ||||||||
8696 | // incomplete type and the other is a pointer to a qualified or unqualified | ||||||||
8697 | // version of void... | ||||||||
8698 | if (lhptee->isVoidType()) { | ||||||||
8699 | if (rhptee->isIncompleteOrObjectType()) | ||||||||
8700 | return ConvTy; | ||||||||
8701 | |||||||||
8702 | // As an extension, we allow cast to/from void* to function pointer. | ||||||||
8703 | assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8703, __PRETTY_FUNCTION__)); | ||||||||
8704 | return Sema::FunctionVoidPointer; | ||||||||
8705 | } | ||||||||
8706 | |||||||||
8707 | if (rhptee->isVoidType()) { | ||||||||
8708 | if (lhptee->isIncompleteOrObjectType()) | ||||||||
8709 | return ConvTy; | ||||||||
8710 | |||||||||
8711 | // As an extension, we allow cast to/from void* to function pointer. | ||||||||
8712 | assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8712, __PRETTY_FUNCTION__)); | ||||||||
8713 | return Sema::FunctionVoidPointer; | ||||||||
8714 | } | ||||||||
8715 | |||||||||
8716 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | ||||||||
8717 | // unqualified versions of compatible types, ... | ||||||||
8718 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | ||||||||
8719 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | ||||||||
8720 | // Check if the pointee types are compatible ignoring the sign. | ||||||||
8721 | // We explicitly check for char so that we catch "char" vs | ||||||||
8722 | // "unsigned char" on systems where "char" is unsigned. | ||||||||
8723 | if (lhptee->isCharType()) | ||||||||
8724 | ltrans = S.Context.UnsignedCharTy; | ||||||||
8725 | else if (lhptee->hasSignedIntegerRepresentation()) | ||||||||
8726 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | ||||||||
8727 | |||||||||
8728 | if (rhptee->isCharType()) | ||||||||
8729 | rtrans = S.Context.UnsignedCharTy; | ||||||||
8730 | else if (rhptee->hasSignedIntegerRepresentation()) | ||||||||
8731 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | ||||||||
8732 | |||||||||
8733 | if (ltrans == rtrans) { | ||||||||
8734 | // Types are compatible ignoring the sign. Qualifier incompatibility | ||||||||
8735 | // takes priority over sign incompatibility because the sign | ||||||||
8736 | // warning can be disabled. | ||||||||
8737 | if (ConvTy != Sema::Compatible) | ||||||||
8738 | return ConvTy; | ||||||||
8739 | |||||||||
8740 | return Sema::IncompatiblePointerSign; | ||||||||
8741 | } | ||||||||
8742 | |||||||||
8743 | // If we are a multi-level pointer, it's possible that our issue is simply | ||||||||
8744 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | ||||||||
8745 | // the eventual target type is the same and the pointers have the same | ||||||||
8746 | // level of indirection, this must be the issue. | ||||||||
8747 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | ||||||||
8748 | do { | ||||||||
8749 | std::tie(lhptee, lhq) = | ||||||||
8750 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | ||||||||
8751 | std::tie(rhptee, rhq) = | ||||||||
8752 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | ||||||||
8753 | |||||||||
8754 | // Inconsistent address spaces at this point is invalid, even if the | ||||||||
8755 | // address spaces would be compatible. | ||||||||
8756 | // FIXME: This doesn't catch address space mismatches for pointers of | ||||||||
8757 | // different nesting levels, like: | ||||||||
8758 | // __local int *** a; | ||||||||
8759 | // int ** b = a; | ||||||||
8760 | // It's not clear how to actually determine when such pointers are | ||||||||
8761 | // invalidly incompatible. | ||||||||
8762 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | ||||||||
8763 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | ||||||||
8764 | |||||||||
8765 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | ||||||||
8766 | |||||||||
8767 | if (lhptee == rhptee) | ||||||||
8768 | return Sema::IncompatibleNestedPointerQualifiers; | ||||||||
8769 | } | ||||||||
8770 | |||||||||
8771 | // General pointer incompatibility takes priority over qualifiers. | ||||||||
8772 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | ||||||||
8773 | return Sema::IncompatibleFunctionPointer; | ||||||||
8774 | return Sema::IncompatiblePointer; | ||||||||
8775 | } | ||||||||
8776 | if (!S.getLangOpts().CPlusPlus && | ||||||||
8777 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | ||||||||
8778 | return Sema::IncompatibleFunctionPointer; | ||||||||
8779 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | ||||||||
8780 | return Sema::IncompatibleFunctionPointer; | ||||||||
8781 | return ConvTy; | ||||||||
8782 | } | ||||||||
8783 | |||||||||
8784 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | ||||||||
8785 | /// block pointer types are compatible or whether a block and normal pointer | ||||||||
8786 | /// are compatible. It is more restrict than comparing two function pointer | ||||||||
8787 | // types. | ||||||||
8788 | static Sema::AssignConvertType | ||||||||
8789 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||||||
8790 | QualType RHSType) { | ||||||||
8791 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8791, __PRETTY_FUNCTION__)); | ||||||||
8792 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8792, __PRETTY_FUNCTION__)); | ||||||||
8793 | |||||||||
8794 | QualType lhptee, rhptee; | ||||||||
8795 | |||||||||
8796 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||||||
8797 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | ||||||||
8798 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | ||||||||
8799 | |||||||||
8800 | // In C++, the types have to match exactly. | ||||||||
8801 | if (S.getLangOpts().CPlusPlus) | ||||||||
8802 | return Sema::IncompatibleBlockPointer; | ||||||||
8803 | |||||||||
8804 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||||||
8805 | |||||||||
8806 | // For blocks we enforce that qualifiers are identical. | ||||||||
8807 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | ||||||||
8808 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | ||||||||
8809 | if (S.getLangOpts().OpenCL) { | ||||||||
8810 | LQuals.removeAddressSpace(); | ||||||||
8811 | RQuals.removeAddressSpace(); | ||||||||
8812 | } | ||||||||
8813 | if (LQuals != RQuals) | ||||||||
8814 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||||||
8815 | |||||||||
8816 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | ||||||||
8817 | // assignment. | ||||||||
8818 | // The current behavior is similar to C++ lambdas. A block might be | ||||||||
8819 | // assigned to a variable iff its return type and parameters are compatible | ||||||||
8820 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | ||||||||
8821 | // an assignment. Presumably it should behave in way that a function pointer | ||||||||
8822 | // assignment does in C, so for each parameter and return type: | ||||||||
8823 | // * CVR and address space of LHS should be a superset of CVR and address | ||||||||
8824 | // space of RHS. | ||||||||
8825 | // * unqualified types should be compatible. | ||||||||
8826 | if (S.getLangOpts().OpenCL) { | ||||||||
8827 | if (!S.Context.typesAreBlockPointerCompatible( | ||||||||
8828 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | ||||||||
8829 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | ||||||||
8830 | return Sema::IncompatibleBlockPointer; | ||||||||
8831 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | ||||||||
8832 | return Sema::IncompatibleBlockPointer; | ||||||||
8833 | |||||||||
8834 | return ConvTy; | ||||||||
8835 | } | ||||||||
8836 | |||||||||
8837 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | ||||||||
8838 | /// for assignment compatibility. | ||||||||
8839 | static Sema::AssignConvertType | ||||||||
8840 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||||||
8841 | QualType RHSType) { | ||||||||
8842 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8842, __PRETTY_FUNCTION__)); | ||||||||
8843 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 8843, __PRETTY_FUNCTION__)); | ||||||||
8844 | |||||||||
8845 | if (LHSType->isObjCBuiltinType()) { | ||||||||
8846 | // Class is not compatible with ObjC object pointers. | ||||||||
8847 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | ||||||||
8848 | !RHSType->isObjCQualifiedClassType()) | ||||||||
8849 | return Sema::IncompatiblePointer; | ||||||||
8850 | return Sema::Compatible; | ||||||||
8851 | } | ||||||||
8852 | if (RHSType->isObjCBuiltinType()) { | ||||||||
8853 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | ||||||||
8854 | !LHSType->isObjCQualifiedClassType()) | ||||||||
8855 | return Sema::IncompatiblePointer; | ||||||||
8856 | return Sema::Compatible; | ||||||||
8857 | } | ||||||||
8858 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||||||
8859 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||||||
8860 | |||||||||
8861 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | ||||||||
8862 | // make an exception for id<P> | ||||||||
8863 | !LHSType->isObjCQualifiedIdType()) | ||||||||
8864 | return Sema::CompatiblePointerDiscardsQualifiers; | ||||||||
8865 | |||||||||
8866 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | ||||||||
8867 | return Sema::Compatible; | ||||||||
8868 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | ||||||||
8869 | return Sema::IncompatibleObjCQualifiedId; | ||||||||
8870 | return Sema::IncompatiblePointer; | ||||||||
8871 | } | ||||||||
8872 | |||||||||
8873 | Sema::AssignConvertType | ||||||||
8874 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | ||||||||
8875 | QualType LHSType, QualType RHSType) { | ||||||||
8876 | // Fake up an opaque expression. We don't actually care about what | ||||||||
8877 | // cast operations are required, so if CheckAssignmentConstraints | ||||||||
8878 | // adds casts to this they'll be wasted, but fortunately that doesn't | ||||||||
8879 | // usually happen on valid code. | ||||||||
8880 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); | ||||||||
8881 | ExprResult RHSPtr = &RHSExpr; | ||||||||
8882 | CastKind K; | ||||||||
8883 | |||||||||
8884 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | ||||||||
8885 | } | ||||||||
8886 | |||||||||
8887 | /// This helper function returns true if QT is a vector type that has element | ||||||||
8888 | /// type ElementType. | ||||||||
8889 | static bool isVector(QualType QT, QualType ElementType) { | ||||||||
8890 | if (const VectorType *VT = QT->getAs<VectorType>()) | ||||||||
8891 | return VT->getElementType().getCanonicalType() == ElementType; | ||||||||
8892 | return false; | ||||||||
8893 | } | ||||||||
8894 | |||||||||
8895 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | ||||||||
8896 | /// has code to accommodate several GCC extensions when type checking | ||||||||
8897 | /// pointers. Here are some objectionable examples that GCC considers warnings: | ||||||||
8898 | /// | ||||||||
8899 | /// int a, *pint; | ||||||||
8900 | /// short *pshort; | ||||||||
8901 | /// struct foo *pfoo; | ||||||||
8902 | /// | ||||||||
8903 | /// pint = pshort; // warning: assignment from incompatible pointer type | ||||||||
8904 | /// a = pint; // warning: assignment makes integer from pointer without a cast | ||||||||
8905 | /// pint = a; // warning: assignment makes pointer from integer without a cast | ||||||||
8906 | /// pint = pfoo; // warning: assignment from incompatible pointer type | ||||||||
8907 | /// | ||||||||
8908 | /// As a result, the code for dealing with pointers is more complex than the | ||||||||
8909 | /// C99 spec dictates. | ||||||||
8910 | /// | ||||||||
8911 | /// Sets 'Kind' for any result kind except Incompatible. | ||||||||
8912 | Sema::AssignConvertType | ||||||||
8913 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | ||||||||
8914 | CastKind &Kind, bool ConvertRHS) { | ||||||||
8915 | QualType RHSType = RHS.get()->getType(); | ||||||||
8916 | QualType OrigLHSType = LHSType; | ||||||||
8917 | |||||||||
8918 | // Get canonical types. We're not formatting these types, just comparing | ||||||||
8919 | // them. | ||||||||
8920 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | ||||||||
8921 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | ||||||||
8922 | |||||||||
8923 | // Common case: no conversion required. | ||||||||
8924 | if (LHSType == RHSType) { | ||||||||
| |||||||||
8925 | Kind = CK_NoOp; | ||||||||
8926 | return Compatible; | ||||||||
8927 | } | ||||||||
8928 | |||||||||
8929 | // If we have an atomic type, try a non-atomic assignment, then just add an | ||||||||
8930 | // atomic qualification step. | ||||||||
8931 | if (const AtomicType *AtomicTy
| ||||||||
8932 | Sema::AssignConvertType result = | ||||||||
8933 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | ||||||||
8934 | if (result != Compatible) | ||||||||
8935 | return result; | ||||||||
8936 | if (Kind != CK_NoOp && ConvertRHS) | ||||||||
8937 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | ||||||||
8938 | Kind = CK_NonAtomicToAtomic; | ||||||||
8939 | return Compatible; | ||||||||
8940 | } | ||||||||
8941 | |||||||||
8942 | // If the left-hand side is a reference type, then we are in a | ||||||||
8943 | // (rare!) case where we've allowed the use of references in C, | ||||||||
8944 | // e.g., as a parameter type in a built-in function. In this case, | ||||||||
8945 | // just make sure that the type referenced is compatible with the | ||||||||
8946 | // right-hand side type. The caller is responsible for adjusting | ||||||||
8947 | // LHSType so that the resulting expression does not have reference | ||||||||
8948 | // type. | ||||||||
8949 | if (const ReferenceType *LHSTypeRef
| ||||||||
8950 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | ||||||||
8951 | Kind = CK_LValueBitCast; | ||||||||
8952 | return Compatible; | ||||||||
8953 | } | ||||||||
8954 | return Incompatible; | ||||||||
8955 | } | ||||||||
8956 | |||||||||
8957 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | ||||||||
8958 | // to the same ExtVector type. | ||||||||
8959 | if (LHSType->isExtVectorType()) { | ||||||||
8960 | if (RHSType->isExtVectorType()) | ||||||||
8961 | return Incompatible; | ||||||||
8962 | if (RHSType->isArithmeticType()) { | ||||||||
8963 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | ||||||||
8964 | if (ConvertRHS) | ||||||||
8965 | RHS = prepareVectorSplat(LHSType, RHS.get()); | ||||||||
8966 | Kind = CK_VectorSplat; | ||||||||
8967 | return Compatible; | ||||||||
8968 | } | ||||||||
8969 | } | ||||||||
8970 | |||||||||
8971 | // Conversions to or from vector type. | ||||||||
8972 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | ||||||||
8973 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | ||||||||
8974 | // Allow assignments of an AltiVec vector type to an equivalent GCC | ||||||||
8975 | // vector type and vice versa | ||||||||
8976 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||||||
8977 | Kind = CK_BitCast; | ||||||||
8978 | return Compatible; | ||||||||
8979 | } | ||||||||
8980 | |||||||||
8981 | // If we are allowing lax vector conversions, and LHS and RHS are both | ||||||||
8982 | // vectors, the total size only needs to be the same. This is a bitcast; | ||||||||
8983 | // no bits are changed but the result type is different. | ||||||||
8984 | if (isLaxVectorConversion(RHSType, LHSType)) { | ||||||||
8985 | Kind = CK_BitCast; | ||||||||
8986 | return IncompatibleVectors; | ||||||||
8987 | } | ||||||||
8988 | } | ||||||||
8989 | |||||||||
8990 | // When the RHS comes from another lax conversion (e.g. binops between | ||||||||
8991 | // scalars and vectors) the result is canonicalized as a vector. When the | ||||||||
8992 | // LHS is also a vector, the lax is allowed by the condition above. Handle | ||||||||
8993 | // the case where LHS is a scalar. | ||||||||
8994 | if (LHSType->isScalarType()) { | ||||||||
8995 | const VectorType *VecType = RHSType->getAs<VectorType>(); | ||||||||
8996 | if (VecType && VecType->getNumElements() == 1 && | ||||||||
8997 | isLaxVectorConversion(RHSType, LHSType)) { | ||||||||
8998 | ExprResult *VecExpr = &RHS; | ||||||||
8999 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | ||||||||
9000 | Kind = CK_BitCast; | ||||||||
9001 | return Compatible; | ||||||||
9002 | } | ||||||||
9003 | } | ||||||||
9004 | |||||||||
9005 | // Allow assignments between fixed-length and sizeless SVE vectors. | ||||||||
9006 | if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | ||||||||
9007 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) && | ||||||||
9008 | Context.areCompatibleSveTypes(LHSType, RHSType)) { | ||||||||
9009 | Kind = CK_BitCast; | ||||||||
9010 | return Compatible; | ||||||||
9011 | } | ||||||||
9012 | |||||||||
9013 | return Incompatible; | ||||||||
9014 | } | ||||||||
9015 | |||||||||
9016 | // Diagnose attempts to convert between __float128 and long double where | ||||||||
9017 | // such conversions currently can't be handled. | ||||||||
9018 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||||||
9019 | return Incompatible; | ||||||||
9020 | |||||||||
9021 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | ||||||||
9022 | // discards the imaginary part. | ||||||||
9023 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | ||||||||
9024 | !LHSType->getAs<ComplexType>()) | ||||||||
9025 | return Incompatible; | ||||||||
9026 | |||||||||
9027 | // Arithmetic conversions. | ||||||||
9028 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | ||||||||
9029 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | ||||||||
9030 | if (ConvertRHS) | ||||||||
9031 | Kind = PrepareScalarCast(RHS, LHSType); | ||||||||
9032 | return Compatible; | ||||||||
9033 | } | ||||||||
9034 | |||||||||
9035 | // Conversions to normal pointers. | ||||||||
9036 | if (const PointerType *LHSPointer
| ||||||||
9037 | // U* -> T* | ||||||||
9038 | if (isa<PointerType>(RHSType)) { | ||||||||
9039 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||||||
9040 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | ||||||||
9041 | if (AddrSpaceL != AddrSpaceR) | ||||||||
9042 | Kind = CK_AddressSpaceConversion; | ||||||||
9043 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | ||||||||
9044 | Kind = CK_NoOp; | ||||||||
9045 | else | ||||||||
9046 | Kind = CK_BitCast; | ||||||||
9047 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | ||||||||
9048 | } | ||||||||
9049 | |||||||||
9050 | // int -> T* | ||||||||
9051 | if (RHSType->isIntegerType()) { | ||||||||
9052 | Kind = CK_IntegralToPointer; // FIXME: null? | ||||||||
9053 | return IntToPointer; | ||||||||
9054 | } | ||||||||
9055 | |||||||||
9056 | // C pointers are not compatible with ObjC object pointers, | ||||||||
9057 | // with two exceptions: | ||||||||
9058 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||||||
9059 | // - conversions to void* | ||||||||
9060 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||||||
9061 | Kind = CK_BitCast; | ||||||||
9062 | return Compatible; | ||||||||
9063 | } | ||||||||
9064 | |||||||||
9065 | // - conversions from 'Class' to the redefinition type | ||||||||
9066 | if (RHSType->isObjCClassType() && | ||||||||
9067 | Context.hasSameType(LHSType, | ||||||||
9068 | Context.getObjCClassRedefinitionType())) { | ||||||||
9069 | Kind = CK_BitCast; | ||||||||
9070 | return Compatible; | ||||||||
9071 | } | ||||||||
9072 | |||||||||
9073 | Kind = CK_BitCast; | ||||||||
9074 | return IncompatiblePointer; | ||||||||
9075 | } | ||||||||
9076 | |||||||||
9077 | // U^ -> void* | ||||||||
9078 | if (RHSType->getAs<BlockPointerType>()) { | ||||||||
9079 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||||||
9080 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||||||
9081 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||||||
9082 | ->getPointeeType() | ||||||||
9083 | .getAddressSpace(); | ||||||||
9084 | Kind = | ||||||||
9085 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||||||
9086 | return Compatible; | ||||||||
9087 | } | ||||||||
9088 | } | ||||||||
9089 | |||||||||
9090 | return Incompatible; | ||||||||
9091 | } | ||||||||
9092 | |||||||||
9093 | // Conversions to block pointers. | ||||||||
9094 | if (isa<BlockPointerType>(LHSType)) { | ||||||||
9095 | // U^ -> T^ | ||||||||
9096 | if (RHSType->isBlockPointerType()) { | ||||||||
9097 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | ||||||||
| |||||||||
9098 | ->getPointeeType() | ||||||||
9099 | .getAddressSpace(); | ||||||||
9100 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||||||
9101 | ->getPointeeType() | ||||||||
9102 | .getAddressSpace(); | ||||||||
9103 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||||||
9104 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | ||||||||
9105 | } | ||||||||
9106 | |||||||||
9107 | // int or null -> T^ | ||||||||
9108 | if (RHSType->isIntegerType()) { | ||||||||
9109 | Kind = CK_IntegralToPointer; // FIXME: null | ||||||||
9110 | return IntToBlockPointer; | ||||||||
9111 | } | ||||||||
9112 | |||||||||
9113 | // id -> T^ | ||||||||
9114 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | ||||||||
9115 | Kind = CK_AnyPointerToBlockPointerCast; | ||||||||
9116 | return Compatible; | ||||||||
9117 | } | ||||||||
9118 | |||||||||
9119 | // void* -> T^ | ||||||||
9120 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | ||||||||
9121 | if (RHSPT->getPointeeType()->isVoidType()) { | ||||||||
9122 | Kind = CK_AnyPointerToBlockPointerCast; | ||||||||
9123 | return Compatible; | ||||||||
9124 | } | ||||||||
9125 | |||||||||
9126 | return Incompatible; | ||||||||
9127 | } | ||||||||
9128 | |||||||||
9129 | // Conversions to Objective-C pointers. | ||||||||
9130 | if (isa<ObjCObjectPointerType>(LHSType)) { | ||||||||
9131 | // A* -> B* | ||||||||
9132 | if (RHSType->isObjCObjectPointerType()) { | ||||||||
9133 | Kind = CK_BitCast; | ||||||||
9134 | Sema::AssignConvertType result = | ||||||||
9135 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | ||||||||
9136 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||||||
9137 | result == Compatible && | ||||||||
9138 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | ||||||||
9139 | result = IncompatibleObjCWeakRef; | ||||||||
9140 | return result; | ||||||||
9141 | } | ||||||||
9142 | |||||||||
9143 | // int or null -> A* | ||||||||
9144 | if (RHSType->isIntegerType()) { | ||||||||
9145 | Kind = CK_IntegralToPointer; // FIXME: null | ||||||||
9146 | return IntToPointer; | ||||||||
9147 | } | ||||||||
9148 | |||||||||
9149 | // In general, C pointers are not compatible with ObjC object pointers, | ||||||||
9150 | // with two exceptions: | ||||||||
9151 | if (isa<PointerType>(RHSType)) { | ||||||||
9152 | Kind = CK_CPointerToObjCPointerCast; | ||||||||
9153 | |||||||||
9154 | // - conversions from 'void*' | ||||||||
9155 | if (RHSType->isVoidPointerType()) { | ||||||||
9156 | return Compatible; | ||||||||
9157 | } | ||||||||
9158 | |||||||||
9159 | // - conversions to 'Class' from its redefinition type | ||||||||
9160 | if (LHSType->isObjCClassType() && | ||||||||
9161 | Context.hasSameType(RHSType, | ||||||||
9162 | Context.getObjCClassRedefinitionType())) { | ||||||||
9163 | return Compatible; | ||||||||
9164 | } | ||||||||
9165 | |||||||||
9166 | return IncompatiblePointer; | ||||||||
9167 | } | ||||||||
9168 | |||||||||
9169 | // Only under strict condition T^ is compatible with an Objective-C pointer. | ||||||||
9170 | if (RHSType->isBlockPointerType() && | ||||||||
9171 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||||||
9172 | if (ConvertRHS) | ||||||||
9173 | maybeExtendBlockObject(RHS); | ||||||||
9174 | Kind = CK_BlockPointerToObjCPointerCast; | ||||||||
9175 | return Compatible; | ||||||||
9176 | } | ||||||||
9177 | |||||||||
9178 | return Incompatible; | ||||||||
9179 | } | ||||||||
9180 | |||||||||
9181 | // Conversions from pointers that are not covered by the above. | ||||||||
9182 | if (isa<PointerType>(RHSType)) { | ||||||||
9183 | // T* -> _Bool | ||||||||
9184 | if (LHSType == Context.BoolTy) { | ||||||||
9185 | Kind = CK_PointerToBoolean; | ||||||||
9186 | return Compatible; | ||||||||
9187 | } | ||||||||
9188 | |||||||||
9189 | // T* -> int | ||||||||
9190 | if (LHSType->isIntegerType()) { | ||||||||
9191 | Kind = CK_PointerToIntegral; | ||||||||
9192 | return PointerToInt; | ||||||||
9193 | } | ||||||||
9194 | |||||||||
9195 | return Incompatible; | ||||||||
9196 | } | ||||||||
9197 | |||||||||
9198 | // Conversions from Objective-C pointers that are not covered by the above. | ||||||||
9199 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||||||
9200 | // T* -> _Bool | ||||||||
9201 | if (LHSType == Context.BoolTy) { | ||||||||
9202 | Kind = CK_PointerToBoolean; | ||||||||
9203 | return Compatible; | ||||||||
9204 | } | ||||||||
9205 | |||||||||
9206 | // T* -> int | ||||||||
9207 | if (LHSType->isIntegerType()) { | ||||||||
9208 | Kind = CK_PointerToIntegral; | ||||||||
9209 | return PointerToInt; | ||||||||
9210 | } | ||||||||
9211 | |||||||||
9212 | return Incompatible; | ||||||||
9213 | } | ||||||||
9214 | |||||||||
9215 | // struct A -> struct B | ||||||||
9216 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | ||||||||
9217 | if (Context.typesAreCompatible(LHSType, RHSType)) { | ||||||||
9218 | Kind = CK_NoOp; | ||||||||
9219 | return Compatible; | ||||||||
9220 | } | ||||||||
9221 | } | ||||||||
9222 | |||||||||
9223 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | ||||||||
9224 | Kind = CK_IntToOCLSampler; | ||||||||
9225 | return Compatible; | ||||||||
9226 | } | ||||||||
9227 | |||||||||
9228 | return Incompatible; | ||||||||
9229 | } | ||||||||
9230 | |||||||||
9231 | /// Constructs a transparent union from an expression that is | ||||||||
9232 | /// used to initialize the transparent union. | ||||||||
9233 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | ||||||||
9234 | ExprResult &EResult, QualType UnionType, | ||||||||
9235 | FieldDecl *Field) { | ||||||||
9236 | // Build an initializer list that designates the appropriate member | ||||||||
9237 | // of the transparent union. | ||||||||
9238 | Expr *E = EResult.get(); | ||||||||
9239 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | ||||||||
9240 | E, SourceLocation()); | ||||||||
9241 | Initializer->setType(UnionType); | ||||||||
9242 | Initializer->setInitializedFieldInUnion(Field); | ||||||||
9243 | |||||||||
9244 | // Build a compound literal constructing a value of the transparent | ||||||||
9245 | // union type from this initializer list. | ||||||||
9246 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | ||||||||
9247 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | ||||||||
9248 | VK_RValue, Initializer, false); | ||||||||
9249 | } | ||||||||
9250 | |||||||||
9251 | Sema::AssignConvertType | ||||||||
9252 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | ||||||||
9253 | ExprResult &RHS) { | ||||||||
9254 | QualType RHSType = RHS.get()->getType(); | ||||||||
9255 | |||||||||
9256 | // If the ArgType is a Union type, we want to handle a potential | ||||||||
9257 | // transparent_union GCC extension. | ||||||||
9258 | const RecordType *UT = ArgType->getAsUnionType(); | ||||||||
9259 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | ||||||||
9260 | return Incompatible; | ||||||||
9261 | |||||||||
9262 | // The field to initialize within the transparent union. | ||||||||
9263 | RecordDecl *UD = UT->getDecl(); | ||||||||
9264 | FieldDecl *InitField = nullptr; | ||||||||
9265 | // It's compatible if the expression matches any of the fields. | ||||||||
9266 | for (auto *it : UD->fields()) { | ||||||||
9267 | if (it->getType()->isPointerType()) { | ||||||||
9268 | // If the transparent union contains a pointer type, we allow: | ||||||||
9269 | // 1) void pointer | ||||||||
9270 | // 2) null pointer constant | ||||||||
9271 | if (RHSType->isPointerType()) | ||||||||
9272 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | ||||||||
9273 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | ||||||||
9274 | InitField = it; | ||||||||
9275 | break; | ||||||||
9276 | } | ||||||||
9277 | |||||||||
9278 | if (RHS.get()->isNullPointerConstant(Context, | ||||||||
9279 | Expr::NPC_ValueDependentIsNull)) { | ||||||||
9280 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | ||||||||
9281 | CK_NullToPointer); | ||||||||
9282 | InitField = it; | ||||||||
9283 | break; | ||||||||
9284 | } | ||||||||
9285 | } | ||||||||
9286 | |||||||||
9287 | CastKind Kind; | ||||||||
9288 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | ||||||||
9289 | == Compatible) { | ||||||||
9290 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | ||||||||
9291 | InitField = it; | ||||||||
9292 | break; | ||||||||
9293 | } | ||||||||
9294 | } | ||||||||
9295 | |||||||||
9296 | if (!InitField) | ||||||||
9297 | return Incompatible; | ||||||||
9298 | |||||||||
9299 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | ||||||||
9300 | return Compatible; | ||||||||
9301 | } | ||||||||
9302 | |||||||||
9303 | Sema::AssignConvertType | ||||||||
9304 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | ||||||||
9305 | bool Diagnose, | ||||||||
9306 | bool DiagnoseCFAudited, | ||||||||
9307 | bool ConvertRHS) { | ||||||||
9308 | // We need to be able to tell the caller whether we diagnosed a problem, if | ||||||||
9309 | // they ask us to issue diagnostics. | ||||||||
9310 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 9310, __PRETTY_FUNCTION__)); | ||||||||
9311 | |||||||||
9312 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | ||||||||
9313 | // we can't avoid *all* modifications at the moment, so we need some somewhere | ||||||||
9314 | // to put the updated value. | ||||||||
9315 | ExprResult LocalRHS = CallerRHS; | ||||||||
9316 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | ||||||||
9317 | |||||||||
9318 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | ||||||||
9319 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | ||||||||
9320 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||||||
9321 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||||||
9322 | Diag(RHS.get()->getExprLoc(), | ||||||||
9323 | diag::warn_noderef_to_dereferenceable_pointer) | ||||||||
9324 | << RHS.get()->getSourceRange(); | ||||||||
9325 | } | ||||||||
9326 | } | ||||||||
9327 | } | ||||||||
9328 | |||||||||
9329 | if (getLangOpts().CPlusPlus) { | ||||||||
9330 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | ||||||||
9331 | // C++ 5.17p3: If the left operand is not of class type, the | ||||||||
9332 | // expression is implicitly converted (C++ 4) to the | ||||||||
9333 | // cv-unqualified type of the left operand. | ||||||||
9334 | QualType RHSType = RHS.get()->getType(); | ||||||||
9335 | if (Diagnose) { | ||||||||
9336 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||||||
9337 | AA_Assigning); | ||||||||
9338 | } else { | ||||||||
9339 | ImplicitConversionSequence ICS = | ||||||||
9340 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||||||
9341 | /*SuppressUserConversions=*/false, | ||||||||
9342 | AllowedExplicit::None, | ||||||||
9343 | /*InOverloadResolution=*/false, | ||||||||
9344 | /*CStyle=*/false, | ||||||||
9345 | /*AllowObjCWritebackConversion=*/false); | ||||||||
9346 | if (ICS.isFailure()) | ||||||||
9347 | return Incompatible; | ||||||||
9348 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||||||
9349 | ICS, AA_Assigning); | ||||||||
9350 | } | ||||||||
9351 | if (RHS.isInvalid()) | ||||||||
9352 | return Incompatible; | ||||||||
9353 | Sema::AssignConvertType result = Compatible; | ||||||||
9354 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||||||
9355 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | ||||||||
9356 | result = IncompatibleObjCWeakRef; | ||||||||
9357 | return result; | ||||||||
9358 | } | ||||||||
9359 | |||||||||
9360 | // FIXME: Currently, we fall through and treat C++ classes like C | ||||||||
9361 | // structures. | ||||||||
9362 | // FIXME: We also fall through for atomics; not sure what should | ||||||||
9363 | // happen there, though. | ||||||||
9364 | } else if (RHS.get()->getType() == Context.OverloadTy) { | ||||||||
9365 | // As a set of extensions to C, we support overloading on functions. These | ||||||||
9366 | // functions need to be resolved here. | ||||||||
9367 | DeclAccessPair DAP; | ||||||||
9368 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | ||||||||
9369 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | ||||||||
9370 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | ||||||||
9371 | else | ||||||||
9372 | return Incompatible; | ||||||||
9373 | } | ||||||||
9374 | |||||||||
9375 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | ||||||||
9376 | // a null pointer constant. | ||||||||
9377 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | ||||||||
9378 | LHSType->isBlockPointerType()) && | ||||||||
9379 | RHS.get()->isNullPointerConstant(Context, | ||||||||
9380 | Expr::NPC_ValueDependentIsNull)) { | ||||||||
9381 | if (Diagnose || ConvertRHS) { | ||||||||
9382 | CastKind Kind; | ||||||||
9383 | CXXCastPath Path; | ||||||||
9384 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | ||||||||
9385 | /*IgnoreBaseAccess=*/false, Diagnose); | ||||||||
9386 | if (ConvertRHS) | ||||||||
9387 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); | ||||||||
9388 | } | ||||||||
9389 | return Compatible; | ||||||||
9390 | } | ||||||||
9391 | |||||||||
9392 | // OpenCL queue_t type assignment. | ||||||||
9393 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | ||||||||
9394 | Context, Expr::NPC_ValueDependentIsNull)) { | ||||||||
9395 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||||||
9396 | return Compatible; | ||||||||
9397 | } | ||||||||
9398 | |||||||||
9399 | // This check seems unnatural, however it is necessary to ensure the proper | ||||||||
9400 | // conversion of functions/arrays. If the conversion were done for all | ||||||||
9401 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | ||||||||
9402 | // expressions that suppress this implicit conversion (&, sizeof). | ||||||||
9403 | // | ||||||||
9404 | // Suppress this for references: C++ 8.5.3p5. | ||||||||
9405 | if (!LHSType->isReferenceType()) { | ||||||||
9406 | // FIXME: We potentially allocate here even if ConvertRHS is false. | ||||||||
9407 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | ||||||||
9408 | if (RHS.isInvalid()) | ||||||||
9409 | return Incompatible; | ||||||||
9410 | } | ||||||||
9411 | CastKind Kind; | ||||||||
9412 | Sema::AssignConvertType result = | ||||||||
9413 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | ||||||||
9414 | |||||||||
9415 | // C99 6.5.16.1p2: The value of the right operand is converted to the | ||||||||
9416 | // type of the assignment expression. | ||||||||
9417 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | ||||||||
9418 | // so that we can use references in built-in functions even in C. | ||||||||
9419 | // The getNonReferenceType() call makes sure that the resulting expression | ||||||||
9420 | // does not have reference type. | ||||||||
9421 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | ||||||||
9422 | QualType Ty = LHSType.getNonLValueExprType(Context); | ||||||||
9423 | Expr *E = RHS.get(); | ||||||||
9424 | |||||||||
9425 | // Check for various Objective-C errors. If we are not reporting | ||||||||
9426 | // diagnostics and just checking for errors, e.g., during overload | ||||||||
9427 | // resolution, return Incompatible to indicate the failure. | ||||||||
9428 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||||||
9429 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | ||||||||
9430 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | ||||||||
9431 | if (!Diagnose) | ||||||||
9432 | return Incompatible; | ||||||||
9433 | } | ||||||||
9434 | if (getLangOpts().ObjC && | ||||||||
9435 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | ||||||||
9436 | E->getType(), E, Diagnose) || | ||||||||
9437 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | ||||||||
9438 | if (!Diagnose) | ||||||||
9439 | return Incompatible; | ||||||||
9440 | // Replace the expression with a corrected version and continue so we | ||||||||
9441 | // can find further errors. | ||||||||
9442 | RHS = E; | ||||||||
9443 | return Compatible; | ||||||||
9444 | } | ||||||||
9445 | |||||||||
9446 | if (ConvertRHS) | ||||||||
9447 | RHS = ImpCastExprToType(E, Ty, Kind); | ||||||||
9448 | } | ||||||||
9449 | |||||||||
9450 | return result; | ||||||||
9451 | } | ||||||||
9452 | |||||||||
9453 | namespace { | ||||||||
9454 | /// The original operand to an operator, prior to the application of the usual | ||||||||
9455 | /// arithmetic conversions and converting the arguments of a builtin operator | ||||||||
9456 | /// candidate. | ||||||||
9457 | struct OriginalOperand { | ||||||||
9458 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | ||||||||
9459 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | ||||||||
9460 | Op = MTE->getSubExpr(); | ||||||||
9461 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | ||||||||
9462 | Op = BTE->getSubExpr(); | ||||||||
9463 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | ||||||||
9464 | Orig = ICE->getSubExprAsWritten(); | ||||||||
9465 | Conversion = ICE->getConversionFunction(); | ||||||||
9466 | } | ||||||||
9467 | } | ||||||||
9468 | |||||||||
9469 | QualType getType() const { return Orig->getType(); } | ||||||||
9470 | |||||||||
9471 | Expr *Orig; | ||||||||
9472 | NamedDecl *Conversion; | ||||||||
9473 | }; | ||||||||
9474 | } | ||||||||
9475 | |||||||||
9476 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | ||||||||
9477 | ExprResult &RHS) { | ||||||||
9478 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | ||||||||
9479 | |||||||||
9480 | Diag(Loc, diag::err_typecheck_invalid_operands) | ||||||||
9481 | << OrigLHS.getType() << OrigRHS.getType() | ||||||||
9482 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
9483 | |||||||||
9484 | // If a user-defined conversion was applied to either of the operands prior | ||||||||
9485 | // to applying the built-in operator rules, tell the user about it. | ||||||||
9486 | if (OrigLHS.Conversion) { | ||||||||
9487 | Diag(OrigLHS.Conversion->getLocation(), | ||||||||
9488 | diag::note_typecheck_invalid_operands_converted) | ||||||||
9489 | << 0 << LHS.get()->getType(); | ||||||||
9490 | } | ||||||||
9491 | if (OrigRHS.Conversion) { | ||||||||
9492 | Diag(OrigRHS.Conversion->getLocation(), | ||||||||
9493 | diag::note_typecheck_invalid_operands_converted) | ||||||||
9494 | << 1 << RHS.get()->getType(); | ||||||||
9495 | } | ||||||||
9496 | |||||||||
9497 | return QualType(); | ||||||||
9498 | } | ||||||||
9499 | |||||||||
9500 | // Diagnose cases where a scalar was implicitly converted to a vector and | ||||||||
9501 | // diagnose the underlying types. Otherwise, diagnose the error | ||||||||
9502 | // as invalid vector logical operands for non-C++ cases. | ||||||||
9503 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | ||||||||
9504 | ExprResult &RHS) { | ||||||||
9505 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | ||||||||
9506 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | ||||||||
9507 | |||||||||
9508 | bool LHSNatVec = LHSType->isVectorType(); | ||||||||
9509 | bool RHSNatVec = RHSType->isVectorType(); | ||||||||
9510 | |||||||||
9511 | if (!(LHSNatVec && RHSNatVec)) { | ||||||||
9512 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | ||||||||
9513 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | ||||||||
9514 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||||||
9515 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | ||||||||
9516 | << Vector->getSourceRange(); | ||||||||
9517 | return QualType(); | ||||||||
9518 | } | ||||||||
9519 | |||||||||
9520 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||||||
9521 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | ||||||||
9522 | << RHS.get()->getSourceRange(); | ||||||||
9523 | |||||||||
9524 | return QualType(); | ||||||||
9525 | } | ||||||||
9526 | |||||||||
9527 | /// Try to convert a value of non-vector type to a vector type by converting | ||||||||
9528 | /// the type to the element type of the vector and then performing a splat. | ||||||||
9529 | /// If the language is OpenCL, we only use conversions that promote scalar | ||||||||
9530 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | ||||||||
9531 | /// for float->int. | ||||||||
9532 | /// | ||||||||
9533 | /// OpenCL V2.0 6.2.6.p2: | ||||||||
9534 | /// An error shall occur if any scalar operand type has greater rank | ||||||||
9535 | /// than the type of the vector element. | ||||||||
9536 | /// | ||||||||
9537 | /// \param scalar - if non-null, actually perform the conversions | ||||||||
9538 | /// \return true if the operation fails (but without diagnosing the failure) | ||||||||
9539 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | ||||||||
9540 | QualType scalarTy, | ||||||||
9541 | QualType vectorEltTy, | ||||||||
9542 | QualType vectorTy, | ||||||||
9543 | unsigned &DiagID) { | ||||||||
9544 | // The conversion to apply to the scalar before splatting it, | ||||||||
9545 | // if necessary. | ||||||||
9546 | CastKind scalarCast = CK_NoOp; | ||||||||
9547 | |||||||||
9548 | if (vectorEltTy->isIntegralType(S.Context)) { | ||||||||
9549 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | ||||||||
9550 | (scalarTy->isIntegerType() && | ||||||||
9551 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | ||||||||
9552 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||||||
9553 | return true; | ||||||||
9554 | } | ||||||||
9555 | if (!scalarTy->isIntegralType(S.Context)) | ||||||||
9556 | return true; | ||||||||
9557 | scalarCast = CK_IntegralCast; | ||||||||
9558 | } else if (vectorEltTy->isRealFloatingType()) { | ||||||||
9559 | if (scalarTy->isRealFloatingType()) { | ||||||||
9560 | if (S.getLangOpts().OpenCL && | ||||||||
9561 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | ||||||||
9562 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||||||
9563 | return true; | ||||||||
9564 | } | ||||||||
9565 | scalarCast = CK_FloatingCast; | ||||||||
9566 | } | ||||||||
9567 | else if (scalarTy->isIntegralType(S.Context)) | ||||||||
9568 | scalarCast = CK_IntegralToFloating; | ||||||||
9569 | else | ||||||||
9570 | return true; | ||||||||
9571 | } else { | ||||||||
9572 | return true; | ||||||||
9573 | } | ||||||||
9574 | |||||||||
9575 | // Adjust scalar if desired. | ||||||||
9576 | if (scalar) { | ||||||||
9577 | if (scalarCast != CK_NoOp) | ||||||||
9578 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | ||||||||
9579 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | ||||||||
9580 | } | ||||||||
9581 | return false; | ||||||||
9582 | } | ||||||||
9583 | |||||||||
9584 | /// Convert vector E to a vector with the same number of elements but different | ||||||||
9585 | /// element type. | ||||||||
9586 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | ||||||||
9587 | const auto *VecTy = E->getType()->getAs<VectorType>(); | ||||||||
9588 | assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast <void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 9588, __PRETTY_FUNCTION__)); | ||||||||
9589 | QualType NewVecTy = S.Context.getVectorType(ElementType, | ||||||||
9590 | VecTy->getNumElements(), | ||||||||
9591 | VecTy->getVectorKind()); | ||||||||
9592 | |||||||||
9593 | // Look through the implicit cast. Return the subexpression if its type is | ||||||||
9594 | // NewVecTy. | ||||||||
9595 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||||||
9596 | if (ICE->getSubExpr()->getType() == NewVecTy) | ||||||||
9597 | return ICE->getSubExpr(); | ||||||||
9598 | |||||||||
9599 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | ||||||||
9600 | return S.ImpCastExprToType(E, NewVecTy, Cast); | ||||||||
9601 | } | ||||||||
9602 | |||||||||
9603 | /// Test if a (constant) integer Int can be casted to another integer type | ||||||||
9604 | /// IntTy without losing precision. | ||||||||
9605 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | ||||||||
9606 | QualType OtherIntTy) { | ||||||||
9607 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||||||
9608 | |||||||||
9609 | // Reject cases where the value of the Int is unknown as that would | ||||||||
9610 | // possibly cause truncation, but accept cases where the scalar can be | ||||||||
9611 | // demoted without loss of precision. | ||||||||
9612 | Expr::EvalResult EVResult; | ||||||||
9613 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||||||
9614 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | ||||||||
9615 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | ||||||||
9616 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | ||||||||
9617 | |||||||||
9618 | if (CstInt) { | ||||||||
9619 | // If the scalar is constant and is of a higher order and has more active | ||||||||
9620 | // bits that the vector element type, reject it. | ||||||||
9621 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||||||
9622 | unsigned NumBits = IntSigned | ||||||||
9623 | ? (Result.isNegative() ? Result.getMinSignedBits() | ||||||||
9624 | : Result.getActiveBits()) | ||||||||
9625 | : Result.getActiveBits(); | ||||||||
9626 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | ||||||||
9627 | return true; | ||||||||
9628 | |||||||||
9629 | // If the signedness of the scalar type and the vector element type | ||||||||
9630 | // differs and the number of bits is greater than that of the vector | ||||||||
9631 | // element reject it. | ||||||||
9632 | return (IntSigned != OtherIntSigned && | ||||||||
9633 | NumBits > S.Context.getIntWidth(OtherIntTy)); | ||||||||
9634 | } | ||||||||
9635 | |||||||||
9636 | // Reject cases where the value of the scalar is not constant and it's | ||||||||
9637 | // order is greater than that of the vector element type. | ||||||||
9638 | return (Order < 0); | ||||||||
9639 | } | ||||||||
9640 | |||||||||
9641 | /// Test if a (constant) integer Int can be casted to floating point type | ||||||||
9642 | /// FloatTy without losing precision. | ||||||||
9643 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | ||||||||
9644 | QualType FloatTy) { | ||||||||
9645 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||||||
9646 | |||||||||
9647 | // Determine if the integer constant can be expressed as a floating point | ||||||||
9648 | // number of the appropriate type. | ||||||||
9649 | Expr::EvalResult EVResult; | ||||||||
9650 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||||||
9651 | |||||||||
9652 | uint64_t Bits = 0; | ||||||||
9653 | if (CstInt) { | ||||||||
9654 | // Reject constants that would be truncated if they were converted to | ||||||||
9655 | // the floating point type. Test by simple to/from conversion. | ||||||||
9656 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | ||||||||
9657 | // could be avoided if there was a convertFromAPInt method | ||||||||
9658 | // which could signal back if implicit truncation occurred. | ||||||||
9659 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||||||
9660 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | ||||||||
9661 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | ||||||||
9662 | llvm::APFloat::rmTowardZero); | ||||||||
9663 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | ||||||||
9664 | !IntTy->hasSignedIntegerRepresentation()); | ||||||||
9665 | bool Ignored = false; | ||||||||
9666 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | ||||||||
9667 | &Ignored); | ||||||||
9668 | if (Result != ConvertBack) | ||||||||
9669 | return true; | ||||||||
9670 | } else { | ||||||||
9671 | // Reject types that cannot be fully encoded into the mantissa of | ||||||||
9672 | // the float. | ||||||||
9673 | Bits = S.Context.getTypeSize(IntTy); | ||||||||
9674 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | ||||||||
9675 | S.Context.getFloatTypeSemantics(FloatTy)); | ||||||||
9676 | if (Bits > FloatPrec) | ||||||||
9677 | return true; | ||||||||
9678 | } | ||||||||
9679 | |||||||||
9680 | return false; | ||||||||
9681 | } | ||||||||
9682 | |||||||||
9683 | /// Attempt to convert and splat Scalar into a vector whose types matches | ||||||||
9684 | /// Vector following GCC conversion rules. The rule is that implicit | ||||||||
9685 | /// conversion can occur when Scalar can be casted to match Vector's element | ||||||||
9686 | /// type without causing truncation of Scalar. | ||||||||
9687 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | ||||||||
9688 | ExprResult *Vector) { | ||||||||
9689 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | ||||||||
9690 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | ||||||||
9691 | const VectorType *VT = VectorTy->getAs<VectorType>(); | ||||||||
9692 | |||||||||
9693 | assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 9694, __PRETTY_FUNCTION__)) | ||||||||
9694 | "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 9694, __PRETTY_FUNCTION__)); | ||||||||
9695 | |||||||||
9696 | QualType VectorEltTy = VT->getElementType(); | ||||||||
9697 | |||||||||
9698 | // Reject cases where the vector element type or the scalar element type are | ||||||||
9699 | // not integral or floating point types. | ||||||||
9700 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | ||||||||
9701 | return true; | ||||||||
9702 | |||||||||
9703 | // The conversion to apply to the scalar before splatting it, | ||||||||
9704 | // if necessary. | ||||||||
9705 | CastKind ScalarCast = CK_NoOp; | ||||||||
9706 | |||||||||
9707 | // Accept cases where the vector elements are integers and the scalar is | ||||||||
9708 | // an integer. | ||||||||
9709 | // FIXME: Notionally if the scalar was a floating point value with a precise | ||||||||
9710 | // integral representation, we could cast it to an appropriate integer | ||||||||
9711 | // type and then perform the rest of the checks here. GCC will perform | ||||||||
9712 | // this conversion in some cases as determined by the input language. | ||||||||
9713 | // We should accept it on a language independent basis. | ||||||||
9714 | if (VectorEltTy->isIntegralType(S.Context) && | ||||||||
9715 | ScalarTy->isIntegralType(S.Context) && | ||||||||
9716 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | ||||||||
9717 | |||||||||
9718 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | ||||||||
9719 | return true; | ||||||||
9720 | |||||||||
9721 | ScalarCast = CK_IntegralCast; | ||||||||
9722 | } else if (VectorEltTy->isIntegralType(S.Context) && | ||||||||
9723 | ScalarTy->isRealFloatingType()) { | ||||||||
9724 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | ||||||||
9725 | ScalarCast = CK_FloatingToIntegral; | ||||||||
9726 | else | ||||||||
9727 | return true; | ||||||||
9728 | } else if (VectorEltTy->isRealFloatingType()) { | ||||||||
9729 | if (ScalarTy->isRealFloatingType()) { | ||||||||
9730 | |||||||||
9731 | // Reject cases where the scalar type is not a constant and has a higher | ||||||||
9732 | // Order than the vector element type. | ||||||||
9733 | llvm::APFloat Result(0.0); | ||||||||
9734 | |||||||||
9735 | // Determine whether this is a constant scalar. In the event that the | ||||||||
9736 | // value is dependent (and thus cannot be evaluated by the constant | ||||||||
9737 | // evaluator), skip the evaluation. This will then diagnose once the | ||||||||
9738 | // expression is instantiated. | ||||||||
9739 | bool CstScalar = Scalar->get()->isValueDependent() || | ||||||||
9740 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | ||||||||
9741 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | ||||||||
9742 | if (!CstScalar && Order < 0) | ||||||||
9743 | return true; | ||||||||
9744 | |||||||||
9745 | // If the scalar cannot be safely casted to the vector element type, | ||||||||
9746 | // reject it. | ||||||||
9747 | if (CstScalar) { | ||||||||
9748 | bool Truncated = false; | ||||||||
9749 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | ||||||||
9750 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | ||||||||
9751 | if (Truncated) | ||||||||
9752 | return true; | ||||||||
9753 | } | ||||||||
9754 | |||||||||
9755 | ScalarCast = CK_FloatingCast; | ||||||||
9756 | } else if (ScalarTy->isIntegralType(S.Context)) { | ||||||||
9757 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | ||||||||
9758 | return true; | ||||||||
9759 | |||||||||
9760 | ScalarCast = CK_IntegralToFloating; | ||||||||
9761 | } else | ||||||||
9762 | return true; | ||||||||
9763 | } else if (ScalarTy->isEnumeralType()) | ||||||||
9764 | return true; | ||||||||
9765 | |||||||||
9766 | // Adjust scalar if desired. | ||||||||
9767 | if (Scalar) { | ||||||||
9768 | if (ScalarCast != CK_NoOp) | ||||||||
9769 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | ||||||||
9770 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | ||||||||
9771 | } | ||||||||
9772 | return false; | ||||||||
9773 | } | ||||||||
9774 | |||||||||
9775 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
9776 | SourceLocation Loc, bool IsCompAssign, | ||||||||
9777 | bool AllowBothBool, | ||||||||
9778 | bool AllowBoolConversions) { | ||||||||
9779 | if (!IsCompAssign) { | ||||||||
9780 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||||||
9781 | if (LHS.isInvalid()) | ||||||||
9782 | return QualType(); | ||||||||
9783 | } | ||||||||
9784 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||||||
9785 | if (RHS.isInvalid()) | ||||||||
9786 | return QualType(); | ||||||||
9787 | |||||||||
9788 | // For conversion purposes, we ignore any qualifiers. | ||||||||
9789 | // For example, "const float" and "float" are equivalent. | ||||||||
9790 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||||||
9791 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||||||
9792 | |||||||||
9793 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | ||||||||
9794 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | ||||||||
9795 | assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail ("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 9795, __PRETTY_FUNCTION__)); | ||||||||
9796 | |||||||||
9797 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | ||||||||
9798 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | ||||||||
9799 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
9800 | |||||||||
9801 | // AltiVec-style "vector bool op vector bool" combinations are allowed | ||||||||
9802 | // for some operators but not others. | ||||||||
9803 | if (!AllowBothBool && | ||||||||
9804 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||||||
9805 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||||||
9806 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
9807 | |||||||||
9808 | // If the vector types are identical, return. | ||||||||
9809 | if (Context.hasSameType(LHSType, RHSType)) | ||||||||
9810 | return LHSType; | ||||||||
9811 | |||||||||
9812 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | ||||||||
9813 | if (LHSVecType && RHSVecType && | ||||||||
9814 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||||||
9815 | if (isa<ExtVectorType>(LHSVecType)) { | ||||||||
9816 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||||||
9817 | return LHSType; | ||||||||
9818 | } | ||||||||
9819 | |||||||||
9820 | if (!IsCompAssign) | ||||||||
9821 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||||||
9822 | return RHSType; | ||||||||
9823 | } | ||||||||
9824 | |||||||||
9825 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | ||||||||
9826 | // can be mixed, with the result being the non-bool type. The non-bool | ||||||||
9827 | // operand must have integer element type. | ||||||||
9828 | if (AllowBoolConversions && LHSVecType && RHSVecType && | ||||||||
9829 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | ||||||||
9830 | (Context.getTypeSize(LHSVecType->getElementType()) == | ||||||||
9831 | Context.getTypeSize(RHSVecType->getElementType()))) { | ||||||||
9832 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||||||
9833 | LHSVecType->getElementType()->isIntegerType() && | ||||||||
9834 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | ||||||||
9835 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||||||
9836 | return LHSType; | ||||||||
9837 | } | ||||||||
9838 | if (!IsCompAssign && | ||||||||
9839 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||||||
9840 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||||||
9841 | RHSVecType->getElementType()->isIntegerType()) { | ||||||||
9842 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||||||
9843 | return RHSType; | ||||||||
9844 | } | ||||||||
9845 | } | ||||||||
9846 | |||||||||
9847 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | ||||||||
9848 | // since the ambiguity can affect the ABI. | ||||||||
9849 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | ||||||||
9850 | const VectorType *VecType = SecondType->getAs<VectorType>(); | ||||||||
9851 | return FirstType->isSizelessBuiltinType() && VecType && | ||||||||
9852 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | ||||||||
9853 | VecType->getVectorKind() == | ||||||||
9854 | VectorType::SveFixedLengthPredicateVector); | ||||||||
9855 | }; | ||||||||
9856 | |||||||||
9857 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | ||||||||
9858 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | ||||||||
9859 | return QualType(); | ||||||||
9860 | } | ||||||||
9861 | |||||||||
9862 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | ||||||||
9863 | // since the ambiguity can affect the ABI. | ||||||||
9864 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | ||||||||
9865 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | ||||||||
9866 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | ||||||||
9867 | |||||||||
9868 | if (FirstVecType && SecondVecType) | ||||||||
9869 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | ||||||||
9870 | (SecondVecType->getVectorKind() == | ||||||||
9871 | VectorType::SveFixedLengthDataVector || | ||||||||
9872 | SecondVecType->getVectorKind() == | ||||||||
9873 | VectorType::SveFixedLengthPredicateVector); | ||||||||
9874 | |||||||||
9875 | return FirstType->isSizelessBuiltinType() && SecondVecType && | ||||||||
9876 | SecondVecType->getVectorKind() == VectorType::GenericVector; | ||||||||
9877 | }; | ||||||||
9878 | |||||||||
9879 | if (IsSveGnuConversion(LHSType, RHSType) || | ||||||||
9880 | IsSveGnuConversion(RHSType, LHSType)) { | ||||||||
9881 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | ||||||||
9882 | return QualType(); | ||||||||
9883 | } | ||||||||
9884 | |||||||||
9885 | // If there's a vector type and a scalar, try to convert the scalar to | ||||||||
9886 | // the vector element type and splat. | ||||||||
9887 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | ||||||||
9888 | if (!RHSVecType) { | ||||||||
9889 | if (isa<ExtVectorType>(LHSVecType)) { | ||||||||
9890 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | ||||||||
9891 | LHSVecType->getElementType(), LHSType, | ||||||||
9892 | DiagID)) | ||||||||
9893 | return LHSType; | ||||||||
9894 | } else { | ||||||||
9895 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||||||
9896 | return LHSType; | ||||||||
9897 | } | ||||||||
9898 | } | ||||||||
9899 | if (!LHSVecType) { | ||||||||
9900 | if (isa<ExtVectorType>(RHSVecType)) { | ||||||||
9901 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | ||||||||
9902 | LHSType, RHSVecType->getElementType(), | ||||||||
9903 | RHSType, DiagID)) | ||||||||
9904 | return RHSType; | ||||||||
9905 | } else { | ||||||||
9906 | if (LHS.get()->getValueKind() == VK_LValue || | ||||||||
9907 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||||||
9908 | return RHSType; | ||||||||
9909 | } | ||||||||
9910 | } | ||||||||
9911 | |||||||||
9912 | // FIXME: The code below also handles conversion between vectors and | ||||||||
9913 | // non-scalars, we should break this down into fine grained specific checks | ||||||||
9914 | // and emit proper diagnostics. | ||||||||
9915 | QualType VecType = LHSVecType ? LHSType : RHSType; | ||||||||
9916 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | ||||||||
9917 | QualType OtherType = LHSVecType ? RHSType : LHSType; | ||||||||
9918 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | ||||||||
9919 | if (isLaxVectorConversion(OtherType, VecType)) { | ||||||||
9920 | // If we're allowing lax vector conversions, only the total (data) size | ||||||||
9921 | // needs to be the same. For non compound assignment, if one of the types is | ||||||||
9922 | // scalar, the result is always the vector type. | ||||||||
9923 | if (!IsCompAssign) { | ||||||||
9924 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | ||||||||
9925 | return VecType; | ||||||||
9926 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | ||||||||
9927 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | ||||||||
9928 | // type. Note that this is already done by non-compound assignments in | ||||||||
9929 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | ||||||||
9930 | // <1 x T> -> T. The result is also a vector type. | ||||||||
9931 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | ||||||||
9932 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | ||||||||
9933 | ExprResult *RHSExpr = &RHS; | ||||||||
9934 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | ||||||||
9935 | return VecType; | ||||||||
9936 | } | ||||||||
9937 | } | ||||||||
9938 | |||||||||
9939 | // Okay, the expression is invalid. | ||||||||
9940 | |||||||||
9941 | // If there's a non-vector, non-real operand, diagnose that. | ||||||||
9942 | if ((!RHSVecType && !RHSType->isRealType()) || | ||||||||
9943 | (!LHSVecType && !LHSType->isRealType())) { | ||||||||
9944 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||||||
9945 | << LHSType << RHSType | ||||||||
9946 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
9947 | return QualType(); | ||||||||
9948 | } | ||||||||
9949 | |||||||||
9950 | // OpenCL V1.1 6.2.6.p1: | ||||||||
9951 | // If the operands are of more than one vector type, then an error shall | ||||||||
9952 | // occur. Implicit conversions between vector types are not permitted, per | ||||||||
9953 | // section 6.2.1. | ||||||||
9954 | if (getLangOpts().OpenCL && | ||||||||
9955 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | ||||||||
9956 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | ||||||||
9957 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | ||||||||
9958 | << RHSType; | ||||||||
9959 | return QualType(); | ||||||||
9960 | } | ||||||||
9961 | |||||||||
9962 | |||||||||
9963 | // If there is a vector type that is not a ExtVector and a scalar, we reach | ||||||||
9964 | // this point if scalar could not be converted to the vector's element type | ||||||||
9965 | // without truncation. | ||||||||
9966 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | ||||||||
9967 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | ||||||||
9968 | QualType Scalar = LHSVecType ? RHSType : LHSType; | ||||||||
9969 | QualType Vector = LHSVecType ? LHSType : RHSType; | ||||||||
9970 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | ||||||||
9971 | Diag(Loc, | ||||||||
9972 | diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||||||
9973 | << ScalarOrVector << Scalar << Vector; | ||||||||
9974 | |||||||||
9975 | return QualType(); | ||||||||
9976 | } | ||||||||
9977 | |||||||||
9978 | // Otherwise, use the generic diagnostic. | ||||||||
9979 | Diag(Loc, DiagID) | ||||||||
9980 | << LHSType << RHSType | ||||||||
9981 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
9982 | return QualType(); | ||||||||
9983 | } | ||||||||
9984 | |||||||||
9985 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | ||||||||
9986 | // expression. These are mainly cases where the null pointer is used as an | ||||||||
9987 | // integer instead of a pointer. | ||||||||
9988 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||||||
9989 | SourceLocation Loc, bool IsCompare) { | ||||||||
9990 | // The canonical way to check for a GNU null is with isNullPointerConstant, | ||||||||
9991 | // but we use a bit of a hack here for speed; this is a relatively | ||||||||
9992 | // hot path, and isNullPointerConstant is slow. | ||||||||
9993 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | ||||||||
9994 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | ||||||||
9995 | |||||||||
9996 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | ||||||||
9997 | |||||||||
9998 | // Avoid analyzing cases where the result will either be invalid (and | ||||||||
9999 | // diagnosed as such) or entirely valid and not something to warn about. | ||||||||
10000 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | ||||||||
10001 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | ||||||||
10002 | return; | ||||||||
10003 | |||||||||
10004 | // Comparison operations would not make sense with a null pointer no matter | ||||||||
10005 | // what the other expression is. | ||||||||
10006 | if (!IsCompare) { | ||||||||
10007 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | ||||||||
10008 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | ||||||||
10009 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | ||||||||
10010 | return; | ||||||||
10011 | } | ||||||||
10012 | |||||||||
10013 | // The rest of the operations only make sense with a null pointer | ||||||||
10014 | // if the other expression is a pointer. | ||||||||
10015 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | ||||||||
10016 | NonNullType->canDecayToPointerType()) | ||||||||
10017 | return; | ||||||||
10018 | |||||||||
10019 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | ||||||||
10020 | << LHSNull /* LHS is NULL */ << NonNullType | ||||||||
10021 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10022 | } | ||||||||
10023 | |||||||||
10024 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | ||||||||
10025 | SourceLocation Loc) { | ||||||||
10026 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | ||||||||
10027 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | ||||||||
10028 | if (!LUE || !RUE) | ||||||||
10029 | return; | ||||||||
10030 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | ||||||||
10031 | RUE->getKind() != UETT_SizeOf) | ||||||||
10032 | return; | ||||||||
10033 | |||||||||
10034 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | ||||||||
10035 | QualType LHSTy = LHSArg->getType(); | ||||||||
10036 | QualType RHSTy; | ||||||||
10037 | |||||||||
10038 | if (RUE->isArgumentType()) | ||||||||
10039 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | ||||||||
10040 | else | ||||||||
10041 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | ||||||||
10042 | |||||||||
10043 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | ||||||||
10044 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | ||||||||
10045 | return; | ||||||||
10046 | |||||||||
10047 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | ||||||||
10048 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||||||
10049 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||||||
10050 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | ||||||||
10051 | << LHSArgDecl; | ||||||||
10052 | } | ||||||||
10053 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | ||||||||
10054 | QualType ArrayElemTy = ArrayTy->getElementType(); | ||||||||
10055 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | ||||||||
10056 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | ||||||||
10057 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | ||||||||
10058 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | ||||||||
10059 | return; | ||||||||
10060 | S.Diag(Loc, diag::warn_division_sizeof_array) | ||||||||
10061 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | ||||||||
10062 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||||||
10063 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||||||
10064 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | ||||||||
10065 | << LHSArgDecl; | ||||||||
10066 | } | ||||||||
10067 | |||||||||
10068 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | ||||||||
10069 | } | ||||||||
10070 | } | ||||||||
10071 | |||||||||
10072 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | ||||||||
10073 | ExprResult &RHS, | ||||||||
10074 | SourceLocation Loc, bool IsDiv) { | ||||||||
10075 | // Check for division/remainder by zero. | ||||||||
10076 | Expr::EvalResult RHSValue; | ||||||||
10077 | if (!RHS.get()->isValueDependent() && | ||||||||
10078 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | ||||||||
10079 | RHSValue.Val.getInt() == 0) | ||||||||
10080 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||||||
10081 | S.PDiag(diag::warn_remainder_division_by_zero) | ||||||||
10082 | << IsDiv << RHS.get()->getSourceRange()); | ||||||||
10083 | } | ||||||||
10084 | |||||||||
10085 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
10086 | SourceLocation Loc, | ||||||||
10087 | bool IsCompAssign, bool IsDiv) { | ||||||||
10088 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||||||
10089 | |||||||||
10090 | if (LHS.get()->getType()->isVectorType() || | ||||||||
10091 | RHS.get()->getType()->isVectorType()) | ||||||||
10092 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||||||
10093 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||||||
10094 | /*AllowBoolConversions*/false); | ||||||||
10095 | if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || | ||||||||
10096 | RHS.get()->getType()->isConstantMatrixType())) | ||||||||
10097 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | ||||||||
10098 | |||||||||
10099 | QualType compType = UsualArithmeticConversions( | ||||||||
10100 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||||||
10101 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
10102 | return QualType(); | ||||||||
10103 | |||||||||
10104 | |||||||||
10105 | if (compType.isNull() || !compType->isArithmeticType()) | ||||||||
10106 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10107 | if (IsDiv) { | ||||||||
10108 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | ||||||||
10109 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | ||||||||
10110 | } | ||||||||
10111 | return compType; | ||||||||
10112 | } | ||||||||
10113 | |||||||||
10114 | QualType Sema::CheckRemainderOperands( | ||||||||
10115 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | ||||||||
10116 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||||||
10117 | |||||||||
10118 | if (LHS.get()->getType()->isVectorType() || | ||||||||
10119 | RHS.get()->getType()->isVectorType()) { | ||||||||
10120 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||||||
10121 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||||||
10122 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||||||
10123 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||||||
10124 | /*AllowBoolConversions*/false); | ||||||||
10125 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10126 | } | ||||||||
10127 | |||||||||
10128 | QualType compType = UsualArithmeticConversions( | ||||||||
10129 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||||||
10130 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
10131 | return QualType(); | ||||||||
10132 | |||||||||
10133 | if (compType.isNull() || !compType->isIntegerType()) | ||||||||
10134 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10135 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | ||||||||
10136 | return compType; | ||||||||
10137 | } | ||||||||
10138 | |||||||||
10139 | /// Diagnose invalid arithmetic on two void pointers. | ||||||||
10140 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | ||||||||
10141 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
10142 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||||||
10143 | ? diag::err_typecheck_pointer_arith_void_type | ||||||||
10144 | : diag::ext_gnu_void_ptr) | ||||||||
10145 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | ||||||||
10146 | << RHSExpr->getSourceRange(); | ||||||||
10147 | } | ||||||||
10148 | |||||||||
10149 | /// Diagnose invalid arithmetic on a void pointer. | ||||||||
10150 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | ||||||||
10151 | Expr *Pointer) { | ||||||||
10152 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||||||
10153 | ? diag::err_typecheck_pointer_arith_void_type | ||||||||
10154 | : diag::ext_gnu_void_ptr) | ||||||||
10155 | << 0 /* one pointer */ << Pointer->getSourceRange(); | ||||||||
10156 | } | ||||||||
10157 | |||||||||
10158 | /// Diagnose invalid arithmetic on a null pointer. | ||||||||
10159 | /// | ||||||||
10160 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | ||||||||
10161 | /// idiom, which we recognize as a GNU extension. | ||||||||
10162 | /// | ||||||||
10163 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | ||||||||
10164 | Expr *Pointer, bool IsGNUIdiom) { | ||||||||
10165 | if (IsGNUIdiom) | ||||||||
10166 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | ||||||||
10167 | << Pointer->getSourceRange(); | ||||||||
10168 | else | ||||||||
10169 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | ||||||||
10170 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||||||
10171 | } | ||||||||
10172 | |||||||||
10173 | /// Diagnose invalid arithmetic on two function pointers. | ||||||||
10174 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | ||||||||
10175 | Expr *LHS, Expr *RHS) { | ||||||||
10176 | assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10176, __PRETTY_FUNCTION__)); | ||||||||
10177 | assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10177, __PRETTY_FUNCTION__)); | ||||||||
10178 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||||||
10179 | ? diag::err_typecheck_pointer_arith_function_type | ||||||||
10180 | : diag::ext_gnu_ptr_func_arith) | ||||||||
10181 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | ||||||||
10182 | // We only show the second type if it differs from the first. | ||||||||
10183 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | ||||||||
10184 | RHS->getType()) | ||||||||
10185 | << RHS->getType()->getPointeeType() | ||||||||
10186 | << LHS->getSourceRange() << RHS->getSourceRange(); | ||||||||
10187 | } | ||||||||
10188 | |||||||||
10189 | /// Diagnose invalid arithmetic on a function pointer. | ||||||||
10190 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | ||||||||
10191 | Expr *Pointer) { | ||||||||
10192 | assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10192, __PRETTY_FUNCTION__)); | ||||||||
10193 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||||||
10194 | ? diag::err_typecheck_pointer_arith_function_type | ||||||||
10195 | : diag::ext_gnu_ptr_func_arith) | ||||||||
10196 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | ||||||||
10197 | << 0 /* one pointer, so only one type */ | ||||||||
10198 | << Pointer->getSourceRange(); | ||||||||
10199 | } | ||||||||
10200 | |||||||||
10201 | /// Emit error if Operand is incomplete pointer type | ||||||||
10202 | /// | ||||||||
10203 | /// \returns True if pointer has incomplete type | ||||||||
10204 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | ||||||||
10205 | Expr *Operand) { | ||||||||
10206 | QualType ResType = Operand->getType(); | ||||||||
10207 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||||||
10208 | ResType = ResAtomicType->getValueType(); | ||||||||
10209 | |||||||||
10210 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType ()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10210, __PRETTY_FUNCTION__)); | ||||||||
10211 | QualType PointeeTy = ResType->getPointeeType(); | ||||||||
10212 | return S.RequireCompleteSizedType( | ||||||||
10213 | Loc, PointeeTy, | ||||||||
10214 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | ||||||||
10215 | Operand->getSourceRange()); | ||||||||
10216 | } | ||||||||
10217 | |||||||||
10218 | /// Check the validity of an arithmetic pointer operand. | ||||||||
10219 | /// | ||||||||
10220 | /// If the operand has pointer type, this code will check for pointer types | ||||||||
10221 | /// which are invalid in arithmetic operations. These will be diagnosed | ||||||||
10222 | /// appropriately, including whether or not the use is supported as an | ||||||||
10223 | /// extension. | ||||||||
10224 | /// | ||||||||
10225 | /// \returns True when the operand is valid to use (even if as an extension). | ||||||||
10226 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | ||||||||
10227 | Expr *Operand) { | ||||||||
10228 | QualType ResType = Operand->getType(); | ||||||||
10229 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||||||
10230 | ResType = ResAtomicType->getValueType(); | ||||||||
10231 | |||||||||
10232 | if (!ResType->isAnyPointerType()) return true; | ||||||||
10233 | |||||||||
10234 | QualType PointeeTy = ResType->getPointeeType(); | ||||||||
10235 | if (PointeeTy->isVoidType()) { | ||||||||
10236 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | ||||||||
10237 | return !S.getLangOpts().CPlusPlus; | ||||||||
10238 | } | ||||||||
10239 | if (PointeeTy->isFunctionType()) { | ||||||||
10240 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | ||||||||
10241 | return !S.getLangOpts().CPlusPlus; | ||||||||
10242 | } | ||||||||
10243 | |||||||||
10244 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | ||||||||
10245 | |||||||||
10246 | return true; | ||||||||
10247 | } | ||||||||
10248 | |||||||||
10249 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | ||||||||
10250 | /// operands. | ||||||||
10251 | /// | ||||||||
10252 | /// This routine will diagnose any invalid arithmetic on pointer operands much | ||||||||
10253 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | ||||||||
10254 | /// for emitting a single diagnostic even for operations where both LHS and RHS | ||||||||
10255 | /// are (potentially problematic) pointers. | ||||||||
10256 | /// | ||||||||
10257 | /// \returns True when the operand is valid to use (even if as an extension). | ||||||||
10258 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | ||||||||
10259 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
10260 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | ||||||||
10261 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | ||||||||
10262 | if (!isLHSPointer && !isRHSPointer) return true; | ||||||||
10263 | |||||||||
10264 | QualType LHSPointeeTy, RHSPointeeTy; | ||||||||
10265 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | ||||||||
10266 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | ||||||||
10267 | |||||||||
10268 | // if both are pointers check if operation is valid wrt address spaces | ||||||||
10269 | if (isLHSPointer && isRHSPointer) { | ||||||||
10270 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | ||||||||
10271 | S.Diag(Loc, | ||||||||
10272 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||||||
10273 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | ||||||||
10274 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | ||||||||
10275 | return false; | ||||||||
10276 | } | ||||||||
10277 | } | ||||||||
10278 | |||||||||
10279 | // Check for arithmetic on pointers to incomplete types. | ||||||||
10280 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | ||||||||
10281 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | ||||||||
10282 | if (isLHSVoidPtr || isRHSVoidPtr) { | ||||||||
10283 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | ||||||||
10284 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | ||||||||
10285 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | ||||||||
10286 | |||||||||
10287 | return !S.getLangOpts().CPlusPlus; | ||||||||
10288 | } | ||||||||
10289 | |||||||||
10290 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | ||||||||
10291 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | ||||||||
10292 | if (isLHSFuncPtr || isRHSFuncPtr) { | ||||||||
10293 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | ||||||||
10294 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | ||||||||
10295 | RHSExpr); | ||||||||
10296 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | ||||||||
10297 | |||||||||
10298 | return !S.getLangOpts().CPlusPlus; | ||||||||
10299 | } | ||||||||
10300 | |||||||||
10301 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | ||||||||
10302 | return false; | ||||||||
10303 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | ||||||||
10304 | return false; | ||||||||
10305 | |||||||||
10306 | return true; | ||||||||
10307 | } | ||||||||
10308 | |||||||||
10309 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | ||||||||
10310 | /// literal. | ||||||||
10311 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | ||||||||
10312 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
10313 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | ||||||||
10314 | Expr* IndexExpr = RHSExpr; | ||||||||
10315 | if (!StrExpr) { | ||||||||
10316 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | ||||||||
10317 | IndexExpr = LHSExpr; | ||||||||
10318 | } | ||||||||
10319 | |||||||||
10320 | bool IsStringPlusInt = StrExpr && | ||||||||
10321 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | ||||||||
10322 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | ||||||||
10323 | return; | ||||||||
10324 | |||||||||
10325 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||||||
10326 | Self.Diag(OpLoc, diag::warn_string_plus_int) | ||||||||
10327 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | ||||||||
10328 | |||||||||
10329 | // Only print a fixit for "str" + int, not for int + "str". | ||||||||
10330 | if (IndexExpr == RHSExpr) { | ||||||||
10331 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||||||
10332 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||||||
10333 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||||||
10334 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||||||
10335 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||||||
10336 | } else | ||||||||
10337 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||||||
10338 | } | ||||||||
10339 | |||||||||
10340 | /// Emit a warning when adding a char literal to a string. | ||||||||
10341 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | ||||||||
10342 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
10343 | const Expr *StringRefExpr = LHSExpr; | ||||||||
10344 | const CharacterLiteral *CharExpr = | ||||||||
10345 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | ||||||||
10346 | |||||||||
10347 | if (!CharExpr) { | ||||||||
10348 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | ||||||||
10349 | StringRefExpr = RHSExpr; | ||||||||
10350 | } | ||||||||
10351 | |||||||||
10352 | if (!CharExpr || !StringRefExpr) | ||||||||
10353 | return; | ||||||||
10354 | |||||||||
10355 | const QualType StringType = StringRefExpr->getType(); | ||||||||
10356 | |||||||||
10357 | // Return if not a PointerType. | ||||||||
10358 | if (!StringType->isAnyPointerType()) | ||||||||
10359 | return; | ||||||||
10360 | |||||||||
10361 | // Return if not a CharacterType. | ||||||||
10362 | if (!StringType->getPointeeType()->isAnyCharacterType()) | ||||||||
10363 | return; | ||||||||
10364 | |||||||||
10365 | ASTContext &Ctx = Self.getASTContext(); | ||||||||
10366 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||||||
10367 | |||||||||
10368 | const QualType CharType = CharExpr->getType(); | ||||||||
10369 | if (!CharType->isAnyCharacterType() && | ||||||||
10370 | CharType->isIntegerType() && | ||||||||
10371 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | ||||||||
10372 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||||||
10373 | << DiagRange << Ctx.CharTy; | ||||||||
10374 | } else { | ||||||||
10375 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||||||
10376 | << DiagRange << CharExpr->getType(); | ||||||||
10377 | } | ||||||||
10378 | |||||||||
10379 | // Only print a fixit for str + char, not for char + str. | ||||||||
10380 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | ||||||||
10381 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||||||
10382 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||||||
10383 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||||||
10384 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||||||
10385 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||||||
10386 | } else { | ||||||||
10387 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||||||
10388 | } | ||||||||
10389 | } | ||||||||
10390 | |||||||||
10391 | /// Emit error when two pointers are incompatible. | ||||||||
10392 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | ||||||||
10393 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
10394 | assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10394, __PRETTY_FUNCTION__)); | ||||||||
10395 | assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10395, __PRETTY_FUNCTION__)); | ||||||||
10396 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | ||||||||
10397 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | ||||||||
10398 | << RHSExpr->getSourceRange(); | ||||||||
10399 | } | ||||||||
10400 | |||||||||
10401 | // C99 6.5.6 | ||||||||
10402 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
10403 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||||||
10404 | QualType* CompLHSTy) { | ||||||||
10405 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||||||
10406 | |||||||||
10407 | if (LHS.get()->getType()->isVectorType() || | ||||||||
10408 | RHS.get()->getType()->isVectorType()) { | ||||||||
10409 | QualType compType = CheckVectorOperands( | ||||||||
10410 | LHS, RHS, Loc, CompLHSTy, | ||||||||
10411 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||||||
10412 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||||||
10413 | if (CompLHSTy) *CompLHSTy = compType; | ||||||||
10414 | return compType; | ||||||||
10415 | } | ||||||||
10416 | |||||||||
10417 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||||||
10418 | RHS.get()->getType()->isConstantMatrixType()) { | ||||||||
10419 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||||||
10420 | } | ||||||||
10421 | |||||||||
10422 | QualType compType = UsualArithmeticConversions( | ||||||||
10423 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||||||
10424 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
10425 | return QualType(); | ||||||||
10426 | |||||||||
10427 | // Diagnose "string literal" '+' int and string '+' "char literal". | ||||||||
10428 | if (Opc == BO_Add) { | ||||||||
10429 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | ||||||||
10430 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | ||||||||
10431 | } | ||||||||
10432 | |||||||||
10433 | // handle the common case first (both operands are arithmetic). | ||||||||
10434 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||||||
10435 | if (CompLHSTy) *CompLHSTy = compType; | ||||||||
10436 | return compType; | ||||||||
10437 | } | ||||||||
10438 | |||||||||
10439 | // Type-checking. Ultimately the pointer's going to be in PExp; | ||||||||
10440 | // note that we bias towards the LHS being the pointer. | ||||||||
10441 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | ||||||||
10442 | |||||||||
10443 | bool isObjCPointer; | ||||||||
10444 | if (PExp->getType()->isPointerType()) { | ||||||||
10445 | isObjCPointer = false; | ||||||||
10446 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||||||
10447 | isObjCPointer = true; | ||||||||
10448 | } else { | ||||||||
10449 | std::swap(PExp, IExp); | ||||||||
10450 | if (PExp->getType()->isPointerType()) { | ||||||||
10451 | isObjCPointer = false; | ||||||||
10452 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||||||
10453 | isObjCPointer = true; | ||||||||
10454 | } else { | ||||||||
10455 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10456 | } | ||||||||
10457 | } | ||||||||
10458 | assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10458, __PRETTY_FUNCTION__)); | ||||||||
10459 | |||||||||
10460 | if (!IExp->getType()->isIntegerType()) | ||||||||
10461 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10462 | |||||||||
10463 | // Adding to a null pointer results in undefined behavior. | ||||||||
10464 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | ||||||||
10465 | Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||||||
10466 | // In C++ adding zero to a null pointer is defined. | ||||||||
10467 | Expr::EvalResult KnownVal; | ||||||||
10468 | if (!getLangOpts().CPlusPlus || | ||||||||
10469 | (!IExp->isValueDependent() && | ||||||||
10470 | (!IExp->EvaluateAsInt(KnownVal, Context) || | ||||||||
10471 | KnownVal.Val.getInt() != 0))) { | ||||||||
10472 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | ||||||||
10473 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | ||||||||
10474 | Context, BO_Add, PExp, IExp); | ||||||||
10475 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | ||||||||
10476 | } | ||||||||
10477 | } | ||||||||
10478 | |||||||||
10479 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | ||||||||
10480 | return QualType(); | ||||||||
10481 | |||||||||
10482 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | ||||||||
10483 | return QualType(); | ||||||||
10484 | |||||||||
10485 | // Check array bounds for pointer arithemtic | ||||||||
10486 | CheckArrayAccess(PExp, IExp); | ||||||||
10487 | |||||||||
10488 | if (CompLHSTy) { | ||||||||
10489 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | ||||||||
10490 | if (LHSTy.isNull()) { | ||||||||
10491 | LHSTy = LHS.get()->getType(); | ||||||||
10492 | if (LHSTy->isPromotableIntegerType()) | ||||||||
10493 | LHSTy = Context.getPromotedIntegerType(LHSTy); | ||||||||
10494 | } | ||||||||
10495 | *CompLHSTy = LHSTy; | ||||||||
10496 | } | ||||||||
10497 | |||||||||
10498 | return PExp->getType(); | ||||||||
10499 | } | ||||||||
10500 | |||||||||
10501 | // C99 6.5.6 | ||||||||
10502 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
10503 | SourceLocation Loc, | ||||||||
10504 | QualType* CompLHSTy) { | ||||||||
10505 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||||||
10506 | |||||||||
10507 | if (LHS.get()->getType()->isVectorType() || | ||||||||
10508 | RHS.get()->getType()->isVectorType()) { | ||||||||
10509 | QualType compType = CheckVectorOperands( | ||||||||
10510 | LHS, RHS, Loc, CompLHSTy, | ||||||||
10511 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||||||
10512 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||||||
10513 | if (CompLHSTy) *CompLHSTy = compType; | ||||||||
10514 | return compType; | ||||||||
10515 | } | ||||||||
10516 | |||||||||
10517 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||||||
10518 | RHS.get()->getType()->isConstantMatrixType()) { | ||||||||
10519 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||||||
10520 | } | ||||||||
10521 | |||||||||
10522 | QualType compType = UsualArithmeticConversions( | ||||||||
10523 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||||||
10524 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
10525 | return QualType(); | ||||||||
10526 | |||||||||
10527 | // Enforce type constraints: C99 6.5.6p3. | ||||||||
10528 | |||||||||
10529 | // Handle the common case first (both operands are arithmetic). | ||||||||
10530 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||||||
10531 | if (CompLHSTy) *CompLHSTy = compType; | ||||||||
10532 | return compType; | ||||||||
10533 | } | ||||||||
10534 | |||||||||
10535 | // Either ptr - int or ptr - ptr. | ||||||||
10536 | if (LHS.get()->getType()->isAnyPointerType()) { | ||||||||
10537 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | ||||||||
10538 | |||||||||
10539 | // Diagnose bad cases where we step over interface counts. | ||||||||
10540 | if (LHS.get()->getType()->isObjCObjectPointerType() && | ||||||||
10541 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | ||||||||
10542 | return QualType(); | ||||||||
10543 | |||||||||
10544 | // The result type of a pointer-int computation is the pointer type. | ||||||||
10545 | if (RHS.get()->getType()->isIntegerType()) { | ||||||||
10546 | // Subtracting from a null pointer should produce a warning. | ||||||||
10547 | // The last argument to the diagnose call says this doesn't match the | ||||||||
10548 | // GNU int-to-pointer idiom. | ||||||||
10549 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | ||||||||
10550 | Expr::NPC_ValueDependentIsNotNull)) { | ||||||||
10551 | // In C++ adding zero to a null pointer is defined. | ||||||||
10552 | Expr::EvalResult KnownVal; | ||||||||
10553 | if (!getLangOpts().CPlusPlus || | ||||||||
10554 | (!RHS.get()->isValueDependent() && | ||||||||
10555 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | ||||||||
10556 | KnownVal.Val.getInt() != 0))) { | ||||||||
10557 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | ||||||||
10558 | } | ||||||||
10559 | } | ||||||||
10560 | |||||||||
10561 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | ||||||||
10562 | return QualType(); | ||||||||
10563 | |||||||||
10564 | // Check array bounds for pointer arithemtic | ||||||||
10565 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | ||||||||
10566 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | ||||||||
10567 | |||||||||
10568 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||||||
10569 | return LHS.get()->getType(); | ||||||||
10570 | } | ||||||||
10571 | |||||||||
10572 | // Handle pointer-pointer subtractions. | ||||||||
10573 | if (const PointerType *RHSPTy | ||||||||
10574 | = RHS.get()->getType()->getAs<PointerType>()) { | ||||||||
10575 | QualType rpointee = RHSPTy->getPointeeType(); | ||||||||
10576 | |||||||||
10577 | if (getLangOpts().CPlusPlus) { | ||||||||
10578 | // Pointee types must be the same: C++ [expr.add] | ||||||||
10579 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | ||||||||
10580 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||||||
10581 | } | ||||||||
10582 | } else { | ||||||||
10583 | // Pointee types must be compatible C99 6.5.6p3 | ||||||||
10584 | if (!Context.typesAreCompatible( | ||||||||
10585 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | ||||||||
10586 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | ||||||||
10587 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||||||
10588 | return QualType(); | ||||||||
10589 | } | ||||||||
10590 | } | ||||||||
10591 | |||||||||
10592 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | ||||||||
10593 | LHS.get(), RHS.get())) | ||||||||
10594 | return QualType(); | ||||||||
10595 | |||||||||
10596 | // FIXME: Add warnings for nullptr - ptr. | ||||||||
10597 | |||||||||
10598 | // The pointee type may have zero size. As an extension, a structure or | ||||||||
10599 | // union may have zero size or an array may have zero length. In this | ||||||||
10600 | // case subtraction does not make sense. | ||||||||
10601 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | ||||||||
10602 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | ||||||||
10603 | if (ElementSize.isZero()) { | ||||||||
10604 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | ||||||||
10605 | << rpointee.getUnqualifiedType() | ||||||||
10606 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10607 | } | ||||||||
10608 | } | ||||||||
10609 | |||||||||
10610 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||||||
10611 | return Context.getPointerDiffType(); | ||||||||
10612 | } | ||||||||
10613 | } | ||||||||
10614 | |||||||||
10615 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10616 | } | ||||||||
10617 | |||||||||
10618 | static bool isScopedEnumerationType(QualType T) { | ||||||||
10619 | if (const EnumType *ET = T->getAs<EnumType>()) | ||||||||
10620 | return ET->getDecl()->isScoped(); | ||||||||
10621 | return false; | ||||||||
10622 | } | ||||||||
10623 | |||||||||
10624 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | ||||||||
10625 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||||||
10626 | QualType LHSType) { | ||||||||
10627 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | ||||||||
10628 | // so skip remaining warnings as we don't want to modify values within Sema. | ||||||||
10629 | if (S.getLangOpts().OpenCL) | ||||||||
10630 | return; | ||||||||
10631 | |||||||||
10632 | // Check right/shifter operand | ||||||||
10633 | Expr::EvalResult RHSResult; | ||||||||
10634 | if (RHS.get()->isValueDependent() || | ||||||||
10635 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | ||||||||
10636 | return; | ||||||||
10637 | llvm::APSInt Right = RHSResult.Val.getInt(); | ||||||||
10638 | |||||||||
10639 | if (Right.isNegative()) { | ||||||||
10640 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||||||
10641 | S.PDiag(diag::warn_shift_negative) | ||||||||
10642 | << RHS.get()->getSourceRange()); | ||||||||
10643 | return; | ||||||||
10644 | } | ||||||||
10645 | |||||||||
10646 | QualType LHSExprType = LHS.get()->getType(); | ||||||||
10647 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | ||||||||
10648 | if (LHSExprType->isExtIntType()) | ||||||||
10649 | LeftSize = S.Context.getIntWidth(LHSExprType); | ||||||||
10650 | else if (LHSExprType->isFixedPointType()) { | ||||||||
10651 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | ||||||||
10652 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | ||||||||
10653 | } | ||||||||
10654 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | ||||||||
10655 | if (Right.uge(LeftBits)) { | ||||||||
10656 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||||||
10657 | S.PDiag(diag::warn_shift_gt_typewidth) | ||||||||
10658 | << RHS.get()->getSourceRange()); | ||||||||
10659 | return; | ||||||||
10660 | } | ||||||||
10661 | |||||||||
10662 | // FIXME: We probably need to handle fixed point types specially here. | ||||||||
10663 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | ||||||||
10664 | return; | ||||||||
10665 | |||||||||
10666 | // When left shifting an ICE which is signed, we can check for overflow which | ||||||||
10667 | // according to C++ standards prior to C++2a has undefined behavior | ||||||||
10668 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | ||||||||
10669 | // more than the maximum value representable in the result type, so never | ||||||||
10670 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | ||||||||
10671 | // expression is still probably a bug.) | ||||||||
10672 | Expr::EvalResult LHSResult; | ||||||||
10673 | if (LHS.get()->isValueDependent() || | ||||||||
10674 | LHSType->hasUnsignedIntegerRepresentation() || | ||||||||
10675 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | ||||||||
10676 | return; | ||||||||
10677 | llvm::APSInt Left = LHSResult.Val.getInt(); | ||||||||
10678 | |||||||||
10679 | // If LHS does not have a signed type and non-negative value | ||||||||
10680 | // then, the behavior is undefined before C++2a. Warn about it. | ||||||||
10681 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && | ||||||||
10682 | !S.getLangOpts().CPlusPlus20) { | ||||||||
10683 | S.DiagRuntimeBehavior(Loc, LHS.get(), | ||||||||
10684 | S.PDiag(diag::warn_shift_lhs_negative) | ||||||||
10685 | << LHS.get()->getSourceRange()); | ||||||||
10686 | return; | ||||||||
10687 | } | ||||||||
10688 | |||||||||
10689 | llvm::APInt ResultBits = | ||||||||
10690 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | ||||||||
10691 | if (LeftBits.uge(ResultBits)) | ||||||||
10692 | return; | ||||||||
10693 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | ||||||||
10694 | Result = Result.shl(Right); | ||||||||
10695 | |||||||||
10696 | // Print the bit representation of the signed integer as an unsigned | ||||||||
10697 | // hexadecimal number. | ||||||||
10698 | SmallString<40> HexResult; | ||||||||
10699 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | ||||||||
10700 | |||||||||
10701 | // If we are only missing a sign bit, this is less likely to result in actual | ||||||||
10702 | // bugs -- if the result is cast back to an unsigned type, it will have the | ||||||||
10703 | // expected value. Thus we place this behind a different warning that can be | ||||||||
10704 | // turned off separately if needed. | ||||||||
10705 | if (LeftBits == ResultBits - 1) { | ||||||||
10706 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | ||||||||
10707 | << HexResult << LHSType | ||||||||
10708 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10709 | return; | ||||||||
10710 | } | ||||||||
10711 | |||||||||
10712 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | ||||||||
10713 | << HexResult.str() << Result.getMinSignedBits() << LHSType | ||||||||
10714 | << Left.getBitWidth() << LHS.get()->getSourceRange() | ||||||||
10715 | << RHS.get()->getSourceRange(); | ||||||||
10716 | } | ||||||||
10717 | |||||||||
10718 | /// Return the resulting type when a vector is shifted | ||||||||
10719 | /// by a scalar or vector shift amount. | ||||||||
10720 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||||||
10721 | SourceLocation Loc, bool IsCompAssign) { | ||||||||
10722 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | ||||||||
10723 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | ||||||||
10724 | !LHS.get()->getType()->isVectorType()) { | ||||||||
10725 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | ||||||||
10726 | << RHS.get()->getType() << LHS.get()->getType() | ||||||||
10727 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10728 | return QualType(); | ||||||||
10729 | } | ||||||||
10730 | |||||||||
10731 | if (!IsCompAssign) { | ||||||||
10732 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||||||
10733 | if (LHS.isInvalid()) return QualType(); | ||||||||
10734 | } | ||||||||
10735 | |||||||||
10736 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||||||
10737 | if (RHS.isInvalid()) return QualType(); | ||||||||
10738 | |||||||||
10739 | QualType LHSType = LHS.get()->getType(); | ||||||||
10740 | // Note that LHS might be a scalar because the routine calls not only in | ||||||||
10741 | // OpenCL case. | ||||||||
10742 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | ||||||||
10743 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | ||||||||
10744 | |||||||||
10745 | // Note that RHS might not be a vector. | ||||||||
10746 | QualType RHSType = RHS.get()->getType(); | ||||||||
10747 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | ||||||||
10748 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | ||||||||
10749 | |||||||||
10750 | // The operands need to be integers. | ||||||||
10751 | if (!LHSEleType->isIntegerType()) { | ||||||||
10752 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||||||
10753 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||||||
10754 | return QualType(); | ||||||||
10755 | } | ||||||||
10756 | |||||||||
10757 | if (!RHSEleType->isIntegerType()) { | ||||||||
10758 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||||||
10759 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||||||
10760 | return QualType(); | ||||||||
10761 | } | ||||||||
10762 | |||||||||
10763 | if (!LHSVecTy) { | ||||||||
10764 | assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10764, __PRETTY_FUNCTION__)); | ||||||||
10765 | if (IsCompAssign) | ||||||||
10766 | return RHSType; | ||||||||
10767 | if (LHSEleType != RHSEleType) { | ||||||||
10768 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | ||||||||
10769 | LHSEleType = RHSEleType; | ||||||||
10770 | } | ||||||||
10771 | QualType VecTy = | ||||||||
10772 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | ||||||||
10773 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | ||||||||
10774 | LHSType = VecTy; | ||||||||
10775 | } else if (RHSVecTy) { | ||||||||
10776 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | ||||||||
10777 | // are applied component-wise. So if RHS is a vector, then ensure | ||||||||
10778 | // that the number of elements is the same as LHS... | ||||||||
10779 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | ||||||||
10780 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||||||
10781 | << LHS.get()->getType() << RHS.get()->getType() | ||||||||
10782 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10783 | return QualType(); | ||||||||
10784 | } | ||||||||
10785 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | ||||||||
10786 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | ||||||||
10787 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | ||||||||
10788 | if (LHSBT != RHSBT && | ||||||||
10789 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | ||||||||
10790 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | ||||||||
10791 | << LHS.get()->getType() << RHS.get()->getType() | ||||||||
10792 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10793 | } | ||||||||
10794 | } | ||||||||
10795 | } else { | ||||||||
10796 | // ...else expand RHS to match the number of elements in LHS. | ||||||||
10797 | QualType VecTy = | ||||||||
10798 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | ||||||||
10799 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||||||
10800 | } | ||||||||
10801 | |||||||||
10802 | return LHSType; | ||||||||
10803 | } | ||||||||
10804 | |||||||||
10805 | // C99 6.5.7 | ||||||||
10806 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
10807 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||||||
10808 | bool IsCompAssign) { | ||||||||
10809 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||||||
10810 | |||||||||
10811 | // Vector shifts promote their scalar inputs to vector type. | ||||||||
10812 | if (LHS.get()->getType()->isVectorType() || | ||||||||
10813 | RHS.get()->getType()->isVectorType()) { | ||||||||
10814 | if (LangOpts.ZVector) { | ||||||||
10815 | // The shift operators for the z vector extensions work basically | ||||||||
10816 | // like general shifts, except that neither the LHS nor the RHS is | ||||||||
10817 | // allowed to be a "vector bool". | ||||||||
10818 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | ||||||||
10819 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||||||
10820 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10821 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | ||||||||
10822 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||||||
10823 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10824 | } | ||||||||
10825 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||||||
10826 | } | ||||||||
10827 | |||||||||
10828 | // Shifts don't perform usual arithmetic conversions, they just do integer | ||||||||
10829 | // promotions on each operand. C99 6.5.7p3 | ||||||||
10830 | |||||||||
10831 | // For the LHS, do usual unary conversions, but then reset them away | ||||||||
10832 | // if this is a compound assignment. | ||||||||
10833 | ExprResult OldLHS = LHS; | ||||||||
10834 | LHS = UsualUnaryConversions(LHS.get()); | ||||||||
10835 | if (LHS.isInvalid()) | ||||||||
10836 | return QualType(); | ||||||||
10837 | QualType LHSType = LHS.get()->getType(); | ||||||||
10838 | if (IsCompAssign) LHS = OldLHS; | ||||||||
10839 | |||||||||
10840 | // The RHS is simpler. | ||||||||
10841 | RHS = UsualUnaryConversions(RHS.get()); | ||||||||
10842 | if (RHS.isInvalid()) | ||||||||
10843 | return QualType(); | ||||||||
10844 | QualType RHSType = RHS.get()->getType(); | ||||||||
10845 | |||||||||
10846 | // C99 6.5.7p2: Each of the operands shall have integer type. | ||||||||
10847 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | ||||||||
10848 | if ((!LHSType->isFixedPointOrIntegerType() && | ||||||||
10849 | !LHSType->hasIntegerRepresentation()) || | ||||||||
10850 | !RHSType->hasIntegerRepresentation()) | ||||||||
10851 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10852 | |||||||||
10853 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | ||||||||
10854 | // hasIntegerRepresentation() above instead of this. | ||||||||
10855 | if (isScopedEnumerationType(LHSType) || | ||||||||
10856 | isScopedEnumerationType(RHSType)) { | ||||||||
10857 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
10858 | } | ||||||||
10859 | // Sanity-check shift operands | ||||||||
10860 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | ||||||||
10861 | |||||||||
10862 | // "The type of the result is that of the promoted left operand." | ||||||||
10863 | return LHSType; | ||||||||
10864 | } | ||||||||
10865 | |||||||||
10866 | /// Diagnose bad pointer comparisons. | ||||||||
10867 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | ||||||||
10868 | ExprResult &LHS, ExprResult &RHS, | ||||||||
10869 | bool IsError) { | ||||||||
10870 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | ||||||||
10871 | : diag::ext_typecheck_comparison_of_distinct_pointers) | ||||||||
10872 | << LHS.get()->getType() << RHS.get()->getType() | ||||||||
10873 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10874 | } | ||||||||
10875 | |||||||||
10876 | /// Returns false if the pointers are converted to a composite type, | ||||||||
10877 | /// true otherwise. | ||||||||
10878 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | ||||||||
10879 | ExprResult &LHS, ExprResult &RHS) { | ||||||||
10880 | // C++ [expr.rel]p2: | ||||||||
10881 | // [...] Pointer conversions (4.10) and qualification | ||||||||
10882 | // conversions (4.4) are performed on pointer operands (or on | ||||||||
10883 | // a pointer operand and a null pointer constant) to bring | ||||||||
10884 | // them to their composite pointer type. [...] | ||||||||
10885 | // | ||||||||
10886 | // C++ [expr.eq]p1 uses the same notion for (in)equality | ||||||||
10887 | // comparisons of pointers. | ||||||||
10888 | |||||||||
10889 | QualType LHSType = LHS.get()->getType(); | ||||||||
10890 | QualType RHSType = RHS.get()->getType(); | ||||||||
10891 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10892, __PRETTY_FUNCTION__)) | ||||||||
10892 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 10892, __PRETTY_FUNCTION__)); | ||||||||
10893 | |||||||||
10894 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | ||||||||
10895 | if (T.isNull()) { | ||||||||
10896 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | ||||||||
10897 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | ||||||||
10898 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | ||||||||
10899 | else | ||||||||
10900 | S.InvalidOperands(Loc, LHS, RHS); | ||||||||
10901 | return true; | ||||||||
10902 | } | ||||||||
10903 | |||||||||
10904 | return false; | ||||||||
10905 | } | ||||||||
10906 | |||||||||
10907 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | ||||||||
10908 | ExprResult &LHS, | ||||||||
10909 | ExprResult &RHS, | ||||||||
10910 | bool IsError) { | ||||||||
10911 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | ||||||||
10912 | : diag::ext_typecheck_comparison_of_fptr_to_void) | ||||||||
10913 | << LHS.get()->getType() << RHS.get()->getType() | ||||||||
10914 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
10915 | } | ||||||||
10916 | |||||||||
10917 | static bool isObjCObjectLiteral(ExprResult &E) { | ||||||||
10918 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | ||||||||
10919 | case Stmt::ObjCArrayLiteralClass: | ||||||||
10920 | case Stmt::ObjCDictionaryLiteralClass: | ||||||||
10921 | case Stmt::ObjCStringLiteralClass: | ||||||||
10922 | case Stmt::ObjCBoxedExprClass: | ||||||||
10923 | return true; | ||||||||
10924 | default: | ||||||||
10925 | // Note that ObjCBoolLiteral is NOT an object literal! | ||||||||
10926 | return false; | ||||||||
10927 | } | ||||||||
10928 | } | ||||||||
10929 | |||||||||
10930 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | ||||||||
10931 | const ObjCObjectPointerType *Type = | ||||||||
10932 | LHS->getType()->getAs<ObjCObjectPointerType>(); | ||||||||
10933 | |||||||||
10934 | // If this is not actually an Objective-C object, bail out. | ||||||||
10935 | if (!Type) | ||||||||
10936 | return false; | ||||||||
10937 | |||||||||
10938 | // Get the LHS object's interface type. | ||||||||
10939 | QualType InterfaceType = Type->getPointeeType(); | ||||||||
10940 | |||||||||
10941 | // If the RHS isn't an Objective-C object, bail out. | ||||||||
10942 | if (!RHS->getType()->isObjCObjectPointerType()) | ||||||||
10943 | return false; | ||||||||
10944 | |||||||||
10945 | // Try to find the -isEqual: method. | ||||||||
10946 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | ||||||||
10947 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | ||||||||
10948 | InterfaceType, | ||||||||
10949 | /*IsInstance=*/true); | ||||||||
10950 | if (!Method) { | ||||||||
10951 | if (Type->isObjCIdType()) { | ||||||||
10952 | // For 'id', just check the global pool. | ||||||||
10953 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | ||||||||
10954 | /*receiverId=*/true); | ||||||||
10955 | } else { | ||||||||
10956 | // Check protocols. | ||||||||
10957 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | ||||||||
10958 | /*IsInstance=*/true); | ||||||||
10959 | } | ||||||||
10960 | } | ||||||||
10961 | |||||||||
10962 | if (!Method) | ||||||||
10963 | return false; | ||||||||
10964 | |||||||||
10965 | QualType T = Method->parameters()[0]->getType(); | ||||||||
10966 | if (!T->isObjCObjectPointerType()) | ||||||||
10967 | return false; | ||||||||
10968 | |||||||||
10969 | QualType R = Method->getReturnType(); | ||||||||
10970 | if (!R->isScalarType()) | ||||||||
10971 | return false; | ||||||||
10972 | |||||||||
10973 | return true; | ||||||||
10974 | } | ||||||||
10975 | |||||||||
10976 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | ||||||||
10977 | FromE = FromE->IgnoreParenImpCasts(); | ||||||||
10978 | switch (FromE->getStmtClass()) { | ||||||||
10979 | default: | ||||||||
10980 | break; | ||||||||
10981 | case Stmt::ObjCStringLiteralClass: | ||||||||
10982 | // "string literal" | ||||||||
10983 | return LK_String; | ||||||||
10984 | case Stmt::ObjCArrayLiteralClass: | ||||||||
10985 | // "array literal" | ||||||||
10986 | return LK_Array; | ||||||||
10987 | case Stmt::ObjCDictionaryLiteralClass: | ||||||||
10988 | // "dictionary literal" | ||||||||
10989 | return LK_Dictionary; | ||||||||
10990 | case Stmt::BlockExprClass: | ||||||||
10991 | return LK_Block; | ||||||||
10992 | case Stmt::ObjCBoxedExprClass: { | ||||||||
10993 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | ||||||||
10994 | switch (Inner->getStmtClass()) { | ||||||||
10995 | case Stmt::IntegerLiteralClass: | ||||||||
10996 | case Stmt::FloatingLiteralClass: | ||||||||
10997 | case Stmt::CharacterLiteralClass: | ||||||||
10998 | case Stmt::ObjCBoolLiteralExprClass: | ||||||||
10999 | case Stmt::CXXBoolLiteralExprClass: | ||||||||
11000 | // "numeric literal" | ||||||||
11001 | return LK_Numeric; | ||||||||
11002 | case Stmt::ImplicitCastExprClass: { | ||||||||
11003 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | ||||||||
11004 | // Boolean literals can be represented by implicit casts. | ||||||||
11005 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | ||||||||
11006 | return LK_Numeric; | ||||||||
11007 | break; | ||||||||
11008 | } | ||||||||
11009 | default: | ||||||||
11010 | break; | ||||||||
11011 | } | ||||||||
11012 | return LK_Boxed; | ||||||||
11013 | } | ||||||||
11014 | } | ||||||||
11015 | return LK_None; | ||||||||
11016 | } | ||||||||
11017 | |||||||||
11018 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | ||||||||
11019 | ExprResult &LHS, ExprResult &RHS, | ||||||||
11020 | BinaryOperator::Opcode Opc){ | ||||||||
11021 | Expr *Literal; | ||||||||
11022 | Expr *Other; | ||||||||
11023 | if (isObjCObjectLiteral(LHS)) { | ||||||||
11024 | Literal = LHS.get(); | ||||||||
11025 | Other = RHS.get(); | ||||||||
11026 | } else { | ||||||||
11027 | Literal = RHS.get(); | ||||||||
11028 | Other = LHS.get(); | ||||||||
11029 | } | ||||||||
11030 | |||||||||
11031 | // Don't warn on comparisons against nil. | ||||||||
11032 | Other = Other->IgnoreParenCasts(); | ||||||||
11033 | if (Other->isNullPointerConstant(S.getASTContext(), | ||||||||
11034 | Expr::NPC_ValueDependentIsNotNull)) | ||||||||
11035 | return; | ||||||||
11036 | |||||||||
11037 | // This should be kept in sync with warn_objc_literal_comparison. | ||||||||
11038 | // LK_String should always be after the other literals, since it has its own | ||||||||
11039 | // warning flag. | ||||||||
11040 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | ||||||||
11041 | assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0 ) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11041, __PRETTY_FUNCTION__)); | ||||||||
11042 | if (LiteralKind == Sema::LK_None) { | ||||||||
11043 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11043); | ||||||||
11044 | } | ||||||||
11045 | |||||||||
11046 | if (LiteralKind == Sema::LK_String) | ||||||||
11047 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | ||||||||
11048 | << Literal->getSourceRange(); | ||||||||
11049 | else | ||||||||
11050 | S.Diag(Loc, diag::warn_objc_literal_comparison) | ||||||||
11051 | << LiteralKind << Literal->getSourceRange(); | ||||||||
11052 | |||||||||
11053 | if (BinaryOperator::isEqualityOp(Opc) && | ||||||||
11054 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | ||||||||
11055 | SourceLocation Start = LHS.get()->getBeginLoc(); | ||||||||
11056 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||||||
11057 | CharSourceRange OpRange = | ||||||||
11058 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||||||
11059 | |||||||||
11060 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | ||||||||
11061 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | ||||||||
11062 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | ||||||||
11063 | << FixItHint::CreateInsertion(End, "]"); | ||||||||
11064 | } | ||||||||
11065 | } | ||||||||
11066 | |||||||||
11067 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | ||||||||
11068 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | ||||||||
11069 | ExprResult &RHS, SourceLocation Loc, | ||||||||
11070 | BinaryOperatorKind Opc) { | ||||||||
11071 | // Check that left hand side is !something. | ||||||||
11072 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | ||||||||
11073 | if (!UO || UO->getOpcode() != UO_LNot) return; | ||||||||
11074 | |||||||||
11075 | // Only check if the right hand side is non-bool arithmetic type. | ||||||||
11076 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | ||||||||
11077 | |||||||||
11078 | // Make sure that the something in !something is not bool. | ||||||||
11079 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | ||||||||
11080 | if (SubExpr->isKnownToHaveBooleanValue()) return; | ||||||||
11081 | |||||||||
11082 | // Emit warning. | ||||||||
11083 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | ||||||||
11084 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | ||||||||
11085 | << Loc << IsBitwiseOp; | ||||||||
11086 | |||||||||
11087 | // First note suggest !(x < y) | ||||||||
11088 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | ||||||||
11089 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | ||||||||
11090 | FirstClose = S.getLocForEndOfToken(FirstClose); | ||||||||
11091 | if (FirstClose.isInvalid()) | ||||||||
11092 | FirstOpen = SourceLocation(); | ||||||||
11093 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | ||||||||
11094 | << IsBitwiseOp | ||||||||
11095 | << FixItHint::CreateInsertion(FirstOpen, "(") | ||||||||
11096 | << FixItHint::CreateInsertion(FirstClose, ")"); | ||||||||
11097 | |||||||||
11098 | // Second note suggests (!x) < y | ||||||||
11099 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | ||||||||
11100 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | ||||||||
11101 | SecondClose = S.getLocForEndOfToken(SecondClose); | ||||||||
11102 | if (SecondClose.isInvalid()) | ||||||||
11103 | SecondOpen = SourceLocation(); | ||||||||
11104 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | ||||||||
11105 | << FixItHint::CreateInsertion(SecondOpen, "(") | ||||||||
11106 | << FixItHint::CreateInsertion(SecondClose, ")"); | ||||||||
11107 | } | ||||||||
11108 | |||||||||
11109 | // Returns true if E refers to a non-weak array. | ||||||||
11110 | static bool checkForArray(const Expr *E) { | ||||||||
11111 | const ValueDecl *D = nullptr; | ||||||||
11112 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | ||||||||
11113 | D = DR->getDecl(); | ||||||||
11114 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | ||||||||
11115 | if (Mem->isImplicitAccess()) | ||||||||
11116 | D = Mem->getMemberDecl(); | ||||||||
11117 | } | ||||||||
11118 | if (!D) | ||||||||
11119 | return false; | ||||||||
11120 | return D->getType()->isArrayType() && !D->isWeak(); | ||||||||
11121 | } | ||||||||
11122 | |||||||||
11123 | /// Diagnose some forms of syntactically-obvious tautological comparison. | ||||||||
11124 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | ||||||||
11125 | Expr *LHS, Expr *RHS, | ||||||||
11126 | BinaryOperatorKind Opc) { | ||||||||
11127 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | ||||||||
11128 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | ||||||||
11129 | |||||||||
11130 | QualType LHSType = LHS->getType(); | ||||||||
11131 | QualType RHSType = RHS->getType(); | ||||||||
11132 | if (LHSType->hasFloatingRepresentation() || | ||||||||
11133 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | ||||||||
11134 | S.inTemplateInstantiation()) | ||||||||
11135 | return; | ||||||||
11136 | |||||||||
11137 | // Comparisons between two array types are ill-formed for operator<=>, so | ||||||||
11138 | // we shouldn't emit any additional warnings about it. | ||||||||
11139 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | ||||||||
11140 | return; | ||||||||
11141 | |||||||||
11142 | // For non-floating point types, check for self-comparisons of the form | ||||||||
11143 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||||||
11144 | // often indicate logic errors in the program. | ||||||||
11145 | // | ||||||||
11146 | // NOTE: Don't warn about comparison expressions resulting from macro | ||||||||
11147 | // expansion. Also don't warn about comparisons which are only self | ||||||||
11148 | // comparisons within a template instantiation. The warnings should catch | ||||||||
11149 | // obvious cases in the definition of the template anyways. The idea is to | ||||||||
11150 | // warn when the typed comparison operator will always evaluate to the same | ||||||||
11151 | // result. | ||||||||
11152 | |||||||||
11153 | // Used for indexing into %select in warn_comparison_always | ||||||||
11154 | enum { | ||||||||
11155 | AlwaysConstant, | ||||||||
11156 | AlwaysTrue, | ||||||||
11157 | AlwaysFalse, | ||||||||
11158 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | ||||||||
11159 | }; | ||||||||
11160 | |||||||||
11161 | // C++2a [depr.array.comp]: | ||||||||
11162 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | ||||||||
11163 | // operands of array type are deprecated. | ||||||||
11164 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | ||||||||
11165 | RHSStripped->getType()->isArrayType()) { | ||||||||
11166 | S.Diag(Loc, diag::warn_depr_array_comparison) | ||||||||
11167 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||||||
11168 | << LHSStripped->getType() << RHSStripped->getType(); | ||||||||
11169 | // Carry on to produce the tautological comparison warning, if this | ||||||||
11170 | // expression is potentially-evaluated, we can resolve the array to a | ||||||||
11171 | // non-weak declaration, and so on. | ||||||||
11172 | } | ||||||||
11173 | |||||||||
11174 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | ||||||||
11175 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | ||||||||
11176 | unsigned Result; | ||||||||
11177 | switch (Opc) { | ||||||||
11178 | case BO_EQ: | ||||||||
11179 | case BO_LE: | ||||||||
11180 | case BO_GE: | ||||||||
11181 | Result = AlwaysTrue; | ||||||||
11182 | break; | ||||||||
11183 | case BO_NE: | ||||||||
11184 | case BO_LT: | ||||||||
11185 | case BO_GT: | ||||||||
11186 | Result = AlwaysFalse; | ||||||||
11187 | break; | ||||||||
11188 | case BO_Cmp: | ||||||||
11189 | Result = AlwaysEqual; | ||||||||
11190 | break; | ||||||||
11191 | default: | ||||||||
11192 | Result = AlwaysConstant; | ||||||||
11193 | break; | ||||||||
11194 | } | ||||||||
11195 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||||||
11196 | S.PDiag(diag::warn_comparison_always) | ||||||||
11197 | << 0 /*self-comparison*/ | ||||||||
11198 | << Result); | ||||||||
11199 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | ||||||||
11200 | // What is it always going to evaluate to? | ||||||||
11201 | unsigned Result; | ||||||||
11202 | switch (Opc) { | ||||||||
11203 | case BO_EQ: // e.g. array1 == array2 | ||||||||
11204 | Result = AlwaysFalse; | ||||||||
11205 | break; | ||||||||
11206 | case BO_NE: // e.g. array1 != array2 | ||||||||
11207 | Result = AlwaysTrue; | ||||||||
11208 | break; | ||||||||
11209 | default: // e.g. array1 <= array2 | ||||||||
11210 | // The best we can say is 'a constant' | ||||||||
11211 | Result = AlwaysConstant; | ||||||||
11212 | break; | ||||||||
11213 | } | ||||||||
11214 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||||||
11215 | S.PDiag(diag::warn_comparison_always) | ||||||||
11216 | << 1 /*array comparison*/ | ||||||||
11217 | << Result); | ||||||||
11218 | } | ||||||||
11219 | } | ||||||||
11220 | |||||||||
11221 | if (isa<CastExpr>(LHSStripped)) | ||||||||
11222 | LHSStripped = LHSStripped->IgnoreParenCasts(); | ||||||||
11223 | if (isa<CastExpr>(RHSStripped)) | ||||||||
11224 | RHSStripped = RHSStripped->IgnoreParenCasts(); | ||||||||
11225 | |||||||||
11226 | // Warn about comparisons against a string constant (unless the other | ||||||||
11227 | // operand is null); the user probably wants string comparison function. | ||||||||
11228 | Expr *LiteralString = nullptr; | ||||||||
11229 | Expr *LiteralStringStripped = nullptr; | ||||||||
11230 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | ||||||||
11231 | !RHSStripped->isNullPointerConstant(S.Context, | ||||||||
11232 | Expr::NPC_ValueDependentIsNull)) { | ||||||||
11233 | LiteralString = LHS; | ||||||||
11234 | LiteralStringStripped = LHSStripped; | ||||||||
11235 | } else if ((isa<StringLiteral>(RHSStripped) || | ||||||||
11236 | isa<ObjCEncodeExpr>(RHSStripped)) && | ||||||||
11237 | !LHSStripped->isNullPointerConstant(S.Context, | ||||||||
11238 | Expr::NPC_ValueDependentIsNull)) { | ||||||||
11239 | LiteralString = RHS; | ||||||||
11240 | LiteralStringStripped = RHSStripped; | ||||||||
11241 | } | ||||||||
11242 | |||||||||
11243 | if (LiteralString) { | ||||||||
11244 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||||||
11245 | S.PDiag(diag::warn_stringcompare) | ||||||||
11246 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | ||||||||
11247 | << LiteralString->getSourceRange()); | ||||||||
11248 | } | ||||||||
11249 | } | ||||||||
11250 | |||||||||
11251 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | ||||||||
11252 | switch (CK) { | ||||||||
11253 | default: { | ||||||||
11254 | #ifndef NDEBUG | ||||||||
11255 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | ||||||||
11256 | << "\n"; | ||||||||
11257 | #endif | ||||||||
11258 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11258); | ||||||||
11259 | } | ||||||||
11260 | case CK_UserDefinedConversion: | ||||||||
11261 | return ICK_Identity; | ||||||||
11262 | case CK_LValueToRValue: | ||||||||
11263 | return ICK_Lvalue_To_Rvalue; | ||||||||
11264 | case CK_ArrayToPointerDecay: | ||||||||
11265 | return ICK_Array_To_Pointer; | ||||||||
11266 | case CK_FunctionToPointerDecay: | ||||||||
11267 | return ICK_Function_To_Pointer; | ||||||||
11268 | case CK_IntegralCast: | ||||||||
11269 | return ICK_Integral_Conversion; | ||||||||
11270 | case CK_FloatingCast: | ||||||||
11271 | return ICK_Floating_Conversion; | ||||||||
11272 | case CK_IntegralToFloating: | ||||||||
11273 | case CK_FloatingToIntegral: | ||||||||
11274 | return ICK_Floating_Integral; | ||||||||
11275 | case CK_IntegralComplexCast: | ||||||||
11276 | case CK_FloatingComplexCast: | ||||||||
11277 | case CK_FloatingComplexToIntegralComplex: | ||||||||
11278 | case CK_IntegralComplexToFloatingComplex: | ||||||||
11279 | return ICK_Complex_Conversion; | ||||||||
11280 | case CK_FloatingComplexToReal: | ||||||||
11281 | case CK_FloatingRealToComplex: | ||||||||
11282 | case CK_IntegralComplexToReal: | ||||||||
11283 | case CK_IntegralRealToComplex: | ||||||||
11284 | return ICK_Complex_Real; | ||||||||
11285 | } | ||||||||
11286 | } | ||||||||
11287 | |||||||||
11288 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | ||||||||
11289 | QualType FromType, | ||||||||
11290 | SourceLocation Loc) { | ||||||||
11291 | // Check for a narrowing implicit conversion. | ||||||||
11292 | StandardConversionSequence SCS; | ||||||||
11293 | SCS.setAsIdentityConversion(); | ||||||||
11294 | SCS.setToType(0, FromType); | ||||||||
11295 | SCS.setToType(1, ToType); | ||||||||
11296 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||||||
11297 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | ||||||||
11298 | |||||||||
11299 | APValue PreNarrowingValue; | ||||||||
11300 | QualType PreNarrowingType; | ||||||||
11301 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | ||||||||
11302 | PreNarrowingType, | ||||||||
11303 | /*IgnoreFloatToIntegralConversion*/ true)) { | ||||||||
11304 | case NK_Dependent_Narrowing: | ||||||||
11305 | // Implicit conversion to a narrower type, but the expression is | ||||||||
11306 | // value-dependent so we can't tell whether it's actually narrowing. | ||||||||
11307 | case NK_Not_Narrowing: | ||||||||
11308 | return false; | ||||||||
11309 | |||||||||
11310 | case NK_Constant_Narrowing: | ||||||||
11311 | // Implicit conversion to a narrower type, and the value is not a constant | ||||||||
11312 | // expression. | ||||||||
11313 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||||||
11314 | << /*Constant*/ 1 | ||||||||
11315 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | ||||||||
11316 | return true; | ||||||||
11317 | |||||||||
11318 | case NK_Variable_Narrowing: | ||||||||
11319 | // Implicit conversion to a narrower type, and the value is not a constant | ||||||||
11320 | // expression. | ||||||||
11321 | case NK_Type_Narrowing: | ||||||||
11322 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||||||
11323 | << /*Constant*/ 0 << FromType << ToType; | ||||||||
11324 | // TODO: It's not a constant expression, but what if the user intended it | ||||||||
11325 | // to be? Can we produce notes to help them figure out why it isn't? | ||||||||
11326 | return true; | ||||||||
11327 | } | ||||||||
11328 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11328); | ||||||||
11329 | } | ||||||||
11330 | |||||||||
11331 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | ||||||||
11332 | ExprResult &LHS, | ||||||||
11333 | ExprResult &RHS, | ||||||||
11334 | SourceLocation Loc) { | ||||||||
11335 | QualType LHSType = LHS.get()->getType(); | ||||||||
11336 | QualType RHSType = RHS.get()->getType(); | ||||||||
11337 | // Dig out the original argument type and expression before implicit casts | ||||||||
11338 | // were applied. These are the types/expressions we need to check the | ||||||||
11339 | // [expr.spaceship] requirements against. | ||||||||
11340 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | ||||||||
11341 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | ||||||||
11342 | QualType LHSStrippedType = LHSStripped.get()->getType(); | ||||||||
11343 | QualType RHSStrippedType = RHSStripped.get()->getType(); | ||||||||
11344 | |||||||||
11345 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | ||||||||
11346 | // other is not, the program is ill-formed. | ||||||||
11347 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | ||||||||
11348 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||||||
11349 | return QualType(); | ||||||||
11350 | } | ||||||||
11351 | |||||||||
11352 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | ||||||||
11353 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | ||||||||
11354 | RHSStrippedType->isEnumeralType(); | ||||||||
11355 | if (NumEnumArgs == 1) { | ||||||||
11356 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | ||||||||
11357 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | ||||||||
11358 | if (OtherTy->hasFloatingRepresentation()) { | ||||||||
11359 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||||||
11360 | return QualType(); | ||||||||
11361 | } | ||||||||
11362 | } | ||||||||
11363 | if (NumEnumArgs == 2) { | ||||||||
11364 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | ||||||||
11365 | // type E, the operator yields the result of converting the operands | ||||||||
11366 | // to the underlying type of E and applying <=> to the converted operands. | ||||||||
11367 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | ||||||||
11368 | S.InvalidOperands(Loc, LHS, RHS); | ||||||||
11369 | return QualType(); | ||||||||
11370 | } | ||||||||
11371 | QualType IntType = | ||||||||
11372 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | ||||||||
11373 | assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> ( 0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11373, __PRETTY_FUNCTION__)); | ||||||||
11374 | |||||||||
11375 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | ||||||||
11376 | // promote the boolean type, and all other promotable integer types, to | ||||||||
11377 | // avoid this. | ||||||||
11378 | if (IntType->isPromotableIntegerType()) | ||||||||
11379 | IntType = S.Context.getPromotedIntegerType(IntType); | ||||||||
11380 | |||||||||
11381 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | ||||||||
11382 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | ||||||||
11383 | LHSType = RHSType = IntType; | ||||||||
11384 | } | ||||||||
11385 | |||||||||
11386 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | ||||||||
11387 | // usual arithmetic conversions are applied to the operands. | ||||||||
11388 | QualType Type = | ||||||||
11389 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||||||
11390 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
11391 | return QualType(); | ||||||||
11392 | if (Type.isNull()) | ||||||||
11393 | return S.InvalidOperands(Loc, LHS, RHS); | ||||||||
11394 | |||||||||
11395 | Optional<ComparisonCategoryType> CCT = | ||||||||
11396 | getComparisonCategoryForBuiltinCmp(Type); | ||||||||
11397 | if (!CCT) | ||||||||
11398 | return S.InvalidOperands(Loc, LHS, RHS); | ||||||||
11399 | |||||||||
11400 | bool HasNarrowing = checkThreeWayNarrowingConversion( | ||||||||
11401 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | ||||||||
11402 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | ||||||||
11403 | RHS.get()->getBeginLoc()); | ||||||||
11404 | if (HasNarrowing) | ||||||||
11405 | return QualType(); | ||||||||
11406 | |||||||||
11407 | assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set" ) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11407, __PRETTY_FUNCTION__)); | ||||||||
11408 | |||||||||
11409 | return S.CheckComparisonCategoryType( | ||||||||
11410 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | ||||||||
11411 | } | ||||||||
11412 | |||||||||
11413 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | ||||||||
11414 | ExprResult &RHS, | ||||||||
11415 | SourceLocation Loc, | ||||||||
11416 | BinaryOperatorKind Opc) { | ||||||||
11417 | if (Opc == BO_Cmp) | ||||||||
11418 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | ||||||||
11419 | |||||||||
11420 | // C99 6.5.8p3 / C99 6.5.9p4 | ||||||||
11421 | QualType Type = | ||||||||
11422 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||||||
11423 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
11424 | return QualType(); | ||||||||
11425 | if (Type.isNull()) | ||||||||
11426 | return S.InvalidOperands(Loc, LHS, RHS); | ||||||||
11427 | assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ? static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11427, __PRETTY_FUNCTION__)); | ||||||||
11428 | |||||||||
11429 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | ||||||||
11430 | return S.InvalidOperands(Loc, LHS, RHS); | ||||||||
11431 | |||||||||
11432 | // Check for comparisons of floating point operands using != and ==. | ||||||||
11433 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | ||||||||
11434 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||||||
11435 | |||||||||
11436 | // The result of comparisons is 'bool' in C++, 'int' in C. | ||||||||
11437 | return S.Context.getLogicalOperationType(); | ||||||||
11438 | } | ||||||||
11439 | |||||||||
11440 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | ||||||||
11441 | if (!NullE.get()->getType()->isAnyPointerType()) | ||||||||
11442 | return; | ||||||||
11443 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | ||||||||
11444 | if (!E.get()->getType()->isAnyPointerType() && | ||||||||
11445 | E.get()->isNullPointerConstant(Context, | ||||||||
11446 | Expr::NPC_ValueDependentIsNotNull) == | ||||||||
11447 | Expr::NPCK_ZeroExpression) { | ||||||||
11448 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | ||||||||
11449 | if (CL->getValue() == 0) | ||||||||
11450 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||||||
11451 | << NullValue | ||||||||
11452 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||||||
11453 | NullValue ? "NULL" : "(void *)0"); | ||||||||
11454 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | ||||||||
11455 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | ||||||||
11456 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | ||||||||
11457 | if (T == Context.CharTy) | ||||||||
11458 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||||||
11459 | << NullValue | ||||||||
11460 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||||||
11461 | NullValue ? "NULL" : "(void *)0"); | ||||||||
11462 | } | ||||||||
11463 | } | ||||||||
11464 | } | ||||||||
11465 | |||||||||
11466 | // C99 6.5.8, C++ [expr.rel] | ||||||||
11467 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
11468 | SourceLocation Loc, | ||||||||
11469 | BinaryOperatorKind Opc) { | ||||||||
11470 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | ||||||||
11471 | bool IsThreeWay = Opc == BO_Cmp; | ||||||||
11472 | bool IsOrdered = IsRelational || IsThreeWay; | ||||||||
11473 | auto IsAnyPointerType = [](ExprResult E) { | ||||||||
11474 | QualType Ty = E.get()->getType(); | ||||||||
11475 | return Ty->isPointerType() || Ty->isMemberPointerType(); | ||||||||
11476 | }; | ||||||||
11477 | |||||||||
11478 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | ||||||||
11479 | // type, array-to-pointer, ..., conversions are performed on both operands to | ||||||||
11480 | // bring them to their composite type. | ||||||||
11481 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | ||||||||
11482 | // any type-related checks. | ||||||||
11483 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | ||||||||
11484 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||||||
11485 | if (LHS.isInvalid()) | ||||||||
11486 | return QualType(); | ||||||||
11487 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||||||
11488 | if (RHS.isInvalid()) | ||||||||
11489 | return QualType(); | ||||||||
11490 | } else { | ||||||||
11491 | LHS = DefaultLvalueConversion(LHS.get()); | ||||||||
11492 | if (LHS.isInvalid()) | ||||||||
11493 | return QualType(); | ||||||||
11494 | RHS = DefaultLvalueConversion(RHS.get()); | ||||||||
11495 | if (RHS.isInvalid()) | ||||||||
11496 | return QualType(); | ||||||||
11497 | } | ||||||||
11498 | |||||||||
11499 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | ||||||||
11500 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | ||||||||
11501 | CheckPtrComparisonWithNullChar(LHS, RHS); | ||||||||
11502 | CheckPtrComparisonWithNullChar(RHS, LHS); | ||||||||
11503 | } | ||||||||
11504 | |||||||||
11505 | // Handle vector comparisons separately. | ||||||||
11506 | if (LHS.get()->getType()->isVectorType() || | ||||||||
11507 | RHS.get()->getType()->isVectorType()) | ||||||||
11508 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||||||
11509 | |||||||||
11510 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||||||
11511 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||||||
11512 | |||||||||
11513 | QualType LHSType = LHS.get()->getType(); | ||||||||
11514 | QualType RHSType = RHS.get()->getType(); | ||||||||
11515 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | ||||||||
11516 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | ||||||||
11517 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | ||||||||
11518 | |||||||||
11519 | const Expr::NullPointerConstantKind LHSNullKind = | ||||||||
11520 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||||||
11521 | const Expr::NullPointerConstantKind RHSNullKind = | ||||||||
11522 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||||||
11523 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | ||||||||
11524 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | ||||||||
11525 | |||||||||
11526 | auto computeResultTy = [&]() { | ||||||||
11527 | if (Opc != BO_Cmp) | ||||||||
11528 | return Context.getLogicalOperationType(); | ||||||||
11529 | assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11529, __PRETTY_FUNCTION__)); | ||||||||
11530 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()-> getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11530, __PRETTY_FUNCTION__)); | ||||||||
11531 | |||||||||
11532 | QualType CompositeTy = LHS.get()->getType(); | ||||||||
11533 | assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void> (0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11533, __PRETTY_FUNCTION__)); | ||||||||
11534 | |||||||||
11535 | Optional<ComparisonCategoryType> CCT = | ||||||||
11536 | getComparisonCategoryForBuiltinCmp(CompositeTy); | ||||||||
11537 | if (!CCT) | ||||||||
11538 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
11539 | |||||||||
11540 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | ||||||||
11541 | // P0946R0: Comparisons between a null pointer constant and an object | ||||||||
11542 | // pointer result in std::strong_equality, which is ill-formed under | ||||||||
11543 | // P1959R0. | ||||||||
11544 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | ||||||||
11545 | << (LHSIsNull ? LHS.get()->getSourceRange() | ||||||||
11546 | : RHS.get()->getSourceRange()); | ||||||||
11547 | return QualType(); | ||||||||
11548 | } | ||||||||
11549 | |||||||||
11550 | return CheckComparisonCategoryType( | ||||||||
11551 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | ||||||||
11552 | }; | ||||||||
11553 | |||||||||
11554 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | ||||||||
11555 | bool IsEquality = Opc == BO_EQ; | ||||||||
11556 | if (RHSIsNull) | ||||||||
11557 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | ||||||||
11558 | RHS.get()->getSourceRange()); | ||||||||
11559 | else | ||||||||
11560 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | ||||||||
11561 | LHS.get()->getSourceRange()); | ||||||||
11562 | } | ||||||||
11563 | |||||||||
11564 | if ((LHSType->isIntegerType() && !LHSIsNull) || | ||||||||
11565 | (RHSType->isIntegerType() && !RHSIsNull)) { | ||||||||
11566 | // Skip normal pointer conversion checks in this case; we have better | ||||||||
11567 | // diagnostics for this below. | ||||||||
11568 | } else if (getLangOpts().CPlusPlus) { | ||||||||
11569 | // Equality comparison of a function pointer to a void pointer is invalid, | ||||||||
11570 | // but we allow it as an extension. | ||||||||
11571 | // FIXME: If we really want to allow this, should it be part of composite | ||||||||
11572 | // pointer type computation so it works in conditionals too? | ||||||||
11573 | if (!IsOrdered && | ||||||||
11574 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | ||||||||
11575 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | ||||||||
11576 | // This is a gcc extension compatibility comparison. | ||||||||
11577 | // In a SFINAE context, we treat this as a hard error to maintain | ||||||||
11578 | // conformance with the C++ standard. | ||||||||
11579 | diagnoseFunctionPointerToVoidComparison( | ||||||||
11580 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | ||||||||
11581 | |||||||||
11582 | if (isSFINAEContext()) | ||||||||
11583 | return QualType(); | ||||||||
11584 | |||||||||
11585 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||||||
11586 | return computeResultTy(); | ||||||||
11587 | } | ||||||||
11588 | |||||||||
11589 | // C++ [expr.eq]p2: | ||||||||
11590 | // If at least one operand is a pointer [...] bring them to their | ||||||||
11591 | // composite pointer type. | ||||||||
11592 | // C++ [expr.spaceship]p6 | ||||||||
11593 | // If at least one of the operands is of pointer type, [...] bring them | ||||||||
11594 | // to their composite pointer type. | ||||||||
11595 | // C++ [expr.rel]p2: | ||||||||
11596 | // If both operands are pointers, [...] bring them to their composite | ||||||||
11597 | // pointer type. | ||||||||
11598 | // For <=>, the only valid non-pointer types are arrays and functions, and | ||||||||
11599 | // we already decayed those, so this is really the same as the relational | ||||||||
11600 | // comparison rule. | ||||||||
11601 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | ||||||||
11602 | (IsOrdered ? 2 : 1) && | ||||||||
11603 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | ||||||||
11604 | RHSType->isObjCObjectPointerType()))) { | ||||||||
11605 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||||||
11606 | return QualType(); | ||||||||
11607 | return computeResultTy(); | ||||||||
11608 | } | ||||||||
11609 | } else if (LHSType->isPointerType() && | ||||||||
11610 | RHSType->isPointerType()) { // C99 6.5.8p2 | ||||||||
11611 | // All of the following pointer-related warnings are GCC extensions, except | ||||||||
11612 | // when handling null pointer constants. | ||||||||
11613 | QualType LCanPointeeTy = | ||||||||
11614 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||||||
11615 | QualType RCanPointeeTy = | ||||||||
11616 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||||||
11617 | |||||||||
11618 | // C99 6.5.9p2 and C99 6.5.8p2 | ||||||||
11619 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | ||||||||
11620 | RCanPointeeTy.getUnqualifiedType())) { | ||||||||
11621 | if (IsRelational) { | ||||||||
11622 | // Pointers both need to point to complete or incomplete types | ||||||||
11623 | if ((LCanPointeeTy->isIncompleteType() != | ||||||||
11624 | RCanPointeeTy->isIncompleteType()) && | ||||||||
11625 | !getLangOpts().C11) { | ||||||||
11626 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | ||||||||
11627 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | ||||||||
11628 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | ||||||||
11629 | << RCanPointeeTy->isIncompleteType(); | ||||||||
11630 | } | ||||||||
11631 | if (LCanPointeeTy->isFunctionType()) { | ||||||||
11632 | // Valid unless a relational comparison of function pointers | ||||||||
11633 | Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) | ||||||||
11634 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||||||
11635 | << RHS.get()->getSourceRange(); | ||||||||
11636 | } | ||||||||
11637 | } | ||||||||
11638 | } else if (!IsRelational && | ||||||||
11639 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | ||||||||
11640 | // Valid unless comparison between non-null pointer and function pointer | ||||||||
11641 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | ||||||||
11642 | && !LHSIsNull && !RHSIsNull) | ||||||||
11643 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | ||||||||
11644 | /*isError*/false); | ||||||||
11645 | } else { | ||||||||
11646 | // Invalid | ||||||||
11647 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | ||||||||
11648 | } | ||||||||
11649 | if (LCanPointeeTy != RCanPointeeTy) { | ||||||||
11650 | // Treat NULL constant as a special case in OpenCL. | ||||||||
11651 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | ||||||||
11652 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | ||||||||
11653 | Diag(Loc, | ||||||||
11654 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||||||
11655 | << LHSType << RHSType << 0 /* comparison */ | ||||||||
11656 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||||||
11657 | } | ||||||||
11658 | } | ||||||||
11659 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | ||||||||
11660 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | ||||||||
11661 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | ||||||||
11662 | : CK_BitCast; | ||||||||
11663 | if (LHSIsNull && !RHSIsNull) | ||||||||
11664 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | ||||||||
11665 | else | ||||||||
11666 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | ||||||||
11667 | } | ||||||||
11668 | return computeResultTy(); | ||||||||
11669 | } | ||||||||
11670 | |||||||||
11671 | if (getLangOpts().CPlusPlus) { | ||||||||
11672 | // C++ [expr.eq]p4: | ||||||||
11673 | // Two operands of type std::nullptr_t or one operand of type | ||||||||
11674 | // std::nullptr_t and the other a null pointer constant compare equal. | ||||||||
11675 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | ||||||||
11676 | if (LHSType->isNullPtrType()) { | ||||||||
11677 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||||||
11678 | return computeResultTy(); | ||||||||
11679 | } | ||||||||
11680 | if (RHSType->isNullPtrType()) { | ||||||||
11681 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||||||
11682 | return computeResultTy(); | ||||||||
11683 | } | ||||||||
11684 | } | ||||||||
11685 | |||||||||
11686 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | ||||||||
11687 | // These aren't covered by the composite pointer type rules. | ||||||||
11688 | if (!IsOrdered && RHSType->isNullPtrType() && | ||||||||
11689 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | ||||||||
11690 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||||||
11691 | return computeResultTy(); | ||||||||
11692 | } | ||||||||
11693 | if (!IsOrdered && LHSType->isNullPtrType() && | ||||||||
11694 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | ||||||||
11695 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||||||
11696 | return computeResultTy(); | ||||||||
11697 | } | ||||||||
11698 | |||||||||
11699 | if (IsRelational && | ||||||||
11700 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | ||||||||
11701 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | ||||||||
11702 | // HACK: Relational comparison of nullptr_t against a pointer type is | ||||||||
11703 | // invalid per DR583, but we allow it within std::less<> and friends, | ||||||||
11704 | // since otherwise common uses of it break. | ||||||||
11705 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | ||||||||
11706 | // friends to have std::nullptr_t overload candidates. | ||||||||
11707 | DeclContext *DC = CurContext; | ||||||||
11708 | if (isa<FunctionDecl>(DC)) | ||||||||
11709 | DC = DC->getParent(); | ||||||||
11710 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | ||||||||
11711 | if (CTSD->isInStdNamespace() && | ||||||||
11712 | llvm::StringSwitch<bool>(CTSD->getName()) | ||||||||
11713 | .Cases("less", "less_equal", "greater", "greater_equal", true) | ||||||||
11714 | .Default(false)) { | ||||||||
11715 | if (RHSType->isNullPtrType()) | ||||||||
11716 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||||||
11717 | else | ||||||||
11718 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||||||
11719 | return computeResultTy(); | ||||||||
11720 | } | ||||||||
11721 | } | ||||||||
11722 | } | ||||||||
11723 | |||||||||
11724 | // C++ [expr.eq]p2: | ||||||||
11725 | // If at least one operand is a pointer to member, [...] bring them to | ||||||||
11726 | // their composite pointer type. | ||||||||
11727 | if (!IsOrdered && | ||||||||
11728 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | ||||||||
11729 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||||||
11730 | return QualType(); | ||||||||
11731 | else | ||||||||
11732 | return computeResultTy(); | ||||||||
11733 | } | ||||||||
11734 | } | ||||||||
11735 | |||||||||
11736 | // Handle block pointer types. | ||||||||
11737 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||||||
11738 | RHSType->isBlockPointerType()) { | ||||||||
11739 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||||||
11740 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||||||
11741 | |||||||||
11742 | if (!LHSIsNull && !RHSIsNull && | ||||||||
11743 | !Context.typesAreCompatible(lpointee, rpointee)) { | ||||||||
11744 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||||||
11745 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||||||
11746 | << RHS.get()->getSourceRange(); | ||||||||
11747 | } | ||||||||
11748 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||||||
11749 | return computeResultTy(); | ||||||||
11750 | } | ||||||||
11751 | |||||||||
11752 | // Allow block pointers to be compared with null pointer constants. | ||||||||
11753 | if (!IsOrdered | ||||||||
11754 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | ||||||||
11755 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | ||||||||
11756 | if (!LHSIsNull && !RHSIsNull) { | ||||||||
11757 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | ||||||||
11758 | ->getPointeeType()->isVoidType()) | ||||||||
11759 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | ||||||||
11760 | ->getPointeeType()->isVoidType()))) | ||||||||
11761 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||||||
11762 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||||||
11763 | << RHS.get()->getSourceRange(); | ||||||||
11764 | } | ||||||||
11765 | if (LHSIsNull && !RHSIsNull) | ||||||||
11766 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||||||
11767 | RHSType->isPointerType() ? CK_BitCast | ||||||||
11768 | : CK_AnyPointerToBlockPointerCast); | ||||||||
11769 | else | ||||||||
11770 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||||||
11771 | LHSType->isPointerType() ? CK_BitCast | ||||||||
11772 | : CK_AnyPointerToBlockPointerCast); | ||||||||
11773 | return computeResultTy(); | ||||||||
11774 | } | ||||||||
11775 | |||||||||
11776 | if (LHSType->isObjCObjectPointerType() || | ||||||||
11777 | RHSType->isObjCObjectPointerType()) { | ||||||||
11778 | const PointerType *LPT = LHSType->getAs<PointerType>(); | ||||||||
11779 | const PointerType *RPT = RHSType->getAs<PointerType>(); | ||||||||
11780 | if (LPT || RPT) { | ||||||||
11781 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | ||||||||
11782 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | ||||||||
11783 | |||||||||
11784 | if (!LPtrToVoid && !RPtrToVoid && | ||||||||
11785 | !Context.typesAreCompatible(LHSType, RHSType)) { | ||||||||
11786 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||||||
11787 | /*isError*/false); | ||||||||
11788 | } | ||||||||
11789 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | ||||||||
11790 | // the RHS, but we have test coverage for this behavior. | ||||||||
11791 | // FIXME: Consider using convertPointersToCompositeType in C++. | ||||||||
11792 | if (LHSIsNull && !RHSIsNull) { | ||||||||
11793 | Expr *E = LHS.get(); | ||||||||
11794 | if (getLangOpts().ObjCAutoRefCount) | ||||||||
11795 | CheckObjCConversion(SourceRange(), RHSType, E, | ||||||||
11796 | CCK_ImplicitConversion); | ||||||||
11797 | LHS = ImpCastExprToType(E, RHSType, | ||||||||
11798 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||||||
11799 | } | ||||||||
11800 | else { | ||||||||
11801 | Expr *E = RHS.get(); | ||||||||
11802 | if (getLangOpts().ObjCAutoRefCount) | ||||||||
11803 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | ||||||||
11804 | /*Diagnose=*/true, | ||||||||
11805 | /*DiagnoseCFAudited=*/false, Opc); | ||||||||
11806 | RHS = ImpCastExprToType(E, LHSType, | ||||||||
11807 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||||||
11808 | } | ||||||||
11809 | return computeResultTy(); | ||||||||
11810 | } | ||||||||
11811 | if (LHSType->isObjCObjectPointerType() && | ||||||||
11812 | RHSType->isObjCObjectPointerType()) { | ||||||||
11813 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | ||||||||
11814 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||||||
11815 | /*isError*/false); | ||||||||
11816 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | ||||||||
11817 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | ||||||||
11818 | |||||||||
11819 | if (LHSIsNull && !RHSIsNull) | ||||||||
11820 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||||||
11821 | else | ||||||||
11822 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||||||
11823 | return computeResultTy(); | ||||||||
11824 | } | ||||||||
11825 | |||||||||
11826 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||||||
11827 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||||||
11828 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||||||
11829 | CK_BlockPointerToObjCPointerCast); | ||||||||
11830 | return computeResultTy(); | ||||||||
11831 | } else if (!IsOrdered && | ||||||||
11832 | LHSType->isBlockCompatibleObjCPointerType(Context) && | ||||||||
11833 | RHSType->isBlockPointerType()) { | ||||||||
11834 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||||||
11835 | CK_BlockPointerToObjCPointerCast); | ||||||||
11836 | return computeResultTy(); | ||||||||
11837 | } | ||||||||
11838 | } | ||||||||
11839 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | ||||||||
11840 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | ||||||||
11841 | unsigned DiagID = 0; | ||||||||
11842 | bool isError = false; | ||||||||
11843 | if (LangOpts.DebuggerSupport) { | ||||||||
11844 | // Under a debugger, allow the comparison of pointers to integers, | ||||||||
11845 | // since users tend to want to compare addresses. | ||||||||
11846 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | ||||||||
11847 | (RHSIsNull && RHSType->isIntegerType())) { | ||||||||
11848 | if (IsOrdered) { | ||||||||
11849 | isError = getLangOpts().CPlusPlus; | ||||||||
11850 | DiagID = | ||||||||
11851 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | ||||||||
11852 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | ||||||||
11853 | } | ||||||||
11854 | } else if (getLangOpts().CPlusPlus) { | ||||||||
11855 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | ||||||||
11856 | isError = true; | ||||||||
11857 | } else if (IsOrdered) | ||||||||
11858 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | ||||||||
11859 | else | ||||||||
11860 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | ||||||||
11861 | |||||||||
11862 | if (DiagID) { | ||||||||
11863 | Diag(Loc, DiagID) | ||||||||
11864 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||||||
11865 | << RHS.get()->getSourceRange(); | ||||||||
11866 | if (isError) | ||||||||
11867 | return QualType(); | ||||||||
11868 | } | ||||||||
11869 | |||||||||
11870 | if (LHSType->isIntegerType()) | ||||||||
11871 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||||||
11872 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||||||
11873 | else | ||||||||
11874 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||||||
11875 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||||||
11876 | return computeResultTy(); | ||||||||
11877 | } | ||||||||
11878 | |||||||||
11879 | // Handle block pointers. | ||||||||
11880 | if (!IsOrdered && RHSIsNull | ||||||||
11881 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | ||||||||
11882 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||||||
11883 | return computeResultTy(); | ||||||||
11884 | } | ||||||||
11885 | if (!IsOrdered && LHSIsNull | ||||||||
11886 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | ||||||||
11887 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||||||
11888 | return computeResultTy(); | ||||||||
11889 | } | ||||||||
11890 | |||||||||
11891 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||||||
11892 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | ||||||||
11893 | return computeResultTy(); | ||||||||
11894 | } | ||||||||
11895 | |||||||||
11896 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | ||||||||
11897 | return computeResultTy(); | ||||||||
11898 | } | ||||||||
11899 | |||||||||
11900 | if (LHSIsNull && RHSType->isQueueT()) { | ||||||||
11901 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||||||
11902 | return computeResultTy(); | ||||||||
11903 | } | ||||||||
11904 | |||||||||
11905 | if (LHSType->isQueueT() && RHSIsNull) { | ||||||||
11906 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||||||
11907 | return computeResultTy(); | ||||||||
11908 | } | ||||||||
11909 | } | ||||||||
11910 | |||||||||
11911 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
11912 | } | ||||||||
11913 | |||||||||
11914 | // Return a signed ext_vector_type that is of identical size and number of | ||||||||
11915 | // elements. For floating point vectors, return an integer type of identical | ||||||||
11916 | // size and number of elements. In the non ext_vector_type case, search from | ||||||||
11917 | // the largest type to the smallest type to avoid cases where long long == long, | ||||||||
11918 | // where long gets picked over long long. | ||||||||
11919 | QualType Sema::GetSignedVectorType(QualType V) { | ||||||||
11920 | const VectorType *VTy = V->castAs<VectorType>(); | ||||||||
11921 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | ||||||||
11922 | |||||||||
11923 | if (isa<ExtVectorType>(VTy)) { | ||||||||
11924 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | ||||||||
11925 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | ||||||||
11926 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||||||
11927 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | ||||||||
11928 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||||||
11929 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | ||||||||
11930 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||||||
11931 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | ||||||||
11932 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11933, __PRETTY_FUNCTION__)) | ||||||||
11933 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11933, __PRETTY_FUNCTION__)); | ||||||||
11934 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | ||||||||
11935 | } | ||||||||
11936 | |||||||||
11937 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | ||||||||
11938 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | ||||||||
11939 | VectorType::GenericVector); | ||||||||
11940 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||||||
11941 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | ||||||||
11942 | VectorType::GenericVector); | ||||||||
11943 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||||||
11944 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | ||||||||
11945 | VectorType::GenericVector); | ||||||||
11946 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||||||
11947 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | ||||||||
11948 | VectorType::GenericVector); | ||||||||
11949 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11950, __PRETTY_FUNCTION__)) | ||||||||
11950 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11950, __PRETTY_FUNCTION__)); | ||||||||
11951 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | ||||||||
11952 | VectorType::GenericVector); | ||||||||
11953 | } | ||||||||
11954 | |||||||||
11955 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | ||||||||
11956 | /// operates on extended vector types. Instead of producing an IntTy result, | ||||||||
11957 | /// like a scalar comparison, a vector comparison produces a vector of integer | ||||||||
11958 | /// types. | ||||||||
11959 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
11960 | SourceLocation Loc, | ||||||||
11961 | BinaryOperatorKind Opc) { | ||||||||
11962 | if (Opc == BO_Cmp) { | ||||||||
11963 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||||||
11964 | return QualType(); | ||||||||
11965 | } | ||||||||
11966 | |||||||||
11967 | // Check to make sure we're operating on vectors of the same type and width, | ||||||||
11968 | // Allowing one side to be a scalar of element type. | ||||||||
11969 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | ||||||||
11970 | /*AllowBothBool*/true, | ||||||||
11971 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||||||
11972 | if (vType.isNull()) | ||||||||
11973 | return vType; | ||||||||
11974 | |||||||||
11975 | QualType LHSType = LHS.get()->getType(); | ||||||||
11976 | |||||||||
11977 | // If AltiVec, the comparison results in a numeric type, i.e. | ||||||||
11978 | // bool for C++, int for C | ||||||||
11979 | if (getLangOpts().AltiVec && | ||||||||
11980 | vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) | ||||||||
11981 | return Context.getLogicalOperationType(); | ||||||||
11982 | |||||||||
11983 | // For non-floating point types, check for self-comparisons of the form | ||||||||
11984 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||||||
11985 | // often indicate logic errors in the program. | ||||||||
11986 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||||||
11987 | |||||||||
11988 | // Check for comparisons of floating point operands using != and ==. | ||||||||
11989 | if (BinaryOperator::isEqualityOp(Opc) && | ||||||||
11990 | LHSType->hasFloatingRepresentation()) { | ||||||||
11991 | assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast <void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 11991, __PRETTY_FUNCTION__)); | ||||||||
11992 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||||||
11993 | } | ||||||||
11994 | |||||||||
11995 | // Return a signed type for the vector. | ||||||||
11996 | return GetSignedVectorType(vType); | ||||||||
11997 | } | ||||||||
11998 | |||||||||
11999 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | ||||||||
12000 | const ExprResult &XorRHS, | ||||||||
12001 | const SourceLocation Loc) { | ||||||||
12002 | // Do not diagnose macros. | ||||||||
12003 | if (Loc.isMacroID()) | ||||||||
12004 | return; | ||||||||
12005 | |||||||||
12006 | bool Negative = false; | ||||||||
12007 | bool ExplicitPlus = false; | ||||||||
12008 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | ||||||||
12009 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | ||||||||
12010 | |||||||||
12011 | if (!LHSInt) | ||||||||
12012 | return; | ||||||||
12013 | if (!RHSInt) { | ||||||||
12014 | // Check negative literals. | ||||||||
12015 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | ||||||||
12016 | UnaryOperatorKind Opc = UO->getOpcode(); | ||||||||
12017 | if (Opc != UO_Minus && Opc != UO_Plus) | ||||||||
12018 | return; | ||||||||
12019 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | ||||||||
12020 | if (!RHSInt) | ||||||||
12021 | return; | ||||||||
12022 | Negative = (Opc == UO_Minus); | ||||||||
12023 | ExplicitPlus = !Negative; | ||||||||
12024 | } else { | ||||||||
12025 | return; | ||||||||
12026 | } | ||||||||
12027 | } | ||||||||
12028 | |||||||||
12029 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | ||||||||
12030 | llvm::APInt RightSideValue = RHSInt->getValue(); | ||||||||
12031 | if (LeftSideValue != 2 && LeftSideValue != 10) | ||||||||
12032 | return; | ||||||||
12033 | |||||||||
12034 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | ||||||||
12035 | return; | ||||||||
12036 | |||||||||
12037 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | ||||||||
12038 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | ||||||||
12039 | llvm::StringRef ExprStr = | ||||||||
12040 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | ||||||||
12041 | |||||||||
12042 | CharSourceRange XorRange = | ||||||||
12043 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||||||
12044 | llvm::StringRef XorStr = | ||||||||
12045 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | ||||||||
12046 | // Do not diagnose if xor keyword/macro is used. | ||||||||
12047 | if (XorStr == "xor") | ||||||||
12048 | return; | ||||||||
12049 | |||||||||
12050 | std::string LHSStr = std::string(Lexer::getSourceText( | ||||||||
12051 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | ||||||||
12052 | S.getSourceManager(), S.getLangOpts())); | ||||||||
12053 | std::string RHSStr = std::string(Lexer::getSourceText( | ||||||||
12054 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | ||||||||
12055 | S.getSourceManager(), S.getLangOpts())); | ||||||||
12056 | |||||||||
12057 | if (Negative) { | ||||||||
12058 | RightSideValue = -RightSideValue; | ||||||||
12059 | RHSStr = "-" + RHSStr; | ||||||||
12060 | } else if (ExplicitPlus) { | ||||||||
12061 | RHSStr = "+" + RHSStr; | ||||||||
12062 | } | ||||||||
12063 | |||||||||
12064 | StringRef LHSStrRef = LHSStr; | ||||||||
12065 | StringRef RHSStrRef = RHSStr; | ||||||||
12066 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | ||||||||
12067 | // literals. | ||||||||
12068 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | ||||||||
12069 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | ||||||||
12070 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | ||||||||
12071 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | ||||||||
12072 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | ||||||||
12073 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | ||||||||
12074 | LHSStrRef.find('\'') != StringRef::npos || | ||||||||
12075 | RHSStrRef.find('\'') != StringRef::npos) | ||||||||
12076 | return; | ||||||||
12077 | |||||||||
12078 | bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | ||||||||
12079 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | ||||||||
12080 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | ||||||||
12081 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | ||||||||
12082 | std::string SuggestedExpr = "1 << " + RHSStr; | ||||||||
12083 | bool Overflow = false; | ||||||||
12084 | llvm::APInt One = (LeftSideValue - 1); | ||||||||
12085 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | ||||||||
12086 | if (Overflow) { | ||||||||
12087 | if (RightSideIntValue < 64) | ||||||||
12088 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||||||
12089 | << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) | ||||||||
12090 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | ||||||||
12091 | else if (RightSideIntValue == 64) | ||||||||
12092 | S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); | ||||||||
12093 | else | ||||||||
12094 | return; | ||||||||
12095 | } else { | ||||||||
12096 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | ||||||||
12097 | << ExprStr << XorValue.toString(10, true) << SuggestedExpr | ||||||||
12098 | << PowValue.toString(10, true) | ||||||||
12099 | << FixItHint::CreateReplacement( | ||||||||
12100 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | ||||||||
12101 | } | ||||||||
12102 | |||||||||
12103 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; | ||||||||
12104 | } else if (LeftSideValue == 10) { | ||||||||
12105 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | ||||||||
12106 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||||||
12107 | << ExprStr << XorValue.toString(10, true) << SuggestedValue | ||||||||
12108 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | ||||||||
12109 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; | ||||||||
12110 | } | ||||||||
12111 | } | ||||||||
12112 | |||||||||
12113 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
12114 | SourceLocation Loc) { | ||||||||
12115 | // Ensure that either both operands are of the same vector type, or | ||||||||
12116 | // one operand is of a vector type and the other is of its element type. | ||||||||
12117 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | ||||||||
12118 | /*AllowBothBool*/true, | ||||||||
12119 | /*AllowBoolConversions*/false); | ||||||||
12120 | if (vType.isNull()) | ||||||||
12121 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12122 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && | ||||||||
12123 | !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) | ||||||||
12124 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12125 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | ||||||||
12126 | // usage of the logical operators && and || with vectors in C. This | ||||||||
12127 | // check could be notionally dropped. | ||||||||
12128 | if (!getLangOpts().CPlusPlus && | ||||||||
12129 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | ||||||||
12130 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | ||||||||
12131 | |||||||||
12132 | return GetSignedVectorType(LHS.get()->getType()); | ||||||||
12133 | } | ||||||||
12134 | |||||||||
12135 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
12136 | SourceLocation Loc, | ||||||||
12137 | bool IsCompAssign) { | ||||||||
12138 | if (!IsCompAssign) { | ||||||||
12139 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||||||
12140 | if (LHS.isInvalid()) | ||||||||
12141 | return QualType(); | ||||||||
12142 | } | ||||||||
12143 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||||||
12144 | if (RHS.isInvalid()) | ||||||||
12145 | return QualType(); | ||||||||
12146 | |||||||||
12147 | // For conversion purposes, we ignore any qualifiers. | ||||||||
12148 | // For example, "const float" and "float" are equivalent. | ||||||||
12149 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||||||
12150 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||||||
12151 | |||||||||
12152 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | ||||||||
12153 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | ||||||||
12154 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12154, __PRETTY_FUNCTION__)); | ||||||||
12155 | |||||||||
12156 | if (Context.hasSameType(LHSType, RHSType)) | ||||||||
12157 | return LHSType; | ||||||||
12158 | |||||||||
12159 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | ||||||||
12160 | // case we have to return InvalidOperands. | ||||||||
12161 | ExprResult OriginalLHS = LHS; | ||||||||
12162 | ExprResult OriginalRHS = RHS; | ||||||||
12163 | if (LHSMatType && !RHSMatType) { | ||||||||
12164 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | ||||||||
12165 | if (!RHS.isInvalid()) | ||||||||
12166 | return LHSType; | ||||||||
12167 | |||||||||
12168 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||||||
12169 | } | ||||||||
12170 | |||||||||
12171 | if (!LHSMatType && RHSMatType) { | ||||||||
12172 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | ||||||||
12173 | if (!LHS.isInvalid()) | ||||||||
12174 | return RHSType; | ||||||||
12175 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||||||
12176 | } | ||||||||
12177 | |||||||||
12178 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12179 | } | ||||||||
12180 | |||||||||
12181 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
12182 | SourceLocation Loc, | ||||||||
12183 | bool IsCompAssign) { | ||||||||
12184 | if (!IsCompAssign) { | ||||||||
12185 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||||||
12186 | if (LHS.isInvalid()) | ||||||||
12187 | return QualType(); | ||||||||
12188 | } | ||||||||
12189 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||||||
12190 | if (RHS.isInvalid()) | ||||||||
12191 | return QualType(); | ||||||||
12192 | |||||||||
12193 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||||||
12194 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||||||
12195 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12195, __PRETTY_FUNCTION__)); | ||||||||
12196 | |||||||||
12197 | if (LHSMatType && RHSMatType) { | ||||||||
12198 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | ||||||||
12199 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12200 | |||||||||
12201 | if (!Context.hasSameType(LHSMatType->getElementType(), | ||||||||
12202 | RHSMatType->getElementType())) | ||||||||
12203 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12204 | |||||||||
12205 | return Context.getConstantMatrixType(LHSMatType->getElementType(), | ||||||||
12206 | LHSMatType->getNumRows(), | ||||||||
12207 | RHSMatType->getNumColumns()); | ||||||||
12208 | } | ||||||||
12209 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||||||
12210 | } | ||||||||
12211 | |||||||||
12212 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
12213 | SourceLocation Loc, | ||||||||
12214 | BinaryOperatorKind Opc) { | ||||||||
12215 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||||||
12216 | |||||||||
12217 | bool IsCompAssign = | ||||||||
12218 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | ||||||||
12219 | |||||||||
12220 | if (LHS.get()->getType()->isVectorType() || | ||||||||
12221 | RHS.get()->getType()->isVectorType()) { | ||||||||
12222 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||||||
12223 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||||||
12224 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||||||
12225 | /*AllowBothBool*/true, | ||||||||
12226 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||||||
12227 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12228 | } | ||||||||
12229 | |||||||||
12230 | if (Opc == BO_And) | ||||||||
12231 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||||||
12232 | |||||||||
12233 | if (LHS.get()->getType()->hasFloatingRepresentation() || | ||||||||
12234 | RHS.get()->getType()->hasFloatingRepresentation()) | ||||||||
12235 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12236 | |||||||||
12237 | ExprResult LHSResult = LHS, RHSResult = RHS; | ||||||||
12238 | QualType compType = UsualArithmeticConversions( | ||||||||
12239 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | ||||||||
12240 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | ||||||||
12241 | return QualType(); | ||||||||
12242 | LHS = LHSResult.get(); | ||||||||
12243 | RHS = RHSResult.get(); | ||||||||
12244 | |||||||||
12245 | if (Opc == BO_Xor) | ||||||||
12246 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | ||||||||
12247 | |||||||||
12248 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | ||||||||
12249 | return compType; | ||||||||
12250 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12251 | } | ||||||||
12252 | |||||||||
12253 | // C99 6.5.[13,14] | ||||||||
12254 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||||||
12255 | SourceLocation Loc, | ||||||||
12256 | BinaryOperatorKind Opc) { | ||||||||
12257 | // Check vector operands differently. | ||||||||
12258 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | ||||||||
12259 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | ||||||||
12260 | |||||||||
12261 | bool EnumConstantInBoolContext = false; | ||||||||
12262 | for (const ExprResult &HS : {LHS, RHS}) { | ||||||||
12263 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | ||||||||
12264 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | ||||||||
12265 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | ||||||||
12266 | EnumConstantInBoolContext = true; | ||||||||
12267 | } | ||||||||
12268 | } | ||||||||
12269 | |||||||||
12270 | if (EnumConstantInBoolContext) | ||||||||
12271 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | ||||||||
12272 | |||||||||
12273 | // Diagnose cases where the user write a logical and/or but probably meant a | ||||||||
12274 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | ||||||||
12275 | // is a constant. | ||||||||
12276 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | ||||||||
12277 | !LHS.get()->getType()->isBooleanType() && | ||||||||
12278 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | ||||||||
12279 | // Don't warn in macros or template instantiations. | ||||||||
12280 | !Loc.isMacroID() && !inTemplateInstantiation()) { | ||||||||
12281 | // If the RHS can be constant folded, and if it constant folds to something | ||||||||
12282 | // that isn't 0 or 1 (which indicate a potential logical operation that | ||||||||
12283 | // happened to fold to true/false) then warn. | ||||||||
12284 | // Parens on the RHS are ignored. | ||||||||
12285 | Expr::EvalResult EVResult; | ||||||||
12286 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | ||||||||
12287 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||||||
12288 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | ||||||||
12289 | !RHS.get()->getExprLoc().isMacroID()) || | ||||||||
12290 | (Result != 0 && Result != 1)) { | ||||||||
12291 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | ||||||||
12292 | << RHS.get()->getSourceRange() | ||||||||
12293 | << (Opc == BO_LAnd ? "&&" : "||"); | ||||||||
12294 | // Suggest replacing the logical operator with the bitwise version | ||||||||
12295 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | ||||||||
12296 | << (Opc == BO_LAnd ? "&" : "|") | ||||||||
12297 | << FixItHint::CreateReplacement(SourceRange( | ||||||||
12298 | Loc, getLocForEndOfToken(Loc)), | ||||||||
12299 | Opc == BO_LAnd ? "&" : "|"); | ||||||||
12300 | if (Opc == BO_LAnd) | ||||||||
12301 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | ||||||||
12302 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | ||||||||
12303 | << FixItHint::CreateRemoval( | ||||||||
12304 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | ||||||||
12305 | RHS.get()->getEndLoc())); | ||||||||
12306 | } | ||||||||
12307 | } | ||||||||
12308 | } | ||||||||
12309 | |||||||||
12310 | if (!Context.getLangOpts().CPlusPlus) { | ||||||||
12311 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | ||||||||
12312 | // not operate on the built-in scalar and vector float types. | ||||||||
12313 | if (Context.getLangOpts().OpenCL && | ||||||||
12314 | Context.getLangOpts().OpenCLVersion < 120) { | ||||||||
12315 | if (LHS.get()->getType()->isFloatingType() || | ||||||||
12316 | RHS.get()->getType()->isFloatingType()) | ||||||||
12317 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12318 | } | ||||||||
12319 | |||||||||
12320 | LHS = UsualUnaryConversions(LHS.get()); | ||||||||
12321 | if (LHS.isInvalid()) | ||||||||
12322 | return QualType(); | ||||||||
12323 | |||||||||
12324 | RHS = UsualUnaryConversions(RHS.get()); | ||||||||
12325 | if (RHS.isInvalid()) | ||||||||
12326 | return QualType(); | ||||||||
12327 | |||||||||
12328 | if (!LHS.get()->getType()->isScalarType() || | ||||||||
12329 | !RHS.get()->getType()->isScalarType()) | ||||||||
12330 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12331 | |||||||||
12332 | return Context.IntTy; | ||||||||
12333 | } | ||||||||
12334 | |||||||||
12335 | // The following is safe because we only use this method for | ||||||||
12336 | // non-overloadable operands. | ||||||||
12337 | |||||||||
12338 | // C++ [expr.log.and]p1 | ||||||||
12339 | // C++ [expr.log.or]p1 | ||||||||
12340 | // The operands are both contextually converted to type bool. | ||||||||
12341 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | ||||||||
12342 | if (LHSRes.isInvalid()) | ||||||||
12343 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12344 | LHS = LHSRes; | ||||||||
12345 | |||||||||
12346 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | ||||||||
12347 | if (RHSRes.isInvalid()) | ||||||||
12348 | return InvalidOperands(Loc, LHS, RHS); | ||||||||
12349 | RHS = RHSRes; | ||||||||
12350 | |||||||||
12351 | // C++ [expr.log.and]p2 | ||||||||
12352 | // C++ [expr.log.or]p2 | ||||||||
12353 | // The result is a bool. | ||||||||
12354 | return Context.BoolTy; | ||||||||
12355 | } | ||||||||
12356 | |||||||||
12357 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | ||||||||
12358 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||||||
12359 | if (!ME) return false; | ||||||||
12360 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | ||||||||
12361 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | ||||||||
12362 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | ||||||||
12363 | if (!Base) return false; | ||||||||
12364 | return Base->getMethodDecl() != nullptr; | ||||||||
12365 | } | ||||||||
12366 | |||||||||
12367 | /// Is the given expression (which must be 'const') a reference to a | ||||||||
12368 | /// variable which was originally non-const, but which has become | ||||||||
12369 | /// 'const' due to being captured within a block? | ||||||||
12370 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | ||||||||
12371 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | ||||||||
12372 | assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified ()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12372, __PRETTY_FUNCTION__)); | ||||||||
12373 | E = E->IgnoreParens(); | ||||||||
12374 | |||||||||
12375 | // Must be a reference to a declaration from an enclosing scope. | ||||||||
12376 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||||||
12377 | if (!DRE) return NCCK_None; | ||||||||
12378 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | ||||||||
12379 | |||||||||
12380 | // The declaration must be a variable which is not declared 'const'. | ||||||||
12381 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | ||||||||
12382 | if (!var) return NCCK_None; | ||||||||
12383 | if (var->getType().isConstQualified()) return NCCK_None; | ||||||||
12384 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?" ) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12384, __PRETTY_FUNCTION__)); | ||||||||
12385 | |||||||||
12386 | // Decide whether the first capture was for a block or a lambda. | ||||||||
12387 | DeclContext *DC = S.CurContext, *Prev = nullptr; | ||||||||
12388 | // Decide whether the first capture was for a block or a lambda. | ||||||||
12389 | while (DC) { | ||||||||
12390 | // For init-capture, it is possible that the variable belongs to the | ||||||||
12391 | // template pattern of the current context. | ||||||||
12392 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | ||||||||
12393 | if (var->isInitCapture() && | ||||||||
12394 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | ||||||||
12395 | break; | ||||||||
12396 | if (DC == var->getDeclContext()) | ||||||||
12397 | break; | ||||||||
12398 | Prev = DC; | ||||||||
12399 | DC = DC->getParent(); | ||||||||
12400 | } | ||||||||
12401 | // Unless we have an init-capture, we've gone one step too far. | ||||||||
12402 | if (!var->isInitCapture()) | ||||||||
12403 | DC = Prev; | ||||||||
12404 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | ||||||||
12405 | } | ||||||||
12406 | |||||||||
12407 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | ||||||||
12408 | Ty = Ty.getNonReferenceType(); | ||||||||
12409 | if (IsDereference && Ty->isPointerType()) | ||||||||
12410 | Ty = Ty->getPointeeType(); | ||||||||
12411 | return !Ty.isConstQualified(); | ||||||||
12412 | } | ||||||||
12413 | |||||||||
12414 | // Update err_typecheck_assign_const and note_typecheck_assign_const | ||||||||
12415 | // when this enum is changed. | ||||||||
12416 | enum { | ||||||||
12417 | ConstFunction, | ||||||||
12418 | ConstVariable, | ||||||||
12419 | ConstMember, | ||||||||
12420 | ConstMethod, | ||||||||
12421 | NestedConstMember, | ||||||||
12422 | ConstUnknown, // Keep as last element | ||||||||
12423 | }; | ||||||||
12424 | |||||||||
12425 | /// Emit the "read-only variable not assignable" error and print notes to give | ||||||||
12426 | /// more information about why the variable is not assignable, such as pointing | ||||||||
12427 | /// to the declaration of a const variable, showing that a method is const, or | ||||||||
12428 | /// that the function is returning a const reference. | ||||||||
12429 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | ||||||||
12430 | SourceLocation Loc) { | ||||||||
12431 | SourceRange ExprRange = E->getSourceRange(); | ||||||||
12432 | |||||||||
12433 | // Only emit one error on the first const found. All other consts will emit | ||||||||
12434 | // a note to the error. | ||||||||
12435 | bool DiagnosticEmitted = false; | ||||||||
12436 | |||||||||
12437 | // Track if the current expression is the result of a dereference, and if the | ||||||||
12438 | // next checked expression is the result of a dereference. | ||||||||
12439 | bool IsDereference = false; | ||||||||
12440 | bool NextIsDereference = false; | ||||||||
12441 | |||||||||
12442 | // Loop to process MemberExpr chains. | ||||||||
12443 | while (true) { | ||||||||
12444 | IsDereference = NextIsDereference; | ||||||||
12445 | |||||||||
12446 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | ||||||||
12447 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||||||
12448 | NextIsDereference = ME->isArrow(); | ||||||||
12449 | const ValueDecl *VD = ME->getMemberDecl(); | ||||||||
12450 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | ||||||||
12451 | // Mutable fields can be modified even if the class is const. | ||||||||
12452 | if (Field->isMutable()) { | ||||||||
12453 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted." ) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12453, __PRETTY_FUNCTION__)); | ||||||||
12454 | break; | ||||||||
12455 | } | ||||||||
12456 | |||||||||
12457 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | ||||||||
12458 | if (!DiagnosticEmitted) { | ||||||||
12459 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||||||
12460 | << ExprRange << ConstMember << false /*static*/ << Field | ||||||||
12461 | << Field->getType(); | ||||||||
12462 | DiagnosticEmitted = true; | ||||||||
12463 | } | ||||||||
12464 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||||||
12465 | << ConstMember << false /*static*/ << Field << Field->getType() | ||||||||
12466 | << Field->getSourceRange(); | ||||||||
12467 | } | ||||||||
12468 | E = ME->getBase(); | ||||||||
12469 | continue; | ||||||||
12470 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | ||||||||
12471 | if (VDecl->getType().isConstQualified()) { | ||||||||
12472 | if (!DiagnosticEmitted) { | ||||||||
12473 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||||||
12474 | << ExprRange << ConstMember << true /*static*/ << VDecl | ||||||||
12475 | << VDecl->getType(); | ||||||||
12476 | DiagnosticEmitted = true; | ||||||||
12477 | } | ||||||||
12478 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||||||
12479 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | ||||||||
12480 | << VDecl->getSourceRange(); | ||||||||
12481 | } | ||||||||
12482 | // Static fields do not inherit constness from parents. | ||||||||
12483 | break; | ||||||||
12484 | } | ||||||||
12485 | break; // End MemberExpr | ||||||||
12486 | } else if (const ArraySubscriptExpr *ASE = | ||||||||
12487 | dyn_cast<ArraySubscriptExpr>(E)) { | ||||||||
12488 | E = ASE->getBase()->IgnoreParenImpCasts(); | ||||||||
12489 | continue; | ||||||||
12490 | } else if (const ExtVectorElementExpr *EVE = | ||||||||
12491 | dyn_cast<ExtVectorElementExpr>(E)) { | ||||||||
12492 | E = EVE->getBase()->IgnoreParenImpCasts(); | ||||||||
12493 | continue; | ||||||||
12494 | } | ||||||||
12495 | break; | ||||||||
12496 | } | ||||||||
12497 | |||||||||
12498 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||||||
12499 | // Function calls | ||||||||
12500 | const FunctionDecl *FD = CE->getDirectCallee(); | ||||||||
12501 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | ||||||||
12502 | if (!DiagnosticEmitted) { | ||||||||
12503 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||||||
12504 | << ConstFunction << FD; | ||||||||
12505 | DiagnosticEmitted = true; | ||||||||
12506 | } | ||||||||
12507 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | ||||||||
12508 | diag::note_typecheck_assign_const) | ||||||||
12509 | << ConstFunction << FD << FD->getReturnType() | ||||||||
12510 | << FD->getReturnTypeSourceRange(); | ||||||||
12511 | } | ||||||||
12512 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||||||
12513 | // Point to variable declaration. | ||||||||
12514 | if (const ValueDecl *VD = DRE->getDecl()) { | ||||||||
12515 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | ||||||||
12516 | if (!DiagnosticEmitted) { | ||||||||
12517 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||||||
12518 | << ExprRange << ConstVariable << VD << VD->getType(); | ||||||||
12519 | DiagnosticEmitted = true; | ||||||||
12520 | } | ||||||||
12521 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||||||
12522 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | ||||||||
12523 | } | ||||||||
12524 | } | ||||||||
12525 | } else if (isa<CXXThisExpr>(E)) { | ||||||||
12526 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | ||||||||
12527 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | ||||||||
12528 | if (MD->isConst()) { | ||||||||
12529 | if (!DiagnosticEmitted) { | ||||||||
12530 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||||||
12531 | << ConstMethod << MD; | ||||||||
12532 | DiagnosticEmitted = true; | ||||||||
12533 | } | ||||||||
12534 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | ||||||||
12535 | << ConstMethod << MD << MD->getSourceRange(); | ||||||||
12536 | } | ||||||||
12537 | } | ||||||||
12538 | } | ||||||||
12539 | } | ||||||||
12540 | |||||||||
12541 | if (DiagnosticEmitted) | ||||||||
12542 | return; | ||||||||
12543 | |||||||||
12544 | // Can't determine a more specific message, so display the generic error. | ||||||||
12545 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | ||||||||
12546 | } | ||||||||
12547 | |||||||||
12548 | enum OriginalExprKind { | ||||||||
12549 | OEK_Variable, | ||||||||
12550 | OEK_Member, | ||||||||
12551 | OEK_LValue | ||||||||
12552 | }; | ||||||||
12553 | |||||||||
12554 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | ||||||||
12555 | const RecordType *Ty, | ||||||||
12556 | SourceLocation Loc, SourceRange Range, | ||||||||
12557 | OriginalExprKind OEK, | ||||||||
12558 | bool &DiagnosticEmitted) { | ||||||||
12559 | std::vector<const RecordType *> RecordTypeList; | ||||||||
12560 | RecordTypeList.push_back(Ty); | ||||||||
12561 | unsigned NextToCheckIndex = 0; | ||||||||
12562 | // We walk the record hierarchy breadth-first to ensure that we print | ||||||||
12563 | // diagnostics in field nesting order. | ||||||||
12564 | while (RecordTypeList.size() > NextToCheckIndex) { | ||||||||
12565 | bool IsNested = NextToCheckIndex > 0; | ||||||||
12566 | for (const FieldDecl *Field : | ||||||||
12567 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | ||||||||
12568 | // First, check every field for constness. | ||||||||
12569 | QualType FieldTy = Field->getType(); | ||||||||
12570 | if (FieldTy.isConstQualified()) { | ||||||||
12571 | if (!DiagnosticEmitted) { | ||||||||
12572 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||||||
12573 | << Range << NestedConstMember << OEK << VD | ||||||||
12574 | << IsNested << Field; | ||||||||
12575 | DiagnosticEmitted = true; | ||||||||
12576 | } | ||||||||
12577 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | ||||||||
12578 | << NestedConstMember << IsNested << Field | ||||||||
12579 | << FieldTy << Field->getSourceRange(); | ||||||||
12580 | } | ||||||||
12581 | |||||||||
12582 | // Then we append it to the list to check next in order. | ||||||||
12583 | FieldTy = FieldTy.getCanonicalType(); | ||||||||
12584 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | ||||||||
12585 | if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) | ||||||||
12586 | RecordTypeList.push_back(FieldRecTy); | ||||||||
12587 | } | ||||||||
12588 | } | ||||||||
12589 | ++NextToCheckIndex; | ||||||||
12590 | } | ||||||||
12591 | } | ||||||||
12592 | |||||||||
12593 | /// Emit an error for the case where a record we are trying to assign to has a | ||||||||
12594 | /// const-qualified field somewhere in its hierarchy. | ||||||||
12595 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | ||||||||
12596 | SourceLocation Loc) { | ||||||||
12597 | QualType Ty = E->getType(); | ||||||||
12598 | assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ? static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12598, __PRETTY_FUNCTION__)); | ||||||||
12599 | SourceRange Range = E->getSourceRange(); | ||||||||
12600 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | ||||||||
12601 | bool DiagEmitted = false; | ||||||||
12602 | |||||||||
12603 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||||||
12604 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | ||||||||
12605 | Range, OEK_Member, DiagEmitted); | ||||||||
12606 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||||||
12607 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | ||||||||
12608 | Range, OEK_Variable, DiagEmitted); | ||||||||
12609 | else | ||||||||
12610 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | ||||||||
12611 | Range, OEK_LValue, DiagEmitted); | ||||||||
12612 | if (!DiagEmitted) | ||||||||
12613 | DiagnoseConstAssignment(S, E, Loc); | ||||||||
12614 | } | ||||||||
12615 | |||||||||
12616 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | ||||||||
12617 | /// emit an error and return true. If so, return false. | ||||||||
12618 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | ||||||||
12619 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast <void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12619, __PRETTY_FUNCTION__)); | ||||||||
12620 | |||||||||
12621 | S.CheckShadowingDeclModification(E, Loc); | ||||||||
12622 | |||||||||
12623 | SourceLocation OrigLoc = Loc; | ||||||||
12624 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | ||||||||
12625 | &Loc); | ||||||||
12626 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | ||||||||
12627 | IsLV = Expr::MLV_InvalidMessageExpression; | ||||||||
12628 | if (IsLV == Expr::MLV_Valid) | ||||||||
12629 | return false; | ||||||||
12630 | |||||||||
12631 | unsigned DiagID = 0; | ||||||||
12632 | bool NeedType = false; | ||||||||
12633 | switch (IsLV) { // C99 6.5.16p2 | ||||||||
12634 | case Expr::MLV_ConstQualified: | ||||||||
12635 | // Use a specialized diagnostic when we're assigning to an object | ||||||||
12636 | // from an enclosing function or block. | ||||||||
12637 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | ||||||||
12638 | if (NCCK == NCCK_Block) | ||||||||
12639 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | ||||||||
12640 | else | ||||||||
12641 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | ||||||||
12642 | break; | ||||||||
12643 | } | ||||||||
12644 | |||||||||
12645 | // In ARC, use some specialized diagnostics for occasions where we | ||||||||
12646 | // infer 'const'. These are always pseudo-strong variables. | ||||||||
12647 | if (S.getLangOpts().ObjCAutoRefCount) { | ||||||||
12648 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | ||||||||
12649 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | ||||||||
12650 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | ||||||||
12651 | |||||||||
12652 | // Use the normal diagnostic if it's pseudo-__strong but the | ||||||||
12653 | // user actually wrote 'const'. | ||||||||
12654 | if (var->isARCPseudoStrong() && | ||||||||
12655 | (!var->getTypeSourceInfo() || | ||||||||
12656 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | ||||||||
12657 | // There are three pseudo-strong cases: | ||||||||
12658 | // - self | ||||||||
12659 | ObjCMethodDecl *method = S.getCurMethodDecl(); | ||||||||
12660 | if (method && var == method->getSelfDecl()) { | ||||||||
12661 | DiagID = method->isClassMethod() | ||||||||
12662 | ? diag::err_typecheck_arc_assign_self_class_method | ||||||||
12663 | : diag::err_typecheck_arc_assign_self; | ||||||||
12664 | |||||||||
12665 | // - Objective-C externally_retained attribute. | ||||||||
12666 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | ||||||||
12667 | isa<ParmVarDecl>(var)) { | ||||||||
12668 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | ||||||||
12669 | |||||||||
12670 | // - fast enumeration variables | ||||||||
12671 | } else { | ||||||||
12672 | DiagID = diag::err_typecheck_arr_assign_enumeration; | ||||||||
12673 | } | ||||||||
12674 | |||||||||
12675 | SourceRange Assign; | ||||||||
12676 | if (Loc != OrigLoc) | ||||||||
12677 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||||||
12678 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||||||
12679 | // We need to preserve the AST regardless, so migration tool | ||||||||
12680 | // can do its job. | ||||||||
12681 | return false; | ||||||||
12682 | } | ||||||||
12683 | } | ||||||||
12684 | } | ||||||||
12685 | |||||||||
12686 | // If none of the special cases above are triggered, then this is a | ||||||||
12687 | // simple const assignment. | ||||||||
12688 | if (DiagID == 0) { | ||||||||
12689 | DiagnoseConstAssignment(S, E, Loc); | ||||||||
12690 | return true; | ||||||||
12691 | } | ||||||||
12692 | |||||||||
12693 | break; | ||||||||
12694 | case Expr::MLV_ConstAddrSpace: | ||||||||
12695 | DiagnoseConstAssignment(S, E, Loc); | ||||||||
12696 | return true; | ||||||||
12697 | case Expr::MLV_ConstQualifiedField: | ||||||||
12698 | DiagnoseRecursiveConstFields(S, E, Loc); | ||||||||
12699 | return true; | ||||||||
12700 | case Expr::MLV_ArrayType: | ||||||||
12701 | case Expr::MLV_ArrayTemporary: | ||||||||
12702 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | ||||||||
12703 | NeedType = true; | ||||||||
12704 | break; | ||||||||
12705 | case Expr::MLV_NotObjectType: | ||||||||
12706 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | ||||||||
12707 | NeedType = true; | ||||||||
12708 | break; | ||||||||
12709 | case Expr::MLV_LValueCast: | ||||||||
12710 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | ||||||||
12711 | break; | ||||||||
12712 | case Expr::MLV_Valid: | ||||||||
12713 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12713); | ||||||||
12714 | case Expr::MLV_InvalidExpression: | ||||||||
12715 | case Expr::MLV_MemberFunction: | ||||||||
12716 | case Expr::MLV_ClassTemporary: | ||||||||
12717 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | ||||||||
12718 | break; | ||||||||
12719 | case Expr::MLV_IncompleteType: | ||||||||
12720 | case Expr::MLV_IncompleteVoidType: | ||||||||
12721 | return S.RequireCompleteType(Loc, E->getType(), | ||||||||
12722 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | ||||||||
12723 | case Expr::MLV_DuplicateVectorComponents: | ||||||||
12724 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | ||||||||
12725 | break; | ||||||||
12726 | case Expr::MLV_NoSetterProperty: | ||||||||
12727 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12727); | ||||||||
12728 | case Expr::MLV_InvalidMessageExpression: | ||||||||
12729 | DiagID = diag::err_readonly_message_assignment; | ||||||||
12730 | break; | ||||||||
12731 | case Expr::MLV_SubObjCPropertySetting: | ||||||||
12732 | DiagID = diag::err_no_subobject_property_setting; | ||||||||
12733 | break; | ||||||||
12734 | } | ||||||||
12735 | |||||||||
12736 | SourceRange Assign; | ||||||||
12737 | if (Loc != OrigLoc) | ||||||||
12738 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||||||
12739 | if (NeedType) | ||||||||
12740 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | ||||||||
12741 | else | ||||||||
12742 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||||||
12743 | return true; | ||||||||
12744 | } | ||||||||
12745 | |||||||||
12746 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | ||||||||
12747 | SourceLocation Loc, | ||||||||
12748 | Sema &Sema) { | ||||||||
12749 | if (Sema.inTemplateInstantiation()) | ||||||||
12750 | return; | ||||||||
12751 | if (Sema.isUnevaluatedContext()) | ||||||||
12752 | return; | ||||||||
12753 | if (Loc.isInvalid() || Loc.isMacroID()) | ||||||||
12754 | return; | ||||||||
12755 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | ||||||||
12756 | return; | ||||||||
12757 | |||||||||
12758 | // C / C++ fields | ||||||||
12759 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | ||||||||
12760 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | ||||||||
12761 | if (ML && MR) { | ||||||||
12762 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | ||||||||
12763 | return; | ||||||||
12764 | const ValueDecl *LHSDecl = | ||||||||
12765 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | ||||||||
12766 | const ValueDecl *RHSDecl = | ||||||||
12767 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | ||||||||
12768 | if (LHSDecl != RHSDecl) | ||||||||
12769 | return; | ||||||||
12770 | if (LHSDecl->getType().isVolatileQualified()) | ||||||||
12771 | return; | ||||||||
12772 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||||||
12773 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||||||
12774 | return; | ||||||||
12775 | |||||||||
12776 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | ||||||||
12777 | } | ||||||||
12778 | |||||||||
12779 | // Objective-C instance variables | ||||||||
12780 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | ||||||||
12781 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | ||||||||
12782 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | ||||||||
12783 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | ||||||||
12784 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | ||||||||
12785 | if (RL && RR && RL->getDecl() == RR->getDecl()) | ||||||||
12786 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | ||||||||
12787 | } | ||||||||
12788 | } | ||||||||
12789 | |||||||||
12790 | // C99 6.5.16.1 | ||||||||
12791 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | ||||||||
12792 | SourceLocation Loc, | ||||||||
12793 | QualType CompoundType) { | ||||||||
12794 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 12794, __PRETTY_FUNCTION__)); | ||||||||
12795 | |||||||||
12796 | // Verify that LHS is a modifiable lvalue, and emit error if not. | ||||||||
12797 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | ||||||||
12798 | return QualType(); | ||||||||
12799 | |||||||||
12800 | QualType LHSType = LHSExpr->getType(); | ||||||||
12801 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | ||||||||
12802 | CompoundType; | ||||||||
12803 | // OpenCL v1.2 s6.1.1.1 p2: | ||||||||
12804 | // The half data type can only be used to declare a pointer to a buffer that | ||||||||
12805 | // contains half values | ||||||||
12806 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | ||||||||
12807 | LHSType->isHalfType()) { | ||||||||
12808 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | ||||||||
12809 | << LHSType.getUnqualifiedType(); | ||||||||
12810 | return QualType(); | ||||||||
12811 | } | ||||||||
12812 | |||||||||
12813 | AssignConvertType ConvTy; | ||||||||
12814 | if (CompoundType.isNull()) { | ||||||||
12815 | Expr *RHSCheck = RHS.get(); | ||||||||
12816 | |||||||||
12817 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | ||||||||
12818 | |||||||||
12819 | QualType LHSTy(LHSType); | ||||||||
12820 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | ||||||||
12821 | if (RHS.isInvalid()) | ||||||||
12822 | return QualType(); | ||||||||
12823 | // Special case of NSObject attributes on c-style pointer types. | ||||||||
12824 | if (ConvTy == IncompatiblePointer && | ||||||||
12825 | ((Context.isObjCNSObjectType(LHSType) && | ||||||||
12826 | RHSType->isObjCObjectPointerType()) || | ||||||||
12827 | (Context.isObjCNSObjectType(RHSType) && | ||||||||
12828 | LHSType->isObjCObjectPointerType()))) | ||||||||
12829 | ConvTy = Compatible; | ||||||||
12830 | |||||||||
12831 | if (ConvTy == Compatible && | ||||||||
12832 | LHSType->isObjCObjectType()) | ||||||||
12833 | Diag(Loc, diag::err_objc_object_assignment) | ||||||||
12834 | << LHSType; | ||||||||
12835 | |||||||||
12836 | // If the RHS is a unary plus or minus, check to see if they = and + are | ||||||||
12837 | // right next to each other. If so, the user may have typo'd "x =+ 4" | ||||||||
12838 | // instead of "x += 4". | ||||||||
12839 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | ||||||||
12840 | RHSCheck = ICE->getSubExpr(); | ||||||||
12841 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | ||||||||
12842 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | ||||||||
12843 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | ||||||||
12844 | // Only if the two operators are exactly adjacent. | ||||||||
12845 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | ||||||||
12846 | // And there is a space or other character before the subexpr of the | ||||||||
12847 | // unary +/-. We don't want to warn on "x=-1". | ||||||||
12848 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | ||||||||
12849 | UO->getSubExpr()->getBeginLoc().isFileID()) { | ||||||||
12850 | Diag(Loc, diag::warn_not_compound_assign) | ||||||||
12851 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | ||||||||
12852 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | ||||||||
12853 | } | ||||||||
12854 | } | ||||||||
12855 | |||||||||
12856 | if (ConvTy == Compatible) { | ||||||||
12857 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | ||||||||
12858 | // Warn about retain cycles where a block captures the LHS, but | ||||||||
12859 | // not if the LHS is a simple variable into which the block is | ||||||||
12860 | // being stored...unless that variable can be captured by reference! | ||||||||
12861 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | ||||||||
12862 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | ||||||||
12863 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | ||||||||
12864 | checkRetainCycles(LHSExpr, RHS.get()); | ||||||||
12865 | } | ||||||||
12866 | |||||||||
12867 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | ||||||||
12868 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | ||||||||
12869 | // It is safe to assign a weak reference into a strong variable. | ||||||||
12870 | // Although this code can still have problems: | ||||||||
12871 | // id x = self.weakProp; | ||||||||
12872 | // id y = self.weakProp; | ||||||||
12873 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||||||
12874 | // paths through the function. This should be revisited if | ||||||||
12875 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||||||
12876 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | ||||||||
12877 | // variable, which will be valid for the current autorelease scope. | ||||||||
12878 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||||||
12879 | RHS.get()->getBeginLoc())) | ||||||||
12880 | getCurFunction()->markSafeWeakUse(RHS.get()); | ||||||||
12881 | |||||||||
12882 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | ||||||||
12883 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | ||||||||
12884 | } | ||||||||
12885 | } | ||||||||
12886 | } else { | ||||||||
12887 | // Compound assignment "x += y" | ||||||||
12888 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | ||||||||
12889 | } | ||||||||
12890 | |||||||||
12891 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | ||||||||
12892 | RHS.get(), AA_Assigning)) | ||||||||
12893 | return QualType(); | ||||||||
12894 | |||||||||
12895 | CheckForNullPointerDereference(*this, LHSExpr); | ||||||||
12896 | |||||||||
12897 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | ||||||||
12898 | if (CompoundType.isNull()) { | ||||||||
12899 | // C++2a [expr.ass]p5: | ||||||||
12900 | // A simple-assignment whose left operand is of a volatile-qualified | ||||||||
12901 | // type is deprecated unless the assignment is either a discarded-value | ||||||||
12902 | // expression or an unevaluated operand | ||||||||
12903 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | ||||||||
12904 | } else { | ||||||||
12905 | // C++2a [expr.ass]p6: | ||||||||
12906 | // [Compound-assignment] expressions are deprecated if E1 has | ||||||||
12907 | // volatile-qualified type | ||||||||
12908 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | ||||||||
12909 | } | ||||||||
12910 | } | ||||||||
12911 | |||||||||
12912 | // C99 6.5.16p3: The type of an assignment expression is the type of the | ||||||||
12913 | // left operand unless the left operand has qualified type, in which case | ||||||||
12914 | // it is the unqualified version of the type of the left operand. | ||||||||
12915 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | ||||||||
12916 | // is converted to the type of the assignment expression (above). | ||||||||
12917 | // C++ 5.17p1: the type of the assignment expression is that of its left | ||||||||
12918 | // operand. | ||||||||
12919 | return (getLangOpts().CPlusPlus | ||||||||
12920 | ? LHSType : LHSType.getUnqualifiedType()); | ||||||||
12921 | } | ||||||||
12922 | |||||||||
12923 | // Only ignore explicit casts to void. | ||||||||
12924 | static bool IgnoreCommaOperand(const Expr *E) { | ||||||||
12925 | E = E->IgnoreParens(); | ||||||||
12926 | |||||||||
12927 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | ||||||||
12928 | if (CE->getCastKind() == CK_ToVoid) { | ||||||||
12929 | return true; | ||||||||
12930 | } | ||||||||
12931 | |||||||||
12932 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | ||||||||
12933 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | ||||||||
12934 | CE->getSubExpr()->getType()->isDependentType()) { | ||||||||
12935 | return true; | ||||||||
12936 | } | ||||||||
12937 | } | ||||||||
12938 | |||||||||
12939 | return false; | ||||||||
12940 | } | ||||||||
12941 | |||||||||
12942 | // Look for instances where it is likely the comma operator is confused with | ||||||||
12943 | // another operator. There is an explicit list of acceptable expressions for | ||||||||
12944 | // the left hand side of the comma operator, otherwise emit a warning. | ||||||||
12945 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | ||||||||
12946 | // No warnings in macros | ||||||||
12947 | if (Loc.isMacroID()) | ||||||||
12948 | return; | ||||||||
12949 | |||||||||
12950 | // Don't warn in template instantiations. | ||||||||
12951 | if (inTemplateInstantiation()) | ||||||||
12952 | return; | ||||||||
12953 | |||||||||
12954 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | ||||||||
12955 | // instead, skip more than needed, then call back into here with the | ||||||||
12956 | // CommaVisitor in SemaStmt.cpp. | ||||||||
12957 | // The listed locations are the initialization and increment portions | ||||||||
12958 | // of a for loop. The additional checks are on the condition of | ||||||||
12959 | // if statements, do/while loops, and for loops. | ||||||||
12960 | // Differences in scope flags for C89 mode requires the extra logic. | ||||||||
12961 | const unsigned ForIncrementFlags = | ||||||||
12962 | getLangOpts().C99 || getLangOpts().CPlusPlus | ||||||||
12963 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | ||||||||
12964 | : Scope::ContinueScope | Scope::BreakScope; | ||||||||
12965 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | ||||||||
12966 | const unsigned ScopeFlags = getCurScope()->getFlags(); | ||||||||
12967 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | ||||||||
12968 | (ScopeFlags & ForInitFlags) == ForInitFlags) | ||||||||
12969 | return; | ||||||||
12970 | |||||||||
12971 | // If there are multiple comma operators used together, get the RHS of the | ||||||||
12972 | // of the comma operator as the LHS. | ||||||||
12973 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | ||||||||
12974 | if (BO->getOpcode() != BO_Comma) | ||||||||
12975 | break; | ||||||||
12976 | LHS = BO->getRHS(); | ||||||||
12977 | } | ||||||||
12978 | |||||||||
12979 | // Only allow some expressions on LHS to not warn. | ||||||||
12980 | if (IgnoreCommaOperand(LHS)) | ||||||||
12981 | return; | ||||||||
12982 | |||||||||
12983 | Diag(Loc, diag::warn_comma_operator); | ||||||||
12984 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | ||||||||
12985 | << LHS->getSourceRange() | ||||||||
12986 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | ||||||||
12987 | LangOpts.CPlusPlus ? "static_cast<void>(" | ||||||||
12988 | : "(void)(") | ||||||||
12989 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | ||||||||
12990 | ")"); | ||||||||
12991 | } | ||||||||
12992 | |||||||||
12993 | // C99 6.5.17 | ||||||||
12994 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||||||
12995 | SourceLocation Loc) { | ||||||||
12996 | LHS = S.CheckPlaceholderExpr(LHS.get()); | ||||||||
12997 | RHS = S.CheckPlaceholderExpr(RHS.get()); | ||||||||
12998 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||||||
12999 | return QualType(); | ||||||||
13000 | |||||||||
13001 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | ||||||||
13002 | // operands, but not unary promotions. | ||||||||
13003 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | ||||||||
13004 | |||||||||
13005 | // So we treat the LHS as a ignored value, and in C++ we allow the | ||||||||
13006 | // containing site to determine what should be done with the RHS. | ||||||||
13007 | LHS = S.IgnoredValueConversions(LHS.get()); | ||||||||
13008 | if (LHS.isInvalid()) | ||||||||
13009 | return QualType(); | ||||||||
13010 | |||||||||
13011 | S.DiagnoseUnusedExprResult(LHS.get()); | ||||||||
13012 | |||||||||
13013 | if (!S.getLangOpts().CPlusPlus) { | ||||||||
13014 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||||||
13015 | if (RHS.isInvalid()) | ||||||||
13016 | return QualType(); | ||||||||
13017 | if (!RHS.get()->getType()->isVoidType()) | ||||||||
13018 | S.RequireCompleteType(Loc, RHS.get()->getType(), | ||||||||
13019 | diag::err_incomplete_type); | ||||||||
13020 | } | ||||||||
13021 | |||||||||
13022 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | ||||||||
13023 | S.DiagnoseCommaOperator(LHS.get(), Loc); | ||||||||
13024 | |||||||||
13025 | return RHS.get()->getType(); | ||||||||
13026 | } | ||||||||
13027 | |||||||||
13028 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | ||||||||
13029 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | ||||||||
13030 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | ||||||||
13031 | ExprValueKind &VK, | ||||||||
13032 | ExprObjectKind &OK, | ||||||||
13033 | SourceLocation OpLoc, | ||||||||
13034 | bool IsInc, bool IsPrefix) { | ||||||||
13035 | if (Op->isTypeDependent()) | ||||||||
13036 | return S.Context.DependentTy; | ||||||||
13037 | |||||||||
13038 | QualType ResType = Op->getType(); | ||||||||
13039 | // Atomic types can be used for increment / decrement where the non-atomic | ||||||||
13040 | // versions can, so ignore the _Atomic() specifier for the purpose of | ||||||||
13041 | // checking. | ||||||||
13042 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||||||
13043 | ResType = ResAtomicType->getValueType(); | ||||||||
13044 | |||||||||
13045 | assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression" ) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13045, __PRETTY_FUNCTION__)); | ||||||||
13046 | |||||||||
13047 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | ||||||||
13048 | // Decrement of bool is not allowed. | ||||||||
13049 | if (!IsInc) { | ||||||||
13050 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | ||||||||
13051 | return QualType(); | ||||||||
13052 | } | ||||||||
13053 | // Increment of bool sets it to true, but is deprecated. | ||||||||
13054 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | ||||||||
13055 | : diag::warn_increment_bool) | ||||||||
13056 | << Op->getSourceRange(); | ||||||||
13057 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | ||||||||
13058 | // Error on enum increments and decrements in C++ mode | ||||||||
13059 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | ||||||||
13060 | return QualType(); | ||||||||
13061 | } else if (ResType->isRealType()) { | ||||||||
13062 | // OK! | ||||||||
13063 | } else if (ResType->isPointerType()) { | ||||||||
13064 | // C99 6.5.2.4p2, 6.5.6p2 | ||||||||
13065 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | ||||||||
13066 | return QualType(); | ||||||||
13067 | } else if (ResType->isObjCObjectPointerType()) { | ||||||||
13068 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | ||||||||
13069 | // Otherwise, we just need a complete type. | ||||||||
13070 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | ||||||||
13071 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | ||||||||
13072 | return QualType(); | ||||||||
13073 | } else if (ResType->isAnyComplexType()) { | ||||||||
13074 | // C99 does not support ++/-- on complex types, we allow as an extension. | ||||||||
13075 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | ||||||||
13076 | << ResType << Op->getSourceRange(); | ||||||||
13077 | } else if (ResType->isPlaceholderType()) { | ||||||||
13078 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||||||
13079 | if (PR.isInvalid()) return QualType(); | ||||||||
13080 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | ||||||||
13081 | IsInc, IsPrefix); | ||||||||
13082 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | ||||||||
13083 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | ||||||||
13084 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | ||||||||
13085 | (ResType->castAs<VectorType>()->getVectorKind() != | ||||||||
13086 | VectorType::AltiVecBool)) { | ||||||||
13087 | // The z vector extensions allow ++ and -- for non-bool vectors. | ||||||||
13088 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | ||||||||
13089 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | ||||||||
13090 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | ||||||||
13091 | } else { | ||||||||
13092 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | ||||||||
13093 | << ResType << int(IsInc) << Op->getSourceRange(); | ||||||||
13094 | return QualType(); | ||||||||
13095 | } | ||||||||
13096 | // At this point, we know we have a real, complex or pointer type. | ||||||||
13097 | // Now make sure the operand is a modifiable lvalue. | ||||||||
13098 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | ||||||||
13099 | return QualType(); | ||||||||
13100 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | ||||||||
13101 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | ||||||||
13102 | // An operand with volatile-qualified type is deprecated | ||||||||
13103 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | ||||||||
13104 | << IsInc << ResType; | ||||||||
13105 | } | ||||||||
13106 | // In C++, a prefix increment is the same type as the operand. Otherwise | ||||||||
13107 | // (in C or with postfix), the increment is the unqualified type of the | ||||||||
13108 | // operand. | ||||||||
13109 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | ||||||||
13110 | VK = VK_LValue; | ||||||||
13111 | OK = Op->getObjectKind(); | ||||||||
13112 | return ResType; | ||||||||
13113 | } else { | ||||||||
13114 | VK = VK_RValue; | ||||||||
13115 | return ResType.getUnqualifiedType(); | ||||||||
13116 | } | ||||||||
13117 | } | ||||||||
13118 | |||||||||
13119 | |||||||||
13120 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | ||||||||
13121 | /// This routine allows us to typecheck complex/recursive expressions | ||||||||
13122 | /// where the declaration is needed for type checking. We only need to | ||||||||
13123 | /// handle cases when the expression references a function designator | ||||||||
13124 | /// or is an lvalue. Here are some examples: | ||||||||
13125 | /// - &(x) => x | ||||||||
13126 | /// - &*****f => f for f a function designator. | ||||||||
13127 | /// - &s.xx => s | ||||||||
13128 | /// - &s.zz[1].yy -> s, if zz is an array | ||||||||
13129 | /// - *(x + 1) -> x, if x is an array | ||||||||
13130 | /// - &"123"[2] -> 0 | ||||||||
13131 | /// - & __real__ x -> x | ||||||||
13132 | /// | ||||||||
13133 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | ||||||||
13134 | /// members. | ||||||||
13135 | static ValueDecl *getPrimaryDecl(Expr *E) { | ||||||||
13136 | switch (E->getStmtClass()) { | ||||||||
13137 | case Stmt::DeclRefExprClass: | ||||||||
13138 | return cast<DeclRefExpr>(E)->getDecl(); | ||||||||
13139 | case Stmt::MemberExprClass: | ||||||||
13140 | // If this is an arrow operator, the address is an offset from | ||||||||
13141 | // the base's value, so the object the base refers to is | ||||||||
13142 | // irrelevant. | ||||||||
13143 | if (cast<MemberExpr>(E)->isArrow()) | ||||||||
13144 | return nullptr; | ||||||||
13145 | // Otherwise, the expression refers to a part of the base | ||||||||
13146 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | ||||||||
13147 | case Stmt::ArraySubscriptExprClass: { | ||||||||
13148 | // FIXME: This code shouldn't be necessary! We should catch the implicit | ||||||||
13149 | // promotion of register arrays earlier. | ||||||||
13150 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | ||||||||
13151 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | ||||||||
13152 | if (ICE->getSubExpr()->getType()->isArrayType()) | ||||||||
13153 | return getPrimaryDecl(ICE->getSubExpr()); | ||||||||
13154 | } | ||||||||
13155 | return nullptr; | ||||||||
13156 | } | ||||||||
13157 | case Stmt::UnaryOperatorClass: { | ||||||||
13158 | UnaryOperator *UO = cast<UnaryOperator>(E); | ||||||||
13159 | |||||||||
13160 | switch(UO->getOpcode()) { | ||||||||
13161 | case UO_Real: | ||||||||
13162 | case UO_Imag: | ||||||||
13163 | case UO_Extension: | ||||||||
13164 | return getPrimaryDecl(UO->getSubExpr()); | ||||||||
13165 | default: | ||||||||
13166 | return nullptr; | ||||||||
13167 | } | ||||||||
13168 | } | ||||||||
13169 | case Stmt::ParenExprClass: | ||||||||
13170 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | ||||||||
13171 | case Stmt::ImplicitCastExprClass: | ||||||||
13172 | // If the result of an implicit cast is an l-value, we care about | ||||||||
13173 | // the sub-expression; otherwise, the result here doesn't matter. | ||||||||
13174 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | ||||||||
13175 | case Stmt::CXXUuidofExprClass: | ||||||||
13176 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | ||||||||
13177 | default: | ||||||||
13178 | return nullptr; | ||||||||
13179 | } | ||||||||
13180 | } | ||||||||
13181 | |||||||||
13182 | namespace { | ||||||||
13183 | enum { | ||||||||
13184 | AO_Bit_Field = 0, | ||||||||
13185 | AO_Vector_Element = 1, | ||||||||
13186 | AO_Property_Expansion = 2, | ||||||||
13187 | AO_Register_Variable = 3, | ||||||||
13188 | AO_Matrix_Element = 4, | ||||||||
13189 | AO_No_Error = 5 | ||||||||
13190 | }; | ||||||||
13191 | } | ||||||||
13192 | /// Diagnose invalid operand for address of operations. | ||||||||
13193 | /// | ||||||||
13194 | /// \param Type The type of operand which cannot have its address taken. | ||||||||
13195 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | ||||||||
13196 | Expr *E, unsigned Type) { | ||||||||
13197 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | ||||||||
13198 | } | ||||||||
13199 | |||||||||
13200 | /// CheckAddressOfOperand - The operand of & must be either a function | ||||||||
13201 | /// designator or an lvalue designating an object. If it is an lvalue, the | ||||||||
13202 | /// object cannot be declared with storage class register or be a bit field. | ||||||||
13203 | /// Note: The usual conversions are *not* applied to the operand of the & | ||||||||
13204 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | ||||||||
13205 | /// In C++, the operand might be an overloaded function name, in which case | ||||||||
13206 | /// we allow the '&' but retain the overloaded-function type. | ||||||||
13207 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | ||||||||
13208 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | ||||||||
13209 | if (PTy->getKind() == BuiltinType::Overload) { | ||||||||
13210 | Expr *E = OrigOp.get()->IgnoreParens(); | ||||||||
13211 | if (!isa<OverloadExpr>(E)) { | ||||||||
13212 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13212, __PRETTY_FUNCTION__)); | ||||||||
13213 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | ||||||||
13214 | << OrigOp.get()->getSourceRange(); | ||||||||
13215 | return QualType(); | ||||||||
13216 | } | ||||||||
13217 | |||||||||
13218 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | ||||||||
13219 | if (isa<UnresolvedMemberExpr>(Ovl)) | ||||||||
13220 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | ||||||||
13221 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||||||
13222 | << OrigOp.get()->getSourceRange(); | ||||||||
13223 | return QualType(); | ||||||||
13224 | } | ||||||||
13225 | |||||||||
13226 | return Context.OverloadTy; | ||||||||
13227 | } | ||||||||
13228 | |||||||||
13229 | if (PTy->getKind() == BuiltinType::UnknownAny) | ||||||||
13230 | return Context.UnknownAnyTy; | ||||||||
13231 | |||||||||
13232 | if (PTy->getKind() == BuiltinType::BoundMember) { | ||||||||
13233 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||||||
13234 | << OrigOp.get()->getSourceRange(); | ||||||||
13235 | return QualType(); | ||||||||
13236 | } | ||||||||
13237 | |||||||||
13238 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | ||||||||
13239 | if (OrigOp.isInvalid()) return QualType(); | ||||||||
13240 | } | ||||||||
13241 | |||||||||
13242 | if (OrigOp.get()->isTypeDependent()) | ||||||||
13243 | return Context.DependentTy; | ||||||||
13244 | |||||||||
13245 | assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast <void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13245, __PRETTY_FUNCTION__)); | ||||||||
13246 | |||||||||
13247 | // Make sure to ignore parentheses in subsequent checks | ||||||||
13248 | Expr *op = OrigOp.get()->IgnoreParens(); | ||||||||
13249 | |||||||||
13250 | // In OpenCL captures for blocks called as lambda functions | ||||||||
13251 | // are located in the private address space. Blocks used in | ||||||||
13252 | // enqueue_kernel can be located in a different address space | ||||||||
13253 | // depending on a vendor implementation. Thus preventing | ||||||||
13254 | // taking an address of the capture to avoid invalid AS casts. | ||||||||
13255 | if (LangOpts.OpenCL) { | ||||||||
13256 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | ||||||||
13257 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | ||||||||
13258 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | ||||||||
13259 | return QualType(); | ||||||||
13260 | } | ||||||||
13261 | } | ||||||||
13262 | |||||||||
13263 | if (getLangOpts().C99) { | ||||||||
13264 | // Implement C99-only parts of addressof rules. | ||||||||
13265 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | ||||||||
13266 | if (uOp->getOpcode() == UO_Deref) | ||||||||
13267 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | ||||||||
13268 | // (assuming the deref expression is valid). | ||||||||
13269 | return uOp->getSubExpr()->getType(); | ||||||||
13270 | } | ||||||||
13271 | // Technically, there should be a check for array subscript | ||||||||
13272 | // expressions here, but the result of one is always an lvalue anyway. | ||||||||
13273 | } | ||||||||
13274 | ValueDecl *dcl = getPrimaryDecl(op); | ||||||||
13275 | |||||||||
13276 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | ||||||||
13277 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||||||
13278 | op->getBeginLoc())) | ||||||||
13279 | return QualType(); | ||||||||
13280 | |||||||||
13281 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | ||||||||
13282 | unsigned AddressOfError = AO_No_Error; | ||||||||
13283 | |||||||||
13284 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | ||||||||
13285 | bool sfinae = (bool)isSFINAEContext(); | ||||||||
13286 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | ||||||||
13287 | : diag::ext_typecheck_addrof_temporary) | ||||||||
13288 | << op->getType() << op->getSourceRange(); | ||||||||
13289 | if (sfinae) | ||||||||
13290 | return QualType(); | ||||||||
13291 | // Materialize the temporary as an lvalue so that we can take its address. | ||||||||
13292 | OrigOp = op = | ||||||||
13293 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | ||||||||
13294 | } else if (isa<ObjCSelectorExpr>(op)) { | ||||||||
13295 | return Context.getPointerType(op->getType()); | ||||||||
13296 | } else if (lval == Expr::LV_MemberFunction) { | ||||||||
13297 | // If it's an instance method, make a member pointer. | ||||||||
13298 | // The expression must have exactly the form &A::foo. | ||||||||
13299 | |||||||||
13300 | // If the underlying expression isn't a decl ref, give up. | ||||||||
13301 | if (!isa<DeclRefExpr>(op)) { | ||||||||
13302 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||||||
13303 | << OrigOp.get()->getSourceRange(); | ||||||||
13304 | return QualType(); | ||||||||
13305 | } | ||||||||
13306 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | ||||||||
13307 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | ||||||||
13308 | |||||||||
13309 | // The id-expression was parenthesized. | ||||||||
13310 | if (OrigOp.get() != DRE) { | ||||||||
13311 | Diag(OpLoc, diag::err_parens_pointer_member_function) | ||||||||
13312 | << OrigOp.get()->getSourceRange(); | ||||||||
13313 | |||||||||
13314 | // The method was named without a qualifier. | ||||||||
13315 | } else if (!DRE->getQualifier()) { | ||||||||
13316 | if (MD->getParent()->getName().empty()) | ||||||||
13317 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||||||
13318 | << op->getSourceRange(); | ||||||||
13319 | else { | ||||||||
13320 | SmallString<32> Str; | ||||||||
13321 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | ||||||||
13322 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||||||
13323 | << op->getSourceRange() | ||||||||
13324 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | ||||||||
13325 | } | ||||||||
13326 | } | ||||||||
13327 | |||||||||
13328 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | ||||||||
13329 | if (isa<CXXDestructorDecl>(MD)) | ||||||||
13330 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | ||||||||
13331 | |||||||||
13332 | QualType MPTy = Context.getMemberPointerType( | ||||||||
13333 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | ||||||||
13334 | // Under the MS ABI, lock down the inheritance model now. | ||||||||
13335 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||||||
13336 | (void)isCompleteType(OpLoc, MPTy); | ||||||||
13337 | return MPTy; | ||||||||
13338 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | ||||||||
13339 | // C99 6.5.3.2p1 | ||||||||
13340 | // The operand must be either an l-value or a function designator | ||||||||
13341 | if (!op->getType()->isFunctionType()) { | ||||||||
13342 | // Use a special diagnostic for loads from property references. | ||||||||
13343 | if (isa<PseudoObjectExpr>(op)) { | ||||||||
13344 | AddressOfError = AO_Property_Expansion; | ||||||||
13345 | } else { | ||||||||
13346 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | ||||||||
13347 | << op->getType() << op->getSourceRange(); | ||||||||
13348 | return QualType(); | ||||||||
13349 | } | ||||||||
13350 | } | ||||||||
13351 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | ||||||||
13352 | // The operand cannot be a bit-field | ||||||||
13353 | AddressOfError = AO_Bit_Field; | ||||||||
13354 | } else if (op->getObjectKind() == OK_VectorComponent) { | ||||||||
13355 | // The operand cannot be an element of a vector | ||||||||
13356 | AddressOfError = AO_Vector_Element; | ||||||||
13357 | } else if (op->getObjectKind() == OK_MatrixComponent) { | ||||||||
13358 | // The operand cannot be an element of a matrix. | ||||||||
13359 | AddressOfError = AO_Matrix_Element; | ||||||||
13360 | } else if (dcl) { // C99 6.5.3.2p1 | ||||||||
13361 | // We have an lvalue with a decl. Make sure the decl is not declared | ||||||||
13362 | // with the register storage-class specifier. | ||||||||
13363 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | ||||||||
13364 | // in C++ it is not error to take address of a register | ||||||||
13365 | // variable (c++03 7.1.1P3) | ||||||||
13366 | if (vd->getStorageClass() == SC_Register && | ||||||||
13367 | !getLangOpts().CPlusPlus) { | ||||||||
13368 | AddressOfError = AO_Register_Variable; | ||||||||
13369 | } | ||||||||
13370 | } else if (isa<MSPropertyDecl>(dcl)) { | ||||||||
13371 | AddressOfError = AO_Property_Expansion; | ||||||||
13372 | } else if (isa<FunctionTemplateDecl>(dcl)) { | ||||||||
13373 | return Context.OverloadTy; | ||||||||
13374 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | ||||||||
13375 | // Okay: we can take the address of a field. | ||||||||
13376 | // Could be a pointer to member, though, if there is an explicit | ||||||||
13377 | // scope qualifier for the class. | ||||||||
13378 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | ||||||||
13379 | DeclContext *Ctx = dcl->getDeclContext(); | ||||||||
13380 | if (Ctx && Ctx->isRecord()) { | ||||||||
13381 | if (dcl->getType()->isReferenceType()) { | ||||||||
13382 | Diag(OpLoc, | ||||||||
13383 | diag::err_cannot_form_pointer_to_member_of_reference_type) | ||||||||
13384 | << dcl->getDeclName() << dcl->getType(); | ||||||||
13385 | return QualType(); | ||||||||
13386 | } | ||||||||
13387 | |||||||||
13388 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | ||||||||
13389 | Ctx = Ctx->getParent(); | ||||||||
13390 | |||||||||
13391 | QualType MPTy = Context.getMemberPointerType( | ||||||||
13392 | op->getType(), | ||||||||
13393 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | ||||||||
13394 | // Under the MS ABI, lock down the inheritance model now. | ||||||||
13395 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||||||
13396 | (void)isCompleteType(OpLoc, MPTy); | ||||||||
13397 | return MPTy; | ||||||||
13398 | } | ||||||||
13399 | } | ||||||||
13400 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | ||||||||
13401 | !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) | ||||||||
13402 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13402); | ||||||||
13403 | } | ||||||||
13404 | |||||||||
13405 | if (AddressOfError != AO_No_Error) { | ||||||||
13406 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | ||||||||
13407 | return QualType(); | ||||||||
13408 | } | ||||||||
13409 | |||||||||
13410 | if (lval == Expr::LV_IncompleteVoidType) { | ||||||||
13411 | // Taking the address of a void variable is technically illegal, but we | ||||||||
13412 | // allow it in cases which are otherwise valid. | ||||||||
13413 | // Example: "extern void x; void* y = &x;". | ||||||||
13414 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | ||||||||
13415 | } | ||||||||
13416 | |||||||||
13417 | // If the operand has type "type", the result has type "pointer to type". | ||||||||
13418 | if (op->getType()->isObjCObjectType()) | ||||||||
13419 | return Context.getObjCObjectPointerType(op->getType()); | ||||||||
13420 | |||||||||
13421 | CheckAddressOfPackedMember(op); | ||||||||
13422 | |||||||||
13423 | return Context.getPointerType(op->getType()); | ||||||||
13424 | } | ||||||||
13425 | |||||||||
13426 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | ||||||||
13427 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | ||||||||
13428 | if (!DRE) | ||||||||
13429 | return; | ||||||||
13430 | const Decl *D = DRE->getDecl(); | ||||||||
13431 | if (!D) | ||||||||
13432 | return; | ||||||||
13433 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | ||||||||
13434 | if (!Param) | ||||||||
13435 | return; | ||||||||
13436 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | ||||||||
13437 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | ||||||||
13438 | return; | ||||||||
13439 | if (FunctionScopeInfo *FD = S.getCurFunction()) | ||||||||
13440 | if (!FD->ModifiedNonNullParams.count(Param)) | ||||||||
13441 | FD->ModifiedNonNullParams.insert(Param); | ||||||||
13442 | } | ||||||||
13443 | |||||||||
13444 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | ||||||||
13445 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | ||||||||
13446 | SourceLocation OpLoc) { | ||||||||
13447 | if (Op->isTypeDependent()) | ||||||||
13448 | return S.Context.DependentTy; | ||||||||
13449 | |||||||||
13450 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | ||||||||
13451 | if (ConvResult.isInvalid()) | ||||||||
13452 | return QualType(); | ||||||||
13453 | Op = ConvResult.get(); | ||||||||
13454 | QualType OpTy = Op->getType(); | ||||||||
13455 | QualType Result; | ||||||||
13456 | |||||||||
13457 | if (isa<CXXReinterpretCastExpr>(Op)) { | ||||||||
13458 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | ||||||||
13459 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | ||||||||
13460 | Op->getSourceRange()); | ||||||||
13461 | } | ||||||||
13462 | |||||||||
13463 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | ||||||||
13464 | { | ||||||||
13465 | Result = PT->getPointeeType(); | ||||||||
13466 | } | ||||||||
13467 | else if (const ObjCObjectPointerType *OPT = | ||||||||
13468 | OpTy->getAs<ObjCObjectPointerType>()) | ||||||||
13469 | Result = OPT->getPointeeType(); | ||||||||
13470 | else { | ||||||||
13471 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||||||
13472 | if (PR.isInvalid()) return QualType(); | ||||||||
13473 | if (PR.get() != Op) | ||||||||
13474 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | ||||||||
13475 | } | ||||||||
13476 | |||||||||
13477 | if (Result.isNull()) { | ||||||||
13478 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | ||||||||
13479 | << OpTy << Op->getSourceRange(); | ||||||||
13480 | return QualType(); | ||||||||
13481 | } | ||||||||
13482 | |||||||||
13483 | // Note that per both C89 and C99, indirection is always legal, even if Result | ||||||||
13484 | // is an incomplete type or void. It would be possible to warn about | ||||||||
13485 | // dereferencing a void pointer, but it's completely well-defined, and such a | ||||||||
13486 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | ||||||||
13487 | // for pointers to 'void' but is fine for any other pointer type: | ||||||||
13488 | // | ||||||||
13489 | // C++ [expr.unary.op]p1: | ||||||||
13490 | // [...] the expression to which [the unary * operator] is applied shall | ||||||||
13491 | // be a pointer to an object type, or a pointer to a function type | ||||||||
13492 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | ||||||||
13493 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | ||||||||
13494 | << OpTy << Op->getSourceRange(); | ||||||||
13495 | |||||||||
13496 | // Dereferences are usually l-values... | ||||||||
13497 | VK = VK_LValue; | ||||||||
13498 | |||||||||
13499 | // ...except that certain expressions are never l-values in C. | ||||||||
13500 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | ||||||||
13501 | VK = VK_RValue; | ||||||||
13502 | |||||||||
13503 | return Result; | ||||||||
13504 | } | ||||||||
13505 | |||||||||
13506 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | ||||||||
13507 | BinaryOperatorKind Opc; | ||||||||
13508 | switch (Kind) { | ||||||||
13509 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13509); | ||||||||
13510 | case tok::periodstar: Opc = BO_PtrMemD; break; | ||||||||
13511 | case tok::arrowstar: Opc = BO_PtrMemI; break; | ||||||||
13512 | case tok::star: Opc = BO_Mul; break; | ||||||||
13513 | case tok::slash: Opc = BO_Div; break; | ||||||||
13514 | case tok::percent: Opc = BO_Rem; break; | ||||||||
13515 | case tok::plus: Opc = BO_Add; break; | ||||||||
13516 | case tok::minus: Opc = BO_Sub; break; | ||||||||
13517 | case tok::lessless: Opc = BO_Shl; break; | ||||||||
13518 | case tok::greatergreater: Opc = BO_Shr; break; | ||||||||
13519 | case tok::lessequal: Opc = BO_LE; break; | ||||||||
13520 | case tok::less: Opc = BO_LT; break; | ||||||||
13521 | case tok::greaterequal: Opc = BO_GE; break; | ||||||||
13522 | case tok::greater: Opc = BO_GT; break; | ||||||||
13523 | case tok::exclaimequal: Opc = BO_NE; break; | ||||||||
13524 | case tok::equalequal: Opc = BO_EQ; break; | ||||||||
13525 | case tok::spaceship: Opc = BO_Cmp; break; | ||||||||
13526 | case tok::amp: Opc = BO_And; break; | ||||||||
13527 | case tok::caret: Opc = BO_Xor; break; | ||||||||
13528 | case tok::pipe: Opc = BO_Or; break; | ||||||||
13529 | case tok::ampamp: Opc = BO_LAnd; break; | ||||||||
13530 | case tok::pipepipe: Opc = BO_LOr; break; | ||||||||
13531 | case tok::equal: Opc = BO_Assign; break; | ||||||||
13532 | case tok::starequal: Opc = BO_MulAssign; break; | ||||||||
13533 | case tok::slashequal: Opc = BO_DivAssign; break; | ||||||||
13534 | case tok::percentequal: Opc = BO_RemAssign; break; | ||||||||
13535 | case tok::plusequal: Opc = BO_AddAssign; break; | ||||||||
13536 | case tok::minusequal: Opc = BO_SubAssign; break; | ||||||||
13537 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | ||||||||
13538 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | ||||||||
13539 | case tok::ampequal: Opc = BO_AndAssign; break; | ||||||||
13540 | case tok::caretequal: Opc = BO_XorAssign; break; | ||||||||
13541 | case tok::pipeequal: Opc = BO_OrAssign; break; | ||||||||
13542 | case tok::comma: Opc = BO_Comma; break; | ||||||||
13543 | } | ||||||||
13544 | return Opc; | ||||||||
13545 | } | ||||||||
13546 | |||||||||
13547 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | ||||||||
13548 | tok::TokenKind Kind) { | ||||||||
13549 | UnaryOperatorKind Opc; | ||||||||
13550 | switch (Kind) { | ||||||||
13551 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13551); | ||||||||
13552 | case tok::plusplus: Opc = UO_PreInc; break; | ||||||||
13553 | case tok::minusminus: Opc = UO_PreDec; break; | ||||||||
13554 | case tok::amp: Opc = UO_AddrOf; break; | ||||||||
13555 | case tok::star: Opc = UO_Deref; break; | ||||||||
13556 | case tok::plus: Opc = UO_Plus; break; | ||||||||
13557 | case tok::minus: Opc = UO_Minus; break; | ||||||||
13558 | case tok::tilde: Opc = UO_Not; break; | ||||||||
13559 | case tok::exclaim: Opc = UO_LNot; break; | ||||||||
13560 | case tok::kw___real: Opc = UO_Real; break; | ||||||||
13561 | case tok::kw___imag: Opc = UO_Imag; break; | ||||||||
13562 | case tok::kw___extension__: Opc = UO_Extension; break; | ||||||||
13563 | } | ||||||||
13564 | return Opc; | ||||||||
13565 | } | ||||||||
13566 | |||||||||
13567 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | ||||||||
13568 | /// This warning suppressed in the event of macro expansions. | ||||||||
13569 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | ||||||||
13570 | SourceLocation OpLoc, bool IsBuiltin) { | ||||||||
13571 | if (S.inTemplateInstantiation()) | ||||||||
13572 | return; | ||||||||
13573 | if (S.isUnevaluatedContext()) | ||||||||
13574 | return; | ||||||||
13575 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | ||||||||
13576 | return; | ||||||||
13577 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | ||||||||
13578 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | ||||||||
13579 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | ||||||||
13580 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | ||||||||
13581 | if (!LHSDeclRef || !RHSDeclRef || | ||||||||
13582 | LHSDeclRef->getLocation().isMacroID() || | ||||||||
13583 | RHSDeclRef->getLocation().isMacroID()) | ||||||||
13584 | return; | ||||||||
13585 | const ValueDecl *LHSDecl = | ||||||||
13586 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | ||||||||
13587 | const ValueDecl *RHSDecl = | ||||||||
13588 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | ||||||||
13589 | if (LHSDecl != RHSDecl) | ||||||||
13590 | return; | ||||||||
13591 | if (LHSDecl->getType().isVolatileQualified()) | ||||||||
13592 | return; | ||||||||
13593 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||||||
13594 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||||||
13595 | return; | ||||||||
13596 | |||||||||
13597 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | ||||||||
13598 | : diag::warn_self_assignment_overloaded) | ||||||||
13599 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | ||||||||
13600 | << RHSExpr->getSourceRange(); | ||||||||
13601 | } | ||||||||
13602 | |||||||||
13603 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | ||||||||
13604 | /// is usually indicative of introspection within the Objective-C pointer. | ||||||||
13605 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | ||||||||
13606 | SourceLocation OpLoc) { | ||||||||
13607 | if (!S.getLangOpts().ObjC) | ||||||||
13608 | return; | ||||||||
13609 | |||||||||
13610 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | ||||||||
13611 | const Expr *LHS = L.get(); | ||||||||
13612 | const Expr *RHS = R.get(); | ||||||||
13613 | |||||||||
13614 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||||||
13615 | ObjCPointerExpr = LHS; | ||||||||
13616 | OtherExpr = RHS; | ||||||||
13617 | } | ||||||||
13618 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||||||
13619 | ObjCPointerExpr = RHS; | ||||||||
13620 | OtherExpr = LHS; | ||||||||
13621 | } | ||||||||
13622 | |||||||||
13623 | // This warning is deliberately made very specific to reduce false | ||||||||
13624 | // positives with logic that uses '&' for hashing. This logic mainly | ||||||||
13625 | // looks for code trying to introspect into tagged pointers, which | ||||||||
13626 | // code should generally never do. | ||||||||
13627 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | ||||||||
13628 | unsigned Diag = diag::warn_objc_pointer_masking; | ||||||||
13629 | // Determine if we are introspecting the result of performSelectorXXX. | ||||||||
13630 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | ||||||||
13631 | // Special case messages to -performSelector and friends, which | ||||||||
13632 | // can return non-pointer values boxed in a pointer value. | ||||||||
13633 | // Some clients may wish to silence warnings in this subcase. | ||||||||
13634 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | ||||||||
13635 | Selector S = ME->getSelector(); | ||||||||
13636 | StringRef SelArg0 = S.getNameForSlot(0); | ||||||||
13637 | if (SelArg0.startswith("performSelector")) | ||||||||
13638 | Diag = diag::warn_objc_pointer_masking_performSelector; | ||||||||
13639 | } | ||||||||
13640 | |||||||||
13641 | S.Diag(OpLoc, Diag) | ||||||||
13642 | << ObjCPointerExpr->getSourceRange(); | ||||||||
13643 | } | ||||||||
13644 | } | ||||||||
13645 | |||||||||
13646 | static NamedDecl *getDeclFromExpr(Expr *E) { | ||||||||
13647 | if (!E) | ||||||||
13648 | return nullptr; | ||||||||
13649 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | ||||||||
13650 | return DRE->getDecl(); | ||||||||
13651 | if (auto *ME = dyn_cast<MemberExpr>(E)) | ||||||||
13652 | return ME->getMemberDecl(); | ||||||||
13653 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | ||||||||
13654 | return IRE->getDecl(); | ||||||||
13655 | return nullptr; | ||||||||
13656 | } | ||||||||
13657 | |||||||||
13658 | // This helper function promotes a binary operator's operands (which are of a | ||||||||
13659 | // half vector type) to a vector of floats and then truncates the result to | ||||||||
13660 | // a vector of either half or short. | ||||||||
13661 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | ||||||||
13662 | BinaryOperatorKind Opc, QualType ResultTy, | ||||||||
13663 | ExprValueKind VK, ExprObjectKind OK, | ||||||||
13664 | bool IsCompAssign, SourceLocation OpLoc, | ||||||||
13665 | FPOptionsOverride FPFeatures) { | ||||||||
13666 | auto &Context = S.getASTContext(); | ||||||||
13667 | assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13669, __PRETTY_FUNCTION__)) | ||||||||
13668 | isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13669, __PRETTY_FUNCTION__)) | ||||||||
13669 | "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13669, __PRETTY_FUNCTION__)); | ||||||||
13670 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13672, __PRETTY_FUNCTION__)) | ||||||||
13671 | isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13672, __PRETTY_FUNCTION__)) | ||||||||
13672 | "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13672, __PRETTY_FUNCTION__)); | ||||||||
13673 | |||||||||
13674 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | ||||||||
13675 | QualType BinOpResTy = RHS.get()->getType(); | ||||||||
13676 | |||||||||
13677 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | ||||||||
13678 | // change BinOpResTy to a vector of ints. | ||||||||
13679 | if (isVector(ResultTy, Context.ShortTy)) | ||||||||
13680 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | ||||||||
13681 | |||||||||
13682 | if (IsCompAssign) | ||||||||
13683 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||||||
13684 | ResultTy, VK, OK, OpLoc, FPFeatures, | ||||||||
13685 | BinOpResTy, BinOpResTy); | ||||||||
13686 | |||||||||
13687 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | ||||||||
13688 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||||||
13689 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | ||||||||
13690 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | ||||||||
13691 | } | ||||||||
13692 | |||||||||
13693 | static std::pair<ExprResult, ExprResult> | ||||||||
13694 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | ||||||||
13695 | Expr *RHSExpr) { | ||||||||
13696 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||||||
13697 | if (!S.Context.isDependenceAllowed()) { | ||||||||
13698 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||||||
13699 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||||||
13700 | // been dealt with before checking the operands. | ||||||||
13701 | LHS = S.CorrectDelayedTyposInExpr(LHS); | ||||||||
13702 | RHS = S.CorrectDelayedTyposInExpr( | ||||||||
13703 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | ||||||||
13704 | [Opc, LHS](Expr *E) { | ||||||||
13705 | if (Opc != BO_Assign) | ||||||||
13706 | return ExprResult(E); | ||||||||
13707 | // Avoid correcting the RHS to the same Expr as the LHS. | ||||||||
13708 | Decl *D = getDeclFromExpr(E); | ||||||||
13709 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | ||||||||
13710 | }); | ||||||||
13711 | } | ||||||||
13712 | return std::make_pair(LHS, RHS); | ||||||||
13713 | } | ||||||||
13714 | |||||||||
13715 | /// Returns true if conversion between vectors of halfs and vectors of floats | ||||||||
13716 | /// is needed. | ||||||||
13717 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | ||||||||
13718 | Expr *E0, Expr *E1 = nullptr) { | ||||||||
13719 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | ||||||||
13720 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | ||||||||
13721 | return false; | ||||||||
13722 | |||||||||
13723 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | ||||||||
13724 | QualType Ty = E->IgnoreImplicit()->getType(); | ||||||||
13725 | |||||||||
13726 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | ||||||||
13727 | // to vectors of floats. Although the element type of the vectors is __fp16, | ||||||||
13728 | // the vectors shouldn't be treated as storage-only types. See the | ||||||||
13729 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | ||||||||
13730 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | ||||||||
13731 | if (VT->getVectorKind() == VectorType::NeonVector) | ||||||||
13732 | return false; | ||||||||
13733 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | ||||||||
13734 | } | ||||||||
13735 | return false; | ||||||||
13736 | }; | ||||||||
13737 | |||||||||
13738 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | ||||||||
13739 | } | ||||||||
13740 | |||||||||
13741 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | ||||||||
13742 | /// operator @p Opc at location @c TokLoc. This routine only supports | ||||||||
13743 | /// built-in operations; ActOnBinOp handles overloaded operators. | ||||||||
13744 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | ||||||||
13745 | BinaryOperatorKind Opc, | ||||||||
13746 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
13747 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | ||||||||
13748 | // The syntax only allows initializer lists on the RHS of assignment, | ||||||||
13749 | // so we don't need to worry about accepting invalid code for | ||||||||
13750 | // non-assignment operators. | ||||||||
13751 | // C++11 5.17p9: | ||||||||
13752 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | ||||||||
13753 | // of x = {} is x = T(). | ||||||||
13754 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||||||
13755 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||||||
13756 | InitializedEntity Entity = | ||||||||
13757 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | ||||||||
13758 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | ||||||||
13759 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | ||||||||
13760 | if (Init.isInvalid()) | ||||||||
13761 | return Init; | ||||||||
13762 | RHSExpr = Init.get(); | ||||||||
13763 | } | ||||||||
13764 | |||||||||
13765 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||||||
13766 | QualType ResultTy; // Result type of the binary operator. | ||||||||
13767 | // The following two variables are used for compound assignment operators | ||||||||
13768 | QualType CompLHSTy; // Type of LHS after promotions for computation | ||||||||
13769 | QualType CompResultTy; // Type of computation result | ||||||||
13770 | ExprValueKind VK = VK_RValue; | ||||||||
13771 | ExprObjectKind OK = OK_Ordinary; | ||||||||
13772 | bool ConvertHalfVec = false; | ||||||||
13773 | |||||||||
13774 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||||||
13775 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||||||
13776 | return ExprError(); | ||||||||
13777 | |||||||||
13778 | if (getLangOpts().OpenCL) { | ||||||||
13779 | QualType LHSTy = LHSExpr->getType(); | ||||||||
13780 | QualType RHSTy = RHSExpr->getType(); | ||||||||
13781 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | ||||||||
13782 | // the ATOMIC_VAR_INIT macro. | ||||||||
13783 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | ||||||||
13784 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||||||
13785 | if (BO_Assign == Opc) | ||||||||
13786 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | ||||||||
13787 | else | ||||||||
13788 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||||||
13789 | return ExprError(); | ||||||||
13790 | } | ||||||||
13791 | |||||||||
13792 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||||||
13793 | // only with a builtin functions and therefore should be disallowed here. | ||||||||
13794 | if (LHSTy->isImageType() || RHSTy->isImageType() || | ||||||||
13795 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | ||||||||
13796 | LHSTy->isPipeType() || RHSTy->isPipeType() || | ||||||||
13797 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | ||||||||
13798 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||||||
13799 | return ExprError(); | ||||||||
13800 | } | ||||||||
13801 | } | ||||||||
13802 | |||||||||
13803 | switch (Opc) { | ||||||||
13804 | case BO_Assign: | ||||||||
13805 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | ||||||||
13806 | if (getLangOpts().CPlusPlus && | ||||||||
13807 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | ||||||||
13808 | VK = LHS.get()->getValueKind(); | ||||||||
13809 | OK = LHS.get()->getObjectKind(); | ||||||||
13810 | } | ||||||||
13811 | if (!ResultTy.isNull()) { | ||||||||
13812 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||||||
13813 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | ||||||||
13814 | |||||||||
13815 | // Avoid copying a block to the heap if the block is assigned to a local | ||||||||
13816 | // auto variable that is declared in the same scope as the block. This | ||||||||
13817 | // optimization is unsafe if the local variable is declared in an outer | ||||||||
13818 | // scope. For example: | ||||||||
13819 | // | ||||||||
13820 | // BlockTy b; | ||||||||
13821 | // { | ||||||||
13822 | // b = ^{...}; | ||||||||
13823 | // } | ||||||||
13824 | // // It is unsafe to invoke the block here if it wasn't copied to the | ||||||||
13825 | // // heap. | ||||||||
13826 | // b(); | ||||||||
13827 | |||||||||
13828 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | ||||||||
13829 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | ||||||||
13830 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | ||||||||
13831 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | ||||||||
13832 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||||||
13833 | |||||||||
13834 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||||
13835 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | ||||||||
13836 | NTCUC_Assignment, NTCUK_Copy); | ||||||||
13837 | } | ||||||||
13838 | RecordModifiableNonNullParam(*this, LHS.get()); | ||||||||
13839 | break; | ||||||||
13840 | case BO_PtrMemD: | ||||||||
13841 | case BO_PtrMemI: | ||||||||
13842 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | ||||||||
13843 | Opc == BO_PtrMemI); | ||||||||
13844 | break; | ||||||||
13845 | case BO_Mul: | ||||||||
13846 | case BO_Div: | ||||||||
13847 | ConvertHalfVec = true; | ||||||||
13848 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | ||||||||
13849 | Opc == BO_Div); | ||||||||
13850 | break; | ||||||||
13851 | case BO_Rem: | ||||||||
13852 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | ||||||||
13853 | break; | ||||||||
13854 | case BO_Add: | ||||||||
13855 | ConvertHalfVec = true; | ||||||||
13856 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13857 | break; | ||||||||
13858 | case BO_Sub: | ||||||||
13859 | ConvertHalfVec = true; | ||||||||
13860 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | ||||||||
13861 | break; | ||||||||
13862 | case BO_Shl: | ||||||||
13863 | case BO_Shr: | ||||||||
13864 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13865 | break; | ||||||||
13866 | case BO_LE: | ||||||||
13867 | case BO_LT: | ||||||||
13868 | case BO_GE: | ||||||||
13869 | case BO_GT: | ||||||||
13870 | ConvertHalfVec = true; | ||||||||
13871 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13872 | break; | ||||||||
13873 | case BO_EQ: | ||||||||
13874 | case BO_NE: | ||||||||
13875 | ConvertHalfVec = true; | ||||||||
13876 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13877 | break; | ||||||||
13878 | case BO_Cmp: | ||||||||
13879 | ConvertHalfVec = true; | ||||||||
13880 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13881 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast <void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13881, __PRETTY_FUNCTION__)); | ||||||||
13882 | break; | ||||||||
13883 | case BO_And: | ||||||||
13884 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | ||||||||
13885 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
13886 | case BO_Xor: | ||||||||
13887 | case BO_Or: | ||||||||
13888 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13889 | break; | ||||||||
13890 | case BO_LAnd: | ||||||||
13891 | case BO_LOr: | ||||||||
13892 | ConvertHalfVec = true; | ||||||||
13893 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13894 | break; | ||||||||
13895 | case BO_MulAssign: | ||||||||
13896 | case BO_DivAssign: | ||||||||
13897 | ConvertHalfVec = true; | ||||||||
13898 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | ||||||||
13899 | Opc == BO_DivAssign); | ||||||||
13900 | CompLHSTy = CompResultTy; | ||||||||
13901 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||||||
13902 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||||||
13903 | break; | ||||||||
13904 | case BO_RemAssign: | ||||||||
13905 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | ||||||||
13906 | CompLHSTy = CompResultTy; | ||||||||
13907 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||||||
13908 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||||||
13909 | break; | ||||||||
13910 | case BO_AddAssign: | ||||||||
13911 | ConvertHalfVec = true; | ||||||||
13912 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | ||||||||
13913 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||||||
13914 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||||||
13915 | break; | ||||||||
13916 | case BO_SubAssign: | ||||||||
13917 | ConvertHalfVec = true; | ||||||||
13918 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | ||||||||
13919 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||||||
13920 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||||||
13921 | break; | ||||||||
13922 | case BO_ShlAssign: | ||||||||
13923 | case BO_ShrAssign: | ||||||||
13924 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | ||||||||
13925 | CompLHSTy = CompResultTy; | ||||||||
13926 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||||||
13927 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||||||
13928 | break; | ||||||||
13929 | case BO_AndAssign: | ||||||||
13930 | case BO_OrAssign: // fallthrough | ||||||||
13931 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||||||
13932 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||
13933 | case BO_XorAssign: | ||||||||
13934 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||||||
13935 | CompLHSTy = CompResultTy; | ||||||||
13936 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||||||
13937 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||||||
13938 | break; | ||||||||
13939 | case BO_Comma: | ||||||||
13940 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | ||||||||
13941 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | ||||||||
13942 | VK = RHS.get()->getValueKind(); | ||||||||
13943 | OK = RHS.get()->getObjectKind(); | ||||||||
13944 | } | ||||||||
13945 | break; | ||||||||
13946 | } | ||||||||
13947 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | ||||||||
13948 | return ExprError(); | ||||||||
13949 | |||||||||
13950 | // Some of the binary operations require promoting operands of half vector to | ||||||||
13951 | // float vectors and truncating the result back to half vector. For now, we do | ||||||||
13952 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | ||||||||
13953 | // arm64). | ||||||||
13954 | assert((((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13957, __PRETTY_FUNCTION__)) | ||||||||
13955 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13957, __PRETTY_FUNCTION__)) | ||||||||
13956 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13957, __PRETTY_FUNCTION__)) | ||||||||
13957 | "both sides are half vectors or neither sides are")(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<void> (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 13957, __PRETTY_FUNCTION__)); | ||||||||
13958 | ConvertHalfVec = | ||||||||
13959 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | ||||||||
13960 | |||||||||
13961 | // Check for array bounds violations for both sides of the BinaryOperator | ||||||||
13962 | CheckArrayAccess(LHS.get()); | ||||||||
13963 | CheckArrayAccess(RHS.get()); | ||||||||
13964 | |||||||||
13965 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | ||||||||
13966 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | ||||||||
13967 | &Context.Idents.get("object_setClass"), | ||||||||
13968 | SourceLocation(), LookupOrdinaryName); | ||||||||
13969 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | ||||||||
13970 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||||||
13971 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | ||||||||
13972 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | ||||||||
13973 | "object_setClass(") | ||||||||
13974 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | ||||||||
13975 | ",") | ||||||||
13976 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||||||
13977 | } | ||||||||
13978 | else | ||||||||
13979 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | ||||||||
13980 | } | ||||||||
13981 | else if (const ObjCIvarRefExpr *OIRE = | ||||||||
13982 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | ||||||||
13983 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | ||||||||
13984 | |||||||||
13985 | // Opc is not a compound assignment if CompResultTy is null. | ||||||||
13986 | if (CompResultTy.isNull()) { | ||||||||
13987 | if (ConvertHalfVec) | ||||||||
13988 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | ||||||||
13989 | OpLoc, CurFPFeatureOverrides()); | ||||||||
13990 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | ||||||||
13991 | VK, OK, OpLoc, CurFPFeatureOverrides()); | ||||||||
13992 | } | ||||||||
13993 | |||||||||
13994 | // Handle compound assignments. | ||||||||
13995 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | ||||||||
13996 | OK_ObjCProperty) { | ||||||||
13997 | VK = VK_LValue; | ||||||||
13998 | OK = LHS.get()->getObjectKind(); | ||||||||
13999 | } | ||||||||
14000 | |||||||||
14001 | // The LHS is not converted to the result type for fixed-point compound | ||||||||
14002 | // assignment as the common type is computed on demand. Reset the CompLHSTy | ||||||||
14003 | // to the LHS type we would have gotten after unary conversions. | ||||||||
14004 | if (CompResultTy->isFixedPointType()) | ||||||||
14005 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | ||||||||
14006 | |||||||||
14007 | if (ConvertHalfVec) | ||||||||
14008 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | ||||||||
14009 | OpLoc, CurFPFeatureOverrides()); | ||||||||
14010 | |||||||||
14011 | return CompoundAssignOperator::Create( | ||||||||
14012 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | ||||||||
14013 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | ||||||||
14014 | } | ||||||||
14015 | |||||||||
14016 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | ||||||||
14017 | /// operators are mixed in a way that suggests that the programmer forgot that | ||||||||
14018 | /// comparison operators have higher precedence. The most typical example of | ||||||||
14019 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | ||||||||
14020 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||||||
14021 | SourceLocation OpLoc, Expr *LHSExpr, | ||||||||
14022 | Expr *RHSExpr) { | ||||||||
14023 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | ||||||||
14024 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | ||||||||
14025 | |||||||||
14026 | // Check that one of the sides is a comparison operator and the other isn't. | ||||||||
14027 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | ||||||||
14028 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | ||||||||
14029 | if (isLeftComp == isRightComp) | ||||||||
14030 | return; | ||||||||
14031 | |||||||||
14032 | // Bitwise operations are sometimes used as eager logical ops. | ||||||||
14033 | // Don't diagnose this. | ||||||||
14034 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | ||||||||
14035 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | ||||||||
14036 | if (isLeftBitwise || isRightBitwise) | ||||||||
14037 | return; | ||||||||
14038 | |||||||||
14039 | SourceRange DiagRange = isLeftComp | ||||||||
14040 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | ||||||||
14041 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | ||||||||
14042 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | ||||||||
14043 | SourceRange ParensRange = | ||||||||
14044 | isLeftComp | ||||||||
14045 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | ||||||||
14046 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | ||||||||
14047 | |||||||||
14048 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | ||||||||
14049 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | ||||||||
14050 | SuggestParentheses(Self, OpLoc, | ||||||||
14051 | Self.PDiag(diag::note_precedence_silence) << OpStr, | ||||||||
14052 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | ||||||||
14053 | SuggestParentheses(Self, OpLoc, | ||||||||
14054 | Self.PDiag(diag::note_precedence_bitwise_first) | ||||||||
14055 | << BinaryOperator::getOpcodeStr(Opc), | ||||||||
14056 | ParensRange); | ||||||||
14057 | } | ||||||||
14058 | |||||||||
14059 | /// It accepts a '&&' expr that is inside a '||' one. | ||||||||
14060 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | ||||||||
14061 | /// in parentheses. | ||||||||
14062 | static void | ||||||||
14063 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | ||||||||
14064 | BinaryOperator *Bop) { | ||||||||
14065 | assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> ( 0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14065, __PRETTY_FUNCTION__)); | ||||||||
14066 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | ||||||||
14067 | << Bop->getSourceRange() << OpLoc; | ||||||||
14068 | SuggestParentheses(Self, Bop->getOperatorLoc(), | ||||||||
14069 | Self.PDiag(diag::note_precedence_silence) | ||||||||
14070 | << Bop->getOpcodeStr(), | ||||||||
14071 | Bop->getSourceRange()); | ||||||||
14072 | } | ||||||||
14073 | |||||||||
14074 | /// Returns true if the given expression can be evaluated as a constant | ||||||||
14075 | /// 'true'. | ||||||||
14076 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | ||||||||
14077 | bool Res; | ||||||||
14078 | return !E->isValueDependent() && | ||||||||
14079 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | ||||||||
14080 | } | ||||||||
14081 | |||||||||
14082 | /// Returns true if the given expression can be evaluated as a constant | ||||||||
14083 | /// 'false'. | ||||||||
14084 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | ||||||||
14085 | bool Res; | ||||||||
14086 | return !E->isValueDependent() && | ||||||||
14087 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | ||||||||
14088 | } | ||||||||
14089 | |||||||||
14090 | /// Look for '&&' in the left hand of a '||' expr. | ||||||||
14091 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | ||||||||
14092 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
14093 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | ||||||||
14094 | if (Bop->getOpcode() == BO_LAnd) { | ||||||||
14095 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | ||||||||
14096 | if (EvaluatesAsFalse(S, RHSExpr)) | ||||||||
14097 | return; | ||||||||
14098 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | ||||||||
14099 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | ||||||||
14100 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||||||
14101 | } else if (Bop->getOpcode() == BO_LOr) { | ||||||||
14102 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | ||||||||
14103 | // If it's "a || b && 1 || c" we didn't warn earlier for | ||||||||
14104 | // "a || b && 1", but warn now. | ||||||||
14105 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | ||||||||
14106 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | ||||||||
14107 | } | ||||||||
14108 | } | ||||||||
14109 | } | ||||||||
14110 | } | ||||||||
14111 | |||||||||
14112 | /// Look for '&&' in the right hand of a '||' expr. | ||||||||
14113 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | ||||||||
14114 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
14115 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | ||||||||
14116 | if (Bop->getOpcode() == BO_LAnd) { | ||||||||
14117 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | ||||||||
14118 | if (EvaluatesAsFalse(S, LHSExpr)) | ||||||||
14119 | return; | ||||||||
14120 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | ||||||||
14121 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | ||||||||
14122 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||||||
14123 | } | ||||||||
14124 | } | ||||||||
14125 | } | ||||||||
14126 | |||||||||
14127 | /// Look for bitwise op in the left or right hand of a bitwise op with | ||||||||
14128 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | ||||||||
14129 | /// the '&' expression in parentheses. | ||||||||
14130 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | ||||||||
14131 | SourceLocation OpLoc, Expr *SubExpr) { | ||||||||
14132 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||||||
14133 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | ||||||||
14134 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | ||||||||
14135 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | ||||||||
14136 | << Bop->getSourceRange() << OpLoc; | ||||||||
14137 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||||||
14138 | S.PDiag(diag::note_precedence_silence) | ||||||||
14139 | << Bop->getOpcodeStr(), | ||||||||
14140 | Bop->getSourceRange()); | ||||||||
14141 | } | ||||||||
14142 | } | ||||||||
14143 | } | ||||||||
14144 | |||||||||
14145 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | ||||||||
14146 | Expr *SubExpr, StringRef Shift) { | ||||||||
14147 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||||||
14148 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | ||||||||
14149 | StringRef Op = Bop->getOpcodeStr(); | ||||||||
14150 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | ||||||||
14151 | << Bop->getSourceRange() << OpLoc << Shift << Op; | ||||||||
14152 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||||||
14153 | S.PDiag(diag::note_precedence_silence) << Op, | ||||||||
14154 | Bop->getSourceRange()); | ||||||||
14155 | } | ||||||||
14156 | } | ||||||||
14157 | } | ||||||||
14158 | |||||||||
14159 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | ||||||||
14160 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
14161 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | ||||||||
14162 | if (!OCE) | ||||||||
14163 | return; | ||||||||
14164 | |||||||||
14165 | FunctionDecl *FD = OCE->getDirectCallee(); | ||||||||
14166 | if (!FD || !FD->isOverloadedOperator()) | ||||||||
14167 | return; | ||||||||
14168 | |||||||||
14169 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | ||||||||
14170 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | ||||||||
14171 | return; | ||||||||
14172 | |||||||||
14173 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | ||||||||
14174 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | ||||||||
14175 | << (Kind == OO_LessLess); | ||||||||
14176 | SuggestParentheses(S, OCE->getOperatorLoc(), | ||||||||
14177 | S.PDiag(diag::note_precedence_silence) | ||||||||
14178 | << (Kind == OO_LessLess ? "<<" : ">>"), | ||||||||
14179 | OCE->getSourceRange()); | ||||||||
14180 | SuggestParentheses( | ||||||||
14181 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | ||||||||
14182 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | ||||||||
14183 | } | ||||||||
14184 | |||||||||
14185 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | ||||||||
14186 | /// precedence. | ||||||||
14187 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||||||
14188 | SourceLocation OpLoc, Expr *LHSExpr, | ||||||||
14189 | Expr *RHSExpr){ | ||||||||
14190 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | ||||||||
14191 | if (BinaryOperator::isBitwiseOp(Opc)) | ||||||||
14192 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | ||||||||
14193 | |||||||||
14194 | // Diagnose "arg1 & arg2 | arg3" | ||||||||
14195 | if ((Opc == BO_Or || Opc == BO_Xor) && | ||||||||
14196 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||||||
14197 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | ||||||||
14198 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | ||||||||
14199 | } | ||||||||
14200 | |||||||||
14201 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | ||||||||
14202 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | ||||||||
14203 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||||||
14204 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||||||
14205 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||||||
14206 | } | ||||||||
14207 | |||||||||
14208 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | ||||||||
14209 | || Opc == BO_Shr) { | ||||||||
14210 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | ||||||||
14211 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | ||||||||
14212 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | ||||||||
14213 | } | ||||||||
14214 | |||||||||
14215 | // Warn on overloaded shift operators and comparisons, such as: | ||||||||
14216 | // cout << 5 == 4; | ||||||||
14217 | if (BinaryOperator::isComparisonOp(Opc)) | ||||||||
14218 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | ||||||||
14219 | } | ||||||||
14220 | |||||||||
14221 | // Binary Operators. 'Tok' is the token for the operator. | ||||||||
14222 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | ||||||||
14223 | tok::TokenKind Kind, | ||||||||
14224 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
14225 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | ||||||||
14226 | assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression") ? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14226, __PRETTY_FUNCTION__)); | ||||||||
14227 | assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression" ) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14227, __PRETTY_FUNCTION__)); | ||||||||
14228 | |||||||||
14229 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | ||||||||
14230 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | ||||||||
14231 | |||||||||
14232 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14233 | } | ||||||||
14234 | |||||||||
14235 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | ||||||||
14236 | UnresolvedSetImpl &Functions) { | ||||||||
14237 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | ||||||||
14238 | if (OverOp != OO_None && OverOp != OO_Equal) | ||||||||
14239 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||||||
14240 | |||||||||
14241 | // In C++20 onwards, we may have a second operator to look up. | ||||||||
14242 | if (getLangOpts().CPlusPlus20) { | ||||||||
14243 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | ||||||||
14244 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | ||||||||
14245 | } | ||||||||
14246 | } | ||||||||
14247 | |||||||||
14248 | /// Build an overloaded binary operator expression in the given scope. | ||||||||
14249 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | ||||||||
14250 | BinaryOperatorKind Opc, | ||||||||
14251 | Expr *LHS, Expr *RHS) { | ||||||||
14252 | switch (Opc) { | ||||||||
14253 | case BO_Assign: | ||||||||
14254 | case BO_DivAssign: | ||||||||
14255 | case BO_RemAssign: | ||||||||
14256 | case BO_SubAssign: | ||||||||
14257 | case BO_AndAssign: | ||||||||
14258 | case BO_OrAssign: | ||||||||
14259 | case BO_XorAssign: | ||||||||
14260 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | ||||||||
14261 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | ||||||||
14262 | break; | ||||||||
14263 | default: | ||||||||
14264 | break; | ||||||||
14265 | } | ||||||||
14266 | |||||||||
14267 | // Find all of the overloaded operators visible from this point. | ||||||||
14268 | UnresolvedSet<16> Functions; | ||||||||
14269 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | ||||||||
14270 | |||||||||
14271 | // Build the (potentially-overloaded, potentially-dependent) | ||||||||
14272 | // binary operation. | ||||||||
14273 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | ||||||||
14274 | } | ||||||||
14275 | |||||||||
14276 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | ||||||||
14277 | BinaryOperatorKind Opc, | ||||||||
14278 | Expr *LHSExpr, Expr *RHSExpr) { | ||||||||
14279 | ExprResult LHS, RHS; | ||||||||
14280 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||||||
14281 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||||||
14282 | return ExprError(); | ||||||||
14283 | LHSExpr = LHS.get(); | ||||||||
14284 | RHSExpr = RHS.get(); | ||||||||
14285 | |||||||||
14286 | // We want to end up calling one of checkPseudoObjectAssignment | ||||||||
14287 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | ||||||||
14288 | // both expressions are overloadable or either is type-dependent), | ||||||||
14289 | // or CreateBuiltinBinOp (in any other case). We also want to get | ||||||||
14290 | // any placeholder types out of the way. | ||||||||
14291 | |||||||||
14292 | // Handle pseudo-objects in the LHS. | ||||||||
14293 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | ||||||||
14294 | // Assignments with a pseudo-object l-value need special analysis. | ||||||||
14295 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||||||
14296 | BinaryOperator::isAssignmentOp(Opc)) | ||||||||
14297 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14298 | |||||||||
14299 | // Don't resolve overloads if the other type is overloadable. | ||||||||
14300 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | ||||||||
14301 | // We can't actually test that if we still have a placeholder, | ||||||||
14302 | // though. Fortunately, none of the exceptions we see in that | ||||||||
14303 | // code below are valid when the LHS is an overload set. Note | ||||||||
14304 | // that an overload set can be dependently-typed, but it never | ||||||||
14305 | // instantiates to having an overloadable type. | ||||||||
14306 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||||||
14307 | if (resolvedRHS.isInvalid()) return ExprError(); | ||||||||
14308 | RHSExpr = resolvedRHS.get(); | ||||||||
14309 | |||||||||
14310 | if (RHSExpr->isTypeDependent() || | ||||||||
14311 | RHSExpr->getType()->isOverloadableType()) | ||||||||
14312 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14313 | } | ||||||||
14314 | |||||||||
14315 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | ||||||||
14316 | // template, diagnose the missing 'template' keyword instead of diagnosing | ||||||||
14317 | // an invalid use of a bound member function. | ||||||||
14318 | // | ||||||||
14319 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | ||||||||
14320 | // to C++1z [over.over]/1.4, but we already checked for that case above. | ||||||||
14321 | if (Opc == BO_LT && inTemplateInstantiation() && | ||||||||
14322 | (pty->getKind() == BuiltinType::BoundMember || | ||||||||
14323 | pty->getKind() == BuiltinType::Overload)) { | ||||||||
14324 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | ||||||||
14325 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | ||||||||
14326 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | ||||||||
14327 | return isa<FunctionTemplateDecl>(ND); | ||||||||
14328 | })) { | ||||||||
14329 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | ||||||||
14330 | : OE->getNameLoc(), | ||||||||
14331 | diag::err_template_kw_missing) | ||||||||
14332 | << OE->getName().getAsString() << ""; | ||||||||
14333 | return ExprError(); | ||||||||
14334 | } | ||||||||
14335 | } | ||||||||
14336 | |||||||||
14337 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | ||||||||
14338 | if (LHS.isInvalid()) return ExprError(); | ||||||||
14339 | LHSExpr = LHS.get(); | ||||||||
14340 | } | ||||||||
14341 | |||||||||
14342 | // Handle pseudo-objects in the RHS. | ||||||||
14343 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | ||||||||
14344 | // An overload in the RHS can potentially be resolved by the type | ||||||||
14345 | // being assigned to. | ||||||||
14346 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | ||||||||
14347 | if (getLangOpts().CPlusPlus && | ||||||||
14348 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | ||||||||
14349 | LHSExpr->getType()->isOverloadableType())) | ||||||||
14350 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14351 | |||||||||
14352 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14353 | } | ||||||||
14354 | |||||||||
14355 | // Don't resolve overloads if the other type is overloadable. | ||||||||
14356 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | ||||||||
14357 | LHSExpr->getType()->isOverloadableType()) | ||||||||
14358 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14359 | |||||||||
14360 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||||||
14361 | if (!resolvedRHS.isUsable()) return ExprError(); | ||||||||
14362 | RHSExpr = resolvedRHS.get(); | ||||||||
14363 | } | ||||||||
14364 | |||||||||
14365 | if (getLangOpts().CPlusPlus) { | ||||||||
14366 | // If either expression is type-dependent, always build an | ||||||||
14367 | // overloaded op. | ||||||||
14368 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | ||||||||
14369 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14370 | |||||||||
14371 | // Otherwise, build an overloaded op if either expression has an | ||||||||
14372 | // overloadable type. | ||||||||
14373 | if (LHSExpr->getType()->isOverloadableType() || | ||||||||
14374 | RHSExpr->getType()->isOverloadableType()) | ||||||||
14375 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14376 | } | ||||||||
14377 | |||||||||
14378 | if (getLangOpts().RecoveryAST && | ||||||||
14379 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | ||||||||
14380 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14380, __PRETTY_FUNCTION__)); | ||||||||
14381 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14382, __PRETTY_FUNCTION__)) | ||||||||
14382 | "Should only occur in error-recovery path.")(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14382, __PRETTY_FUNCTION__)); | ||||||||
14383 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | ||||||||
14384 | // C [6.15.16] p3: | ||||||||
14385 | // An assignment expression has the value of the left operand after the | ||||||||
14386 | // assignment, but is not an lvalue. | ||||||||
14387 | return CompoundAssignOperator::Create( | ||||||||
14388 | Context, LHSExpr, RHSExpr, Opc, | ||||||||
14389 | LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, | ||||||||
14390 | OpLoc, CurFPFeatureOverrides()); | ||||||||
14391 | QualType ResultType; | ||||||||
14392 | switch (Opc) { | ||||||||
14393 | case BO_Assign: | ||||||||
14394 | ResultType = LHSExpr->getType().getUnqualifiedType(); | ||||||||
14395 | break; | ||||||||
14396 | case BO_LT: | ||||||||
14397 | case BO_GT: | ||||||||
14398 | case BO_LE: | ||||||||
14399 | case BO_GE: | ||||||||
14400 | case BO_EQ: | ||||||||
14401 | case BO_NE: | ||||||||
14402 | case BO_LAnd: | ||||||||
14403 | case BO_LOr: | ||||||||
14404 | // These operators have a fixed result type regardless of operands. | ||||||||
14405 | ResultType = Context.IntTy; | ||||||||
14406 | break; | ||||||||
14407 | case BO_Comma: | ||||||||
14408 | ResultType = RHSExpr->getType(); | ||||||||
14409 | break; | ||||||||
14410 | default: | ||||||||
14411 | ResultType = Context.DependentTy; | ||||||||
14412 | break; | ||||||||
14413 | } | ||||||||
14414 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | ||||||||
14415 | VK_RValue, OK_Ordinary, OpLoc, | ||||||||
14416 | CurFPFeatureOverrides()); | ||||||||
14417 | } | ||||||||
14418 | |||||||||
14419 | // Build a built-in binary operation. | ||||||||
14420 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||||||
14421 | } | ||||||||
14422 | |||||||||
14423 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | ||||||||
14424 | if (T.isNull() || T->isDependentType()) | ||||||||
14425 | return false; | ||||||||
14426 | |||||||||
14427 | if (!T->isPromotableIntegerType()) | ||||||||
14428 | return true; | ||||||||
14429 | |||||||||
14430 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | ||||||||
14431 | } | ||||||||
14432 | |||||||||
14433 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | ||||||||
14434 | UnaryOperatorKind Opc, | ||||||||
14435 | Expr *InputExpr) { | ||||||||
14436 | ExprResult Input = InputExpr; | ||||||||
14437 | ExprValueKind VK = VK_RValue; | ||||||||
14438 | ExprObjectKind OK = OK_Ordinary; | ||||||||
14439 | QualType resultType; | ||||||||
14440 | bool CanOverflow = false; | ||||||||
14441 | |||||||||
14442 | bool ConvertHalfVec = false; | ||||||||
14443 | if (getLangOpts().OpenCL) { | ||||||||
14444 | QualType Ty = InputExpr->getType(); | ||||||||
14445 | // The only legal unary operation for atomics is '&'. | ||||||||
14446 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | ||||||||
14447 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||||||
14448 | // only with a builtin functions and therefore should be disallowed here. | ||||||||
14449 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | ||||||||
14450 | || Ty->isBlockPointerType())) { | ||||||||
14451 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14452 | << InputExpr->getType() | ||||||||
14453 | << Input.get()->getSourceRange()); | ||||||||
14454 | } | ||||||||
14455 | } | ||||||||
14456 | |||||||||
14457 | switch (Opc) { | ||||||||
14458 | case UO_PreInc: | ||||||||
14459 | case UO_PreDec: | ||||||||
14460 | case UO_PostInc: | ||||||||
14461 | case UO_PostDec: | ||||||||
14462 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | ||||||||
14463 | OpLoc, | ||||||||
14464 | Opc == UO_PreInc || | ||||||||
14465 | Opc == UO_PostInc, | ||||||||
14466 | Opc == UO_PreInc || | ||||||||
14467 | Opc == UO_PreDec); | ||||||||
14468 | CanOverflow = isOverflowingIntegerType(Context, resultType); | ||||||||
14469 | break; | ||||||||
14470 | case UO_AddrOf: | ||||||||
14471 | resultType = CheckAddressOfOperand(Input, OpLoc); | ||||||||
14472 | CheckAddressOfNoDeref(InputExpr); | ||||||||
14473 | RecordModifiableNonNullParam(*this, InputExpr); | ||||||||
14474 | break; | ||||||||
14475 | case UO_Deref: { | ||||||||
14476 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||||||
14477 | if (Input.isInvalid()) return ExprError(); | ||||||||
14478 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | ||||||||
14479 | break; | ||||||||
14480 | } | ||||||||
14481 | case UO_Plus: | ||||||||
14482 | case UO_Minus: | ||||||||
14483 | CanOverflow = Opc == UO_Minus && | ||||||||
14484 | isOverflowingIntegerType(Context, Input.get()->getType()); | ||||||||
14485 | Input = UsualUnaryConversions(Input.get()); | ||||||||
14486 | if (Input.isInvalid()) return ExprError(); | ||||||||
14487 | // Unary plus and minus require promoting an operand of half vector to a | ||||||||
14488 | // float vector and truncating the result back to a half vector. For now, we | ||||||||
14489 | // do this only when HalfArgsAndReturns is set (that is, when the target is | ||||||||
14490 | // arm or arm64). | ||||||||
14491 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | ||||||||
14492 | |||||||||
14493 | // If the operand is a half vector, promote it to a float vector. | ||||||||
14494 | if (ConvertHalfVec) | ||||||||
14495 | Input = convertVector(Input.get(), Context.FloatTy, *this); | ||||||||
14496 | resultType = Input.get()->getType(); | ||||||||
14497 | if (resultType->isDependentType()) | ||||||||
14498 | break; | ||||||||
14499 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | ||||||||
14500 | break; | ||||||||
14501 | else if (resultType->isVectorType() && | ||||||||
14502 | // The z vector extensions don't allow + or - with bool vectors. | ||||||||
14503 | (!Context.getLangOpts().ZVector || | ||||||||
14504 | resultType->castAs<VectorType>()->getVectorKind() != | ||||||||
14505 | VectorType::AltiVecBool)) | ||||||||
14506 | break; | ||||||||
14507 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | ||||||||
14508 | Opc == UO_Plus && | ||||||||
14509 | resultType->isPointerType()) | ||||||||
14510 | break; | ||||||||
14511 | |||||||||
14512 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14513 | << resultType << Input.get()->getSourceRange()); | ||||||||
14514 | |||||||||
14515 | case UO_Not: // bitwise complement | ||||||||
14516 | Input = UsualUnaryConversions(Input.get()); | ||||||||
14517 | if (Input.isInvalid()) | ||||||||
14518 | return ExprError(); | ||||||||
14519 | resultType = Input.get()->getType(); | ||||||||
14520 | if (resultType->isDependentType()) | ||||||||
14521 | break; | ||||||||
14522 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | ||||||||
14523 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | ||||||||
14524 | // C99 does not support '~' for complex conjugation. | ||||||||
14525 | Diag(OpLoc, diag::ext_integer_complement_complex) | ||||||||
14526 | << resultType << Input.get()->getSourceRange(); | ||||||||
14527 | else if (resultType->hasIntegerRepresentation()) | ||||||||
14528 | break; | ||||||||
14529 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | ||||||||
14530 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | ||||||||
14531 | // on vector float types. | ||||||||
14532 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||||||
14533 | if (!T->isIntegerType()) | ||||||||
14534 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14535 | << resultType << Input.get()->getSourceRange()); | ||||||||
14536 | } else { | ||||||||
14537 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14538 | << resultType << Input.get()->getSourceRange()); | ||||||||
14539 | } | ||||||||
14540 | break; | ||||||||
14541 | |||||||||
14542 | case UO_LNot: // logical negation | ||||||||
14543 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | ||||||||
14544 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||||||
14545 | if (Input.isInvalid()) return ExprError(); | ||||||||
14546 | resultType = Input.get()->getType(); | ||||||||
14547 | |||||||||
14548 | // Though we still have to promote half FP to float... | ||||||||
14549 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | ||||||||
14550 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | ||||||||
14551 | resultType = Context.FloatTy; | ||||||||
14552 | } | ||||||||
14553 | |||||||||
14554 | if (resultType->isDependentType()) | ||||||||
14555 | break; | ||||||||
14556 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | ||||||||
14557 | // C99 6.5.3.3p1: ok, fallthrough; | ||||||||
14558 | if (Context.getLangOpts().CPlusPlus) { | ||||||||
14559 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | ||||||||
14560 | // operand contextually converted to bool. | ||||||||
14561 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | ||||||||
14562 | ScalarTypeToBooleanCastKind(resultType)); | ||||||||
14563 | } else if (Context.getLangOpts().OpenCL && | ||||||||
14564 | Context.getLangOpts().OpenCLVersion < 120) { | ||||||||
14565 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||||||
14566 | // operate on scalar float types. | ||||||||
14567 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | ||||||||
14568 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14569 | << resultType << Input.get()->getSourceRange()); | ||||||||
14570 | } | ||||||||
14571 | } else if (resultType->isExtVectorType()) { | ||||||||
14572 | if (Context.getLangOpts().OpenCL && | ||||||||
14573 | Context.getLangOpts().OpenCLVersion < 120 && | ||||||||
14574 | !Context.getLangOpts().OpenCLCPlusPlus) { | ||||||||
14575 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||||||
14576 | // operate on vector float types. | ||||||||
14577 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||||||
14578 | if (!T->isIntegerType()) | ||||||||
14579 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14580 | << resultType << Input.get()->getSourceRange()); | ||||||||
14581 | } | ||||||||
14582 | // Vector logical not returns the signed variant of the operand type. | ||||||||
14583 | resultType = GetSignedVectorType(resultType); | ||||||||
14584 | break; | ||||||||
14585 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | ||||||||
14586 | const VectorType *VTy = resultType->castAs<VectorType>(); | ||||||||
14587 | if (VTy->getVectorKind() != VectorType::GenericVector) | ||||||||
14588 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14589 | << resultType << Input.get()->getSourceRange()); | ||||||||
14590 | |||||||||
14591 | // Vector logical not returns the signed variant of the operand type. | ||||||||
14592 | resultType = GetSignedVectorType(resultType); | ||||||||
14593 | break; | ||||||||
14594 | } else { | ||||||||
14595 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||||||
14596 | << resultType << Input.get()->getSourceRange()); | ||||||||
14597 | } | ||||||||
14598 | |||||||||
14599 | // LNot always has type int. C99 6.5.3.3p5. | ||||||||
14600 | // In C++, it's bool. C++ 5.3.1p8 | ||||||||
14601 | resultType = Context.getLogicalOperationType(); | ||||||||
14602 | break; | ||||||||
14603 | case UO_Real: | ||||||||
14604 | case UO_Imag: | ||||||||
14605 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | ||||||||
14606 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | ||||||||
14607 | // complex l-values to ordinary l-values and all other values to r-values. | ||||||||
14608 | if (Input.isInvalid()) return ExprError(); | ||||||||
14609 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | ||||||||
14610 | if (Input.get()->getValueKind() != VK_RValue && | ||||||||
14611 | Input.get()->getObjectKind() == OK_Ordinary) | ||||||||
14612 | VK = Input.get()->getValueKind(); | ||||||||
14613 | } else if (!getLangOpts().CPlusPlus) { | ||||||||
14614 | // In C, a volatile scalar is read by __imag. In C++, it is not. | ||||||||
14615 | Input = DefaultLvalueConversion(Input.get()); | ||||||||
14616 | } | ||||||||
14617 | break; | ||||||||
14618 | case UO_Extension: | ||||||||
14619 | resultType = Input.get()->getType(); | ||||||||
14620 | VK = Input.get()->getValueKind(); | ||||||||
14621 | OK = Input.get()->getObjectKind(); | ||||||||
14622 | break; | ||||||||
14623 | case UO_Coawait: | ||||||||
14624 | // It's unnecessary to represent the pass-through operator co_await in the | ||||||||
14625 | // AST; just return the input expression instead. | ||||||||
14626 | assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14628, __PRETTY_FUNCTION__)) | ||||||||
14627 | "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14628, __PRETTY_FUNCTION__)) | ||||||||
14628 | "building operator co_await")((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14628, __PRETTY_FUNCTION__)); | ||||||||
14629 | return Input; | ||||||||
14630 | } | ||||||||
14631 | if (resultType.isNull() || Input.isInvalid()) | ||||||||
14632 | return ExprError(); | ||||||||
14633 | |||||||||
14634 | // Check for array bounds violations in the operand of the UnaryOperator, | ||||||||
14635 | // except for the '*' and '&' operators that have to be handled specially | ||||||||
14636 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | ||||||||
14637 | // that are explicitly defined as valid by the standard). | ||||||||
14638 | if (Opc != UO_AddrOf && Opc != UO_Deref) | ||||||||
14639 | CheckArrayAccess(Input.get()); | ||||||||
14640 | |||||||||
14641 | auto *UO = | ||||||||
14642 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | ||||||||
14643 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | ||||||||
14644 | |||||||||
14645 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | ||||||||
14646 | !isa<ArrayType>(UO->getType().getDesugaredType(Context))) | ||||||||
14647 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | ||||||||
14648 | |||||||||
14649 | // Convert the result back to a half vector. | ||||||||
14650 | if (ConvertHalfVec) | ||||||||
14651 | return convertVector(UO, Context.HalfTy, *this); | ||||||||
14652 | return UO; | ||||||||
14653 | } | ||||||||
14654 | |||||||||
14655 | /// Determine whether the given expression is a qualified member | ||||||||
14656 | /// access expression, of a form that could be turned into a pointer to member | ||||||||
14657 | /// with the address-of operator. | ||||||||
14658 | bool Sema::isQualifiedMemberAccess(Expr *E) { | ||||||||
14659 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||||||
14660 | if (!DRE->getQualifier()) | ||||||||
14661 | return false; | ||||||||
14662 | |||||||||
14663 | ValueDecl *VD = DRE->getDecl(); | ||||||||
14664 | if (!VD->isCXXClassMember()) | ||||||||
14665 | return false; | ||||||||
14666 | |||||||||
14667 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | ||||||||
14668 | return true; | ||||||||
14669 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | ||||||||
14670 | return Method->isInstance(); | ||||||||
14671 | |||||||||
14672 | return false; | ||||||||
14673 | } | ||||||||
14674 | |||||||||
14675 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | ||||||||
14676 | if (!ULE->getQualifier()) | ||||||||
14677 | return false; | ||||||||
14678 | |||||||||
14679 | for (NamedDecl *D : ULE->decls()) { | ||||||||
14680 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | ||||||||
14681 | if (Method->isInstance()) | ||||||||
14682 | return true; | ||||||||
14683 | } else { | ||||||||
14684 | // Overload set does not contain methods. | ||||||||
14685 | break; | ||||||||
14686 | } | ||||||||
14687 | } | ||||||||
14688 | |||||||||
14689 | return false; | ||||||||
14690 | } | ||||||||
14691 | |||||||||
14692 | return false; | ||||||||
14693 | } | ||||||||
14694 | |||||||||
14695 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | ||||||||
14696 | UnaryOperatorKind Opc, Expr *Input) { | ||||||||
14697 | // First things first: handle placeholders so that the | ||||||||
14698 | // overloaded-operator check considers the right type. | ||||||||
14699 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | ||||||||
14700 | // Increment and decrement of pseudo-object references. | ||||||||
14701 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||||||
14702 | UnaryOperator::isIncrementDecrementOp(Opc)) | ||||||||
14703 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | ||||||||
14704 | |||||||||
14705 | // extension is always a builtin operator. | ||||||||
14706 | if (Opc == UO_Extension) | ||||||||
14707 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||||||
14708 | |||||||||
14709 | // & gets special logic for several kinds of placeholder. | ||||||||
14710 | // The builtin code knows what to do. | ||||||||
14711 | if (Opc == UO_AddrOf && | ||||||||
14712 | (pty->getKind() == BuiltinType::Overload || | ||||||||
14713 | pty->getKind() == BuiltinType::UnknownAny || | ||||||||
14714 | pty->getKind() == BuiltinType::BoundMember)) | ||||||||
14715 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||||||
14716 | |||||||||
14717 | // Anything else needs to be handled now. | ||||||||
14718 | ExprResult Result = CheckPlaceholderExpr(Input); | ||||||||
14719 | if (Result.isInvalid()) return ExprError(); | ||||||||
14720 | Input = Result.get(); | ||||||||
14721 | } | ||||||||
14722 | |||||||||
14723 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | ||||||||
14724 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | ||||||||
14725 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | ||||||||
14726 | // Find all of the overloaded operators visible from this point. | ||||||||
14727 | UnresolvedSet<16> Functions; | ||||||||
14728 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | ||||||||
14729 | if (S && OverOp != OO_None) | ||||||||
14730 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||||||
14731 | |||||||||
14732 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | ||||||||
14733 | } | ||||||||
14734 | |||||||||
14735 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||||||
14736 | } | ||||||||
14737 | |||||||||
14738 | // Unary Operators. 'Tok' is the token for the operator. | ||||||||
14739 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | ||||||||
14740 | tok::TokenKind Op, Expr *Input) { | ||||||||
14741 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | ||||||||
14742 | } | ||||||||
14743 | |||||||||
14744 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | ||||||||
14745 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | ||||||||
14746 | LabelDecl *TheDecl) { | ||||||||
14747 | TheDecl->markUsed(Context); | ||||||||
14748 | // Create the AST node. The address of a label always has type 'void*'. | ||||||||
14749 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | ||||||||
14750 | Context.getPointerType(Context.VoidTy)); | ||||||||
14751 | } | ||||||||
14752 | |||||||||
14753 | void Sema::ActOnStartStmtExpr() { | ||||||||
14754 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||||||
14755 | } | ||||||||
14756 | |||||||||
14757 | void Sema::ActOnStmtExprError() { | ||||||||
14758 | // Note that function is also called by TreeTransform when leaving a | ||||||||
14759 | // StmtExpr scope without rebuilding anything. | ||||||||
14760 | |||||||||
14761 | DiscardCleanupsInEvaluationContext(); | ||||||||
14762 | PopExpressionEvaluationContext(); | ||||||||
14763 | } | ||||||||
14764 | |||||||||
14765 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | ||||||||
14766 | SourceLocation RPLoc) { | ||||||||
14767 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | ||||||||
14768 | } | ||||||||
14769 | |||||||||
14770 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | ||||||||
14771 | SourceLocation RPLoc, unsigned TemplateDepth) { | ||||||||
14772 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!") ? static_cast<void> (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14772, __PRETTY_FUNCTION__)); | ||||||||
14773 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | ||||||||
14774 | |||||||||
14775 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||||||
14776 | DiscardCleanupsInEvaluationContext(); | ||||||||
14777 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14778, __PRETTY_FUNCTION__)) | ||||||||
14778 | "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14778, __PRETTY_FUNCTION__)); | ||||||||
14779 | PopExpressionEvaluationContext(); | ||||||||
14780 | |||||||||
14781 | // FIXME: there are a variety of strange constraints to enforce here, for | ||||||||
14782 | // example, it is not possible to goto into a stmt expression apparently. | ||||||||
14783 | // More semantic analysis is needed. | ||||||||
14784 | |||||||||
14785 | // If there are sub-stmts in the compound stmt, take the type of the last one | ||||||||
14786 | // as the type of the stmtexpr. | ||||||||
14787 | QualType Ty = Context.VoidTy; | ||||||||
14788 | bool StmtExprMayBindToTemp = false; | ||||||||
14789 | if (!Compound->body_empty()) { | ||||||||
14790 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | ||||||||
14791 | if (const auto *LastStmt = | ||||||||
14792 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | ||||||||
14793 | if (const Expr *Value = LastStmt->getExprStmt()) { | ||||||||
14794 | StmtExprMayBindToTemp = true; | ||||||||
14795 | Ty = Value->getType(); | ||||||||
14796 | } | ||||||||
14797 | } | ||||||||
14798 | } | ||||||||
14799 | |||||||||
14800 | // FIXME: Check that expression type is complete/non-abstract; statement | ||||||||
14801 | // expressions are not lvalues. | ||||||||
14802 | Expr *ResStmtExpr = | ||||||||
14803 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | ||||||||
14804 | if (StmtExprMayBindToTemp) | ||||||||
14805 | return MaybeBindToTemporary(ResStmtExpr); | ||||||||
14806 | return ResStmtExpr; | ||||||||
14807 | } | ||||||||
14808 | |||||||||
14809 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | ||||||||
14810 | if (ER.isInvalid()) | ||||||||
14811 | return ExprError(); | ||||||||
14812 | |||||||||
14813 | // Do function/array conversion on the last expression, but not | ||||||||
14814 | // lvalue-to-rvalue. However, initialize an unqualified type. | ||||||||
14815 | ER = DefaultFunctionArrayConversion(ER.get()); | ||||||||
14816 | if (ER.isInvalid()) | ||||||||
14817 | return ExprError(); | ||||||||
14818 | Expr *E = ER.get(); | ||||||||
14819 | |||||||||
14820 | if (E->isTypeDependent()) | ||||||||
14821 | return E; | ||||||||
14822 | |||||||||
14823 | // In ARC, if the final expression ends in a consume, splice | ||||||||
14824 | // the consume out and bind it later. In the alternate case | ||||||||
14825 | // (when dealing with a retainable type), the result | ||||||||
14826 | // initialization will create a produce. In both cases the | ||||||||
14827 | // result will be +1, and we'll need to balance that out with | ||||||||
14828 | // a bind. | ||||||||
14829 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | ||||||||
14830 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | ||||||||
14831 | return Cast->getSubExpr(); | ||||||||
14832 | |||||||||
14833 | // FIXME: Provide a better location for the initialization. | ||||||||
14834 | return PerformCopyInitialization( | ||||||||
14835 | InitializedEntity::InitializeStmtExprResult( | ||||||||
14836 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | ||||||||
14837 | SourceLocation(), E); | ||||||||
14838 | } | ||||||||
14839 | |||||||||
14840 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | ||||||||
14841 | TypeSourceInfo *TInfo, | ||||||||
14842 | ArrayRef<OffsetOfComponent> Components, | ||||||||
14843 | SourceLocation RParenLoc) { | ||||||||
14844 | QualType ArgTy = TInfo->getType(); | ||||||||
14845 | bool Dependent = ArgTy->isDependentType(); | ||||||||
14846 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | ||||||||
14847 | |||||||||
14848 | // We must have at least one component that refers to the type, and the first | ||||||||
14849 | // one is known to be a field designator. Verify that the ArgTy represents | ||||||||
14850 | // a struct/union/class. | ||||||||
14851 | if (!Dependent && !ArgTy->isRecordType()) | ||||||||
14852 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | ||||||||
14853 | << ArgTy << TypeRange); | ||||||||
14854 | |||||||||
14855 | // Type must be complete per C99 7.17p3 because a declaring a variable | ||||||||
14856 | // with an incomplete type would be ill-formed. | ||||||||
14857 | if (!Dependent | ||||||||
14858 | && RequireCompleteType(BuiltinLoc, ArgTy, | ||||||||
14859 | diag::err_offsetof_incomplete_type, TypeRange)) | ||||||||
14860 | return ExprError(); | ||||||||
14861 | |||||||||
14862 | bool DidWarnAboutNonPOD = false; | ||||||||
14863 | QualType CurrentType = ArgTy; | ||||||||
14864 | SmallVector<OffsetOfNode, 4> Comps; | ||||||||
14865 | SmallVector<Expr*, 4> Exprs; | ||||||||
14866 | for (const OffsetOfComponent &OC : Components) { | ||||||||
14867 | if (OC.isBrackets) { | ||||||||
14868 | // Offset of an array sub-field. TODO: Should we allow vector elements? | ||||||||
14869 | if (!CurrentType->isDependentType()) { | ||||||||
14870 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | ||||||||
14871 | if(!AT) | ||||||||
14872 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | ||||||||
14873 | << CurrentType); | ||||||||
14874 | CurrentType = AT->getElementType(); | ||||||||
14875 | } else | ||||||||
14876 | CurrentType = Context.DependentTy; | ||||||||
14877 | |||||||||
14878 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | ||||||||
14879 | if (IdxRval.isInvalid()) | ||||||||
14880 | return ExprError(); | ||||||||
14881 | Expr *Idx = IdxRval.get(); | ||||||||
14882 | |||||||||
14883 | // The expression must be an integral expression. | ||||||||
14884 | // FIXME: An integral constant expression? | ||||||||
14885 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | ||||||||
14886 | !Idx->getType()->isIntegerType()) | ||||||||
14887 | return ExprError( | ||||||||
14888 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | ||||||||
14889 | << Idx->getSourceRange()); | ||||||||
14890 | |||||||||
14891 | // Record this array index. | ||||||||
14892 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | ||||||||
14893 | Exprs.push_back(Idx); | ||||||||
14894 | continue; | ||||||||
14895 | } | ||||||||
14896 | |||||||||
14897 | // Offset of a field. | ||||||||
14898 | if (CurrentType->isDependentType()) { | ||||||||
14899 | // We have the offset of a field, but we can't look into the dependent | ||||||||
14900 | // type. Just record the identifier of the field. | ||||||||
14901 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | ||||||||
14902 | CurrentType = Context.DependentTy; | ||||||||
14903 | continue; | ||||||||
14904 | } | ||||||||
14905 | |||||||||
14906 | // We need to have a complete type to look into. | ||||||||
14907 | if (RequireCompleteType(OC.LocStart, CurrentType, | ||||||||
14908 | diag::err_offsetof_incomplete_type)) | ||||||||
14909 | return ExprError(); | ||||||||
14910 | |||||||||
14911 | // Look for the designated field. | ||||||||
14912 | const RecordType *RC = CurrentType->getAs<RecordType>(); | ||||||||
14913 | if (!RC) | ||||||||
14914 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | ||||||||
14915 | << CurrentType); | ||||||||
14916 | RecordDecl *RD = RC->getDecl(); | ||||||||
14917 | |||||||||
14918 | // C++ [lib.support.types]p5: | ||||||||
14919 | // The macro offsetof accepts a restricted set of type arguments in this | ||||||||
14920 | // International Standard. type shall be a POD structure or a POD union | ||||||||
14921 | // (clause 9). | ||||||||
14922 | // C++11 [support.types]p4: | ||||||||
14923 | // If type is not a standard-layout class (Clause 9), the results are | ||||||||
14924 | // undefined. | ||||||||
14925 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||||||
14926 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | ||||||||
14927 | unsigned DiagID = | ||||||||
14928 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | ||||||||
14929 | : diag::ext_offsetof_non_pod_type; | ||||||||
14930 | |||||||||
14931 | if (!IsSafe && !DidWarnAboutNonPOD && | ||||||||
14932 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | ||||||||
14933 | PDiag(DiagID) | ||||||||
14934 | << SourceRange(Components[0].LocStart, OC.LocEnd) | ||||||||
14935 | << CurrentType)) | ||||||||
14936 | DidWarnAboutNonPOD = true; | ||||||||
14937 | } | ||||||||
14938 | |||||||||
14939 | // Look for the field. | ||||||||
14940 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | ||||||||
14941 | LookupQualifiedName(R, RD); | ||||||||
14942 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | ||||||||
14943 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | ||||||||
14944 | if (!MemberDecl) { | ||||||||
14945 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | ||||||||
14946 | MemberDecl = IndirectMemberDecl->getAnonField(); | ||||||||
14947 | } | ||||||||
14948 | |||||||||
14949 | if (!MemberDecl) | ||||||||
14950 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | ||||||||
14951 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | ||||||||
14952 | OC.LocEnd)); | ||||||||
14953 | |||||||||
14954 | // C99 7.17p3: | ||||||||
14955 | // (If the specified member is a bit-field, the behavior is undefined.) | ||||||||
14956 | // | ||||||||
14957 | // We diagnose this as an error. | ||||||||
14958 | if (MemberDecl->isBitField()) { | ||||||||
14959 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | ||||||||
14960 | << MemberDecl->getDeclName() | ||||||||
14961 | << SourceRange(BuiltinLoc, RParenLoc); | ||||||||
14962 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | ||||||||
14963 | return ExprError(); | ||||||||
14964 | } | ||||||||
14965 | |||||||||
14966 | RecordDecl *Parent = MemberDecl->getParent(); | ||||||||
14967 | if (IndirectMemberDecl) | ||||||||
14968 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | ||||||||
14969 | |||||||||
14970 | // If the member was found in a base class, introduce OffsetOfNodes for | ||||||||
14971 | // the base class indirections. | ||||||||
14972 | CXXBasePaths Paths; | ||||||||
14973 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | ||||||||
14974 | Paths)) { | ||||||||
14975 | if (Paths.getDetectedVirtual()) { | ||||||||
14976 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | ||||||||
14977 | << MemberDecl->getDeclName() | ||||||||
14978 | << SourceRange(BuiltinLoc, RParenLoc); | ||||||||
14979 | return ExprError(); | ||||||||
14980 | } | ||||||||
14981 | |||||||||
14982 | CXXBasePath &Path = Paths.front(); | ||||||||
14983 | for (const CXXBasePathElement &B : Path) | ||||||||
14984 | Comps.push_back(OffsetOfNode(B.Base)); | ||||||||
14985 | } | ||||||||
14986 | |||||||||
14987 | if (IndirectMemberDecl) { | ||||||||
14988 | for (auto *FI : IndirectMemberDecl->chain()) { | ||||||||
14989 | assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 14989, __PRETTY_FUNCTION__)); | ||||||||
14990 | Comps.push_back(OffsetOfNode(OC.LocStart, | ||||||||
14991 | cast<FieldDecl>(FI), OC.LocEnd)); | ||||||||
14992 | } | ||||||||
14993 | } else | ||||||||
14994 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | ||||||||
14995 | |||||||||
14996 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||||||
14997 | } | ||||||||
14998 | |||||||||
14999 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | ||||||||
15000 | Comps, Exprs, RParenLoc); | ||||||||
15001 | } | ||||||||
15002 | |||||||||
15003 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | ||||||||
15004 | SourceLocation BuiltinLoc, | ||||||||
15005 | SourceLocation TypeLoc, | ||||||||
15006 | ParsedType ParsedArgTy, | ||||||||
15007 | ArrayRef<OffsetOfComponent> Components, | ||||||||
15008 | SourceLocation RParenLoc) { | ||||||||
15009 | |||||||||
15010 | TypeSourceInfo *ArgTInfo; | ||||||||
15011 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | ||||||||
15012 | if (ArgTy.isNull()) | ||||||||
15013 | return ExprError(); | ||||||||
15014 | |||||||||
15015 | if (!ArgTInfo) | ||||||||
15016 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | ||||||||
15017 | |||||||||
15018 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | ||||||||
15019 | } | ||||||||
15020 | |||||||||
15021 | |||||||||
15022 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | ||||||||
15023 | Expr *CondExpr, | ||||||||
15024 | Expr *LHSExpr, Expr *RHSExpr, | ||||||||
15025 | SourceLocation RPLoc) { | ||||||||
15026 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? static_cast<void> (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15026, __PRETTY_FUNCTION__)); | ||||||||
15027 | |||||||||
15028 | ExprValueKind VK = VK_RValue; | ||||||||
15029 | ExprObjectKind OK = OK_Ordinary; | ||||||||
15030 | QualType resType; | ||||||||
15031 | bool CondIsTrue = false; | ||||||||
15032 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | ||||||||
15033 | resType = Context.DependentTy; | ||||||||
15034 | } else { | ||||||||
15035 | // The conditional expression is required to be a constant expression. | ||||||||
15036 | llvm::APSInt condEval(32); | ||||||||
15037 | ExprResult CondICE = VerifyIntegerConstantExpression( | ||||||||
15038 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | ||||||||
15039 | if (CondICE.isInvalid()) | ||||||||
15040 | return ExprError(); | ||||||||
15041 | CondExpr = CondICE.get(); | ||||||||
15042 | CondIsTrue = condEval.getZExtValue(); | ||||||||
15043 | |||||||||
15044 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | ||||||||
15045 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | ||||||||
15046 | |||||||||
15047 | resType = ActiveExpr->getType(); | ||||||||
15048 | VK = ActiveExpr->getValueKind(); | ||||||||
15049 | OK = ActiveExpr->getObjectKind(); | ||||||||
15050 | } | ||||||||
15051 | |||||||||
15052 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | ||||||||
15053 | resType, VK, OK, RPLoc, CondIsTrue); | ||||||||
15054 | } | ||||||||
15055 | |||||||||
15056 | //===----------------------------------------------------------------------===// | ||||||||
15057 | // Clang Extensions. | ||||||||
15058 | //===----------------------------------------------------------------------===// | ||||||||
15059 | |||||||||
15060 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | ||||||||
15061 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | ||||||||
15062 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | ||||||||
15063 | |||||||||
15064 | if (LangOpts.CPlusPlus) { | ||||||||
15065 | MangleNumberingContext *MCtx; | ||||||||
15066 | Decl *ManglingContextDecl; | ||||||||
15067 | std::tie(MCtx, ManglingContextDecl) = | ||||||||
15068 | getCurrentMangleNumberContext(Block->getDeclContext()); | ||||||||
15069 | if (MCtx) { | ||||||||
15070 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | ||||||||
15071 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | ||||||||
15072 | } | ||||||||
15073 | } | ||||||||
15074 | |||||||||
15075 | PushBlockScope(CurScope, Block); | ||||||||
15076 | CurContext->addDecl(Block); | ||||||||
15077 | if (CurScope) | ||||||||
15078 | PushDeclContext(CurScope, Block); | ||||||||
15079 | else | ||||||||
15080 | CurContext = Block; | ||||||||
15081 | |||||||||
15082 | getCurBlock()->HasImplicitReturnType = true; | ||||||||
15083 | |||||||||
15084 | // Enter a new evaluation context to insulate the block from any | ||||||||
15085 | // cleanups from the enclosing full-expression. | ||||||||
15086 | PushExpressionEvaluationContext( | ||||||||
15087 | ExpressionEvaluationContext::PotentiallyEvaluated); | ||||||||
15088 | } | ||||||||
15089 | |||||||||
15090 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | ||||||||
15091 | Scope *CurScope) { | ||||||||
15092 | assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15093, __PRETTY_FUNCTION__)) | ||||||||
15093 | "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15093, __PRETTY_FUNCTION__)); | ||||||||
15094 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext)((ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15094, __PRETTY_FUNCTION__)); | ||||||||
15095 | BlockScopeInfo *CurBlock = getCurBlock(); | ||||||||
15096 | |||||||||
15097 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | ||||||||
15098 | QualType T = Sig->getType(); | ||||||||
15099 | |||||||||
15100 | // FIXME: We should allow unexpanded parameter packs here, but that would, | ||||||||
15101 | // in turn, make the block expression contain unexpanded parameter packs. | ||||||||
15102 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | ||||||||
15103 | // Drop the parameters. | ||||||||
15104 | FunctionProtoType::ExtProtoInfo EPI; | ||||||||
15105 | EPI.HasTrailingReturn = false; | ||||||||
15106 | EPI.TypeQuals.addConst(); | ||||||||
15107 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | ||||||||
15108 | Sig = Context.getTrivialTypeSourceInfo(T); | ||||||||
15109 | } | ||||||||
15110 | |||||||||
15111 | // GetTypeForDeclarator always produces a function type for a block | ||||||||
15112 | // literal signature. Furthermore, it is always a FunctionProtoType | ||||||||
15113 | // unless the function was written with a typedef. | ||||||||
15114 | assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15115, __PRETTY_FUNCTION__)) | ||||||||
15115 | "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15115, __PRETTY_FUNCTION__)); | ||||||||
15116 | |||||||||
15117 | // Look for an explicit signature in that function type. | ||||||||
15118 | FunctionProtoTypeLoc ExplicitSignature; | ||||||||
15119 | |||||||||
15120 | if ((ExplicitSignature = Sig->getTypeLoc() | ||||||||
15121 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | ||||||||
15122 | |||||||||
15123 | // Check whether that explicit signature was synthesized by | ||||||||
15124 | // GetTypeForDeclarator. If so, don't save that as part of the | ||||||||
15125 | // written signature. | ||||||||
15126 | if (ExplicitSignature.getLocalRangeBegin() == | ||||||||
15127 | ExplicitSignature.getLocalRangeEnd()) { | ||||||||
15128 | // This would be much cheaper if we stored TypeLocs instead of | ||||||||
15129 | // TypeSourceInfos. | ||||||||
15130 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | ||||||||
15131 | unsigned Size = Result.getFullDataSize(); | ||||||||
15132 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | ||||||||
15133 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | ||||||||
15134 | |||||||||
15135 | ExplicitSignature = FunctionProtoTypeLoc(); | ||||||||
15136 | } | ||||||||
15137 | } | ||||||||
15138 | |||||||||
15139 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | ||||||||
15140 | CurBlock->FunctionType = T; | ||||||||
15141 | |||||||||
15142 | const FunctionType *Fn = T->getAs<FunctionType>(); | ||||||||
15143 | QualType RetTy = Fn->getReturnType(); | ||||||||
15144 | bool isVariadic = | ||||||||
15145 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | ||||||||
15146 | |||||||||
15147 | CurBlock->TheDecl->setIsVariadic(isVariadic); | ||||||||
15148 | |||||||||
15149 | // Context.DependentTy is used as a placeholder for a missing block | ||||||||
15150 | // return type. TODO: what should we do with declarators like: | ||||||||
15151 | // ^ * { ... } | ||||||||
15152 | // If the answer is "apply template argument deduction".... | ||||||||
15153 | if (RetTy != Context.DependentTy) { | ||||||||
15154 | CurBlock->ReturnType = RetTy; | ||||||||
15155 | CurBlock->TheDecl->setBlockMissingReturnType(false); | ||||||||
15156 | CurBlock->HasImplicitReturnType = false; | ||||||||
15157 | } | ||||||||
15158 | |||||||||
15159 | // Push block parameters from the declarator if we had them. | ||||||||
15160 | SmallVector<ParmVarDecl*, 8> Params; | ||||||||
15161 | if (ExplicitSignature) { | ||||||||
15162 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | ||||||||
15163 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | ||||||||
15164 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | ||||||||
15165 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | ||||||||
15166 | // Diagnose this as an extension in C17 and earlier. | ||||||||
15167 | if (!getLangOpts().C2x) | ||||||||
15168 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | ||||||||
15169 | } | ||||||||
15170 | Params.push_back(Param); | ||||||||
15171 | } | ||||||||
15172 | |||||||||
15173 | // Fake up parameter variables if we have a typedef, like | ||||||||
15174 | // ^ fntype { ... } | ||||||||
15175 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | ||||||||
15176 | for (const auto &I : Fn->param_types()) { | ||||||||
15177 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | ||||||||
15178 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | ||||||||
15179 | Params.push_back(Param); | ||||||||
15180 | } | ||||||||
15181 | } | ||||||||
15182 | |||||||||
15183 | // Set the parameters on the block decl. | ||||||||
15184 | if (!Params.empty()) { | ||||||||
15185 | CurBlock->TheDecl->setParams(Params); | ||||||||
15186 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | ||||||||
15187 | /*CheckParameterNames=*/false); | ||||||||
15188 | } | ||||||||
15189 | |||||||||
15190 | // Finally we can process decl attributes. | ||||||||
15191 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | ||||||||
15192 | |||||||||
15193 | // Put the parameter variables in scope. | ||||||||
15194 | for (auto AI : CurBlock->TheDecl->parameters()) { | ||||||||
15195 | AI->setOwningFunction(CurBlock->TheDecl); | ||||||||
15196 | |||||||||
15197 | // If this has an identifier, add it to the scope stack. | ||||||||
15198 | if (AI->getIdentifier()) { | ||||||||
15199 | CheckShadow(CurBlock->TheScope, AI); | ||||||||
15200 | |||||||||
15201 | PushOnScopeChains(AI, CurBlock->TheScope); | ||||||||
15202 | } | ||||||||
15203 | } | ||||||||
15204 | } | ||||||||
15205 | |||||||||
15206 | /// ActOnBlockError - If there is an error parsing a block, this callback | ||||||||
15207 | /// is invoked to pop the information about the block from the action impl. | ||||||||
15208 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | ||||||||
15209 | // Leave the expression-evaluation context. | ||||||||
15210 | DiscardCleanupsInEvaluationContext(); | ||||||||
15211 | PopExpressionEvaluationContext(); | ||||||||
15212 | |||||||||
15213 | // Pop off CurBlock, handle nested blocks. | ||||||||
15214 | PopDeclContext(); | ||||||||
15215 | PopFunctionScopeInfo(); | ||||||||
15216 | } | ||||||||
15217 | |||||||||
15218 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | ||||||||
15219 | /// literal was successfully completed. ^(int x){...} | ||||||||
15220 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | ||||||||
15221 | Stmt *Body, Scope *CurScope) { | ||||||||
15222 | // If blocks are disabled, emit an error. | ||||||||
15223 | if (!LangOpts.Blocks) | ||||||||
15224 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||||||
15225 | |||||||||
15226 | // Leave the expression-evaluation context. | ||||||||
15227 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||||||
15228 | DiscardCleanupsInEvaluationContext(); | ||||||||
15229 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15230, __PRETTY_FUNCTION__)) | ||||||||
15230 | "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15230, __PRETTY_FUNCTION__)); | ||||||||
15231 | PopExpressionEvaluationContext(); | ||||||||
15232 | |||||||||
15233 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | ||||||||
15234 | BlockDecl *BD = BSI->TheDecl; | ||||||||
15235 | |||||||||
15236 | if (BSI->HasImplicitReturnType) | ||||||||
15237 | deduceClosureReturnType(*BSI); | ||||||||
15238 | |||||||||
15239 | QualType RetTy = Context.VoidTy; | ||||||||
15240 | if (!BSI->ReturnType.isNull()) | ||||||||
15241 | RetTy = BSI->ReturnType; | ||||||||
15242 | |||||||||
15243 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | ||||||||
15244 | QualType BlockTy; | ||||||||
15245 | |||||||||
15246 | // If the user wrote a function type in some form, try to use that. | ||||||||
15247 | if (!BSI->FunctionType.isNull()) { | ||||||||
15248 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | ||||||||
15249 | |||||||||
15250 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | ||||||||
15251 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | ||||||||
15252 | |||||||||
15253 | // Turn protoless block types into nullary block types. | ||||||||
15254 | if (isa<FunctionNoProtoType>(FTy)) { | ||||||||
15255 | FunctionProtoType::ExtProtoInfo EPI; | ||||||||
15256 | EPI.ExtInfo = Ext; | ||||||||
15257 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||||||
15258 | |||||||||
15259 | // Otherwise, if we don't need to change anything about the function type, | ||||||||
15260 | // preserve its sugar structure. | ||||||||
15261 | } else if (FTy->getReturnType() == RetTy && | ||||||||
15262 | (!NoReturn || FTy->getNoReturnAttr())) { | ||||||||
15263 | BlockTy = BSI->FunctionType; | ||||||||
15264 | |||||||||
15265 | // Otherwise, make the minimal modifications to the function type. | ||||||||
15266 | } else { | ||||||||
15267 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | ||||||||
15268 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||||||
15269 | EPI.TypeQuals = Qualifiers(); | ||||||||
15270 | EPI.ExtInfo = Ext; | ||||||||
15271 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | ||||||||
15272 | } | ||||||||
15273 | |||||||||
15274 | // If we don't have a function type, just build one from nothing. | ||||||||
15275 | } else { | ||||||||
15276 | FunctionProtoType::ExtProtoInfo EPI; | ||||||||
15277 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | ||||||||
15278 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||||||
15279 | } | ||||||||
15280 | |||||||||
15281 | DiagnoseUnusedParameters(BD->parameters()); | ||||||||
15282 | BlockTy = Context.getBlockPointerType(BlockTy); | ||||||||
15283 | |||||||||
15284 | // If needed, diagnose invalid gotos and switches in the block. | ||||||||
15285 | if (getCurFunction()->NeedsScopeChecking() && | ||||||||
15286 | !PP.isCodeCompletionEnabled()) | ||||||||
15287 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | ||||||||
15288 | |||||||||
15289 | BD->setBody(cast<CompoundStmt>(Body)); | ||||||||
15290 | |||||||||
15291 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||||||
15292 | DiagnoseUnguardedAvailabilityViolations(BD); | ||||||||
15293 | |||||||||
15294 | // Try to apply the named return value optimization. We have to check again | ||||||||
15295 | // if we can do this, though, because blocks keep return statements around | ||||||||
15296 | // to deduce an implicit return type. | ||||||||
15297 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | ||||||||
15298 | !BD->isDependentContext()) | ||||||||
15299 | computeNRVO(Body, BSI); | ||||||||
15300 | |||||||||
15301 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | ||||||||
15302 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||||
15303 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | ||||||||
15304 | NTCUK_Destruct|NTCUK_Copy); | ||||||||
15305 | |||||||||
15306 | PopDeclContext(); | ||||||||
15307 | |||||||||
15308 | // Pop the block scope now but keep it alive to the end of this function. | ||||||||
15309 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||||||
15310 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | ||||||||
15311 | |||||||||
15312 | // Set the captured variables on the block. | ||||||||
15313 | SmallVector<BlockDecl::Capture, 4> Captures; | ||||||||
15314 | for (Capture &Cap : BSI->Captures) { | ||||||||
15315 | if (Cap.isInvalid() || Cap.isThisCapture()) | ||||||||
15316 | continue; | ||||||||
15317 | |||||||||
15318 | VarDecl *Var = Cap.getVariable(); | ||||||||
15319 | Expr *CopyExpr = nullptr; | ||||||||
15320 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | ||||||||
15321 | if (const RecordType *Record = | ||||||||
15322 | Cap.getCaptureType()->getAs<RecordType>()) { | ||||||||
15323 | // The capture logic needs the destructor, so make sure we mark it. | ||||||||
15324 | // Usually this is unnecessary because most local variables have | ||||||||
15325 | // their destructors marked at declaration time, but parameters are | ||||||||
15326 | // an exception because it's technically only the call site that | ||||||||
15327 | // actually requires the destructor. | ||||||||
15328 | if (isa<ParmVarDecl>(Var)) | ||||||||
15329 | FinalizeVarWithDestructor(Var, Record); | ||||||||
15330 | |||||||||
15331 | // Enter a separate potentially-evaluated context while building block | ||||||||
15332 | // initializers to isolate their cleanups from those of the block | ||||||||
15333 | // itself. | ||||||||
15334 | // FIXME: Is this appropriate even when the block itself occurs in an | ||||||||
15335 | // unevaluated operand? | ||||||||
15336 | EnterExpressionEvaluationContext EvalContext( | ||||||||
15337 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||||||
15338 | |||||||||
15339 | SourceLocation Loc = Cap.getLocation(); | ||||||||
15340 | |||||||||
15341 | ExprResult Result = BuildDeclarationNameExpr( | ||||||||
15342 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | ||||||||
15343 | |||||||||
15344 | // According to the blocks spec, the capture of a variable from | ||||||||
15345 | // the stack requires a const copy constructor. This is not true | ||||||||
15346 | // of the copy/move done to move a __block variable to the heap. | ||||||||
15347 | if (!Result.isInvalid() && | ||||||||
15348 | !Result.get()->getType().isConstQualified()) { | ||||||||
15349 | Result = ImpCastExprToType(Result.get(), | ||||||||
15350 | Result.get()->getType().withConst(), | ||||||||
15351 | CK_NoOp, VK_LValue); | ||||||||
15352 | } | ||||||||
15353 | |||||||||
15354 | if (!Result.isInvalid()) { | ||||||||
15355 | Result = PerformCopyInitialization( | ||||||||
15356 | InitializedEntity::InitializeBlock(Var->getLocation(), | ||||||||
15357 | Cap.getCaptureType(), false), | ||||||||
15358 | Loc, Result.get()); | ||||||||
15359 | } | ||||||||
15360 | |||||||||
15361 | // Build a full-expression copy expression if initialization | ||||||||
15362 | // succeeded and used a non-trivial constructor. Recover from | ||||||||
15363 | // errors by pretending that the copy isn't necessary. | ||||||||
15364 | if (!Result.isInvalid() && | ||||||||
15365 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | ||||||||
15366 | ->isTrivial()) { | ||||||||
15367 | Result = MaybeCreateExprWithCleanups(Result); | ||||||||
15368 | CopyExpr = Result.get(); | ||||||||
15369 | } | ||||||||
15370 | } | ||||||||
15371 | } | ||||||||
15372 | |||||||||
15373 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | ||||||||
15374 | CopyExpr); | ||||||||
15375 | Captures.push_back(NewCap); | ||||||||
15376 | } | ||||||||
15377 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | ||||||||
15378 | |||||||||
15379 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | ||||||||
15380 | |||||||||
15381 | // If the block isn't obviously global, i.e. it captures anything at | ||||||||
15382 | // all, then we need to do a few things in the surrounding context: | ||||||||
15383 | if (Result->getBlockDecl()->hasCaptures()) { | ||||||||
15384 | // First, this expression has a new cleanup object. | ||||||||
15385 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | ||||||||
15386 | Cleanup.setExprNeedsCleanups(true); | ||||||||
15387 | |||||||||
15388 | // It also gets a branch-protected scope if any of the captured | ||||||||
15389 | // variables needs destruction. | ||||||||
15390 | for (const auto &CI : Result->getBlockDecl()->captures()) { | ||||||||
15391 | const VarDecl *var = CI.getVariable(); | ||||||||
15392 | if (var->getType().isDestructedType() != QualType::DK_none) { | ||||||||
15393 | setFunctionHasBranchProtectedScope(); | ||||||||
15394 | break; | ||||||||
15395 | } | ||||||||
15396 | } | ||||||||
15397 | } | ||||||||
15398 | |||||||||
15399 | if (getCurFunction()) | ||||||||
15400 | getCurFunction()->addBlock(BD); | ||||||||
15401 | |||||||||
15402 | return Result; | ||||||||
15403 | } | ||||||||
15404 | |||||||||
15405 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | ||||||||
15406 | SourceLocation RPLoc) { | ||||||||
15407 | TypeSourceInfo *TInfo; | ||||||||
15408 | GetTypeFromParser(Ty, &TInfo); | ||||||||
15409 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | ||||||||
15410 | } | ||||||||
15411 | |||||||||
15412 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | ||||||||
15413 | Expr *E, TypeSourceInfo *TInfo, | ||||||||
15414 | SourceLocation RPLoc) { | ||||||||
15415 | Expr *OrigExpr = E; | ||||||||
15416 | bool IsMS = false; | ||||||||
15417 | |||||||||
15418 | // CUDA device code does not support varargs. | ||||||||
15419 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | ||||||||
15420 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | ||||||||
15421 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | ||||||||
15422 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | ||||||||
15423 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | ||||||||
15424 | } | ||||||||
15425 | } | ||||||||
15426 | |||||||||
15427 | // NVPTX does not support va_arg expression. | ||||||||
15428 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | ||||||||
15429 | Context.getTargetInfo().getTriple().isNVPTX()) | ||||||||
15430 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | ||||||||
15431 | |||||||||
15432 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | ||||||||
15433 | // as Microsoft ABI on an actual Microsoft platform, where | ||||||||
15434 | // __builtin_ms_va_list and __builtin_va_list are the same.) | ||||||||
15435 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | ||||||||
15436 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | ||||||||
15437 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | ||||||||
15438 | if (Context.hasSameType(MSVaListType, E->getType())) { | ||||||||
15439 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||||||
15440 | return ExprError(); | ||||||||
15441 | IsMS = true; | ||||||||
15442 | } | ||||||||
15443 | } | ||||||||
15444 | |||||||||
15445 | // Get the va_list type | ||||||||
15446 | QualType VaListType = Context.getBuiltinVaListType(); | ||||||||
15447 | if (!IsMS) { | ||||||||
15448 | if (VaListType->isArrayType()) { | ||||||||
15449 | // Deal with implicit array decay; for example, on x86-64, | ||||||||
15450 | // va_list is an array, but it's supposed to decay to | ||||||||
15451 | // a pointer for va_arg. | ||||||||
15452 | VaListType = Context.getArrayDecayedType(VaListType); | ||||||||
15453 | // Make sure the input expression also decays appropriately. | ||||||||
15454 | ExprResult Result = UsualUnaryConversions(E); | ||||||||
15455 | if (Result.isInvalid()) | ||||||||
15456 | return ExprError(); | ||||||||
15457 | E = Result.get(); | ||||||||
15458 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | ||||||||
15459 | // If va_list is a record type and we are compiling in C++ mode, | ||||||||
15460 | // check the argument using reference binding. | ||||||||
15461 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||||||
15462 | Context, Context.getLValueReferenceType(VaListType), false); | ||||||||
15463 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | ||||||||
15464 | if (Init.isInvalid()) | ||||||||
15465 | return ExprError(); | ||||||||
15466 | E = Init.getAs<Expr>(); | ||||||||
15467 | } else { | ||||||||
15468 | // Otherwise, the va_list argument must be an l-value because | ||||||||
15469 | // it is modified by va_arg. | ||||||||
15470 | if (!E->isTypeDependent() && | ||||||||
15471 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||||||
15472 | return ExprError(); | ||||||||
15473 | } | ||||||||
15474 | } | ||||||||
15475 | |||||||||
15476 | if (!IsMS && !E->isTypeDependent() && | ||||||||
15477 | !Context.hasSameType(VaListType, E->getType())) | ||||||||
15478 | return ExprError( | ||||||||
15479 | Diag(E->getBeginLoc(), | ||||||||
15480 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | ||||||||
15481 | << OrigExpr->getType() << E->getSourceRange()); | ||||||||
15482 | |||||||||
15483 | if (!TInfo->getType()->isDependentType()) { | ||||||||
15484 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | ||||||||
15485 | diag::err_second_parameter_to_va_arg_incomplete, | ||||||||
15486 | TInfo->getTypeLoc())) | ||||||||
15487 | return ExprError(); | ||||||||
15488 | |||||||||
15489 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | ||||||||
15490 | TInfo->getType(), | ||||||||
15491 | diag::err_second_parameter_to_va_arg_abstract, | ||||||||
15492 | TInfo->getTypeLoc())) | ||||||||
15493 | return ExprError(); | ||||||||
15494 | |||||||||
15495 | if (!TInfo->getType().isPODType(Context)) { | ||||||||
15496 | Diag(TInfo->getTypeLoc().getBeginLoc(), | ||||||||
15497 | TInfo->getType()->isObjCLifetimeType() | ||||||||
15498 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | ||||||||
15499 | : diag::warn_second_parameter_to_va_arg_not_pod) | ||||||||
15500 | << TInfo->getType() | ||||||||
15501 | << TInfo->getTypeLoc().getSourceRange(); | ||||||||
15502 | } | ||||||||
15503 | |||||||||
15504 | // Check for va_arg where arguments of the given type will be promoted | ||||||||
15505 | // (i.e. this va_arg is guaranteed to have undefined behavior). | ||||||||
15506 | QualType PromoteType; | ||||||||
15507 | if (TInfo->getType()->isPromotableIntegerType()) { | ||||||||
15508 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | ||||||||
15509 | if (Context.typesAreCompatible(PromoteType, TInfo->getType())) | ||||||||
15510 | PromoteType = QualType(); | ||||||||
15511 | } | ||||||||
15512 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | ||||||||
15513 | PromoteType = Context.DoubleTy; | ||||||||
15514 | if (!PromoteType.isNull()) | ||||||||
15515 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | ||||||||
15516 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | ||||||||
15517 | << TInfo->getType() | ||||||||
15518 | << PromoteType | ||||||||
15519 | << TInfo->getTypeLoc().getSourceRange()); | ||||||||
15520 | } | ||||||||
15521 | |||||||||
15522 | QualType T = TInfo->getType().getNonLValueExprType(Context); | ||||||||
15523 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | ||||||||
15524 | } | ||||||||
15525 | |||||||||
15526 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | ||||||||
15527 | // The type of __null will be int or long, depending on the size of | ||||||||
15528 | // pointers on the target. | ||||||||
15529 | QualType Ty; | ||||||||
15530 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | ||||||||
15531 | if (pw == Context.getTargetInfo().getIntWidth()) | ||||||||
15532 | Ty = Context.IntTy; | ||||||||
15533 | else if (pw == Context.getTargetInfo().getLongWidth()) | ||||||||
15534 | Ty = Context.LongTy; | ||||||||
15535 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | ||||||||
15536 | Ty = Context.LongLongTy; | ||||||||
15537 | else { | ||||||||
15538 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15538); | ||||||||
15539 | } | ||||||||
15540 | |||||||||
15541 | return new (Context) GNUNullExpr(Ty, TokenLoc); | ||||||||
15542 | } | ||||||||
15543 | |||||||||
15544 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||||||
15545 | SourceLocation BuiltinLoc, | ||||||||
15546 | SourceLocation RPLoc) { | ||||||||
15547 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); | ||||||||
15548 | } | ||||||||
15549 | |||||||||
15550 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||||||
15551 | SourceLocation BuiltinLoc, | ||||||||
15552 | SourceLocation RPLoc, | ||||||||
15553 | DeclContext *ParentContext) { | ||||||||
15554 | return new (Context) | ||||||||
15555 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); | ||||||||
15556 | } | ||||||||
15557 | |||||||||
15558 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | ||||||||
15559 | bool Diagnose) { | ||||||||
15560 | if (!getLangOpts().ObjC) | ||||||||
15561 | return false; | ||||||||
15562 | |||||||||
15563 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | ||||||||
15564 | if (!PT) | ||||||||
15565 | return false; | ||||||||
15566 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | ||||||||
15567 | |||||||||
15568 | // Ignore any parens, implicit casts (should only be | ||||||||
15569 | // array-to-pointer decays), and not-so-opaque values. The last is | ||||||||
15570 | // important for making this trigger for property assignments. | ||||||||
15571 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | ||||||||
15572 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | ||||||||
15573 | if (OV->getSourceExpr()) | ||||||||
15574 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | ||||||||
15575 | |||||||||
15576 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | ||||||||
15577 | if (!PT->isObjCIdType() && | ||||||||
15578 | !(ID && ID->getIdentifier()->isStr("NSString"))) | ||||||||
15579 | return false; | ||||||||
15580 | if (!SL->isAscii()) | ||||||||
15581 | return false; | ||||||||
15582 | |||||||||
15583 | if (Diagnose) { | ||||||||
15584 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||||||
15585 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | ||||||||
15586 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | ||||||||
15587 | } | ||||||||
15588 | return true; | ||||||||
15589 | } | ||||||||
15590 | |||||||||
15591 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | ||||||||
15592 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | ||||||||
15593 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | ||||||||
15594 | !SrcExpr->isNullPointerConstant( | ||||||||
15595 | getASTContext(), Expr::NPC_NeverValueDependent)) { | ||||||||
15596 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | ||||||||
15597 | return false; | ||||||||
15598 | if (Diagnose) { | ||||||||
15599 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||||||
15600 | << /*number*/1 | ||||||||
15601 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | ||||||||
15602 | Expr *NumLit = | ||||||||
15603 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | ||||||||
15604 | if (NumLit) | ||||||||
15605 | Exp = NumLit; | ||||||||
15606 | } | ||||||||
15607 | return true; | ||||||||
15608 | } | ||||||||
15609 | |||||||||
15610 | return false; | ||||||||
15611 | } | ||||||||
15612 | |||||||||
15613 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | ||||||||
15614 | const Expr *SrcExpr) { | ||||||||
15615 | if (!DstType->isFunctionPointerType() || | ||||||||
15616 | !SrcExpr->getType()->isFunctionType()) | ||||||||
15617 | return false; | ||||||||
15618 | |||||||||
15619 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | ||||||||
15620 | if (!DRE) | ||||||||
15621 | return false; | ||||||||
15622 | |||||||||
15623 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||||||
15624 | if (!FD) | ||||||||
15625 | return false; | ||||||||
15626 | |||||||||
15627 | return !S.checkAddressOfFunctionIsAvailable(FD, | ||||||||
15628 | /*Complain=*/true, | ||||||||
15629 | SrcExpr->getBeginLoc()); | ||||||||
15630 | } | ||||||||
15631 | |||||||||
15632 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | ||||||||
15633 | SourceLocation Loc, | ||||||||
15634 | QualType DstType, QualType SrcType, | ||||||||
15635 | Expr *SrcExpr, AssignmentAction Action, | ||||||||
15636 | bool *Complained) { | ||||||||
15637 | if (Complained) | ||||||||
15638 | *Complained = false; | ||||||||
15639 | |||||||||
15640 | // Decode the result (notice that AST's are still created for extensions). | ||||||||
15641 | bool CheckInferredResultType = false; | ||||||||
15642 | bool isInvalid = false; | ||||||||
15643 | unsigned DiagKind = 0; | ||||||||
15644 | ConversionFixItGenerator ConvHints; | ||||||||
15645 | bool MayHaveConvFixit = false; | ||||||||
15646 | bool MayHaveFunctionDiff = false; | ||||||||
15647 | const ObjCInterfaceDecl *IFace = nullptr; | ||||||||
15648 | const ObjCProtocolDecl *PDecl = nullptr; | ||||||||
15649 | |||||||||
15650 | switch (ConvTy) { | ||||||||
15651 | case Compatible: | ||||||||
15652 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | ||||||||
15653 | return false; | ||||||||
15654 | |||||||||
15655 | case PointerToInt: | ||||||||
15656 | if (getLangOpts().CPlusPlus) { | ||||||||
15657 | DiagKind = diag::err_typecheck_convert_pointer_int; | ||||||||
15658 | isInvalid = true; | ||||||||
15659 | } else { | ||||||||
15660 | DiagKind = diag::ext_typecheck_convert_pointer_int; | ||||||||
15661 | } | ||||||||
15662 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||||||
15663 | MayHaveConvFixit = true; | ||||||||
15664 | break; | ||||||||
15665 | case IntToPointer: | ||||||||
15666 | if (getLangOpts().CPlusPlus) { | ||||||||
15667 | DiagKind = diag::err_typecheck_convert_int_pointer; | ||||||||
15668 | isInvalid = true; | ||||||||
15669 | } else { | ||||||||
15670 | DiagKind = diag::ext_typecheck_convert_int_pointer; | ||||||||
15671 | } | ||||||||
15672 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||||||
15673 | MayHaveConvFixit = true; | ||||||||
15674 | break; | ||||||||
15675 | case IncompatibleFunctionPointer: | ||||||||
15676 | if (getLangOpts().CPlusPlus) { | ||||||||
15677 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | ||||||||
15678 | isInvalid = true; | ||||||||
15679 | } else { | ||||||||
15680 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | ||||||||
15681 | } | ||||||||
15682 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||||||
15683 | MayHaveConvFixit = true; | ||||||||
15684 | break; | ||||||||
15685 | case IncompatiblePointer: | ||||||||
15686 | if (Action == AA_Passing_CFAudited) { | ||||||||
15687 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | ||||||||
15688 | } else if (getLangOpts().CPlusPlus) { | ||||||||
15689 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | ||||||||
15690 | isInvalid = true; | ||||||||
15691 | } else { | ||||||||
15692 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | ||||||||
15693 | } | ||||||||
15694 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | ||||||||
15695 | SrcType->isObjCObjectPointerType(); | ||||||||
15696 | if (!CheckInferredResultType) { | ||||||||
15697 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||||||
15698 | } else if (CheckInferredResultType) { | ||||||||
15699 | SrcType = SrcType.getUnqualifiedType(); | ||||||||
15700 | DstType = DstType.getUnqualifiedType(); | ||||||||
15701 | } | ||||||||
15702 | MayHaveConvFixit = true; | ||||||||
15703 | break; | ||||||||
15704 | case IncompatiblePointerSign: | ||||||||
15705 | if (getLangOpts().CPlusPlus) { | ||||||||
15706 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | ||||||||
15707 | isInvalid = true; | ||||||||
15708 | } else { | ||||||||
15709 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | ||||||||
15710 | } | ||||||||
15711 | break; | ||||||||
15712 | case FunctionVoidPointer: | ||||||||
15713 | if (getLangOpts().CPlusPlus) { | ||||||||
15714 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | ||||||||
15715 | isInvalid = true; | ||||||||
15716 | } else { | ||||||||
15717 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | ||||||||
15718 | } | ||||||||
15719 | break; | ||||||||
15720 | case IncompatiblePointerDiscardsQualifiers: { | ||||||||
15721 | // Perform array-to-pointer decay if necessary. | ||||||||
15722 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | ||||||||
15723 | |||||||||
15724 | isInvalid = true; | ||||||||
15725 | |||||||||
15726 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | ||||||||
15727 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | ||||||||
15728 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | ||||||||
15729 | DiagKind = diag::err_typecheck_incompatible_address_space; | ||||||||
15730 | break; | ||||||||
15731 | |||||||||
15732 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | ||||||||
15733 | DiagKind = diag::err_typecheck_incompatible_ownership; | ||||||||
15734 | break; | ||||||||
15735 | } | ||||||||
15736 | |||||||||
15737 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 15737); | ||||||||
15738 | // fallthrough | ||||||||
15739 | } | ||||||||
15740 | case CompatiblePointerDiscardsQualifiers: | ||||||||
15741 | // If the qualifiers lost were because we were applying the | ||||||||
15742 | // (deprecated) C++ conversion from a string literal to a char* | ||||||||
15743 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | ||||||||
15744 | // Ideally, this check would be performed in | ||||||||
15745 | // checkPointerTypesForAssignment. However, that would require a | ||||||||
15746 | // bit of refactoring (so that the second argument is an | ||||||||
15747 | // expression, rather than a type), which should be done as part | ||||||||
15748 | // of a larger effort to fix checkPointerTypesForAssignment for | ||||||||
15749 | // C++ semantics. | ||||||||
15750 | if (getLangOpts().CPlusPlus && | ||||||||
15751 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | ||||||||
15752 | return false; | ||||||||
15753 | if (getLangOpts().CPlusPlus) { | ||||||||
15754 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | ||||||||
15755 | isInvalid = true; | ||||||||
15756 | } else { | ||||||||
15757 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | ||||||||
15758 | } | ||||||||
15759 | |||||||||
15760 | break; | ||||||||
15761 | case IncompatibleNestedPointerQualifiers: | ||||||||
15762 | if (getLangOpts().CPlusPlus) { | ||||||||
15763 | isInvalid = true; | ||||||||
15764 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | ||||||||
15765 | } else { | ||||||||
15766 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | ||||||||
15767 | } | ||||||||
15768 | break; | ||||||||
15769 | case IncompatibleNestedPointerAddressSpaceMismatch: | ||||||||
15770 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | ||||||||
15771 | isInvalid = true; | ||||||||
15772 | break; | ||||||||
15773 | case IntToBlockPointer: | ||||||||
15774 | DiagKind = diag::err_int_to_block_pointer; | ||||||||
15775 | isInvalid = true; | ||||||||
15776 | break; | ||||||||
15777 | case IncompatibleBlockPointer: | ||||||||
15778 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | ||||||||
15779 | isInvalid = true; | ||||||||
15780 | break; | ||||||||
15781 | case IncompatibleObjCQualifiedId: { | ||||||||
15782 | if (SrcType->isObjCQualifiedIdType()) { | ||||||||
15783 | const ObjCObjectPointerType *srcOPT = | ||||||||
15784 | SrcType->castAs<ObjCObjectPointerType>(); | ||||||||
15785 | for (auto *srcProto : srcOPT->quals()) { | ||||||||
15786 | PDecl = srcProto; | ||||||||
15787 | break; | ||||||||
15788 | } | ||||||||
15789 | if (const ObjCInterfaceType *IFaceT = | ||||||||
15790 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||||||
15791 | IFace = IFaceT->getDecl(); | ||||||||
15792 | } | ||||||||
15793 | else if (DstType->isObjCQualifiedIdType()) { | ||||||||
15794 | const ObjCObjectPointerType *dstOPT = | ||||||||
15795 | DstType->castAs<ObjCObjectPointerType>(); | ||||||||
15796 | for (auto *dstProto : dstOPT->quals()) { | ||||||||
15797 | PDecl = dstProto; | ||||||||
15798 | break; | ||||||||
15799 | } | ||||||||
15800 | if (const ObjCInterfaceType *IFaceT = | ||||||||
15801 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||||||
15802 | IFace = IFaceT->getDecl(); | ||||||||
15803 | } | ||||||||
15804 | if (getLangOpts().CPlusPlus) { | ||||||||
15805 | DiagKind = diag::err_incompatible_qualified_id; | ||||||||
15806 | isInvalid = true; | ||||||||
15807 | } else { | ||||||||
15808 | DiagKind = diag::warn_incompatible_qualified_id; | ||||||||
15809 | } | ||||||||
15810 | break; | ||||||||
15811 | } | ||||||||
15812 | case IncompatibleVectors: | ||||||||
15813 | if (getLangOpts().CPlusPlus) { | ||||||||
15814 | DiagKind = diag::err_incompatible_vectors; | ||||||||
15815 | isInvalid = true; | ||||||||
15816 | } else { | ||||||||
15817 | DiagKind = diag::warn_incompatible_vectors; | ||||||||
15818 | } | ||||||||
15819 | break; | ||||||||
15820 | case IncompatibleObjCWeakRef: | ||||||||
15821 | DiagKind = diag::err_arc_weak_unavailable_assign; | ||||||||
15822 | isInvalid = true; | ||||||||
15823 | break; | ||||||||
15824 | case Incompatible: | ||||||||
15825 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | ||||||||
15826 | if (Complained) | ||||||||
15827 | *Complained = true; | ||||||||
15828 | return true; | ||||||||
15829 | } | ||||||||
15830 | |||||||||
15831 | DiagKind = diag::err_typecheck_convert_incompatible; | ||||||||
15832 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||||||
15833 | MayHaveConvFixit = true; | ||||||||
15834 | isInvalid = true; | ||||||||
15835 | MayHaveFunctionDiff = true; | ||||||||
15836 | break; | ||||||||
15837 | } | ||||||||
15838 | |||||||||
15839 | QualType FirstType, SecondType; | ||||||||
15840 | switch (Action) { | ||||||||
15841 | case AA_Assigning: | ||||||||
15842 | case AA_Initializing: | ||||||||
15843 | // The destination type comes first. | ||||||||
15844 | FirstType = DstType; | ||||||||
15845 | SecondType = SrcType; | ||||||||
15846 | break; | ||||||||
15847 | |||||||||
15848 | case AA_Returning: | ||||||||
15849 | case AA_Passing: | ||||||||
15850 | case AA_Passing_CFAudited: | ||||||||
15851 | case AA_Converting: | ||||||||
15852 | case AA_Sending: | ||||||||
15853 | case AA_Casting: | ||||||||
15854 | // The source type comes first. | ||||||||
15855 | FirstType = SrcType; | ||||||||
15856 | SecondType = DstType; | ||||||||
15857 | break; | ||||||||
15858 | } | ||||||||
15859 | |||||||||
15860 | PartialDiagnostic FDiag = PDiag(DiagKind); | ||||||||
15861 | if (Action == AA_Passing_CFAudited) | ||||||||
15862 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | ||||||||
15863 | else | ||||||||
15864 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | ||||||||
15865 | |||||||||
15866 | // If we can fix the conversion, suggest the FixIts. | ||||||||
15867 | if (!ConvHints.isNull()) { | ||||||||
15868 | for (FixItHint &H : ConvHints.Hints) | ||||||||
15869 | FDiag << H; | ||||||||
15870 | } | ||||||||
15871 | |||||||||
15872 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | ||||||||
15873 | |||||||||
15874 | if (MayHaveFunctionDiff) | ||||||||
15875 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | ||||||||
15876 | |||||||||
15877 | Diag(Loc, FDiag); | ||||||||
15878 | if ((DiagKind == diag::warn_incompatible_qualified_id || | ||||||||
15879 | DiagKind == diag::err_incompatible_qualified_id) && | ||||||||
15880 | PDecl && IFace && !IFace->hasDefinition()) | ||||||||
15881 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | ||||||||
15882 | << IFace << PDecl; | ||||||||
15883 | |||||||||
15884 | if (SecondType == Context.OverloadTy) | ||||||||
15885 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | ||||||||
15886 | FirstType, /*TakingAddress=*/true); | ||||||||
15887 | |||||||||
15888 | if (CheckInferredResultType) | ||||||||
15889 | EmitRelatedResultTypeNote(SrcExpr); | ||||||||
15890 | |||||||||
15891 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | ||||||||
15892 | EmitRelatedResultTypeNoteForReturn(DstType); | ||||||||
15893 | |||||||||
15894 | if (Complained) | ||||||||
15895 | *Complained = true; | ||||||||
15896 | return isInvalid; | ||||||||
15897 | } | ||||||||
15898 | |||||||||
15899 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||||||
15900 | llvm::APSInt *Result, | ||||||||
15901 | AllowFoldKind CanFold) { | ||||||||
15902 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | ||||||||
15903 | public: | ||||||||
15904 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||||||
15905 | QualType T) override { | ||||||||
15906 | return S.Diag(Loc, diag::err_ice_not_integral) | ||||||||
15907 | << T << S.LangOpts.CPlusPlus; | ||||||||
15908 | } | ||||||||
15909 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||||||
15910 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||||||
15911 | } | ||||||||
15912 | } Diagnoser; | ||||||||
15913 | |||||||||
15914 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||||||
15915 | } | ||||||||
15916 | |||||||||
15917 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||||||
15918 | llvm::APSInt *Result, | ||||||||
15919 | unsigned DiagID, | ||||||||
15920 | AllowFoldKind CanFold) { | ||||||||
15921 | class IDDiagnoser : public VerifyICEDiagnoser { | ||||||||
15922 | unsigned DiagID; | ||||||||
15923 | |||||||||
15924 | public: | ||||||||
15925 | IDDiagnoser(unsigned DiagID) | ||||||||
15926 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | ||||||||
15927 | |||||||||
15928 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||||||
15929 | return S.Diag(Loc, DiagID); | ||||||||
15930 | } | ||||||||
15931 | } Diagnoser(DiagID); | ||||||||
15932 | |||||||||
15933 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||||||
15934 | } | ||||||||
15935 | |||||||||
15936 | Sema::SemaDiagnosticBuilder | ||||||||
15937 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||||||
15938 | QualType T) { | ||||||||
15939 | return diagnoseNotICE(S, Loc); | ||||||||
15940 | } | ||||||||
15941 | |||||||||
15942 | Sema::SemaDiagnosticBuilder | ||||||||
15943 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | ||||||||
15944 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||||||
15945 | } | ||||||||
15946 | |||||||||
15947 | ExprResult | ||||||||
15948 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | ||||||||
15949 | VerifyICEDiagnoser &Diagnoser, | ||||||||
15950 | AllowFoldKind CanFold) { | ||||||||
15951 | SourceLocation DiagLoc = E->getBeginLoc(); | ||||||||
15952 | |||||||||
15953 | if (getLangOpts().CPlusPlus11) { | ||||||||
15954 | // C++11 [expr.const]p5: | ||||||||
15955 | // If an expression of literal class type is used in a context where an | ||||||||
15956 | // integral constant expression is required, then that class type shall | ||||||||
15957 | // have a single non-explicit conversion function to an integral or | ||||||||
15958 | // unscoped enumeration type | ||||||||
15959 | ExprResult Converted; | ||||||||
15960 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | ||||||||
15961 | VerifyICEDiagnoser &BaseDiagnoser; | ||||||||
15962 | public: | ||||||||
15963 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | ||||||||
15964 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | ||||||||
15965 | BaseDiagnoser.Suppress, true), | ||||||||
15966 | BaseDiagnoser(BaseDiagnoser) {} | ||||||||
15967 | |||||||||
15968 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | ||||||||
15969 | QualType T) override { | ||||||||
15970 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | ||||||||
15971 | } | ||||||||
15972 | |||||||||
15973 | SemaDiagnosticBuilder diagnoseIncomplete( | ||||||||
15974 | Sema &S, SourceLocation Loc, QualType T) override { | ||||||||
15975 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | ||||||||
15976 | } | ||||||||
15977 | |||||||||
15978 | SemaDiagnosticBuilder diagnoseExplicitConv( | ||||||||
15979 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||||||
15980 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | ||||||||
15981 | } | ||||||||
15982 | |||||||||
15983 | SemaDiagnosticBuilder noteExplicitConv( | ||||||||
15984 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||||||
15985 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||||||
15986 | << ConvTy->isEnumeralType() << ConvTy; | ||||||||
15987 | } | ||||||||
15988 | |||||||||
15989 | SemaDiagnosticBuilder diagnoseAmbiguous( | ||||||||
15990 | Sema &S, SourceLocation Loc, QualType T) override { | ||||||||
15991 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | ||||||||
15992 | } | ||||||||
15993 | |||||||||
15994 | SemaDiagnosticBuilder noteAmbiguous( | ||||||||
15995 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||||||
15996 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||||||
15997 | << ConvTy->isEnumeralType() << ConvTy; | ||||||||
15998 | } | ||||||||
15999 | |||||||||
16000 | SemaDiagnosticBuilder diagnoseConversion( | ||||||||
16001 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||||||
16002 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16002); | ||||||||
16003 | } | ||||||||
16004 | } ConvertDiagnoser(Diagnoser); | ||||||||
16005 | |||||||||
16006 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | ||||||||
16007 | ConvertDiagnoser); | ||||||||
16008 | if (Converted.isInvalid()) | ||||||||
16009 | return Converted; | ||||||||
16010 | E = Converted.get(); | ||||||||
16011 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | ||||||||
16012 | return ExprError(); | ||||||||
16013 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||||||
16014 | // An ICE must be of integral or unscoped enumeration type. | ||||||||
16015 | if (!Diagnoser.Suppress) | ||||||||
16016 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | ||||||||
16017 | << E->getSourceRange(); | ||||||||
16018 | return ExprError(); | ||||||||
16019 | } | ||||||||
16020 | |||||||||
16021 | ExprResult RValueExpr = DefaultLvalueConversion(E); | ||||||||
16022 | if (RValueExpr.isInvalid()) | ||||||||
16023 | return ExprError(); | ||||||||
16024 | |||||||||
16025 | E = RValueExpr.get(); | ||||||||
16026 | |||||||||
16027 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | ||||||||
16028 | // in the non-ICE case. | ||||||||
16029 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | ||||||||
16030 | if (Result) | ||||||||
16031 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | ||||||||
16032 | if (!isa<ConstantExpr>(E)) | ||||||||
16033 | E = ConstantExpr::Create(Context, E); | ||||||||
16034 | return E; | ||||||||
16035 | } | ||||||||
16036 | |||||||||
16037 | Expr::EvalResult EvalResult; | ||||||||
16038 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||||
16039 | EvalResult.Diag = &Notes; | ||||||||
16040 | |||||||||
16041 | // Try to evaluate the expression, and produce diagnostics explaining why it's | ||||||||
16042 | // not a constant expression as a side-effect. | ||||||||
16043 | bool Folded = | ||||||||
16044 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | ||||||||
16045 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | ||||||||
16046 | |||||||||
16047 | if (!isa<ConstantExpr>(E)) | ||||||||
16048 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | ||||||||
16049 | |||||||||
16050 | // In C++11, we can rely on diagnostics being produced for any expression | ||||||||
16051 | // which is not a constant expression. If no diagnostics were produced, then | ||||||||
16052 | // this is a constant expression. | ||||||||
16053 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | ||||||||
16054 | if (Result) | ||||||||
16055 | *Result = EvalResult.Val.getInt(); | ||||||||
16056 | return E; | ||||||||
16057 | } | ||||||||
16058 | |||||||||
16059 | // If our only note is the usual "invalid subexpression" note, just point | ||||||||
16060 | // the caret at its location rather than producing an essentially | ||||||||
16061 | // redundant note. | ||||||||
16062 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||||||
16063 | diag::note_invalid_subexpr_in_const_expr) { | ||||||||
16064 | DiagLoc = Notes[0].first; | ||||||||
16065 | Notes.clear(); | ||||||||
16066 | } | ||||||||
16067 | |||||||||
16068 | if (!Folded || !CanFold) { | ||||||||
16069 | if (!Diagnoser.Suppress) { | ||||||||
16070 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | ||||||||
16071 | for (const PartialDiagnosticAt &Note : Notes) | ||||||||
16072 | Diag(Note.first, Note.second); | ||||||||
16073 | } | ||||||||
16074 | |||||||||
16075 | return ExprError(); | ||||||||
16076 | } | ||||||||
16077 | |||||||||
16078 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | ||||||||
16079 | for (const PartialDiagnosticAt &Note : Notes) | ||||||||
16080 | Diag(Note.first, Note.second); | ||||||||
16081 | |||||||||
16082 | if (Result) | ||||||||
16083 | *Result = EvalResult.Val.getInt(); | ||||||||
16084 | return E; | ||||||||
16085 | } | ||||||||
16086 | |||||||||
16087 | namespace { | ||||||||
16088 | // Handle the case where we conclude a expression which we speculatively | ||||||||
16089 | // considered to be unevaluated is actually evaluated. | ||||||||
16090 | class TransformToPE : public TreeTransform<TransformToPE> { | ||||||||
16091 | typedef TreeTransform<TransformToPE> BaseTransform; | ||||||||
16092 | |||||||||
16093 | public: | ||||||||
16094 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | ||||||||
16095 | |||||||||
16096 | // Make sure we redo semantic analysis | ||||||||
16097 | bool AlwaysRebuild() { return true; } | ||||||||
16098 | bool ReplacingOriginal() { return true; } | ||||||||
16099 | |||||||||
16100 | // We need to special-case DeclRefExprs referring to FieldDecls which | ||||||||
16101 | // are not part of a member pointer formation; normal TreeTransforming | ||||||||
16102 | // doesn't catch this case because of the way we represent them in the AST. | ||||||||
16103 | // FIXME: This is a bit ugly; is it really the best way to handle this | ||||||||
16104 | // case? | ||||||||
16105 | // | ||||||||
16106 | // Error on DeclRefExprs referring to FieldDecls. | ||||||||
16107 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||||||
16108 | if (isa<FieldDecl>(E->getDecl()) && | ||||||||
16109 | !SemaRef.isUnevaluatedContext()) | ||||||||
16110 | return SemaRef.Diag(E->getLocation(), | ||||||||
16111 | diag::err_invalid_non_static_member_use) | ||||||||
16112 | << E->getDecl() << E->getSourceRange(); | ||||||||
16113 | |||||||||
16114 | return BaseTransform::TransformDeclRefExpr(E); | ||||||||
16115 | } | ||||||||
16116 | |||||||||
16117 | // Exception: filter out member pointer formation | ||||||||
16118 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | ||||||||
16119 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | ||||||||
16120 | return E; | ||||||||
16121 | |||||||||
16122 | return BaseTransform::TransformUnaryOperator(E); | ||||||||
16123 | } | ||||||||
16124 | |||||||||
16125 | // The body of a lambda-expression is in a separate expression evaluation | ||||||||
16126 | // context so never needs to be transformed. | ||||||||
16127 | // FIXME: Ideally we wouldn't transform the closure type either, and would | ||||||||
16128 | // just recreate the capture expressions and lambda expression. | ||||||||
16129 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | ||||||||
16130 | return SkipLambdaBody(E, Body); | ||||||||
16131 | } | ||||||||
16132 | }; | ||||||||
16133 | } | ||||||||
16134 | |||||||||
16135 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | ||||||||
16136 | assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16137, __PRETTY_FUNCTION__)) | ||||||||
16137 | "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16137, __PRETTY_FUNCTION__)); | ||||||||
16138 | ExprEvalContexts.back().Context = | ||||||||
16139 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | ||||||||
16140 | if (isUnevaluatedContext()) | ||||||||
16141 | return E; | ||||||||
16142 | return TransformToPE(*this).TransformExpr(E); | ||||||||
16143 | } | ||||||||
16144 | |||||||||
16145 | void | ||||||||
16146 | Sema::PushExpressionEvaluationContext( | ||||||||
16147 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | ||||||||
16148 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||||||
16149 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | ||||||||
16150 | LambdaContextDecl, ExprContext); | ||||||||
16151 | Cleanup.reset(); | ||||||||
16152 | if (!MaybeODRUseExprs.empty()) | ||||||||
16153 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | ||||||||
16154 | } | ||||||||
16155 | |||||||||
16156 | void | ||||||||
16157 | Sema::PushExpressionEvaluationContext( | ||||||||
16158 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | ||||||||
16159 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||||||
16160 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | ||||||||
16161 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | ||||||||
16162 | } | ||||||||
16163 | |||||||||
16164 | namespace { | ||||||||
16165 | |||||||||
16166 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | ||||||||
16167 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | ||||||||
16168 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | ||||||||
16169 | if (E->getOpcode() == UO_Deref) | ||||||||
16170 | return CheckPossibleDeref(S, E->getSubExpr()); | ||||||||
16171 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | ||||||||
16172 | return CheckPossibleDeref(S, E->getBase()); | ||||||||
16173 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | ||||||||
16174 | return CheckPossibleDeref(S, E->getBase()); | ||||||||
16175 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | ||||||||
16176 | QualType Inner; | ||||||||
16177 | QualType Ty = E->getType(); | ||||||||
16178 | if (const auto *Ptr = Ty->getAs<PointerType>()) | ||||||||
16179 | Inner = Ptr->getPointeeType(); | ||||||||
16180 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | ||||||||
16181 | Inner = Arr->getElementType(); | ||||||||
16182 | else | ||||||||
16183 | return nullptr; | ||||||||
16184 | |||||||||
16185 | if (Inner->hasAttr(attr::NoDeref)) | ||||||||
16186 | return E; | ||||||||
16187 | } | ||||||||
16188 | return nullptr; | ||||||||
16189 | } | ||||||||
16190 | |||||||||
16191 | } // namespace | ||||||||
16192 | |||||||||
16193 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | ||||||||
16194 | for (const Expr *E : Rec.PossibleDerefs) { | ||||||||
16195 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | ||||||||
16196 | if (DeclRef) { | ||||||||
16197 | const ValueDecl *Decl = DeclRef->getDecl(); | ||||||||
16198 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | ||||||||
16199 | << Decl->getName() << E->getSourceRange(); | ||||||||
16200 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | ||||||||
16201 | } else { | ||||||||
16202 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | ||||||||
16203 | << E->getSourceRange(); | ||||||||
16204 | } | ||||||||
16205 | } | ||||||||
16206 | Rec.PossibleDerefs.clear(); | ||||||||
16207 | } | ||||||||
16208 | |||||||||
16209 | /// Check whether E, which is either a discarded-value expression or an | ||||||||
16210 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | ||||||||
16211 | /// and if so, remove it from the list of volatile-qualified assignments that | ||||||||
16212 | /// we are going to warn are deprecated. | ||||||||
16213 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | ||||||||
16214 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | ||||||||
16215 | return; | ||||||||
16216 | |||||||||
16217 | // Note: ignoring parens here is not justified by the standard rules, but | ||||||||
16218 | // ignoring parentheses seems like a more reasonable approach, and this only | ||||||||
16219 | // drives a deprecation warning so doesn't affect conformance. | ||||||||
16220 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | ||||||||
16221 | if (BO->getOpcode() == BO_Assign) { | ||||||||
16222 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | ||||||||
16223 | LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), | ||||||||
16224 | LHSs.end()); | ||||||||
16225 | } | ||||||||
16226 | } | ||||||||
16227 | } | ||||||||
16228 | |||||||||
16229 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | ||||||||
16230 | if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || | ||||||||
16231 | RebuildingImmediateInvocation) | ||||||||
16232 | return E; | ||||||||
16233 | |||||||||
16234 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | ||||||||
16235 | /// It's OK if this fails; we'll also remove this in | ||||||||
16236 | /// HandleImmediateInvocations, but catching it here allows us to avoid | ||||||||
16237 | /// walking the AST looking for it in simple cases. | ||||||||
16238 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | ||||||||
16239 | if (auto *DeclRef = | ||||||||
16240 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | ||||||||
16241 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | ||||||||
16242 | |||||||||
16243 | E = MaybeCreateExprWithCleanups(E); | ||||||||
16244 | |||||||||
16245 | ConstantExpr *Res = ConstantExpr::Create( | ||||||||
16246 | getASTContext(), E.get(), | ||||||||
16247 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | ||||||||
16248 | getASTContext()), | ||||||||
16249 | /*IsImmediateInvocation*/ true); | ||||||||
16250 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | ||||||||
16251 | return Res; | ||||||||
16252 | } | ||||||||
16253 | |||||||||
16254 | static void EvaluateAndDiagnoseImmediateInvocation( | ||||||||
16255 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | ||||||||
16256 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||||
16257 | Expr::EvalResult Eval; | ||||||||
16258 | Eval.Diag = &Notes; | ||||||||
16259 | ConstantExpr *CE = Candidate.getPointer(); | ||||||||
16260 | bool Result = CE->EvaluateAsConstantExpr( | ||||||||
16261 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | ||||||||
16262 | if (!Result || !Notes.empty()) { | ||||||||
16263 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | ||||||||
16264 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | ||||||||
16265 | InnerExpr = FunctionalCast->getSubExpr(); | ||||||||
16266 | FunctionDecl *FD = nullptr; | ||||||||
16267 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | ||||||||
16268 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | ||||||||
16269 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | ||||||||
16270 | FD = Call->getConstructor(); | ||||||||
16271 | else | ||||||||
16272 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16272); | ||||||||
16273 | assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail ("FD->isConsteval()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16273, __PRETTY_FUNCTION__)); | ||||||||
16274 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | ||||||||
16275 | for (auto &Note : Notes) | ||||||||
16276 | SemaRef.Diag(Note.first, Note.second); | ||||||||
16277 | return; | ||||||||
16278 | } | ||||||||
16279 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | ||||||||
16280 | } | ||||||||
16281 | |||||||||
16282 | static void RemoveNestedImmediateInvocation( | ||||||||
16283 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | ||||||||
16284 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | ||||||||
16285 | struct ComplexRemove : TreeTransform<ComplexRemove> { | ||||||||
16286 | using Base = TreeTransform<ComplexRemove>; | ||||||||
16287 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||||||
16288 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | ||||||||
16289 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | ||||||||
16290 | CurrentII; | ||||||||
16291 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | ||||||||
16292 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | ||||||||
16293 | SmallVector<Sema::ImmediateInvocationCandidate, | ||||||||
16294 | 4>::reverse_iterator Current) | ||||||||
16295 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | ||||||||
16296 | void RemoveImmediateInvocation(ConstantExpr* E) { | ||||||||
16297 | auto It = std::find_if(CurrentII, IISet.rend(), | ||||||||
16298 | [E](Sema::ImmediateInvocationCandidate Elem) { | ||||||||
16299 | return Elem.getPointer() == E; | ||||||||
16300 | }); | ||||||||
16301 | assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16303, __PRETTY_FUNCTION__)) | ||||||||
16302 | "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16303, __PRETTY_FUNCTION__)) | ||||||||
16303 | "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16303, __PRETTY_FUNCTION__)); | ||||||||
16304 | It->setInt(1); // Mark as deleted | ||||||||
16305 | } | ||||||||
16306 | ExprResult TransformConstantExpr(ConstantExpr *E) { | ||||||||
16307 | if (!E->isImmediateInvocation()) | ||||||||
16308 | return Base::TransformConstantExpr(E); | ||||||||
16309 | RemoveImmediateInvocation(E); | ||||||||
16310 | return Base::TransformExpr(E->getSubExpr()); | ||||||||
16311 | } | ||||||||
16312 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | ||||||||
16313 | /// we need to remove its DeclRefExpr from the DRSet. | ||||||||
16314 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||||||
16315 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | ||||||||
16316 | return Base::TransformCXXOperatorCallExpr(E); | ||||||||
16317 | } | ||||||||
16318 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | ||||||||
16319 | /// here. | ||||||||
16320 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | ||||||||
16321 | if (!Init) | ||||||||
16322 | return Init; | ||||||||
16323 | /// ConstantExpr are the first layer of implicit node to be removed so if | ||||||||
16324 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | ||||||||
16325 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||||||
16326 | if (CE->isImmediateInvocation()) | ||||||||
16327 | RemoveImmediateInvocation(CE); | ||||||||
16328 | return Base::TransformInitializer(Init, NotCopyInit); | ||||||||
16329 | } | ||||||||
16330 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||||||
16331 | DRSet.erase(E); | ||||||||
16332 | return E; | ||||||||
16333 | } | ||||||||
16334 | bool AlwaysRebuild() { return false; } | ||||||||
16335 | bool ReplacingOriginal() { return true; } | ||||||||
16336 | bool AllowSkippingCXXConstructExpr() { | ||||||||
16337 | bool Res = AllowSkippingFirstCXXConstructExpr; | ||||||||
16338 | AllowSkippingFirstCXXConstructExpr = true; | ||||||||
16339 | return Res; | ||||||||
16340 | } | ||||||||
16341 | bool AllowSkippingFirstCXXConstructExpr = true; | ||||||||
16342 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | ||||||||
16343 | Rec.ImmediateInvocationCandidates, It); | ||||||||
16344 | |||||||||
16345 | /// CXXConstructExpr with a single argument are getting skipped by | ||||||||
16346 | /// TreeTransform in some situtation because they could be implicit. This | ||||||||
16347 | /// can only occur for the top-level CXXConstructExpr because it is used | ||||||||
16348 | /// nowhere in the expression being transformed therefore will not be rebuilt. | ||||||||
16349 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | ||||||||
16350 | /// skipping the first CXXConstructExpr. | ||||||||
16351 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | ||||||||
16352 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | ||||||||
16353 | |||||||||
16354 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | ||||||||
16355 | assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail ("Res.isUsable()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16355, __PRETTY_FUNCTION__)); | ||||||||
16356 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | ||||||||
16357 | It->getPointer()->setSubExpr(Res.get()); | ||||||||
16358 | } | ||||||||
16359 | |||||||||
16360 | static void | ||||||||
16361 | HandleImmediateInvocations(Sema &SemaRef, | ||||||||
16362 | Sema::ExpressionEvaluationContextRecord &Rec) { | ||||||||
16363 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | ||||||||
16364 | Rec.ReferenceToConsteval.size() == 0) || | ||||||||
16365 | SemaRef.RebuildingImmediateInvocation) | ||||||||
16366 | return; | ||||||||
16367 | |||||||||
16368 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | ||||||||
16369 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | ||||||||
16370 | /// need to remove ReferenceToConsteval in the immediate invocation. | ||||||||
16371 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | ||||||||
16372 | |||||||||
16373 | /// Prevent sema calls during the tree transform from adding pointers that | ||||||||
16374 | /// are already in the sets. | ||||||||
16375 | llvm::SaveAndRestore<bool> DisableIITracking( | ||||||||
16376 | SemaRef.RebuildingImmediateInvocation, true); | ||||||||
16377 | |||||||||
16378 | /// Prevent diagnostic during tree transfrom as they are duplicates | ||||||||
16379 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | ||||||||
16380 | |||||||||
16381 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | ||||||||
16382 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | ||||||||
16383 | if (!It->getInt()) | ||||||||
16384 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | ||||||||
16385 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | ||||||||
16386 | Rec.ReferenceToConsteval.size()) { | ||||||||
16387 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | ||||||||
16388 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||||||
16389 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | ||||||||
16390 | bool VisitDeclRefExpr(DeclRefExpr *E) { | ||||||||
16391 | DRSet.erase(E); | ||||||||
16392 | return DRSet.size(); | ||||||||
16393 | } | ||||||||
16394 | } Visitor(Rec.ReferenceToConsteval); | ||||||||
16395 | Visitor.TraverseStmt( | ||||||||
16396 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | ||||||||
16397 | } | ||||||||
16398 | for (auto CE : Rec.ImmediateInvocationCandidates) | ||||||||
16399 | if (!CE.getInt()) | ||||||||
16400 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | ||||||||
16401 | for (auto DR : Rec.ReferenceToConsteval) { | ||||||||
16402 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | ||||||||
16403 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | ||||||||
16404 | << FD; | ||||||||
16405 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | ||||||||
16406 | } | ||||||||
16407 | } | ||||||||
16408 | |||||||||
16409 | void Sema::PopExpressionEvaluationContext() { | ||||||||
16410 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | ||||||||
16411 | unsigned NumTypos = Rec.NumTypos; | ||||||||
16412 | |||||||||
16413 | if (!Rec.Lambdas.empty()) { | ||||||||
16414 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | ||||||||
16415 | if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || | ||||||||
16416 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { | ||||||||
16417 | unsigned D; | ||||||||
16418 | if (Rec.isUnevaluated()) { | ||||||||
16419 | // C++11 [expr.prim.lambda]p2: | ||||||||
16420 | // A lambda-expression shall not appear in an unevaluated operand | ||||||||
16421 | // (Clause 5). | ||||||||
16422 | D = diag::err_lambda_unevaluated_operand; | ||||||||
16423 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | ||||||||
16424 | // C++1y [expr.const]p2: | ||||||||
16425 | // A conditional-expression e is a core constant expression unless the | ||||||||
16426 | // evaluation of e, following the rules of the abstract machine, would | ||||||||
16427 | // evaluate [...] a lambda-expression. | ||||||||
16428 | D = diag::err_lambda_in_constant_expression; | ||||||||
16429 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | ||||||||
16430 | // C++17 [expr.prim.lamda]p2: | ||||||||
16431 | // A lambda-expression shall not appear [...] in a template-argument. | ||||||||
16432 | D = diag::err_lambda_in_invalid_context; | ||||||||
16433 | } else | ||||||||
16434 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16434); | ||||||||
16435 | |||||||||
16436 | for (const auto *L : Rec.Lambdas) | ||||||||
16437 | Diag(L->getBeginLoc(), D); | ||||||||
16438 | } | ||||||||
16439 | } | ||||||||
16440 | |||||||||
16441 | WarnOnPendingNoDerefs(Rec); | ||||||||
16442 | HandleImmediateInvocations(*this, Rec); | ||||||||
16443 | |||||||||
16444 | // Warn on any volatile-qualified simple-assignments that are not discarded- | ||||||||
16445 | // value expressions nor unevaluated operands (those cases get removed from | ||||||||
16446 | // this list by CheckUnusedVolatileAssignment). | ||||||||
16447 | for (auto *BO : Rec.VolatileAssignmentLHSs) | ||||||||
16448 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | ||||||||
16449 | << BO->getType(); | ||||||||
16450 | |||||||||
16451 | // When are coming out of an unevaluated context, clear out any | ||||||||
16452 | // temporaries that we may have created as part of the evaluation of | ||||||||
16453 | // the expression in that context: they aren't relevant because they | ||||||||
16454 | // will never be constructed. | ||||||||
16455 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | ||||||||
16456 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | ||||||||
16457 | ExprCleanupObjects.end()); | ||||||||
16458 | Cleanup = Rec.ParentCleanup; | ||||||||
16459 | CleanupVarDeclMarking(); | ||||||||
16460 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | ||||||||
16461 | // Otherwise, merge the contexts together. | ||||||||
16462 | } else { | ||||||||
16463 | Cleanup.mergeFrom(Rec.ParentCleanup); | ||||||||
16464 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | ||||||||
16465 | Rec.SavedMaybeODRUseExprs.end()); | ||||||||
16466 | } | ||||||||
16467 | |||||||||
16468 | // Pop the current expression evaluation context off the stack. | ||||||||
16469 | ExprEvalContexts.pop_back(); | ||||||||
16470 | |||||||||
16471 | // The global expression evaluation context record is never popped. | ||||||||
16472 | ExprEvalContexts.back().NumTypos += NumTypos; | ||||||||
16473 | } | ||||||||
16474 | |||||||||
16475 | void Sema::DiscardCleanupsInEvaluationContext() { | ||||||||
16476 | ExprCleanupObjects.erase( | ||||||||
16477 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | ||||||||
16478 | ExprCleanupObjects.end()); | ||||||||
16479 | Cleanup.reset(); | ||||||||
16480 | MaybeODRUseExprs.clear(); | ||||||||
16481 | } | ||||||||
16482 | |||||||||
16483 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | ||||||||
16484 | ExprResult Result = CheckPlaceholderExpr(E); | ||||||||
16485 | if (Result.isInvalid()) | ||||||||
16486 | return ExprError(); | ||||||||
16487 | E = Result.get(); | ||||||||
16488 | if (!E->getType()->isVariablyModifiedType()) | ||||||||
16489 | return E; | ||||||||
16490 | return TransformToPotentiallyEvaluated(E); | ||||||||
16491 | } | ||||||||
16492 | |||||||||
16493 | /// Are we in a context that is potentially constant evaluated per C++20 | ||||||||
16494 | /// [expr.const]p12? | ||||||||
16495 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | ||||||||
16496 | /// C++2a [expr.const]p12: | ||||||||
16497 | // An expression or conversion is potentially constant evaluated if it is | ||||||||
16498 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||||||
16499 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||||||
16500 | // -- a manifestly constant-evaluated expression, | ||||||||
16501 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||||||
16502 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||||||
16503 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||||||
16504 | // -- a potentially-evaluated expression, | ||||||||
16505 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||||||
16506 | // -- an immediate subexpression of a braced-init-list, | ||||||||
16507 | |||||||||
16508 | // -- [FIXME] an expression of the form & cast-expression that occurs | ||||||||
16509 | // within a templated entity | ||||||||
16510 | // -- a subexpression of one of the above that is not a subexpression of | ||||||||
16511 | // a nested unevaluated operand. | ||||||||
16512 | return true; | ||||||||
16513 | |||||||||
16514 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||||||
16515 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||||||
16516 | // Expressions in this context are never evaluated. | ||||||||
16517 | return false; | ||||||||
16518 | } | ||||||||
16519 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16519); | ||||||||
16520 | } | ||||||||
16521 | |||||||||
16522 | /// Return true if this function has a calling convention that requires mangling | ||||||||
16523 | /// in the size of the parameter pack. | ||||||||
16524 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | ||||||||
16525 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | ||||||||
16526 | // we don't need parameter type sizes. | ||||||||
16527 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | ||||||||
16528 | if (!TT.isOSWindows() || !TT.isX86()) | ||||||||
16529 | return false; | ||||||||
16530 | |||||||||
16531 | // If this is C++ and this isn't an extern "C" function, parameters do not | ||||||||
16532 | // need to be complete. In this case, C++ mangling will apply, which doesn't | ||||||||
16533 | // use the size of the parameters. | ||||||||
16534 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | ||||||||
16535 | return false; | ||||||||
16536 | |||||||||
16537 | // Stdcall, fastcall, and vectorcall need this special treatment. | ||||||||
16538 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||||||
16539 | switch (CC) { | ||||||||
16540 | case CC_X86StdCall: | ||||||||
16541 | case CC_X86FastCall: | ||||||||
16542 | case CC_X86VectorCall: | ||||||||
16543 | return true; | ||||||||
16544 | default: | ||||||||
16545 | break; | ||||||||
16546 | } | ||||||||
16547 | return false; | ||||||||
16548 | } | ||||||||
16549 | |||||||||
16550 | /// Require that all of the parameter types of function be complete. Normally, | ||||||||
16551 | /// parameter types are only required to be complete when a function is called | ||||||||
16552 | /// or defined, but to mangle functions with certain calling conventions, the | ||||||||
16553 | /// mangler needs to know the size of the parameter list. In this situation, | ||||||||
16554 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | ||||||||
16555 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | ||||||||
16556 | /// result in a linker error. Clang doesn't implement this behavior, and instead | ||||||||
16557 | /// attempts to error at compile time. | ||||||||
16558 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | ||||||||
16559 | SourceLocation Loc) { | ||||||||
16560 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | ||||||||
16561 | FunctionDecl *FD; | ||||||||
16562 | ParmVarDecl *Param; | ||||||||
16563 | |||||||||
16564 | public: | ||||||||
16565 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | ||||||||
16566 | : FD(FD), Param(Param) {} | ||||||||
16567 | |||||||||
16568 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||||||
16569 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||||||
16570 | StringRef CCName; | ||||||||
16571 | switch (CC) { | ||||||||
16572 | case CC_X86StdCall: | ||||||||
16573 | CCName = "stdcall"; | ||||||||
16574 | break; | ||||||||
16575 | case CC_X86FastCall: | ||||||||
16576 | CCName = "fastcall"; | ||||||||
16577 | break; | ||||||||
16578 | case CC_X86VectorCall: | ||||||||
16579 | CCName = "vectorcall"; | ||||||||
16580 | break; | ||||||||
16581 | default: | ||||||||
16582 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16582); | ||||||||
16583 | } | ||||||||
16584 | |||||||||
16585 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | ||||||||
16586 | << Param->getDeclName() << FD->getDeclName() << CCName; | ||||||||
16587 | } | ||||||||
16588 | }; | ||||||||
16589 | |||||||||
16590 | for (ParmVarDecl *Param : FD->parameters()) { | ||||||||
16591 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | ||||||||
16592 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | ||||||||
16593 | } | ||||||||
16594 | } | ||||||||
16595 | |||||||||
16596 | namespace { | ||||||||
16597 | enum class OdrUseContext { | ||||||||
16598 | /// Declarations in this context are not odr-used. | ||||||||
16599 | None, | ||||||||
16600 | /// Declarations in this context are formally odr-used, but this is a | ||||||||
16601 | /// dependent context. | ||||||||
16602 | Dependent, | ||||||||
16603 | /// Declarations in this context are odr-used but not actually used (yet). | ||||||||
16604 | FormallyOdrUsed, | ||||||||
16605 | /// Declarations in this context are used. | ||||||||
16606 | Used | ||||||||
16607 | }; | ||||||||
16608 | } | ||||||||
16609 | |||||||||
16610 | /// Are we within a context in which references to resolved functions or to | ||||||||
16611 | /// variables result in odr-use? | ||||||||
16612 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | ||||||||
16613 | OdrUseContext Result; | ||||||||
16614 | |||||||||
16615 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||||||
16616 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||||||
16617 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||||||
16618 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||||||
16619 | return OdrUseContext::None; | ||||||||
16620 | |||||||||
16621 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||||||
16622 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||||||
16623 | Result = OdrUseContext::Used; | ||||||||
16624 | break; | ||||||||
16625 | |||||||||
16626 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||||||
16627 | Result = OdrUseContext::FormallyOdrUsed; | ||||||||
16628 | break; | ||||||||
16629 | |||||||||
16630 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||||||
16631 | // A default argument formally results in odr-use, but doesn't actually | ||||||||
16632 | // result in a use in any real sense until it itself is used. | ||||||||
16633 | Result = OdrUseContext::FormallyOdrUsed; | ||||||||
16634 | break; | ||||||||
16635 | } | ||||||||
16636 | |||||||||
16637 | if (SemaRef.CurContext->isDependentContext()) | ||||||||
16638 | return OdrUseContext::Dependent; | ||||||||
16639 | |||||||||
16640 | return Result; | ||||||||
16641 | } | ||||||||
16642 | |||||||||
16643 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | ||||||||
16644 | if (!Func->isConstexpr()) | ||||||||
16645 | return false; | ||||||||
16646 | |||||||||
16647 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | ||||||||
16648 | return true; | ||||||||
16649 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | ||||||||
16650 | return CCD && CCD->getInheritedConstructor(); | ||||||||
16651 | } | ||||||||
16652 | |||||||||
16653 | /// Mark a function referenced, and check whether it is odr-used | ||||||||
16654 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | ||||||||
16655 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | ||||||||
16656 | bool MightBeOdrUse) { | ||||||||
16657 | assert(Func && "No function?")((Func && "No function?") ? static_cast<void> ( 0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 16657, __PRETTY_FUNCTION__)); | ||||||||
16658 | |||||||||
16659 | Func->setReferenced(); | ||||||||
16660 | |||||||||
16661 | // Recursive functions aren't really used until they're used from some other | ||||||||
16662 | // context. | ||||||||
16663 | bool IsRecursiveCall = CurContext == Func; | ||||||||
16664 | |||||||||
16665 | // C++11 [basic.def.odr]p3: | ||||||||
16666 | // A function whose name appears as a potentially-evaluated expression is | ||||||||
16667 | // odr-used if it is the unique lookup result or the selected member of a | ||||||||
16668 | // set of overloaded functions [...]. | ||||||||
16669 | // | ||||||||
16670 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | ||||||||
16671 | // can just check that here. | ||||||||
16672 | OdrUseContext OdrUse = | ||||||||
16673 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | ||||||||
16674 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | ||||||||
16675 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||||||
16676 | |||||||||
16677 | // Trivial default constructors and destructors are never actually used. | ||||||||
16678 | // FIXME: What about other special members? | ||||||||
16679 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | ||||||||
16680 | OdrUse == OdrUseContext::Used) { | ||||||||
16681 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | ||||||||
16682 | if (Constructor->isDefaultConstructor()) | ||||||||
16683 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||||||
16684 | if (isa<CXXDestructorDecl>(Func)) | ||||||||
16685 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||||||
16686 | } | ||||||||
16687 | |||||||||
16688 | // C++20 [expr.const]p12: | ||||||||
16689 | // A function [...] is needed for constant evaluation if it is [...] a | ||||||||
16690 | // constexpr function that is named by an expression that is potentially | ||||||||
16691 | // constant evaluated | ||||||||
16692 | bool NeededForConstantEvaluation = | ||||||||
16693 | isPotentiallyConstantEvaluatedContext(*this) && | ||||||||
16694 | isImplicitlyDefinableConstexprFunction(Func); | ||||||||
16695 | |||||||||
16696 | // Determine whether we require a function definition to exist, per | ||||||||
16697 | // C++11 [temp.inst]p3: | ||||||||
16698 | // Unless a function template specialization has been explicitly | ||||||||
16699 | // instantiated or explicitly specialized, the function template | ||||||||
16700 | // specialization is implicitly instantiated when the specialization is | ||||||||
16701 | // referenced in a context that requires a function definition to exist. | ||||||||
16702 | // C++20 [temp.inst]p7: | ||||||||
16703 | // The existence of a definition of a [...] function is considered to | ||||||||
16704 | // affect the semantics of the program if the [...] function is needed for | ||||||||
16705 | // constant evaluation by an expression | ||||||||
16706 | // C++20 [basic.def.odr]p10: | ||||||||
16707 | // Every program shall contain exactly one definition of every non-inline | ||||||||
16708 | // function or variable that is odr-used in that program outside of a | ||||||||
16709 | // discarded statement | ||||||||
16710 | // C++20 [special]p1: | ||||||||
16711 | // The implementation will implicitly define [defaulted special members] | ||||||||
16712 | // if they are odr-used or needed for constant evaluation. | ||||||||
16713 | // | ||||||||
16714 | // Note that we skip the implicit instantiation of templates that are only | ||||||||
16715 | // used in unused default arguments or by recursive calls to themselves. | ||||||||
16716 | // This is formally non-conforming, but seems reasonable in practice. | ||||||||
16717 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | ||||||||
16718 | NeededForConstantEvaluation); | ||||||||
16719 | |||||||||
16720 | // C++14 [temp.expl.spec]p6: | ||||||||
16721 | // If a template [...] is explicitly specialized then that specialization | ||||||||
16722 | // shall be declared before the first use of that specialization that would | ||||||||
16723 | // cause an implicit instantiation to take place, in every translation unit | ||||||||
16724 | // in which such a use occurs | ||||||||
16725 | if (NeedDefinition && | ||||||||
16726 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | ||||||||
16727 | Func->getMemberSpecializationInfo())) | ||||||||
16728 | checkSpecializationVisibility(Loc, Func); | ||||||||
16729 | |||||||||
16730 | if (getLangOpts().CUDA) | ||||||||
16731 | CheckCUDACall(Loc, Func); | ||||||||
16732 | |||||||||
16733 | if (getLangOpts().SYCLIsDevice) | ||||||||
16734 | checkSYCLDeviceFunction(Loc, Func); | ||||||||
16735 | |||||||||
16736 | // If we need a definition, try to create one. | ||||||||
16737 | if (NeedDefinition && !Func->getBody()) { | ||||||||
16738 | runWithSufficientStackSpace(Loc, [&] { | ||||||||
16739 | if (CXXConstructorDecl *Constructor = | ||||||||
16740 | dyn_cast<CXXConstructorDecl>(Func)) { | ||||||||
16741 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | ||||||||
16742 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | ||||||||
16743 | if (Constructor->isDefaultConstructor()) { | ||||||||
16744 | if (Constructor->isTrivial() && | ||||||||
16745 | !Constructor->hasAttr<DLLExportAttr>()) | ||||||||
16746 | return; | ||||||||
16747 | DefineImplicitDefaultConstructor(Loc, Constructor); | ||||||||
16748 | } else if (Constructor->isCopyConstructor()) { | ||||||||
16749 | DefineImplicitCopyConstructor(Loc, Constructor); | ||||||||
16750 | } else if (Constructor->isMoveConstructor()) { | ||||||||
16751 | DefineImplicitMoveConstructor(Loc, Constructor); | ||||||||
16752 | } | ||||||||
16753 | } else if (Constructor->getInheritedConstructor()) { | ||||||||
16754 | DefineInheritingConstructor(Loc, Constructor); | ||||||||
16755 | } | ||||||||
16756 | } else if (CXXDestructorDecl *Destructor = | ||||||||
16757 | dyn_cast<CXXDestructorDecl>(Func)) { | ||||||||
16758 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | ||||||||
16759 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | ||||||||
16760 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | ||||||||
16761 | return; | ||||||||
16762 | DefineImplicitDestructor(Loc, Destructor); | ||||||||
16763 | } | ||||||||
16764 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | ||||||||
16765 | MarkVTableUsed(Loc, Destructor->getParent()); | ||||||||
16766 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | ||||||||
16767 | if (MethodDecl->isOverloadedOperator() && | ||||||||
16768 | MethodDecl->getOverloadedOperator() == OO_Equal) { | ||||||||
16769 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | ||||||||
16770 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | ||||||||
16771 | if (MethodDecl->isCopyAssignmentOperator()) | ||||||||
16772 | DefineImplicitCopyAssignment(Loc, MethodDecl); | ||||||||
16773 | else if (MethodDecl->isMoveAssignmentOperator()) | ||||||||
16774 | DefineImplicitMoveAssignment(Loc, MethodDecl); | ||||||||
16775 | } | ||||||||
16776 | } else if (isa<CXXConversionDecl>(MethodDecl) && | ||||||||
16777 | MethodDecl->getParent()->isLambda()) { | ||||||||
16778 | CXXConversionDecl *Conversion = | ||||||||
16779 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | ||||||||
16780 | if (Conversion->isLambdaToBlockPointerConversion()) | ||||||||
16781 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | ||||||||
16782 | else | ||||||||
16783 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | ||||||||
16784 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | ||||||||
16785 | MarkVTableUsed(Loc, MethodDecl->getParent()); | ||||||||
16786 | } | ||||||||
16787 | |||||||||
16788 | if (Func->isDefaulted() && !Func->isDeleted()) { | ||||||||
16789 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | ||||||||
16790 | if (DCK != DefaultedComparisonKind::None) | ||||||||
16791 | DefineDefaultedComparison(Loc, Func, DCK); | ||||||||
16792 | } | ||||||||
16793 | |||||||||
16794 | // Implicit instantiation of function templates and member functions of | ||||||||
16795 | // class templates. | ||||||||
16796 | if (Func->isImplicitlyInstantiable()) { | ||||||||
16797 | TemplateSpecializationKind TSK = | ||||||||
16798 | Func->getTemplateSpecializationKindForInstantiation(); | ||||||||
16799 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | ||||||||
16800 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||||||
16801 | if (FirstInstantiation) { | ||||||||
16802 | PointOfInstantiation = Loc; | ||||||||
16803 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||||||
16804 | } else if (TSK != TSK_ImplicitInstantiation) { | ||||||||
16805 | // Use the point of use as the point of instantiation, instead of the | ||||||||
16806 | // point of explicit instantiation (which we track as the actual point | ||||||||
16807 | // of instantiation). This gives better backtraces in diagnostics. | ||||||||
16808 | PointOfInstantiation = Loc; | ||||||||
16809 | } | ||||||||
16810 | |||||||||
16811 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | ||||||||
16812 | Func->isConstexpr()) { | ||||||||
16813 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | ||||||||
16814 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | ||||||||
16815 | CodeSynthesisContexts.size()) | ||||||||
16816 | PendingLocalImplicitInstantiations.push_back( | ||||||||
16817 | std::make_pair(Func, PointOfInstantiation)); | ||||||||
16818 | else if (Func->isConstexpr()) | ||||||||
16819 | // Do not defer instantiations of constexpr functions, to avoid the | ||||||||
16820 | // expression evaluator needing to call back into Sema if it sees a | ||||||||
16821 | // call to such a function. | ||||||||
16822 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | ||||||||
16823 | else { | ||||||||
16824 | Func->setInstantiationIsPending(true); | ||||||||
16825 | PendingInstantiations.push_back( | ||||||||
16826 | std::make_pair(Func, PointOfInstantiation)); | ||||||||
16827 | // Notify the consumer that a function was implicitly instantiated. | ||||||||
16828 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | ||||||||
16829 | } | ||||||||
16830 | } | ||||||||
16831 | } else { | ||||||||
16832 | // Walk redefinitions, as some of them may be instantiable. | ||||||||
16833 | for (auto i : Func->redecls()) { | ||||||||
16834 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | ||||||||
16835 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | ||||||||
16836 | } | ||||||||
16837 | } | ||||||||
16838 | }); | ||||||||
16839 | } | ||||||||
16840 | |||||||||
16841 | // C++14 [except.spec]p17: | ||||||||
16842 | // An exception-specification is considered to be needed when: | ||||||||
16843 | // - the function is odr-used or, if it appears in an unevaluated operand, | ||||||||
16844 | // would be odr-used if the expression were potentially-evaluated; | ||||||||
16845 | // | ||||||||
16846 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | ||||||||
16847 | // function is a pure virtual function we're calling, and in that case the | ||||||||
16848 | // function was selected by overload resolution and we need to resolve its | ||||||||
16849 | // exception specification for a different reason. | ||||||||
16850 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | ||||||||
16851 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | ||||||||
16852 | ResolveExceptionSpec(Loc, FPT); | ||||||||
16853 | |||||||||
16854 | // If this is the first "real" use, act on that. | ||||||||
16855 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | ||||||||
16856 | // Keep track of used but undefined functions. | ||||||||
16857 | if (!Func->isDefined()) { | ||||||||
16858 | if (mightHaveNonExternalLinkage(Func)) | ||||||||
16859 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||||||
16860 | else if (Func->getMostRecentDecl()->isInlined() && | ||||||||
16861 | !LangOpts.GNUInline && | ||||||||
16862 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | ||||||||
16863 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||||||
16864 | else if (isExternalWithNoLinkageType(Func)) | ||||||||
16865 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||||||
16866 | } | ||||||||
16867 | |||||||||
16868 | // Some x86 Windows calling conventions mangle the size of the parameter | ||||||||
16869 | // pack into the name. Computing the size of the parameters requires the | ||||||||
16870 | // parameter types to be complete. Check that now. | ||||||||
16871 | if (funcHasParameterSizeMangling(*this, Func)) | ||||||||
16872 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | ||||||||
16873 | |||||||||
16874 | // In the MS C++ ABI, the compiler emits destructor variants where they are | ||||||||
16875 | // used. If the destructor is used here but defined elsewhere, mark the | ||||||||
16876 | // virtual base destructors referenced. If those virtual base destructors | ||||||||
16877 | // are inline, this will ensure they are defined when emitting the complete | ||||||||
16878 | // destructor variant. This checking may be redundant if the destructor is | ||||||||
16879 | // provided later in this TU. | ||||||||
16880 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||||||
16881 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | ||||||||
16882 | CXXRecordDecl *Parent = Dtor->getParent(); | ||||||||
16883 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | ||||||||
16884 | CheckCompleteDestructorVariant(Loc, Dtor); | ||||||||
16885 | } | ||||||||
16886 | } | ||||||||
16887 | |||||||||
16888 | Func->markUsed(Context); | ||||||||
16889 | } | ||||||||
16890 | } | ||||||||
16891 | |||||||||
16892 | /// Directly mark a variable odr-used. Given a choice, prefer to use | ||||||||
16893 | /// MarkVariableReferenced since it does additional checks and then | ||||||||
16894 | /// calls MarkVarDeclODRUsed. | ||||||||
16895 | /// If the variable must be captured: | ||||||||
16896 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | ||||||||
16897 | /// - else capture it in the DeclContext that maps to the | ||||||||
16898 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | ||||||||
16899 | static void | ||||||||
16900 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | ||||||||
16901 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | ||||||||
16902 | // Keep track of used but undefined variables. | ||||||||
16903 | // FIXME: We shouldn't suppress this warning for static data members. | ||||||||
16904 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | ||||||||
16905 | (!Var->isExternallyVisible() || Var->isInline() || | ||||||||
16906 | SemaRef.isExternalWithNoLinkageType(Var)) && | ||||||||
16907 | !(Var->isStaticDataMember() && Var->hasInit())) { | ||||||||
16908 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | ||||||||
16909 | if (old.isInvalid()) | ||||||||
16910 | old = Loc; | ||||||||
16911 | } | ||||||||
16912 | QualType CaptureType, DeclRefType; | ||||||||
16913 | if (SemaRef.LangOpts.OpenMP) | ||||||||
16914 | SemaRef.tryCaptureOpenMPLambdas(Var); | ||||||||
16915 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | ||||||||
16916 | /*EllipsisLoc*/ SourceLocation(), | ||||||||
16917 | /*BuildAndDiagnose*/ true, | ||||||||
16918 | CaptureType, DeclRefType, | ||||||||
16919 | FunctionScopeIndexToStopAt); | ||||||||
16920 | |||||||||
16921 | Var->markUsed(SemaRef.Context); | ||||||||
16922 | } | ||||||||
16923 | |||||||||
16924 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | ||||||||
16925 | SourceLocation Loc, | ||||||||
16926 | unsigned CapturingScopeIndex) { | ||||||||
16927 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | ||||||||
16928 | } | ||||||||
16929 | |||||||||
16930 | static void | ||||||||
16931 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||||||
16932 | ValueDecl *var, DeclContext *DC) { | ||||||||
16933 | DeclContext *VarDC = var->getDeclContext(); | ||||||||
16934 | |||||||||
16935 | // If the parameter still belongs to the translation unit, then | ||||||||
16936 | // we're actually just using one parameter in the declaration of | ||||||||
16937 | // the next. | ||||||||
16938 | if (isa<ParmVarDecl>(var) && | ||||||||
16939 | isa<TranslationUnitDecl>(VarDC)) | ||||||||
16940 | return; | ||||||||
16941 | |||||||||
16942 | // For C code, don't diagnose about capture if we're not actually in code | ||||||||
16943 | // right now; it's impossible to write a non-constant expression outside of | ||||||||
16944 | // function context, so we'll get other (more useful) diagnostics later. | ||||||||
16945 | // | ||||||||
16946 | // For C++, things get a bit more nasty... it would be nice to suppress this | ||||||||
16947 | // diagnostic for certain cases like using a local variable in an array bound | ||||||||
16948 | // for a member of a local class, but the correct predicate is not obvious. | ||||||||
16949 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | ||||||||
16950 | return; | ||||||||
16951 | |||||||||
16952 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | ||||||||
16953 | unsigned ContextKind = 3; // unknown | ||||||||
16954 | if (isa<CXXMethodDecl>(VarDC) && | ||||||||
16955 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | ||||||||
16956 | ContextKind = 2; | ||||||||
16957 | } else if (isa<FunctionDecl>(VarDC)) { | ||||||||
16958 | ContextKind = 0; | ||||||||
16959 | } else if (isa<BlockDecl>(VarDC)) { | ||||||||
16960 | ContextKind = 1; | ||||||||
16961 | } | ||||||||
16962 | |||||||||
16963 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | ||||||||
16964 | << var << ValueKind << ContextKind << VarDC; | ||||||||
16965 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | ||||||||
16966 | << var; | ||||||||
16967 | |||||||||
16968 | // FIXME: Add additional diagnostic info about class etc. which prevents | ||||||||
16969 | // capture. | ||||||||
16970 | } | ||||||||
16971 | |||||||||
16972 | |||||||||
16973 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | ||||||||
16974 | bool &SubCapturesAreNested, | ||||||||
16975 | QualType &CaptureType, | ||||||||
16976 | QualType &DeclRefType) { | ||||||||
16977 | // Check whether we've already captured it. | ||||||||
16978 | if (CSI->CaptureMap.count(Var)) { | ||||||||
16979 | // If we found a capture, any subcaptures are nested. | ||||||||
16980 | SubCapturesAreNested = true; | ||||||||
16981 | |||||||||
16982 | // Retrieve the capture type for this variable. | ||||||||
16983 | CaptureType = CSI->getCapture(Var).getCaptureType(); | ||||||||
16984 | |||||||||
16985 | // Compute the type of an expression that refers to this variable. | ||||||||
16986 | DeclRefType = CaptureType.getNonReferenceType(); | ||||||||
16987 | |||||||||
16988 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | ||||||||
16989 | // are mutable in the sense that user can change their value - they are | ||||||||
16990 | // private instances of the captured declarations. | ||||||||
16991 | const Capture &Cap = CSI->getCapture(Var); | ||||||||
16992 | if (Cap.isCopyCapture() && | ||||||||
16993 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | ||||||||
16994 | !(isa<CapturedRegionScopeInfo>(CSI) && | ||||||||
16995 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | ||||||||
16996 | DeclRefType.addConst(); | ||||||||
16997 | return true; | ||||||||
16998 | } | ||||||||
16999 | return false; | ||||||||
17000 | } | ||||||||
17001 | |||||||||
17002 | // Only block literals, captured statements, and lambda expressions can | ||||||||
17003 | // capture; other scopes don't work. | ||||||||
17004 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | ||||||||
17005 | SourceLocation Loc, | ||||||||
17006 | const bool Diagnose, Sema &S) { | ||||||||
17007 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | ||||||||
17008 | return getLambdaAwareParentOfDeclContext(DC); | ||||||||
17009 | else if (Var->hasLocalStorage()) { | ||||||||
17010 | if (Diagnose) | ||||||||
17011 | diagnoseUncapturableValueReference(S, Loc, Var, DC); | ||||||||
17012 | } | ||||||||
17013 | return nullptr; | ||||||||
17014 | } | ||||||||
17015 | |||||||||
17016 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||||||
17017 | // certain types of variables (unnamed, variably modified types etc.) | ||||||||
17018 | // so check for eligibility. | ||||||||
17019 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | ||||||||
17020 | SourceLocation Loc, | ||||||||
17021 | const bool Diagnose, Sema &S) { | ||||||||
17022 | |||||||||
17023 | bool IsBlock = isa<BlockScopeInfo>(CSI); | ||||||||
17024 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | ||||||||
17025 | |||||||||
17026 | // Lambdas are not allowed to capture unnamed variables | ||||||||
17027 | // (e.g. anonymous unions). | ||||||||
17028 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | ||||||||
17029 | // assuming that's the intent. | ||||||||
17030 | if (IsLambda && !Var->getDeclName()) { | ||||||||
17031 | if (Diagnose) { | ||||||||
17032 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | ||||||||
17033 | S.Diag(Var->getLocation(), diag::note_declared_at); | ||||||||
17034 | } | ||||||||
17035 | return false; | ||||||||
17036 | } | ||||||||
17037 | |||||||||
17038 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | ||||||||
17039 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | ||||||||
17040 | if (Diagnose) { | ||||||||
17041 | S.Diag(Loc, diag::err_ref_vm_type); | ||||||||
17042 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17043 | } | ||||||||
17044 | return false; | ||||||||
17045 | } | ||||||||
17046 | // Prohibit structs with flexible array members too. | ||||||||
17047 | // We cannot capture what is in the tail end of the struct. | ||||||||
17048 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | ||||||||
17049 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | ||||||||
17050 | if (Diagnose) { | ||||||||
17051 | if (IsBlock) | ||||||||
17052 | S.Diag(Loc, diag::err_ref_flexarray_type); | ||||||||
17053 | else | ||||||||
17054 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | ||||||||
17055 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17056 | } | ||||||||
17057 | return false; | ||||||||
17058 | } | ||||||||
17059 | } | ||||||||
17060 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||||||
17061 | // Lambdas and captured statements are not allowed to capture __block | ||||||||
17062 | // variables; they don't support the expected semantics. | ||||||||
17063 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | ||||||||
17064 | if (Diagnose) { | ||||||||
17065 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | ||||||||
17066 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17067 | } | ||||||||
17068 | return false; | ||||||||
17069 | } | ||||||||
17070 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | ||||||||
17071 | if (S.getLangOpts().OpenCL && IsBlock && | ||||||||
17072 | Var->getType()->isBlockPointerType()) { | ||||||||
17073 | if (Diagnose) | ||||||||
17074 | S.Diag(Loc, diag::err_opencl_block_ref_block); | ||||||||
17075 | return false; | ||||||||
17076 | } | ||||||||
17077 | |||||||||
17078 | return true; | ||||||||
17079 | } | ||||||||
17080 | |||||||||
17081 | // Returns true if the capture by block was successful. | ||||||||
17082 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | ||||||||
17083 | SourceLocation Loc, | ||||||||
17084 | const bool BuildAndDiagnose, | ||||||||
17085 | QualType &CaptureType, | ||||||||
17086 | QualType &DeclRefType, | ||||||||
17087 | const bool Nested, | ||||||||
17088 | Sema &S, bool Invalid) { | ||||||||
17089 | bool ByRef = false; | ||||||||
17090 | |||||||||
17091 | // Blocks are not allowed to capture arrays, excepting OpenCL. | ||||||||
17092 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | ||||||||
17093 | // (decayed to pointers). | ||||||||
17094 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | ||||||||
17095 | if (BuildAndDiagnose) { | ||||||||
17096 | S.Diag(Loc, diag::err_ref_array_type); | ||||||||
17097 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17098 | Invalid = true; | ||||||||
17099 | } else { | ||||||||
17100 | return false; | ||||||||
17101 | } | ||||||||
17102 | } | ||||||||
17103 | |||||||||
17104 | // Forbid the block-capture of autoreleasing variables. | ||||||||
17105 | if (!Invalid && | ||||||||
17106 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||||||
17107 | if (BuildAndDiagnose) { | ||||||||
17108 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | ||||||||
17109 | << /*block*/ 0; | ||||||||
17110 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17111 | Invalid = true; | ||||||||
17112 | } else { | ||||||||
17113 | return false; | ||||||||
17114 | } | ||||||||
17115 | } | ||||||||
17116 | |||||||||
17117 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | ||||||||
17118 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | ||||||||
17119 | QualType PointeeTy = PT->getPointeeType(); | ||||||||
17120 | |||||||||
17121 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | ||||||||
17122 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | ||||||||
17123 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | ||||||||
17124 | if (BuildAndDiagnose) { | ||||||||
17125 | SourceLocation VarLoc = Var->getLocation(); | ||||||||
17126 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | ||||||||
17127 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | ||||||||
17128 | } | ||||||||
17129 | } | ||||||||
17130 | } | ||||||||
17131 | |||||||||
17132 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||||||
17133 | if (HasBlocksAttr || CaptureType->isReferenceType() || | ||||||||
17134 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | ||||||||
17135 | // Block capture by reference does not change the capture or | ||||||||
17136 | // declaration reference types. | ||||||||
17137 | ByRef = true; | ||||||||
17138 | } else { | ||||||||
17139 | // Block capture by copy introduces 'const'. | ||||||||
17140 | CaptureType = CaptureType.getNonReferenceType().withConst(); | ||||||||
17141 | DeclRefType = CaptureType; | ||||||||
17142 | } | ||||||||
17143 | |||||||||
17144 | // Actually capture the variable. | ||||||||
17145 | if (BuildAndDiagnose) | ||||||||
17146 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | ||||||||
17147 | CaptureType, Invalid); | ||||||||
17148 | |||||||||
17149 | return !Invalid; | ||||||||
17150 | } | ||||||||
17151 | |||||||||
17152 | |||||||||
17153 | /// Capture the given variable in the captured region. | ||||||||
17154 | static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, | ||||||||
17155 | VarDecl *Var, | ||||||||
17156 | SourceLocation Loc, | ||||||||
17157 | const bool BuildAndDiagnose, | ||||||||
17158 | QualType &CaptureType, | ||||||||
17159 | QualType &DeclRefType, | ||||||||
17160 | const bool RefersToCapturedVariable, | ||||||||
17161 | Sema &S, bool Invalid) { | ||||||||
17162 | // By default, capture variables by reference. | ||||||||
17163 | bool ByRef = true; | ||||||||
17164 | // Using an LValue reference type is consistent with Lambdas (see below). | ||||||||
17165 | if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | ||||||||
17166 | if (S.isOpenMPCapturedDecl(Var)) { | ||||||||
17167 | bool HasConst = DeclRefType.isConstQualified(); | ||||||||
17168 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||||||
17169 | // Don't lose diagnostics about assignments to const. | ||||||||
17170 | if (HasConst) | ||||||||
17171 | DeclRefType.addConst(); | ||||||||
17172 | } | ||||||||
17173 | // Do not capture firstprivates in tasks. | ||||||||
17174 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | ||||||||
17175 | OMPC_unknown) | ||||||||
17176 | return true; | ||||||||
17177 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | ||||||||
17178 | RSI->OpenMPCaptureLevel); | ||||||||
17179 | } | ||||||||
17180 | |||||||||
17181 | if (ByRef) | ||||||||
17182 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||||||
17183 | else | ||||||||
17184 | CaptureType = DeclRefType; | ||||||||
17185 | |||||||||
17186 | // Actually capture the variable. | ||||||||
17187 | if (BuildAndDiagnose) | ||||||||
17188 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | ||||||||
17189 | Loc, SourceLocation(), CaptureType, Invalid); | ||||||||
17190 | |||||||||
17191 | return !Invalid; | ||||||||
17192 | } | ||||||||
17193 | |||||||||
17194 | /// Capture the given variable in the lambda. | ||||||||
17195 | static bool captureInLambda(LambdaScopeInfo *LSI, | ||||||||
17196 | VarDecl *Var, | ||||||||
17197 | SourceLocation Loc, | ||||||||
17198 | const bool BuildAndDiagnose, | ||||||||
17199 | QualType &CaptureType, | ||||||||
17200 | QualType &DeclRefType, | ||||||||
17201 | const bool RefersToCapturedVariable, | ||||||||
17202 | const Sema::TryCaptureKind Kind, | ||||||||
17203 | SourceLocation EllipsisLoc, | ||||||||
17204 | const bool IsTopScope, | ||||||||
17205 | Sema &S, bool Invalid) { | ||||||||
17206 | // Determine whether we are capturing by reference or by value. | ||||||||
17207 | bool ByRef = false; | ||||||||
17208 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||||||
17209 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||||||
17210 | } else { | ||||||||
17211 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | ||||||||
17212 | } | ||||||||
17213 | |||||||||
17214 | // Compute the type of the field that will capture this variable. | ||||||||
17215 | if (ByRef) { | ||||||||
17216 | // C++11 [expr.prim.lambda]p15: | ||||||||
17217 | // An entity is captured by reference if it is implicitly or | ||||||||
17218 | // explicitly captured but not captured by copy. It is | ||||||||
17219 | // unspecified whether additional unnamed non-static data | ||||||||
17220 | // members are declared in the closure type for entities | ||||||||
17221 | // captured by reference. | ||||||||
17222 | // | ||||||||
17223 | // FIXME: It is not clear whether we want to build an lvalue reference | ||||||||
17224 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | ||||||||
17225 | // to do the former, while EDG does the latter. Core issue 1249 will | ||||||||
17226 | // clarify, but for now we follow GCC because it's a more permissive and | ||||||||
17227 | // easily defensible position. | ||||||||
17228 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||||||
17229 | } else { | ||||||||
17230 | // C++11 [expr.prim.lambda]p14: | ||||||||
17231 | // For each entity captured by copy, an unnamed non-static | ||||||||
17232 | // data member is declared in the closure type. The | ||||||||
17233 | // declaration order of these members is unspecified. The type | ||||||||
17234 | // of such a data member is the type of the corresponding | ||||||||
17235 | // captured entity if the entity is not a reference to an | ||||||||
17236 | // object, or the referenced type otherwise. [Note: If the | ||||||||
17237 | // captured entity is a reference to a function, the | ||||||||
17238 | // corresponding data member is also a reference to a | ||||||||
17239 | // function. - end note ] | ||||||||
17240 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | ||||||||
17241 | if (!RefType->getPointeeType()->isFunctionType()) | ||||||||
17242 | CaptureType = RefType->getPointeeType(); | ||||||||
17243 | } | ||||||||
17244 | |||||||||
17245 | // Forbid the lambda copy-capture of autoreleasing variables. | ||||||||
17246 | if (!Invalid && | ||||||||
17247 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||||||
17248 | if (BuildAndDiagnose) { | ||||||||
17249 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | ||||||||
17250 | S.Diag(Var->getLocation(), diag::note_previous_decl) | ||||||||
17251 | << Var->getDeclName(); | ||||||||
17252 | Invalid = true; | ||||||||
17253 | } else { | ||||||||
17254 | return false; | ||||||||
17255 | } | ||||||||
17256 | } | ||||||||
17257 | |||||||||
17258 | // Make sure that by-copy captures are of a complete and non-abstract type. | ||||||||
17259 | if (!Invalid && BuildAndDiagnose) { | ||||||||
17260 | if (!CaptureType->isDependentType() && | ||||||||
17261 | S.RequireCompleteSizedType( | ||||||||
17262 | Loc, CaptureType, | ||||||||
17263 | diag::err_capture_of_incomplete_or_sizeless_type, | ||||||||
17264 | Var->getDeclName())) | ||||||||
17265 | Invalid = true; | ||||||||
17266 | else if (S.RequireNonAbstractType(Loc, CaptureType, | ||||||||
17267 | diag::err_capture_of_abstract_type)) | ||||||||
17268 | Invalid = true; | ||||||||
17269 | } | ||||||||
17270 | } | ||||||||
17271 | |||||||||
17272 | // Compute the type of a reference to this captured variable. | ||||||||
17273 | if (ByRef) | ||||||||
17274 | DeclRefType = CaptureType.getNonReferenceType(); | ||||||||
17275 | else { | ||||||||
17276 | // C++ [expr.prim.lambda]p5: | ||||||||
17277 | // The closure type for a lambda-expression has a public inline | ||||||||
17278 | // function call operator [...]. This function call operator is | ||||||||
17279 | // declared const (9.3.1) if and only if the lambda-expression's | ||||||||
17280 | // parameter-declaration-clause is not followed by mutable. | ||||||||
17281 | DeclRefType = CaptureType.getNonReferenceType(); | ||||||||
17282 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | ||||||||
17283 | DeclRefType.addConst(); | ||||||||
17284 | } | ||||||||
17285 | |||||||||
17286 | // Add the capture. | ||||||||
17287 | if (BuildAndDiagnose) | ||||||||
17288 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | ||||||||
17289 | Loc, EllipsisLoc, CaptureType, Invalid); | ||||||||
17290 | |||||||||
17291 | return !Invalid; | ||||||||
17292 | } | ||||||||
17293 | |||||||||
17294 | bool Sema::tryCaptureVariable( | ||||||||
17295 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | ||||||||
17296 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | ||||||||
17297 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | ||||||||
17298 | // An init-capture is notionally from the context surrounding its | ||||||||
17299 | // declaration, but its parent DC is the lambda class. | ||||||||
17300 | DeclContext *VarDC = Var->getDeclContext(); | ||||||||
17301 | if (Var->isInitCapture()) | ||||||||
17302 | VarDC = VarDC->getParent(); | ||||||||
17303 | |||||||||
17304 | DeclContext *DC = CurContext; | ||||||||
17305 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | ||||||||
17306 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | ||||||||
17307 | // We need to sync up the Declaration Context with the | ||||||||
17308 | // FunctionScopeIndexToStopAt | ||||||||
17309 | if (FunctionScopeIndexToStopAt) { | ||||||||
17310 | unsigned FSIndex = FunctionScopes.size() - 1; | ||||||||
17311 | while (FSIndex != MaxFunctionScopesIndex) { | ||||||||
17312 | DC = getLambdaAwareParentOfDeclContext(DC); | ||||||||
17313 | --FSIndex; | ||||||||
17314 | } | ||||||||
17315 | } | ||||||||
17316 | |||||||||
17317 | |||||||||
17318 | // If the variable is declared in the current context, there is no need to | ||||||||
17319 | // capture it. | ||||||||
17320 | if (VarDC == DC) return true; | ||||||||
17321 | |||||||||
17322 | // Capture global variables if it is required to use private copy of this | ||||||||
17323 | // variable. | ||||||||
17324 | bool IsGlobal = !Var->hasLocalStorage(); | ||||||||
17325 | if (IsGlobal && | ||||||||
17326 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | ||||||||
17327 | MaxFunctionScopesIndex))) | ||||||||
17328 | return true; | ||||||||
17329 | Var = Var->getCanonicalDecl(); | ||||||||
17330 | |||||||||
17331 | // Walk up the stack to determine whether we can capture the variable, | ||||||||
17332 | // performing the "simple" checks that don't depend on type. We stop when | ||||||||
17333 | // we've either hit the declared scope of the variable or find an existing | ||||||||
17334 | // capture of that variable. We start from the innermost capturing-entity | ||||||||
17335 | // (the DC) and ensure that all intervening capturing-entities | ||||||||
17336 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | ||||||||
17337 | // declcontext can either capture the variable or have already captured | ||||||||
17338 | // the variable. | ||||||||
17339 | CaptureType = Var->getType(); | ||||||||
17340 | DeclRefType = CaptureType.getNonReferenceType(); | ||||||||
17341 | bool Nested = false; | ||||||||
17342 | bool Explicit = (Kind != TryCapture_Implicit); | ||||||||
17343 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | ||||||||
17344 | do { | ||||||||
17345 | // Only block literals, captured statements, and lambda expressions can | ||||||||
17346 | // capture; other scopes don't work. | ||||||||
17347 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | ||||||||
17348 | ExprLoc, | ||||||||
17349 | BuildAndDiagnose, | ||||||||
17350 | *this); | ||||||||
17351 | // We need to check for the parent *first* because, if we *have* | ||||||||
17352 | // private-captured a global variable, we need to recursively capture it in | ||||||||
17353 | // intermediate blocks, lambdas, etc. | ||||||||
17354 | if (!ParentDC) { | ||||||||
17355 | if (IsGlobal) { | ||||||||
17356 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | ||||||||
17357 | break; | ||||||||
17358 | } | ||||||||
17359 | return true; | ||||||||
17360 | } | ||||||||
17361 | |||||||||
17362 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | ||||||||
17363 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | ||||||||
17364 | |||||||||
17365 | |||||||||
17366 | // Check whether we've already captured it. | ||||||||
17367 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | ||||||||
17368 | DeclRefType)) { | ||||||||
17369 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | ||||||||
17370 | break; | ||||||||
17371 | } | ||||||||
17372 | // If we are instantiating a generic lambda call operator body, | ||||||||
17373 | // we do not want to capture new variables. What was captured | ||||||||
17374 | // during either a lambdas transformation or initial parsing | ||||||||
17375 | // should be used. | ||||||||
17376 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | ||||||||
17377 | if (BuildAndDiagnose) { | ||||||||
17378 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||||||
17379 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | ||||||||
17380 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||||||
17381 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17382 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||||||
17383 | } else | ||||||||
17384 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); | ||||||||
17385 | } | ||||||||
17386 | return true; | ||||||||
17387 | } | ||||||||
17388 | |||||||||
17389 | // Try to capture variable-length arrays types. | ||||||||
17390 | if (Var->getType()->isVariablyModifiedType()) { | ||||||||
17391 | // We're going to walk down into the type and look for VLA | ||||||||
17392 | // expressions. | ||||||||
17393 | QualType QTy = Var->getType(); | ||||||||
17394 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||||||
17395 | QTy = PVD->getOriginalType(); | ||||||||
17396 | captureVariablyModifiedType(Context, QTy, CSI); | ||||||||
17397 | } | ||||||||
17398 | |||||||||
17399 | if (getLangOpts().OpenMP) { | ||||||||
17400 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||||||
17401 | // OpenMP private variables should not be captured in outer scope, so | ||||||||
17402 | // just break here. Similarly, global variables that are captured in a | ||||||||
17403 | // target region should not be captured outside the scope of the region. | ||||||||
17404 | if (RSI->CapRegionKind == CR_OpenMP) { | ||||||||
17405 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | ||||||||
17406 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | ||||||||
17407 | // If the variable is private (i.e. not captured) and has variably | ||||||||
17408 | // modified type, we still need to capture the type for correct | ||||||||
17409 | // codegen in all regions, associated with the construct. Currently, | ||||||||
17410 | // it is captured in the innermost captured region only. | ||||||||
17411 | if (IsOpenMPPrivateDecl != OMPC_unknown && | ||||||||
17412 | Var->getType()->isVariablyModifiedType()) { | ||||||||
17413 | QualType QTy = Var->getType(); | ||||||||
17414 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||||||
17415 | QTy = PVD->getOriginalType(); | ||||||||
17416 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | ||||||||
17417 | I < E; ++I) { | ||||||||
17418 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | ||||||||
17419 | FunctionScopes[FunctionScopesIndex - I]); | ||||||||
17420 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17422, __PRETTY_FUNCTION__)) | ||||||||
17421 | "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17422, __PRETTY_FUNCTION__)) | ||||||||
17422 | "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17422, __PRETTY_FUNCTION__)); | ||||||||
17423 | captureVariablyModifiedType(Context, QTy, OuterRSI); | ||||||||
17424 | } | ||||||||
17425 | } | ||||||||
17426 | bool IsTargetCap = | ||||||||
17427 | IsOpenMPPrivateDecl != OMPC_private && | ||||||||
17428 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | ||||||||
17429 | RSI->OpenMPCaptureLevel); | ||||||||
17430 | // Do not capture global if it is not privatized in outer regions. | ||||||||
17431 | bool IsGlobalCap = | ||||||||
17432 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | ||||||||
17433 | RSI->OpenMPCaptureLevel); | ||||||||
17434 | |||||||||
17435 | // When we detect target captures we are looking from inside the | ||||||||
17436 | // target region, therefore we need to propagate the capture from the | ||||||||
17437 | // enclosing region. Therefore, the capture is not initially nested. | ||||||||
17438 | if (IsTargetCap) | ||||||||
17439 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | ||||||||
17440 | |||||||||
17441 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | ||||||||
17442 | (IsGlobal && !IsGlobalCap)) { | ||||||||
17443 | Nested = !IsTargetCap; | ||||||||
17444 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||||||
17445 | CaptureType = Context.getLValueReferenceType(DeclRefType); | ||||||||
17446 | break; | ||||||||
17447 | } | ||||||||
17448 | } | ||||||||
17449 | } | ||||||||
17450 | } | ||||||||
17451 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | ||||||||
17452 | // No capture-default, and this is not an explicit capture | ||||||||
17453 | // so cannot capture this variable. | ||||||||
17454 | if (BuildAndDiagnose) { | ||||||||
17455 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||||||
17456 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||||||
17457 | if (cast<LambdaScopeInfo>(CSI)->Lambda) | ||||||||
17458 | Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), | ||||||||
17459 | diag::note_lambda_decl); | ||||||||
17460 | // FIXME: If we error out because an outer lambda can not implicitly | ||||||||
17461 | // capture a variable that an inner lambda explicitly captures, we | ||||||||
17462 | // should have the inner lambda do the explicit capture - because | ||||||||
17463 | // it makes for cleaner diagnostics later. This would purely be done | ||||||||
17464 | // so that the diagnostic does not misleadingly claim that a variable | ||||||||
17465 | // can not be captured by a lambda implicitly even though it is captured | ||||||||
17466 | // explicitly. Suggestion: | ||||||||
17467 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | ||||||||
17468 | // at the function head | ||||||||
17469 | // - cache the StartingDeclContext - this must be a lambda | ||||||||
17470 | // - captureInLambda in the innermost lambda the variable. | ||||||||
17471 | } | ||||||||
17472 | return true; | ||||||||
17473 | } | ||||||||
17474 | |||||||||
17475 | FunctionScopesIndex--; | ||||||||
17476 | DC = ParentDC; | ||||||||
17477 | Explicit = false; | ||||||||
17478 | } while (!VarDC->Equals(DC)); | ||||||||
17479 | |||||||||
17480 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | ||||||||
17481 | // computing the type of the capture at each step, checking type-specific | ||||||||
17482 | // requirements, and adding captures if requested. | ||||||||
17483 | // If the variable had already been captured previously, we start capturing | ||||||||
17484 | // at the lambda nested within that one. | ||||||||
17485 | bool Invalid = false; | ||||||||
17486 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | ||||||||
17487 | ++I) { | ||||||||
17488 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | ||||||||
17489 | |||||||||
17490 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||||||
17491 | // certain types of variables (unnamed, variably modified types etc.) | ||||||||
17492 | // so check for eligibility. | ||||||||
17493 | if (!Invalid) | ||||||||
17494 | Invalid = | ||||||||
17495 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | ||||||||
17496 | |||||||||
17497 | // After encountering an error, if we're actually supposed to capture, keep | ||||||||
17498 | // capturing in nested contexts to suppress any follow-on diagnostics. | ||||||||
17499 | if (Invalid && !BuildAndDiagnose) | ||||||||
17500 | return true; | ||||||||
17501 | |||||||||
17502 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | ||||||||
17503 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||||||
17504 | DeclRefType, Nested, *this, Invalid); | ||||||||
17505 | Nested = true; | ||||||||
17506 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||||||
17507 | Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, | ||||||||
17508 | CaptureType, DeclRefType, Nested, | ||||||||
17509 | *this, Invalid); | ||||||||
17510 | Nested = true; | ||||||||
17511 | } else { | ||||||||
17512 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||||||
17513 | Invalid = | ||||||||
17514 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||||||
17515 | DeclRefType, Nested, Kind, EllipsisLoc, | ||||||||
17516 | /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||||||
17517 | Nested = true; | ||||||||
17518 | } | ||||||||
17519 | |||||||||
17520 | if (Invalid && !BuildAndDiagnose) | ||||||||
17521 | return true; | ||||||||
17522 | } | ||||||||
17523 | return Invalid; | ||||||||
17524 | } | ||||||||
17525 | |||||||||
17526 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | ||||||||
17527 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | ||||||||
17528 | QualType CaptureType; | ||||||||
17529 | QualType DeclRefType; | ||||||||
17530 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | ||||||||
17531 | /*BuildAndDiagnose=*/true, CaptureType, | ||||||||
17532 | DeclRefType, nullptr); | ||||||||
17533 | } | ||||||||
17534 | |||||||||
17535 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | ||||||||
17536 | QualType CaptureType; | ||||||||
17537 | QualType DeclRefType; | ||||||||
17538 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||||||
17539 | /*BuildAndDiagnose=*/false, CaptureType, | ||||||||
17540 | DeclRefType, nullptr); | ||||||||
17541 | } | ||||||||
17542 | |||||||||
17543 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | ||||||||
17544 | QualType CaptureType; | ||||||||
17545 | QualType DeclRefType; | ||||||||
17546 | |||||||||
17547 | // Determine whether we can capture this variable. | ||||||||
17548 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||||||
17549 | /*BuildAndDiagnose=*/false, CaptureType, | ||||||||
17550 | DeclRefType, nullptr)) | ||||||||
17551 | return QualType(); | ||||||||
17552 | |||||||||
17553 | return DeclRefType; | ||||||||
17554 | } | ||||||||
17555 | |||||||||
17556 | namespace { | ||||||||
17557 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | ||||||||
17558 | // The produced TemplateArgumentListInfo* points to data stored within this | ||||||||
17559 | // object, so should only be used in contexts where the pointer will not be | ||||||||
17560 | // used after the CopiedTemplateArgs object is destroyed. | ||||||||
17561 | class CopiedTemplateArgs { | ||||||||
17562 | bool HasArgs; | ||||||||
17563 | TemplateArgumentListInfo TemplateArgStorage; | ||||||||
17564 | public: | ||||||||
17565 | template<typename RefExpr> | ||||||||
17566 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | ||||||||
17567 | if (HasArgs) | ||||||||
17568 | E->copyTemplateArgumentsInto(TemplateArgStorage); | ||||||||
17569 | } | ||||||||
17570 | operator TemplateArgumentListInfo*() | ||||||||
17571 | #ifdef __has_cpp_attribute | ||||||||
17572 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | ||||||||
17573 | [[clang::lifetimebound]] | ||||||||
17574 | #endif | ||||||||
17575 | #endif | ||||||||
17576 | { | ||||||||
17577 | return HasArgs ? &TemplateArgStorage : nullptr; | ||||||||
17578 | } | ||||||||
17579 | }; | ||||||||
17580 | } | ||||||||
17581 | |||||||||
17582 | /// Walk the set of potential results of an expression and mark them all as | ||||||||
17583 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | ||||||||
17584 | /// | ||||||||
17585 | /// \return A new expression if we found any potential results, ExprEmpty() if | ||||||||
17586 | /// not, and ExprError() if we diagnosed an error. | ||||||||
17587 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | ||||||||
17588 | NonOdrUseReason NOUR) { | ||||||||
17589 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | ||||||||
17590 | // an object that satisfies the requirements for appearing in a | ||||||||
17591 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | ||||||||
17592 | // is immediately applied." This function handles the lvalue-to-rvalue | ||||||||
17593 | // conversion part. | ||||||||
17594 | // | ||||||||
17595 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | ||||||||
17596 | // transform it into the relevant kind of non-odr-use node and rebuild the | ||||||||
17597 | // tree of nodes leading to it. | ||||||||
17598 | // | ||||||||
17599 | // This is a mini-TreeTransform that only transforms a restricted subset of | ||||||||
17600 | // nodes (and only certain operands of them). | ||||||||
17601 | |||||||||
17602 | // Rebuild a subexpression. | ||||||||
17603 | auto Rebuild = [&](Expr *Sub) { | ||||||||
17604 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | ||||||||
17605 | }; | ||||||||
17606 | |||||||||
17607 | // Check whether a potential result satisfies the requirements of NOUR. | ||||||||
17608 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | ||||||||
17609 | // Any entity other than a VarDecl is always odr-used whenever it's named | ||||||||
17610 | // in a potentially-evaluated expression. | ||||||||
17611 | auto *VD = dyn_cast<VarDecl>(D); | ||||||||
17612 | if (!VD) | ||||||||
17613 | return true; | ||||||||
17614 | |||||||||
17615 | // C++2a [basic.def.odr]p4: | ||||||||
17616 | // A variable x whose name appears as a potentially-evalauted expression | ||||||||
17617 | // e is odr-used by e unless | ||||||||
17618 | // -- x is a reference that is usable in constant expressions, or | ||||||||
17619 | // -- x is a variable of non-reference type that is usable in constant | ||||||||
17620 | // expressions and has no mutable subobjects, and e is an element of | ||||||||
17621 | // the set of potential results of an expression of | ||||||||
17622 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||||||
17623 | // conversion is applied, or | ||||||||
17624 | // -- x is a variable of non-reference type, and e is an element of the | ||||||||
17625 | // set of potential results of a discarded-value expression to which | ||||||||
17626 | // the lvalue-to-rvalue conversion is not applied | ||||||||
17627 | // | ||||||||
17628 | // We check the first bullet and the "potentially-evaluated" condition in | ||||||||
17629 | // BuildDeclRefExpr. We check the type requirements in the second bullet | ||||||||
17630 | // in CheckLValueToRValueConversionOperand below. | ||||||||
17631 | switch (NOUR) { | ||||||||
17632 | case NOUR_None: | ||||||||
17633 | case NOUR_Unevaluated: | ||||||||
17634 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17634); | ||||||||
17635 | |||||||||
17636 | case NOUR_Constant: | ||||||||
17637 | // Constant references were handled when they were built. | ||||||||
17638 | if (VD->getType()->isReferenceType()) | ||||||||
17639 | return true; | ||||||||
17640 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | ||||||||
17641 | if (RD->hasMutableFields()) | ||||||||
17642 | return true; | ||||||||
17643 | if (!VD->isUsableInConstantExpressions(S.Context)) | ||||||||
17644 | return true; | ||||||||
17645 | break; | ||||||||
17646 | |||||||||
17647 | case NOUR_Discarded: | ||||||||
17648 | if (VD->getType()->isReferenceType()) | ||||||||
17649 | return true; | ||||||||
17650 | break; | ||||||||
17651 | } | ||||||||
17652 | return false; | ||||||||
17653 | }; | ||||||||
17654 | |||||||||
17655 | // Mark that this expression does not constitute an odr-use. | ||||||||
17656 | auto MarkNotOdrUsed = [&] { | ||||||||
17657 | S.MaybeODRUseExprs.remove(E); | ||||||||
17658 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | ||||||||
17659 | LSI->markVariableExprAsNonODRUsed(E); | ||||||||
17660 | }; | ||||||||
17661 | |||||||||
17662 | // C++2a [basic.def.odr]p2: | ||||||||
17663 | // The set of potential results of an expression e is defined as follows: | ||||||||
17664 | switch (E->getStmtClass()) { | ||||||||
17665 | // -- If e is an id-expression, ... | ||||||||
17666 | case Expr::DeclRefExprClass: { | ||||||||
17667 | auto *DRE = cast<DeclRefExpr>(E); | ||||||||
17668 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | ||||||||
17669 | break; | ||||||||
17670 | |||||||||
17671 | // Rebuild as a non-odr-use DeclRefExpr. | ||||||||
17672 | MarkNotOdrUsed(); | ||||||||
17673 | return DeclRefExpr::Create( | ||||||||
17674 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | ||||||||
17675 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | ||||||||
17676 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | ||||||||
17677 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | ||||||||
17678 | } | ||||||||
17679 | |||||||||
17680 | case Expr::FunctionParmPackExprClass: { | ||||||||
17681 | auto *FPPE = cast<FunctionParmPackExpr>(E); | ||||||||
17682 | // If any of the declarations in the pack is odr-used, then the expression | ||||||||
17683 | // as a whole constitutes an odr-use. | ||||||||
17684 | for (VarDecl *D : *FPPE) | ||||||||
17685 | if (IsPotentialResultOdrUsed(D)) | ||||||||
17686 | return ExprEmpty(); | ||||||||
17687 | |||||||||
17688 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | ||||||||
17689 | // nothing cares about whether we marked this as an odr-use, but it might | ||||||||
17690 | // be useful for non-compiler tools. | ||||||||
17691 | MarkNotOdrUsed(); | ||||||||
17692 | break; | ||||||||
17693 | } | ||||||||
17694 | |||||||||
17695 | // -- If e is a subscripting operation with an array operand... | ||||||||
17696 | case Expr::ArraySubscriptExprClass: { | ||||||||
17697 | auto *ASE = cast<ArraySubscriptExpr>(E); | ||||||||
17698 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | ||||||||
17699 | if (!OldBase->getType()->isArrayType()) | ||||||||
17700 | break; | ||||||||
17701 | ExprResult Base = Rebuild(OldBase); | ||||||||
17702 | if (!Base.isUsable()) | ||||||||
17703 | return Base; | ||||||||
17704 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | ||||||||
17705 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | ||||||||
17706 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | ||||||||
17707 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | ||||||||
17708 | ASE->getRBracketLoc()); | ||||||||
17709 | } | ||||||||
17710 | |||||||||
17711 | case Expr::MemberExprClass: { | ||||||||
17712 | auto *ME = cast<MemberExpr>(E); | ||||||||
17713 | // -- If e is a class member access expression [...] naming a non-static | ||||||||
17714 | // data member... | ||||||||
17715 | if (isa<FieldDecl>(ME->getMemberDecl())) { | ||||||||
17716 | ExprResult Base = Rebuild(ME->getBase()); | ||||||||
17717 | if (!Base.isUsable()) | ||||||||
17718 | return Base; | ||||||||
17719 | return MemberExpr::Create( | ||||||||
17720 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | ||||||||
17721 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | ||||||||
17722 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | ||||||||
17723 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | ||||||||
17724 | ME->getObjectKind(), ME->isNonOdrUse()); | ||||||||
17725 | } | ||||||||
17726 | |||||||||
17727 | if (ME->getMemberDecl()->isCXXInstanceMember()) | ||||||||
17728 | break; | ||||||||
17729 | |||||||||
17730 | // -- If e is a class member access expression naming a static data member, | ||||||||
17731 | // ... | ||||||||
17732 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | ||||||||
17733 | break; | ||||||||
17734 | |||||||||
17735 | // Rebuild as a non-odr-use MemberExpr. | ||||||||
17736 | MarkNotOdrUsed(); | ||||||||
17737 | return MemberExpr::Create( | ||||||||
17738 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | ||||||||
17739 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | ||||||||
17740 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | ||||||||
17741 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | ||||||||
17742 | return ExprEmpty(); | ||||||||
17743 | } | ||||||||
17744 | |||||||||
17745 | case Expr::BinaryOperatorClass: { | ||||||||
17746 | auto *BO = cast<BinaryOperator>(E); | ||||||||
17747 | Expr *LHS = BO->getLHS(); | ||||||||
17748 | Expr *RHS = BO->getRHS(); | ||||||||
17749 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | ||||||||
17750 | if (BO->getOpcode() == BO_PtrMemD) { | ||||||||
17751 | ExprResult Sub = Rebuild(LHS); | ||||||||
17752 | if (!Sub.isUsable()) | ||||||||
17753 | return Sub; | ||||||||
17754 | LHS = Sub.get(); | ||||||||
17755 | // -- If e is a comma expression, ... | ||||||||
17756 | } else if (BO->getOpcode() == BO_Comma) { | ||||||||
17757 | ExprResult Sub = Rebuild(RHS); | ||||||||
17758 | if (!Sub.isUsable()) | ||||||||
17759 | return Sub; | ||||||||
17760 | RHS = Sub.get(); | ||||||||
17761 | } else { | ||||||||
17762 | break; | ||||||||
17763 | } | ||||||||
17764 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | ||||||||
17765 | LHS, RHS); | ||||||||
17766 | } | ||||||||
17767 | |||||||||
17768 | // -- If e has the form (e1)... | ||||||||
17769 | case Expr::ParenExprClass: { | ||||||||
17770 | auto *PE = cast<ParenExpr>(E); | ||||||||
17771 | ExprResult Sub = Rebuild(PE->getSubExpr()); | ||||||||
17772 | if (!Sub.isUsable()) | ||||||||
17773 | return Sub; | ||||||||
17774 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | ||||||||
17775 | } | ||||||||
17776 | |||||||||
17777 | // -- If e is a glvalue conditional expression, ... | ||||||||
17778 | // We don't apply this to a binary conditional operator. FIXME: Should we? | ||||||||
17779 | case Expr::ConditionalOperatorClass: { | ||||||||
17780 | auto *CO = cast<ConditionalOperator>(E); | ||||||||
17781 | ExprResult LHS = Rebuild(CO->getLHS()); | ||||||||
17782 | if (LHS.isInvalid()) | ||||||||
17783 | return ExprError(); | ||||||||
17784 | ExprResult RHS = Rebuild(CO->getRHS()); | ||||||||
17785 | if (RHS.isInvalid()) | ||||||||
17786 | return ExprError(); | ||||||||
17787 | if (!LHS.isUsable() && !RHS.isUsable()) | ||||||||
17788 | return ExprEmpty(); | ||||||||
17789 | if (!LHS.isUsable()) | ||||||||
17790 | LHS = CO->getLHS(); | ||||||||
17791 | if (!RHS.isUsable()) | ||||||||
17792 | RHS = CO->getRHS(); | ||||||||
17793 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | ||||||||
17794 | CO->getCond(), LHS.get(), RHS.get()); | ||||||||
17795 | } | ||||||||
17796 | |||||||||
17797 | // [Clang extension] | ||||||||
17798 | // -- If e has the form __extension__ e1... | ||||||||
17799 | case Expr::UnaryOperatorClass: { | ||||||||
17800 | auto *UO = cast<UnaryOperator>(E); | ||||||||
17801 | if (UO->getOpcode() != UO_Extension) | ||||||||
17802 | break; | ||||||||
17803 | ExprResult Sub = Rebuild(UO->getSubExpr()); | ||||||||
17804 | if (!Sub.isUsable()) | ||||||||
17805 | return Sub; | ||||||||
17806 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | ||||||||
17807 | Sub.get()); | ||||||||
17808 | } | ||||||||
17809 | |||||||||
17810 | // [Clang extension] | ||||||||
17811 | // -- If e has the form _Generic(...), the set of potential results is the | ||||||||
17812 | // union of the sets of potential results of the associated expressions. | ||||||||
17813 | case Expr::GenericSelectionExprClass: { | ||||||||
17814 | auto *GSE = cast<GenericSelectionExpr>(E); | ||||||||
17815 | |||||||||
17816 | SmallVector<Expr *, 4> AssocExprs; | ||||||||
17817 | bool AnyChanged = false; | ||||||||
17818 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | ||||||||
17819 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | ||||||||
17820 | if (AssocExpr.isInvalid()) | ||||||||
17821 | return ExprError(); | ||||||||
17822 | if (AssocExpr.isUsable()) { | ||||||||
17823 | AssocExprs.push_back(AssocExpr.get()); | ||||||||
17824 | AnyChanged = true; | ||||||||
17825 | } else { | ||||||||
17826 | AssocExprs.push_back(OrigAssocExpr); | ||||||||
17827 | } | ||||||||
17828 | } | ||||||||
17829 | |||||||||
17830 | return AnyChanged ? S.CreateGenericSelectionExpr( | ||||||||
17831 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | ||||||||
17832 | GSE->getRParenLoc(), GSE->getControllingExpr(), | ||||||||
17833 | GSE->getAssocTypeSourceInfos(), AssocExprs) | ||||||||
17834 | : ExprEmpty(); | ||||||||
17835 | } | ||||||||
17836 | |||||||||
17837 | // [Clang extension] | ||||||||
17838 | // -- If e has the form __builtin_choose_expr(...), the set of potential | ||||||||
17839 | // results is the union of the sets of potential results of the | ||||||||
17840 | // second and third subexpressions. | ||||||||
17841 | case Expr::ChooseExprClass: { | ||||||||
17842 | auto *CE = cast<ChooseExpr>(E); | ||||||||
17843 | |||||||||
17844 | ExprResult LHS = Rebuild(CE->getLHS()); | ||||||||
17845 | if (LHS.isInvalid()) | ||||||||
17846 | return ExprError(); | ||||||||
17847 | |||||||||
17848 | ExprResult RHS = Rebuild(CE->getLHS()); | ||||||||
17849 | if (RHS.isInvalid()) | ||||||||
17850 | return ExprError(); | ||||||||
17851 | |||||||||
17852 | if (!LHS.get() && !RHS.get()) | ||||||||
17853 | return ExprEmpty(); | ||||||||
17854 | if (!LHS.isUsable()) | ||||||||
17855 | LHS = CE->getLHS(); | ||||||||
17856 | if (!RHS.isUsable()) | ||||||||
17857 | RHS = CE->getRHS(); | ||||||||
17858 | |||||||||
17859 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | ||||||||
17860 | RHS.get(), CE->getRParenLoc()); | ||||||||
17861 | } | ||||||||
17862 | |||||||||
17863 | // Step through non-syntactic nodes. | ||||||||
17864 | case Expr::ConstantExprClass: { | ||||||||
17865 | auto *CE = cast<ConstantExpr>(E); | ||||||||
17866 | ExprResult Sub = Rebuild(CE->getSubExpr()); | ||||||||
17867 | if (!Sub.isUsable()) | ||||||||
17868 | return Sub; | ||||||||
17869 | return ConstantExpr::Create(S.Context, Sub.get()); | ||||||||
17870 | } | ||||||||
17871 | |||||||||
17872 | // We could mostly rely on the recursive rebuilding to rebuild implicit | ||||||||
17873 | // casts, but not at the top level, so rebuild them here. | ||||||||
17874 | case Expr::ImplicitCastExprClass: { | ||||||||
17875 | auto *ICE = cast<ImplicitCastExpr>(E); | ||||||||
17876 | // Only step through the narrow set of cast kinds we expect to encounter. | ||||||||
17877 | // Anything else suggests we've left the region in which potential results | ||||||||
17878 | // can be found. | ||||||||
17879 | switch (ICE->getCastKind()) { | ||||||||
17880 | case CK_NoOp: | ||||||||
17881 | case CK_DerivedToBase: | ||||||||
17882 | case CK_UncheckedDerivedToBase: { | ||||||||
17883 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | ||||||||
17884 | if (!Sub.isUsable()) | ||||||||
17885 | return Sub; | ||||||||
17886 | CXXCastPath Path(ICE->path()); | ||||||||
17887 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | ||||||||
17888 | ICE->getValueKind(), &Path); | ||||||||
17889 | } | ||||||||
17890 | |||||||||
17891 | default: | ||||||||
17892 | break; | ||||||||
17893 | } | ||||||||
17894 | break; | ||||||||
17895 | } | ||||||||
17896 | |||||||||
17897 | default: | ||||||||
17898 | break; | ||||||||
17899 | } | ||||||||
17900 | |||||||||
17901 | // Can't traverse through this node. Nothing to do. | ||||||||
17902 | return ExprEmpty(); | ||||||||
17903 | } | ||||||||
17904 | |||||||||
17905 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | ||||||||
17906 | // Check whether the operand is or contains an object of non-trivial C union | ||||||||
17907 | // type. | ||||||||
17908 | if (E->getType().isVolatileQualified() && | ||||||||
17909 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||||
17910 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | ||||||||
17911 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||||||
17912 | Sema::NTCUC_LValueToRValueVolatile, | ||||||||
17913 | NTCUK_Destruct|NTCUK_Copy); | ||||||||
17914 | |||||||||
17915 | // C++2a [basic.def.odr]p4: | ||||||||
17916 | // [...] an expression of non-volatile-qualified non-class type to which | ||||||||
17917 | // the lvalue-to-rvalue conversion is applied [...] | ||||||||
17918 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | ||||||||
17919 | return E; | ||||||||
17920 | |||||||||
17921 | ExprResult Result = | ||||||||
17922 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | ||||||||
17923 | if (Result.isInvalid()) | ||||||||
17924 | return ExprError(); | ||||||||
17925 | return Result.get() ? Result : E; | ||||||||
17926 | } | ||||||||
17927 | |||||||||
17928 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | ||||||||
17929 | Res = CorrectDelayedTyposInExpr(Res); | ||||||||
17930 | |||||||||
17931 | if (!Res.isUsable()) | ||||||||
17932 | return Res; | ||||||||
17933 | |||||||||
17934 | // If a constant-expression is a reference to a variable where we delay | ||||||||
17935 | // deciding whether it is an odr-use, just assume we will apply the | ||||||||
17936 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | ||||||||
17937 | // (a non-type template argument), we have special handling anyway. | ||||||||
17938 | return CheckLValueToRValueConversionOperand(Res.get()); | ||||||||
17939 | } | ||||||||
17940 | |||||||||
17941 | void Sema::CleanupVarDeclMarking() { | ||||||||
17942 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | ||||||||
17943 | // call. | ||||||||
17944 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | ||||||||
17945 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | ||||||||
17946 | |||||||||
17947 | for (Expr *E : LocalMaybeODRUseExprs) { | ||||||||
17948 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||||||
17949 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | ||||||||
17950 | DRE->getLocation(), *this); | ||||||||
17951 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||||||
17952 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | ||||||||
17953 | *this); | ||||||||
17954 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | ||||||||
17955 | for (VarDecl *VD : *FP) | ||||||||
17956 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | ||||||||
17957 | } else { | ||||||||
17958 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17958); | ||||||||
17959 | } | ||||||||
17960 | } | ||||||||
17961 | |||||||||
17962 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17963, __PRETTY_FUNCTION__)) | ||||||||
17963 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17963, __PRETTY_FUNCTION__)); | ||||||||
17964 | } | ||||||||
17965 | |||||||||
17966 | static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, | ||||||||
17967 | VarDecl *Var, Expr *E) { | ||||||||
17968 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17970, __PRETTY_FUNCTION__)) | ||||||||
17969 | isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17970, __PRETTY_FUNCTION__)) | ||||||||
17970 | "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 17970, __PRETTY_FUNCTION__)); | ||||||||
17971 | Var->setReferenced(); | ||||||||
17972 | |||||||||
17973 | if (Var->isInvalidDecl()) | ||||||||
17974 | return; | ||||||||
17975 | |||||||||
17976 | // Record a CUDA/HIP static device/constant variable if it is referenced | ||||||||
17977 | // by host code. This is done conservatively, when the variable is referenced | ||||||||
17978 | // in any of the following contexts: | ||||||||
17979 | // - a non-function context | ||||||||
17980 | // - a host function | ||||||||
17981 | // - a host device function | ||||||||
17982 | // This also requires the reference of the static device/constant variable by | ||||||||
17983 | // host code to be visible in the device compilation for the compiler to be | ||||||||
17984 | // able to externalize the static device/constant variable. | ||||||||
17985 | if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { | ||||||||
17986 | auto *CurContext = SemaRef.CurContext; | ||||||||
17987 | if (!CurContext || !isa<FunctionDecl>(CurContext) || | ||||||||
17988 | cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || | ||||||||
17989 | (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && | ||||||||
17990 | !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) | ||||||||
17991 | SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); | ||||||||
17992 | } | ||||||||
17993 | |||||||||
17994 | auto *MSI = Var->getMemberSpecializationInfo(); | ||||||||
17995 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | ||||||||
17996 | : Var->getTemplateSpecializationKind(); | ||||||||
17997 | |||||||||
17998 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||||||
17999 | bool UsableInConstantExpr = | ||||||||
18000 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | ||||||||
18001 | |||||||||
18002 | // C++20 [expr.const]p12: | ||||||||
18003 | // A variable [...] is needed for constant evaluation if it is [...] a | ||||||||
18004 | // variable whose name appears as a potentially constant evaluated | ||||||||
18005 | // expression that is either a contexpr variable or is of non-volatile | ||||||||
18006 | // const-qualified integral type or of reference type | ||||||||
18007 | bool NeededForConstantEvaluation = | ||||||||
18008 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | ||||||||
18009 | |||||||||
18010 | bool NeedDefinition = | ||||||||
18011 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | ||||||||
18012 | |||||||||
18013 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18014, __PRETTY_FUNCTION__)) | ||||||||
18014 | "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18014, __PRETTY_FUNCTION__)); | ||||||||
18015 | |||||||||
18016 | // If this might be a member specialization of a static data member, check | ||||||||
18017 | // the specialization is visible. We already did the checks for variable | ||||||||
18018 | // template specializations when we created them. | ||||||||
18019 | if (NeedDefinition && TSK != TSK_Undeclared && | ||||||||
18020 | !isa<VarTemplateSpecializationDecl>(Var)) | ||||||||
18021 | SemaRef.checkSpecializationVisibility(Loc, Var); | ||||||||
18022 | |||||||||
18023 | // Perform implicit instantiation of static data members, static data member | ||||||||
18024 | // templates of class templates, and variable template specializations. Delay | ||||||||
18025 | // instantiations of variable templates, except for those that could be used | ||||||||
18026 | // in a constant expression. | ||||||||
18027 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | ||||||||
18028 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | ||||||||
18029 | // instantiation declaration if a variable is usable in a constant | ||||||||
18030 | // expression (among other cases). | ||||||||
18031 | bool TryInstantiating = | ||||||||
18032 | TSK == TSK_ImplicitInstantiation || | ||||||||
18033 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | ||||||||
18034 | |||||||||
18035 | if (TryInstantiating) { | ||||||||
18036 | SourceLocation PointOfInstantiation = | ||||||||
18037 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | ||||||||
18038 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||||||
18039 | if (FirstInstantiation) { | ||||||||
18040 | PointOfInstantiation = Loc; | ||||||||
18041 | if (MSI) | ||||||||
18042 | MSI->setPointOfInstantiation(PointOfInstantiation); | ||||||||
18043 | else | ||||||||
18044 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||||||
18045 | } | ||||||||
18046 | |||||||||
18047 | if (UsableInConstantExpr) { | ||||||||
18048 | // Do not defer instantiations of variables that could be used in a | ||||||||
18049 | // constant expression. | ||||||||
18050 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||||||
18051 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||||||
18052 | }); | ||||||||
18053 | } else if (FirstInstantiation || | ||||||||
18054 | isa<VarTemplateSpecializationDecl>(Var)) { | ||||||||
18055 | // FIXME: For a specialization of a variable template, we don't | ||||||||
18056 | // distinguish between "declaration and type implicitly instantiated" | ||||||||
18057 | // and "implicit instantiation of definition requested", so we have | ||||||||
18058 | // no direct way to avoid enqueueing the pending instantiation | ||||||||
18059 | // multiple times. | ||||||||
18060 | SemaRef.PendingInstantiations | ||||||||
18061 | .push_back(std::make_pair(Var, PointOfInstantiation)); | ||||||||
18062 | } | ||||||||
18063 | } | ||||||||
18064 | } | ||||||||
18065 | |||||||||
18066 | // C++2a [basic.def.odr]p4: | ||||||||
18067 | // A variable x whose name appears as a potentially-evaluated expression e | ||||||||
18068 | // is odr-used by e unless | ||||||||
18069 | // -- x is a reference that is usable in constant expressions | ||||||||
18070 | // -- x is a variable of non-reference type that is usable in constant | ||||||||
18071 | // expressions and has no mutable subobjects [FIXME], and e is an | ||||||||
18072 | // element of the set of potential results of an expression of | ||||||||
18073 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||||||
18074 | // conversion is applied | ||||||||
18075 | // -- x is a variable of non-reference type, and e is an element of the set | ||||||||
18076 | // of potential results of a discarded-value expression to which the | ||||||||
18077 | // lvalue-to-rvalue conversion is not applied [FIXME] | ||||||||
18078 | // | ||||||||
18079 | // We check the first part of the second bullet here, and | ||||||||
18080 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | ||||||||
18081 | // FIXME: To get the third bullet right, we need to delay this even for | ||||||||
18082 | // variables that are not usable in constant expressions. | ||||||||
18083 | |||||||||
18084 | // If we already know this isn't an odr-use, there's nothing more to do. | ||||||||
18085 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||||||
18086 | if (DRE->isNonOdrUse()) | ||||||||
18087 | return; | ||||||||
18088 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||||||
18089 | if (ME->isNonOdrUse()) | ||||||||
18090 | return; | ||||||||
18091 | |||||||||
18092 | switch (OdrUse) { | ||||||||
18093 | case OdrUseContext::None: | ||||||||
18094 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18095, __PRETTY_FUNCTION__)) | ||||||||
18095 | "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18095, __PRETTY_FUNCTION__)); | ||||||||
18096 | break; | ||||||||
18097 | |||||||||
18098 | case OdrUseContext::FormallyOdrUsed: | ||||||||
18099 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | ||||||||
18100 | // behavior. | ||||||||
18101 | break; | ||||||||
18102 | |||||||||
18103 | case OdrUseContext::Used: | ||||||||
18104 | // If we might later find that this expression isn't actually an odr-use, | ||||||||
18105 | // delay the marking. | ||||||||
18106 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||||||
18107 | SemaRef.MaybeODRUseExprs.insert(E); | ||||||||
18108 | else | ||||||||
18109 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | ||||||||
18110 | break; | ||||||||
18111 | |||||||||
18112 | case OdrUseContext::Dependent: | ||||||||
18113 | // If this is a dependent context, we don't need to mark variables as | ||||||||
18114 | // odr-used, but we may still need to track them for lambda capture. | ||||||||
18115 | // FIXME: Do we also need to do this inside dependent typeid expressions | ||||||||
18116 | // (which are modeled as unevaluated at this point)? | ||||||||
18117 | const bool RefersToEnclosingScope = | ||||||||
18118 | (SemaRef.CurContext != Var->getDeclContext() && | ||||||||
18119 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | ||||||||
18120 | if (RefersToEnclosingScope) { | ||||||||
18121 | LambdaScopeInfo *const LSI = | ||||||||
18122 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | ||||||||
18123 | if (LSI && (!LSI->CallOperator || | ||||||||
18124 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | ||||||||
18125 | // If a variable could potentially be odr-used, defer marking it so | ||||||||
18126 | // until we finish analyzing the full expression for any | ||||||||
18127 | // lvalue-to-rvalue | ||||||||
18128 | // or discarded value conversions that would obviate odr-use. | ||||||||
18129 | // Add it to the list of potential captures that will be analyzed | ||||||||
18130 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | ||||||||
18131 | // unless the variable is a reference that was initialized by a constant | ||||||||
18132 | // expression (this will never need to be captured or odr-used). | ||||||||
18133 | // | ||||||||
18134 | // FIXME: We can simplify this a lot after implementing P0588R1. | ||||||||
18135 | assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression." ) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18135, __PRETTY_FUNCTION__)); | ||||||||
18136 | if (!Var->getType()->isReferenceType() || | ||||||||
18137 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||||||
18138 | LSI->addPotentialCapture(E->IgnoreParens()); | ||||||||
18139 | } | ||||||||
18140 | } | ||||||||
18141 | break; | ||||||||
18142 | } | ||||||||
18143 | } | ||||||||
18144 | |||||||||
18145 | /// Mark a variable referenced, and check whether it is odr-used | ||||||||
18146 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | ||||||||
18147 | /// used directly for normal expressions referring to VarDecl. | ||||||||
18148 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | ||||||||
18149 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); | ||||||||
18150 | } | ||||||||
18151 | |||||||||
18152 | static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, | ||||||||
18153 | Decl *D, Expr *E, bool MightBeOdrUse) { | ||||||||
18154 | if (SemaRef.isInOpenMPDeclareTargetContext()) | ||||||||
18155 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | ||||||||
18156 | |||||||||
18157 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | ||||||||
18158 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); | ||||||||
18159 | return; | ||||||||
18160 | } | ||||||||
18161 | |||||||||
18162 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | ||||||||
18163 | |||||||||
18164 | // If this is a call to a method via a cast, also mark the method in the | ||||||||
18165 | // derived class used in case codegen can devirtualize the call. | ||||||||
18166 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||||||
18167 | if (!ME) | ||||||||
18168 | return; | ||||||||
18169 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||||||
18170 | if (!MD) | ||||||||
18171 | return; | ||||||||
18172 | // Only attempt to devirtualize if this is truly a virtual call. | ||||||||
18173 | bool IsVirtualCall = MD->isVirtual() && | ||||||||
18174 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | ||||||||
18175 | if (!IsVirtualCall) | ||||||||
18176 | return; | ||||||||
18177 | |||||||||
18178 | // If it's possible to devirtualize the call, mark the called function | ||||||||
18179 | // referenced. | ||||||||
18180 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | ||||||||
18181 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | ||||||||
18182 | if (DM) | ||||||||
18183 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | ||||||||
18184 | } | ||||||||
18185 | |||||||||
18186 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | ||||||||
18187 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | ||||||||
18188 | // TODO: update this with DR# once a defect report is filed. | ||||||||
18189 | // C++11 defect. The address of a pure member should not be an ODR use, even | ||||||||
18190 | // if it's a qualified reference. | ||||||||
18191 | bool OdrUse = true; | ||||||||
18192 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | ||||||||
18193 | if (Method->isVirtual() && | ||||||||
18194 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | ||||||||
18195 | OdrUse = false; | ||||||||
18196 | |||||||||
18197 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||||||
18198 | if (!isConstantEvaluated() && FD->isConsteval() && | ||||||||
18199 | !RebuildingImmediateInvocation) | ||||||||
18200 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | ||||||||
18201 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); | ||||||||
18202 | } | ||||||||
18203 | |||||||||
18204 | /// Perform reference-marking and odr-use handling for a MemberExpr. | ||||||||
18205 | void Sema::MarkMemberReferenced(MemberExpr *E) { | ||||||||
18206 | // C++11 [basic.def.odr]p2: | ||||||||
18207 | // A non-overloaded function whose name appears as a potentially-evaluated | ||||||||
18208 | // expression or a member of a set of candidate functions, if selected by | ||||||||
18209 | // overload resolution when referred to from a potentially-evaluated | ||||||||
18210 | // expression, is odr-used, unless it is a pure virtual function and its | ||||||||
18211 | // name is not explicitly qualified. | ||||||||
18212 | bool MightBeOdrUse = true; | ||||||||
18213 | if (E->performsVirtualDispatch(getLangOpts())) { | ||||||||
18214 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | ||||||||
18215 | if (Method->isPure()) | ||||||||
18216 | MightBeOdrUse = false; | ||||||||
18217 | } | ||||||||
18218 | SourceLocation Loc = | ||||||||
18219 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | ||||||||
18220 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); | ||||||||
18221 | } | ||||||||
18222 | |||||||||
18223 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | ||||||||
18224 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | ||||||||
18225 | for (VarDecl *VD : *E) | ||||||||
18226 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); | ||||||||
18227 | } | ||||||||
18228 | |||||||||
18229 | /// Perform marking for a reference to an arbitrary declaration. It | ||||||||
18230 | /// marks the declaration referenced, and performs odr-use checking for | ||||||||
18231 | /// functions and variables. This method should not be used when building a | ||||||||
18232 | /// normal expression which refers to a variable. | ||||||||
18233 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | ||||||||
18234 | bool MightBeOdrUse) { | ||||||||
18235 | if (MightBeOdrUse) { | ||||||||
18236 | if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||||||
18237 | MarkVariableReferenced(Loc, VD); | ||||||||
18238 | return; | ||||||||
18239 | } | ||||||||
18240 | } | ||||||||
18241 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||||||
18242 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | ||||||||
18243 | return; | ||||||||
18244 | } | ||||||||
18245 | D->setReferenced(); | ||||||||
18246 | } | ||||||||
18247 | |||||||||
18248 | namespace { | ||||||||
18249 | // Mark all of the declarations used by a type as referenced. | ||||||||
18250 | // FIXME: Not fully implemented yet! We need to have a better understanding | ||||||||
18251 | // of when we're entering a context we should not recurse into. | ||||||||
18252 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | ||||||||
18253 | // TreeTransforms rebuilding the type in a new context. Rather than | ||||||||
18254 | // duplicating the TreeTransform logic, we should consider reusing it here. | ||||||||
18255 | // Currently that causes problems when rebuilding LambdaExprs. | ||||||||
18256 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | ||||||||
18257 | Sema &S; | ||||||||
18258 | SourceLocation Loc; | ||||||||
18259 | |||||||||
18260 | public: | ||||||||
18261 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | ||||||||
18262 | |||||||||
18263 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | ||||||||
18264 | |||||||||
18265 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | ||||||||
18266 | }; | ||||||||
18267 | } | ||||||||
18268 | |||||||||
18269 | bool MarkReferencedDecls::TraverseTemplateArgument( | ||||||||
18270 | const TemplateArgument &Arg) { | ||||||||
18271 | { | ||||||||
18272 | // A non-type template argument is a constant-evaluated context. | ||||||||
18273 | EnterExpressionEvaluationContext Evaluated( | ||||||||
18274 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||||||
18275 | if (Arg.getKind() == TemplateArgument::Declaration) { | ||||||||
18276 | if (Decl *D = Arg.getAsDecl()) | ||||||||
18277 | S.MarkAnyDeclReferenced(Loc, D, true); | ||||||||
18278 | } else if (Arg.getKind() == TemplateArgument::Expression) { | ||||||||
18279 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | ||||||||
18280 | } | ||||||||
18281 | } | ||||||||
18282 | |||||||||
18283 | return Inherited::TraverseTemplateArgument(Arg); | ||||||||
18284 | } | ||||||||
18285 | |||||||||
18286 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | ||||||||
18287 | MarkReferencedDecls Marker(*this, Loc); | ||||||||
18288 | Marker.TraverseType(T); | ||||||||
18289 | } | ||||||||
18290 | |||||||||
18291 | namespace { | ||||||||
18292 | /// Helper class that marks all of the declarations referenced by | ||||||||
18293 | /// potentially-evaluated subexpressions as "referenced". | ||||||||
18294 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | ||||||||
18295 | public: | ||||||||
18296 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | ||||||||
18297 | bool SkipLocalVariables; | ||||||||
18298 | |||||||||
18299 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) | ||||||||
18300 | : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} | ||||||||
18301 | |||||||||
18302 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | ||||||||
18303 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | ||||||||
18304 | } | ||||||||
18305 | |||||||||
18306 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||||||
18307 | // If we were asked not to visit local variables, don't. | ||||||||
18308 | if (SkipLocalVariables) { | ||||||||
18309 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||||||
18310 | if (VD->hasLocalStorage()) | ||||||||
18311 | return; | ||||||||
18312 | } | ||||||||
18313 | S.MarkDeclRefReferenced(E); | ||||||||
18314 | } | ||||||||
18315 | |||||||||
18316 | void VisitMemberExpr(MemberExpr *E) { | ||||||||
18317 | S.MarkMemberReferenced(E); | ||||||||
18318 | Visit(E->getBase()); | ||||||||
18319 | } | ||||||||
18320 | }; | ||||||||
18321 | } // namespace | ||||||||
18322 | |||||||||
18323 | /// Mark any declarations that appear within this expression or any | ||||||||
18324 | /// potentially-evaluated subexpressions as "referenced". | ||||||||
18325 | /// | ||||||||
18326 | /// \param SkipLocalVariables If true, don't mark local variables as | ||||||||
18327 | /// 'referenced'. | ||||||||
18328 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | ||||||||
18329 | bool SkipLocalVariables) { | ||||||||
18330 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); | ||||||||
18331 | } | ||||||||
18332 | |||||||||
18333 | /// Emit a diagnostic that describes an effect on the run-time behavior | ||||||||
18334 | /// of the program being compiled. | ||||||||
18335 | /// | ||||||||
18336 | /// This routine emits the given diagnostic when the code currently being | ||||||||
18337 | /// type-checked is "potentially evaluated", meaning that there is a | ||||||||
18338 | /// possibility that the code will actually be executable. Code in sizeof() | ||||||||
18339 | /// expressions, code used only during overload resolution, etc., are not | ||||||||
18340 | /// potentially evaluated. This routine will suppress such diagnostics or, | ||||||||
18341 | /// in the absolutely nutty case of potentially potentially evaluated | ||||||||
18342 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | ||||||||
18343 | /// later. | ||||||||
18344 | /// | ||||||||
18345 | /// This routine should be used for all diagnostics that describe the run-time | ||||||||
18346 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | ||||||||
18347 | /// Failure to do so will likely result in spurious diagnostics or failures | ||||||||
18348 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | ||||||||
18349 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | ||||||||
18350 | const PartialDiagnostic &PD) { | ||||||||
18351 | switch (ExprEvalContexts.back().Context) { | ||||||||
18352 | case ExpressionEvaluationContext::Unevaluated: | ||||||||
18353 | case ExpressionEvaluationContext::UnevaluatedList: | ||||||||
18354 | case ExpressionEvaluationContext::UnevaluatedAbstract: | ||||||||
18355 | case ExpressionEvaluationContext::DiscardedStatement: | ||||||||
18356 | // The argument will never be evaluated, so don't complain. | ||||||||
18357 | break; | ||||||||
18358 | |||||||||
18359 | case ExpressionEvaluationContext::ConstantEvaluated: | ||||||||
18360 | // Relevant diagnostics should be produced by constant evaluation. | ||||||||
18361 | break; | ||||||||
18362 | |||||||||
18363 | case ExpressionEvaluationContext::PotentiallyEvaluated: | ||||||||
18364 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||||||
18365 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | ||||||||
18366 | FunctionScopes.back()->PossiblyUnreachableDiags. | ||||||||
18367 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | ||||||||
18368 | return true; | ||||||||
18369 | } | ||||||||
18370 | |||||||||
18371 | // The initializer of a constexpr variable or of the first declaration of a | ||||||||
18372 | // static data member is not syntactically a constant evaluated constant, | ||||||||
18373 | // but nonetheless is always required to be a constant expression, so we | ||||||||
18374 | // can skip diagnosing. | ||||||||
18375 | // FIXME: Using the mangling context here is a hack. | ||||||||
18376 | if (auto *VD = dyn_cast_or_null<VarDecl>( | ||||||||
18377 | ExprEvalContexts.back().ManglingContextDecl)) { | ||||||||
18378 | if (VD->isConstexpr() || | ||||||||
18379 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | ||||||||
18380 | break; | ||||||||
18381 | // FIXME: For any other kind of variable, we should build a CFG for its | ||||||||
18382 | // initializer and check whether the context in question is reachable. | ||||||||
18383 | } | ||||||||
18384 | |||||||||
18385 | Diag(Loc, PD); | ||||||||
18386 | return true; | ||||||||
18387 | } | ||||||||
18388 | |||||||||
18389 | return false; | ||||||||
18390 | } | ||||||||
18391 | |||||||||
18392 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | ||||||||
18393 | const PartialDiagnostic &PD) { | ||||||||
18394 | return DiagRuntimeBehavior( | ||||||||
18395 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | ||||||||
18396 | } | ||||||||
18397 | |||||||||
18398 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | ||||||||
18399 | CallExpr *CE, FunctionDecl *FD) { | ||||||||
18400 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | ||||||||
18401 | return false; | ||||||||
18402 | |||||||||
18403 | // If we're inside a decltype's expression, don't check for a valid return | ||||||||
18404 | // type or construct temporaries until we know whether this is the last call. | ||||||||
18405 | if (ExprEvalContexts.back().ExprContext == | ||||||||
18406 | ExpressionEvaluationContextRecord::EK_Decltype) { | ||||||||
18407 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | ||||||||
18408 | return false; | ||||||||
18409 | } | ||||||||
18410 | |||||||||
18411 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | ||||||||
18412 | FunctionDecl *FD; | ||||||||
18413 | CallExpr *CE; | ||||||||
18414 | |||||||||
18415 | public: | ||||||||
18416 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | ||||||||
18417 | : FD(FD), CE(CE) { } | ||||||||
18418 | |||||||||
18419 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||||||
18420 | if (!FD) { | ||||||||
18421 | S.Diag(Loc, diag::err_call_incomplete_return) | ||||||||
18422 | << T << CE->getSourceRange(); | ||||||||
18423 | return; | ||||||||
18424 | } | ||||||||
18425 | |||||||||
18426 | S.Diag(Loc, diag::err_call_function_incomplete_return) | ||||||||
18427 | << CE->getSourceRange() << FD << T; | ||||||||
18428 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | ||||||||
18429 | << FD->getDeclName(); | ||||||||
18430 | } | ||||||||
18431 | } Diagnoser(FD, CE); | ||||||||
18432 | |||||||||
18433 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | ||||||||
18434 | return true; | ||||||||
18435 | |||||||||
18436 | return false; | ||||||||
18437 | } | ||||||||
18438 | |||||||||
18439 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | ||||||||
18440 | // will prevent this condition from triggering, which is what we want. | ||||||||
18441 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | ||||||||
18442 | SourceLocation Loc; | ||||||||
18443 | |||||||||
18444 | unsigned diagnostic = diag::warn_condition_is_assignment; | ||||||||
18445 | bool IsOrAssign = false; | ||||||||
18446 | |||||||||
18447 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | ||||||||
18448 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | ||||||||
18449 | return; | ||||||||
18450 | |||||||||
18451 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | ||||||||
18452 | |||||||||
18453 | // Greylist some idioms by putting them into a warning subcategory. | ||||||||
18454 | if (ObjCMessageExpr *ME | ||||||||
18455 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | ||||||||
18456 | Selector Sel = ME->getSelector(); | ||||||||
18457 | |||||||||
18458 | // self = [<foo> init...] | ||||||||
18459 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | ||||||||
18460 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||||||
18461 | |||||||||
18462 | // <foo> = [<bar> nextObject] | ||||||||
18463 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | ||||||||
18464 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||||||
18465 | } | ||||||||
18466 | |||||||||
18467 | Loc = Op->getOperatorLoc(); | ||||||||
18468 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||||||
18469 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | ||||||||
18470 | return; | ||||||||
18471 | |||||||||
18472 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | ||||||||
18473 | Loc = Op->getOperatorLoc(); | ||||||||
18474 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | ||||||||
18475 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | ||||||||
18476 | else { | ||||||||
18477 | // Not an assignment. | ||||||||
18478 | return; | ||||||||
18479 | } | ||||||||
18480 | |||||||||
18481 | Diag(Loc, diagnostic) << E->getSourceRange(); | ||||||||
18482 | |||||||||
18483 | SourceLocation Open = E->getBeginLoc(); | ||||||||
18484 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | ||||||||
18485 | Diag(Loc, diag::note_condition_assign_silence) | ||||||||
18486 | << FixItHint::CreateInsertion(Open, "(") | ||||||||
18487 | << FixItHint::CreateInsertion(Close, ")"); | ||||||||
18488 | |||||||||
18489 | if (IsOrAssign) | ||||||||
18490 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | ||||||||
18491 | << FixItHint::CreateReplacement(Loc, "!="); | ||||||||
18492 | else | ||||||||
18493 | Diag(Loc, diag::note_condition_assign_to_comparison) | ||||||||
18494 | << FixItHint::CreateReplacement(Loc, "=="); | ||||||||
18495 | } | ||||||||
18496 | |||||||||
18497 | /// Redundant parentheses over an equality comparison can indicate | ||||||||
18498 | /// that the user intended an assignment used as condition. | ||||||||
18499 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | ||||||||
18500 | // Don't warn if the parens came from a macro. | ||||||||
18501 | SourceLocation parenLoc = ParenE->getBeginLoc(); | ||||||||
18502 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | ||||||||
18503 | return; | ||||||||
18504 | // Don't warn for dependent expressions. | ||||||||
18505 | if (ParenE->isTypeDependent()) | ||||||||
18506 | return; | ||||||||
18507 | |||||||||
18508 | Expr *E = ParenE->IgnoreParens(); | ||||||||
18509 | |||||||||
18510 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | ||||||||
18511 | if (opE->getOpcode() == BO_EQ && | ||||||||
18512 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | ||||||||
18513 | == Expr::MLV_Valid) { | ||||||||
18514 | SourceLocation Loc = opE->getOperatorLoc(); | ||||||||
18515 | |||||||||
18516 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | ||||||||
18517 | SourceRange ParenERange = ParenE->getSourceRange(); | ||||||||
18518 | Diag(Loc, diag::note_equality_comparison_silence) | ||||||||
18519 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | ||||||||
18520 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | ||||||||
18521 | Diag(Loc, diag::note_equality_comparison_to_assign) | ||||||||
18522 | << FixItHint::CreateReplacement(Loc, "="); | ||||||||
18523 | } | ||||||||
18524 | } | ||||||||
18525 | |||||||||
18526 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | ||||||||
18527 | bool IsConstexpr) { | ||||||||
18528 | DiagnoseAssignmentAsCondition(E); | ||||||||
18529 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | ||||||||
18530 | DiagnoseEqualityWithExtraParens(parenE); | ||||||||
18531 | |||||||||
18532 | ExprResult result = CheckPlaceholderExpr(E); | ||||||||
18533 | if (result.isInvalid()) return ExprError(); | ||||||||
18534 | E = result.get(); | ||||||||
18535 | |||||||||
18536 | if (!E->isTypeDependent()) { | ||||||||
18537 | if (getLangOpts().CPlusPlus) | ||||||||
18538 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | ||||||||
18539 | |||||||||
18540 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | ||||||||
18541 | if (ERes.isInvalid()) | ||||||||
18542 | return ExprError(); | ||||||||
18543 | E = ERes.get(); | ||||||||
18544 | |||||||||
18545 | QualType T = E->getType(); | ||||||||
18546 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | ||||||||
18547 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | ||||||||
18548 | << T << E->getSourceRange(); | ||||||||
18549 | return ExprError(); | ||||||||
18550 | } | ||||||||
18551 | CheckBoolLikeConversion(E, Loc); | ||||||||
18552 | } | ||||||||
18553 | |||||||||
18554 | return E; | ||||||||
18555 | } | ||||||||
18556 | |||||||||
18557 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | ||||||||
18558 | Expr *SubExpr, ConditionKind CK) { | ||||||||
18559 | // Empty conditions are valid in for-statements. | ||||||||
18560 | if (!SubExpr) | ||||||||
18561 | return ConditionResult(); | ||||||||
18562 | |||||||||
18563 | ExprResult Cond; | ||||||||
18564 | switch (CK) { | ||||||||
18565 | case ConditionKind::Boolean: | ||||||||
18566 | Cond = CheckBooleanCondition(Loc, SubExpr); | ||||||||
18567 | break; | ||||||||
18568 | |||||||||
18569 | case ConditionKind::ConstexprIf: | ||||||||
18570 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | ||||||||
18571 | break; | ||||||||
18572 | |||||||||
18573 | case ConditionKind::Switch: | ||||||||
18574 | Cond = CheckSwitchCondition(Loc, SubExpr); | ||||||||
18575 | break; | ||||||||
18576 | } | ||||||||
18577 | if (Cond.isInvalid()) { | ||||||||
18578 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | ||||||||
18579 | {SubExpr}); | ||||||||
18580 | if (!Cond.get()) | ||||||||
18581 | return ConditionError(); | ||||||||
18582 | } | ||||||||
18583 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | ||||||||
18584 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | ||||||||
18585 | if (!FullExpr.get()) | ||||||||
18586 | return ConditionError(); | ||||||||
18587 | |||||||||
18588 | return ConditionResult(*this, nullptr, FullExpr, | ||||||||
18589 | CK == ConditionKind::ConstexprIf); | ||||||||
18590 | } | ||||||||
18591 | |||||||||
18592 | namespace { | ||||||||
18593 | /// A visitor for rebuilding a call to an __unknown_any expression | ||||||||
18594 | /// to have an appropriate type. | ||||||||
18595 | struct RebuildUnknownAnyFunction | ||||||||
18596 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | ||||||||
18597 | |||||||||
18598 | Sema &S; | ||||||||
18599 | |||||||||
18600 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | ||||||||
18601 | |||||||||
18602 | ExprResult VisitStmt(Stmt *S) { | ||||||||
18603 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18603); | ||||||||
18604 | } | ||||||||
18605 | |||||||||
18606 | ExprResult VisitExpr(Expr *E) { | ||||||||
18607 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | ||||||||
18608 | << E->getSourceRange(); | ||||||||
18609 | return ExprError(); | ||||||||
18610 | } | ||||||||
18611 | |||||||||
18612 | /// Rebuild an expression which simply semantically wraps another | ||||||||
18613 | /// expression which it shares the type and value kind of. | ||||||||
18614 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||||||
18615 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||||||
18616 | if (SubResult.isInvalid()) return ExprError(); | ||||||||
18617 | |||||||||
18618 | Expr *SubExpr = SubResult.get(); | ||||||||
18619 | E->setSubExpr(SubExpr); | ||||||||
18620 | E->setType(SubExpr->getType()); | ||||||||
18621 | E->setValueKind(SubExpr->getValueKind()); | ||||||||
18622 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18622, __PRETTY_FUNCTION__)); | ||||||||
18623 | return E; | ||||||||
18624 | } | ||||||||
18625 | |||||||||
18626 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||||||
18627 | return rebuildSugarExpr(E); | ||||||||
18628 | } | ||||||||
18629 | |||||||||
18630 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||||||
18631 | return rebuildSugarExpr(E); | ||||||||
18632 | } | ||||||||
18633 | |||||||||
18634 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||||||
18635 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||||||
18636 | if (SubResult.isInvalid()) return ExprError(); | ||||||||
18637 | |||||||||
18638 | Expr *SubExpr = SubResult.get(); | ||||||||
18639 | E->setSubExpr(SubExpr); | ||||||||
18640 | E->setType(S.Context.getPointerType(SubExpr->getType())); | ||||||||
18641 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18641, __PRETTY_FUNCTION__)); | ||||||||
18642 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18642, __PRETTY_FUNCTION__)); | ||||||||
18643 | return E; | ||||||||
18644 | } | ||||||||
18645 | |||||||||
18646 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | ||||||||
18647 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | ||||||||
18648 | |||||||||
18649 | E->setType(VD->getType()); | ||||||||
18650 | |||||||||
18651 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18651, __PRETTY_FUNCTION__)); | ||||||||
18652 | if (S.getLangOpts().CPlusPlus && | ||||||||
18653 | !(isa<CXXMethodDecl>(VD) && | ||||||||
18654 | cast<CXXMethodDecl>(VD)->isInstance())) | ||||||||
18655 | E->setValueKind(VK_LValue); | ||||||||
18656 | |||||||||
18657 | return E; | ||||||||
18658 | } | ||||||||
18659 | |||||||||
18660 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||||||
18661 | return resolveDecl(E, E->getMemberDecl()); | ||||||||
18662 | } | ||||||||
18663 | |||||||||
18664 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||||||
18665 | return resolveDecl(E, E->getDecl()); | ||||||||
18666 | } | ||||||||
18667 | }; | ||||||||
18668 | } | ||||||||
18669 | |||||||||
18670 | /// Given a function expression of unknown-any type, try to rebuild it | ||||||||
18671 | /// to have a function type. | ||||||||
18672 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | ||||||||
18673 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | ||||||||
18674 | if (Result.isInvalid()) return ExprError(); | ||||||||
18675 | return S.DefaultFunctionArrayConversion(Result.get()); | ||||||||
18676 | } | ||||||||
18677 | |||||||||
18678 | namespace { | ||||||||
18679 | /// A visitor for rebuilding an expression of type __unknown_anytype | ||||||||
18680 | /// into one which resolves the type directly on the referring | ||||||||
18681 | /// expression. Strict preservation of the original source | ||||||||
18682 | /// structure is not a goal. | ||||||||
18683 | struct RebuildUnknownAnyExpr | ||||||||
18684 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | ||||||||
18685 | |||||||||
18686 | Sema &S; | ||||||||
18687 | |||||||||
18688 | /// The current destination type. | ||||||||
18689 | QualType DestType; | ||||||||
18690 | |||||||||
18691 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | ||||||||
18692 | : S(S), DestType(CastType) {} | ||||||||
18693 | |||||||||
18694 | ExprResult VisitStmt(Stmt *S) { | ||||||||
18695 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18695); | ||||||||
18696 | } | ||||||||
18697 | |||||||||
18698 | ExprResult VisitExpr(Expr *E) { | ||||||||
18699 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||||||
18700 | << E->getSourceRange(); | ||||||||
18701 | return ExprError(); | ||||||||
18702 | } | ||||||||
18703 | |||||||||
18704 | ExprResult VisitCallExpr(CallExpr *E); | ||||||||
18705 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | ||||||||
18706 | |||||||||
18707 | /// Rebuild an expression which simply semantically wraps another | ||||||||
18708 | /// expression which it shares the type and value kind of. | ||||||||
18709 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||||||
18710 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||||||
18711 | if (SubResult.isInvalid()) return ExprError(); | ||||||||
18712 | Expr *SubExpr = SubResult.get(); | ||||||||
18713 | E->setSubExpr(SubExpr); | ||||||||
18714 | E->setType(SubExpr->getType()); | ||||||||
18715 | E->setValueKind(SubExpr->getValueKind()); | ||||||||
18716 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18716, __PRETTY_FUNCTION__)); | ||||||||
18717 | return E; | ||||||||
18718 | } | ||||||||
18719 | |||||||||
18720 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||||||
18721 | return rebuildSugarExpr(E); | ||||||||
18722 | } | ||||||||
18723 | |||||||||
18724 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||||||
18725 | return rebuildSugarExpr(E); | ||||||||
18726 | } | ||||||||
18727 | |||||||||
18728 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||||||
18729 | const PointerType *Ptr = DestType->getAs<PointerType>(); | ||||||||
18730 | if (!Ptr) { | ||||||||
18731 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | ||||||||
18732 | << E->getSourceRange(); | ||||||||
18733 | return ExprError(); | ||||||||
18734 | } | ||||||||
18735 | |||||||||
18736 | if (isa<CallExpr>(E->getSubExpr())) { | ||||||||
18737 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | ||||||||
18738 | << E->getSourceRange(); | ||||||||
18739 | return ExprError(); | ||||||||
18740 | } | ||||||||
18741 | |||||||||
18742 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18742, __PRETTY_FUNCTION__)); | ||||||||
18743 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18743, __PRETTY_FUNCTION__)); | ||||||||
18744 | E->setType(DestType); | ||||||||
18745 | |||||||||
18746 | // Build the sub-expression as if it were an object of the pointee type. | ||||||||
18747 | DestType = Ptr->getPointeeType(); | ||||||||
18748 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||||||
18749 | if (SubResult.isInvalid()) return ExprError(); | ||||||||
18750 | E->setSubExpr(SubResult.get()); | ||||||||
18751 | return E; | ||||||||
18752 | } | ||||||||
18753 | |||||||||
18754 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | ||||||||
18755 | |||||||||
18756 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | ||||||||
18757 | |||||||||
18758 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||||||
18759 | return resolveDecl(E, E->getMemberDecl()); | ||||||||
18760 | } | ||||||||
18761 | |||||||||
18762 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||||||
18763 | return resolveDecl(E, E->getDecl()); | ||||||||
18764 | } | ||||||||
18765 | }; | ||||||||
18766 | } | ||||||||
18767 | |||||||||
18768 | /// Rebuilds a call expression which yielded __unknown_anytype. | ||||||||
18769 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | ||||||||
18770 | Expr *CalleeExpr = E->getCallee(); | ||||||||
18771 | |||||||||
18772 | enum FnKind { | ||||||||
18773 | FK_MemberFunction, | ||||||||
18774 | FK_FunctionPointer, | ||||||||
18775 | FK_BlockPointer | ||||||||
18776 | }; | ||||||||
18777 | |||||||||
18778 | FnKind Kind; | ||||||||
18779 | QualType CalleeType = CalleeExpr->getType(); | ||||||||
18780 | if (CalleeType == S.Context.BoundMemberTy) { | ||||||||
18781 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr >(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18781, __PRETTY_FUNCTION__)); | ||||||||
18782 | Kind = FK_MemberFunction; | ||||||||
18783 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | ||||||||
18784 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | ||||||||
18785 | CalleeType = Ptr->getPointeeType(); | ||||||||
18786 | Kind = FK_FunctionPointer; | ||||||||
18787 | } else { | ||||||||
18788 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | ||||||||
18789 | Kind = FK_BlockPointer; | ||||||||
18790 | } | ||||||||
18791 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | ||||||||
18792 | |||||||||
18793 | // Verify that this is a legal result type of a function. | ||||||||
18794 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||||||
18795 | unsigned diagID = diag::err_func_returning_array_function; | ||||||||
18796 | if (Kind == FK_BlockPointer) | ||||||||
18797 | diagID = diag::err_block_returning_array_function; | ||||||||
18798 | |||||||||
18799 | S.Diag(E->getExprLoc(), diagID) | ||||||||
18800 | << DestType->isFunctionType() << DestType; | ||||||||
18801 | return ExprError(); | ||||||||
18802 | } | ||||||||
18803 | |||||||||
18804 | // Otherwise, go ahead and set DestType as the call's result. | ||||||||
18805 | E->setType(DestType.getNonLValueExprType(S.Context)); | ||||||||
18806 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||||||
18807 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18807, __PRETTY_FUNCTION__)); | ||||||||
18808 | |||||||||
18809 | // Rebuild the function type, replacing the result type with DestType. | ||||||||
18810 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | ||||||||
18811 | if (Proto) { | ||||||||
18812 | // __unknown_anytype(...) is a special case used by the debugger when | ||||||||
18813 | // it has no idea what a function's signature is. | ||||||||
18814 | // | ||||||||
18815 | // We want to build this call essentially under the K&R | ||||||||
18816 | // unprototyped rules, but making a FunctionNoProtoType in C++ | ||||||||
18817 | // would foul up all sorts of assumptions. However, we cannot | ||||||||
18818 | // simply pass all arguments as variadic arguments, nor can we | ||||||||
18819 | // portably just call the function under a non-variadic type; see | ||||||||
18820 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | ||||||||
18821 | // However, it turns out that in practice it is generally safe to | ||||||||
18822 | // call a function declared as "A foo(B,C,D);" under the prototype | ||||||||
18823 | // "A foo(B,C,D,...);". The only known exception is with the | ||||||||
18824 | // Windows ABI, where any variadic function is implicitly cdecl | ||||||||
18825 | // regardless of its normal CC. Therefore we change the parameter | ||||||||
18826 | // types to match the types of the arguments. | ||||||||
18827 | // | ||||||||
18828 | // This is a hack, but it is far superior to moving the | ||||||||
18829 | // corresponding target-specific code from IR-gen to Sema/AST. | ||||||||
18830 | |||||||||
18831 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | ||||||||
18832 | SmallVector<QualType, 8> ArgTypes; | ||||||||
18833 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | ||||||||
18834 | ArgTypes.reserve(E->getNumArgs()); | ||||||||
18835 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | ||||||||
18836 | Expr *Arg = E->getArg(i); | ||||||||
18837 | QualType ArgType = Arg->getType(); | ||||||||
18838 | if (E->isLValue()) { | ||||||||
18839 | ArgType = S.Context.getLValueReferenceType(ArgType); | ||||||||
18840 | } else if (E->isXValue()) { | ||||||||
18841 | ArgType = S.Context.getRValueReferenceType(ArgType); | ||||||||
18842 | } | ||||||||
18843 | ArgTypes.push_back(ArgType); | ||||||||
18844 | } | ||||||||
18845 | ParamTypes = ArgTypes; | ||||||||
18846 | } | ||||||||
18847 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | ||||||||
18848 | Proto->getExtProtoInfo()); | ||||||||
18849 | } else { | ||||||||
18850 | DestType = S.Context.getFunctionNoProtoType(DestType, | ||||||||
18851 | FnType->getExtInfo()); | ||||||||
18852 | } | ||||||||
18853 | |||||||||
18854 | // Rebuild the appropriate pointer-to-function type. | ||||||||
18855 | switch (Kind) { | ||||||||
18856 | case FK_MemberFunction: | ||||||||
18857 | // Nothing to do. | ||||||||
18858 | break; | ||||||||
18859 | |||||||||
18860 | case FK_FunctionPointer: | ||||||||
18861 | DestType = S.Context.getPointerType(DestType); | ||||||||
18862 | break; | ||||||||
18863 | |||||||||
18864 | case FK_BlockPointer: | ||||||||
18865 | DestType = S.Context.getBlockPointerType(DestType); | ||||||||
18866 | break; | ||||||||
18867 | } | ||||||||
18868 | |||||||||
18869 | // Finally, we can recurse. | ||||||||
18870 | ExprResult CalleeResult = Visit(CalleeExpr); | ||||||||
18871 | if (!CalleeResult.isUsable()) return ExprError(); | ||||||||
18872 | E->setCallee(CalleeResult.get()); | ||||||||
18873 | |||||||||
18874 | // Bind a temporary if necessary. | ||||||||
18875 | return S.MaybeBindToTemporary(E); | ||||||||
18876 | } | ||||||||
18877 | |||||||||
18878 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | ||||||||
18879 | // Verify that this is a legal result type of a call. | ||||||||
18880 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||||||
18881 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | ||||||||
18882 | << DestType->isFunctionType() << DestType; | ||||||||
18883 | return ExprError(); | ||||||||
18884 | } | ||||||||
18885 | |||||||||
18886 | // Rewrite the method result type if available. | ||||||||
18887 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | ||||||||
18888 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast <void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18888, __PRETTY_FUNCTION__)); | ||||||||
18889 | Method->setReturnType(DestType); | ||||||||
18890 | } | ||||||||
18891 | |||||||||
18892 | // Change the type of the message. | ||||||||
18893 | E->setType(DestType.getNonReferenceType()); | ||||||||
18894 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||||||
18895 | |||||||||
18896 | return S.MaybeBindToTemporary(E); | ||||||||
18897 | } | ||||||||
18898 | |||||||||
18899 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||||||
18900 | // The only case we should ever see here is a function-to-pointer decay. | ||||||||
18901 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | ||||||||
18902 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18902, __PRETTY_FUNCTION__)); | ||||||||
18903 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18903, __PRETTY_FUNCTION__)); | ||||||||
18904 | |||||||||
18905 | E->setType(DestType); | ||||||||
18906 | |||||||||
18907 | // Rebuild the sub-expression as the pointee (function) type. | ||||||||
18908 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | ||||||||
18909 | |||||||||
18910 | ExprResult Result = Visit(E->getSubExpr()); | ||||||||
18911 | if (!Result.isUsable()) return ExprError(); | ||||||||
18912 | |||||||||
18913 | E->setSubExpr(Result.get()); | ||||||||
18914 | return E; | ||||||||
18915 | } else if (E->getCastKind() == CK_LValueToRValue) { | ||||||||
18916 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18916, __PRETTY_FUNCTION__)); | ||||||||
18917 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18917, __PRETTY_FUNCTION__)); | ||||||||
18918 | |||||||||
18919 | assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast <void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18919, __PRETTY_FUNCTION__)); | ||||||||
18920 | |||||||||
18921 | E->setType(DestType); | ||||||||
18922 | |||||||||
18923 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | ||||||||
18924 | DestType = S.Context.getLValueReferenceType(DestType); | ||||||||
18925 | |||||||||
18926 | ExprResult Result = Visit(E->getSubExpr()); | ||||||||
18927 | if (!Result.isUsable()) return ExprError(); | ||||||||
18928 | |||||||||
18929 | E->setSubExpr(Result.get()); | ||||||||
18930 | return E; | ||||||||
18931 | } else { | ||||||||
18932 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 18932); | ||||||||
18933 | } | ||||||||
18934 | } | ||||||||
18935 | |||||||||
18936 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | ||||||||
18937 | ExprValueKind ValueKind = VK_LValue; | ||||||||
18938 | QualType Type = DestType; | ||||||||
18939 | |||||||||
18940 | // We know how to make this work for certain kinds of decls: | ||||||||
18941 | |||||||||
18942 | // - functions | ||||||||
18943 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | ||||||||
18944 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | ||||||||
18945 | DestType = Ptr->getPointeeType(); | ||||||||
18946 | ExprResult Result = resolveDecl(E, VD); | ||||||||
18947 | if (Result.isInvalid()) return ExprError(); | ||||||||
18948 | return S.ImpCastExprToType(Result.get(), Type, | ||||||||
18949 | CK_FunctionToPointerDecay, VK_RValue); | ||||||||
18950 | } | ||||||||
18951 | |||||||||
18952 | if (!Type->isFunctionType()) { | ||||||||
18953 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | ||||||||
18954 | << VD << E->getSourceRange(); | ||||||||
18955 | return ExprError(); | ||||||||
18956 | } | ||||||||
18957 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | ||||||||
18958 | // We must match the FunctionDecl's type to the hack introduced in | ||||||||
18959 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | ||||||||
18960 | // type. See the lengthy commentary in that routine. | ||||||||
18961 | QualType FDT = FD->getType(); | ||||||||
18962 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | ||||||||
18963 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | ||||||||
18964 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||||||
18965 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | ||||||||
18966 | SourceLocation Loc = FD->getLocation(); | ||||||||
18967 | FunctionDecl *NewFD = FunctionDecl::Create( | ||||||||
18968 | S.Context, FD->getDeclContext(), Loc, Loc, | ||||||||
18969 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | ||||||||
18970 | SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), | ||||||||
18971 | /*ConstexprKind*/ CSK_unspecified); | ||||||||
18972 | |||||||||
18973 | if (FD->getQualifier()) | ||||||||
18974 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | ||||||||
18975 | |||||||||
18976 | SmallVector<ParmVarDecl*, 16> Params; | ||||||||
18977 | for (const auto &AI : FT->param_types()) { | ||||||||
18978 | ParmVarDecl *Param = | ||||||||
18979 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | ||||||||
18980 | Param->setScopeInfo(0, Params.size()); | ||||||||
18981 | Params.push_back(Param); | ||||||||
18982 | } | ||||||||
18983 | NewFD->setParams(Params); | ||||||||
18984 | DRE->setDecl(NewFD); | ||||||||
18985 | VD = DRE->getDecl(); | ||||||||
18986 | } | ||||||||
18987 | } | ||||||||
18988 | |||||||||
18989 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | ||||||||
18990 | if (MD->isInstance()) { | ||||||||
18991 | ValueKind = VK_RValue; | ||||||||
18992 | Type = S.Context.BoundMemberTy; | ||||||||
18993 | } | ||||||||
18994 | |||||||||
18995 | // Function references aren't l-values in C. | ||||||||
18996 | if (!S.getLangOpts().CPlusPlus) | ||||||||
18997 | ValueKind = VK_RValue; | ||||||||
18998 | |||||||||
18999 | // - variables | ||||||||
19000 | } else if (isa<VarDecl>(VD)) { | ||||||||
19001 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | ||||||||
19002 | Type = RefTy->getPointeeType(); | ||||||||
19003 | } else if (Type->isFunctionType()) { | ||||||||
19004 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | ||||||||
19005 | << VD << E->getSourceRange(); | ||||||||
19006 | return ExprError(); | ||||||||
19007 | } | ||||||||
19008 | |||||||||
19009 | // - nothing else | ||||||||
19010 | } else { | ||||||||
19011 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | ||||||||
19012 | << VD << E->getSourceRange(); | ||||||||
19013 | return ExprError(); | ||||||||
19014 | } | ||||||||
19015 | |||||||||
19016 | // Modifying the declaration like this is friendly to IR-gen but | ||||||||
19017 | // also really dangerous. | ||||||||
19018 | VD->setType(DestType); | ||||||||
19019 | E->setType(Type); | ||||||||
19020 | E->setValueKind(ValueKind); | ||||||||
19021 | return E; | ||||||||
19022 | } | ||||||||
19023 | |||||||||
19024 | /// Check a cast of an unknown-any type. We intentionally only | ||||||||
19025 | /// trigger this for C-style casts. | ||||||||
19026 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | ||||||||
19027 | Expr *CastExpr, CastKind &CastKind, | ||||||||
19028 | ExprValueKind &VK, CXXCastPath &Path) { | ||||||||
19029 | // The type we're casting to must be either void or complete. | ||||||||
19030 | if (!CastType->isVoidType() && | ||||||||
19031 | RequireCompleteType(TypeRange.getBegin(), CastType, | ||||||||
19032 | diag::err_typecheck_cast_to_incomplete)) | ||||||||
19033 | return ExprError(); | ||||||||
19034 | |||||||||
19035 | // Rewrite the casted expression from scratch. | ||||||||
19036 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | ||||||||
19037 | if (!result.isUsable()) return ExprError(); | ||||||||
19038 | |||||||||
19039 | CastExpr = result.get(); | ||||||||
19040 | VK = CastExpr->getValueKind(); | ||||||||
19041 | CastKind = CK_NoOp; | ||||||||
19042 | |||||||||
19043 | return CastExpr; | ||||||||
19044 | } | ||||||||
19045 | |||||||||
19046 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | ||||||||
19047 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | ||||||||
19048 | } | ||||||||
19049 | |||||||||
19050 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | ||||||||
19051 | Expr *arg, QualType ¶mType) { | ||||||||
19052 | // If the syntactic form of the argument is not an explicit cast of | ||||||||
19053 | // any sort, just do default argument promotion. | ||||||||
19054 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | ||||||||
19055 | if (!castArg) { | ||||||||
19056 | ExprResult result = DefaultArgumentPromotion(arg); | ||||||||
19057 | if (result.isInvalid()) return ExprError(); | ||||||||
19058 | paramType = result.get()->getType(); | ||||||||
19059 | return result; | ||||||||
19060 | } | ||||||||
19061 | |||||||||
19062 | // Otherwise, use the type that was written in the explicit cast. | ||||||||
19063 | assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0 ) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 19063, __PRETTY_FUNCTION__)); | ||||||||
19064 | paramType = castArg->getTypeAsWritten(); | ||||||||
19065 | |||||||||
19066 | // Copy-initialize a parameter of that type. | ||||||||
19067 | InitializedEntity entity = | ||||||||
19068 | InitializedEntity::InitializeParameter(Context, paramType, | ||||||||
19069 | /*consumed*/ false); | ||||||||
19070 | return PerformCopyInitialization(entity, callLoc, arg); | ||||||||
19071 | } | ||||||||
19072 | |||||||||
19073 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | ||||||||
19074 | Expr *orig = E; | ||||||||
19075 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | ||||||||
19076 | while (true) { | ||||||||
19077 | E = E->IgnoreParenImpCasts(); | ||||||||
19078 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | ||||||||
19079 | E = call->getCallee(); | ||||||||
19080 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||||||
19081 | } else { | ||||||||
19082 | break; | ||||||||
19083 | } | ||||||||
19084 | } | ||||||||
19085 | |||||||||
19086 | SourceLocation loc; | ||||||||
19087 | NamedDecl *d; | ||||||||
19088 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | ||||||||
19089 | loc = ref->getLocation(); | ||||||||
19090 | d = ref->getDecl(); | ||||||||
19091 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | ||||||||
19092 | loc = mem->getMemberLoc(); | ||||||||
19093 | d = mem->getMemberDecl(); | ||||||||
19094 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | ||||||||
19095 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||||||
19096 | loc = msg->getSelectorStartLoc(); | ||||||||
19097 | d = msg->getMethodDecl(); | ||||||||
19098 | if (!d) { | ||||||||
19099 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | ||||||||
19100 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | ||||||||
19101 | << orig->getSourceRange(); | ||||||||
19102 | return ExprError(); | ||||||||
19103 | } | ||||||||
19104 | } else { | ||||||||
19105 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||||||
19106 | << E->getSourceRange(); | ||||||||
19107 | return ExprError(); | ||||||||
19108 | } | ||||||||
19109 | |||||||||
19110 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | ||||||||
19111 | |||||||||
19112 | // Never recoverable. | ||||||||
19113 | return ExprError(); | ||||||||
19114 | } | ||||||||
19115 | |||||||||
19116 | /// Check for operands with placeholder types and complain if found. | ||||||||
19117 | /// Returns ExprError() if there was an error and no recovery was possible. | ||||||||
19118 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | ||||||||
19119 | if (!Context.isDependenceAllowed()) { | ||||||||
19120 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||||||
19121 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||||||
19122 | // been dealt with before checking the operands. | ||||||||
19123 | ExprResult Result = CorrectDelayedTyposInExpr(E); | ||||||||
19124 | if (!Result.isUsable()) return ExprError(); | ||||||||
19125 | E = Result.get(); | ||||||||
19126 | } | ||||||||
19127 | |||||||||
19128 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | ||||||||
19129 | if (!placeholderType) return E; | ||||||||
19130 | |||||||||
19131 | switch (placeholderType->getKind()) { | ||||||||
19132 | |||||||||
19133 | // Overloaded expressions. | ||||||||
19134 | case BuiltinType::Overload: { | ||||||||
19135 | // Try to resolve a single function template specialization. | ||||||||
19136 | // This is obligatory. | ||||||||
19137 | ExprResult Result = E; | ||||||||
19138 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | ||||||||
19139 | return Result; | ||||||||
19140 | |||||||||
19141 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||||||
19142 | // leaves Result unchanged on failure. | ||||||||
19143 | Result = E; | ||||||||
19144 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | ||||||||
19145 | return Result; | ||||||||
19146 | |||||||||
19147 | // If that failed, try to recover with a call. | ||||||||
19148 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | ||||||||
19149 | /*complain*/ true); | ||||||||
19150 | return Result; | ||||||||
19151 | } | ||||||||
19152 | |||||||||
19153 | // Bound member functions. | ||||||||
19154 | case BuiltinType::BoundMember: { | ||||||||
19155 | ExprResult result = E; | ||||||||
19156 | const Expr *BME = E->IgnoreParens(); | ||||||||
19157 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | ||||||||
19158 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | ||||||||
19159 | if (isa<CXXPseudoDestructorExpr>(BME)) { | ||||||||
19160 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | ||||||||
19161 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | ||||||||
19162 | if (ME->getMemberNameInfo().getName().getNameKind() == | ||||||||
19163 | DeclarationName::CXXDestructorName) | ||||||||
19164 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | ||||||||
19165 | } | ||||||||
19166 | tryToRecoverWithCall(result, PD, | ||||||||
19167 | /*complain*/ true); | ||||||||
19168 | return result; | ||||||||
19169 | } | ||||||||
19170 | |||||||||
19171 | // ARC unbridged casts. | ||||||||
19172 | case BuiltinType::ARCUnbridgedCast: { | ||||||||
19173 | Expr *realCast = stripARCUnbridgedCast(E); | ||||||||
19174 | diagnoseARCUnbridgedCast(realCast); | ||||||||
19175 | return realCast; | ||||||||
19176 | } | ||||||||
19177 | |||||||||
19178 | // Expressions of unknown type. | ||||||||
19179 | case BuiltinType::UnknownAny: | ||||||||
19180 | return diagnoseUnknownAnyExpr(*this, E); | ||||||||
19181 | |||||||||
19182 | // Pseudo-objects. | ||||||||
19183 | case BuiltinType::PseudoObject: | ||||||||
19184 | return checkPseudoObjectRValue(E); | ||||||||
19185 | |||||||||
19186 | case BuiltinType::BuiltinFn: { | ||||||||
19187 | // Accept __noop without parens by implicitly converting it to a call expr. | ||||||||
19188 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | ||||||||
19189 | if (DRE) { | ||||||||
19190 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | ||||||||
19191 | if (FD->getBuiltinID() == Builtin::BI__noop) { | ||||||||
19192 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | ||||||||
19193 | CK_BuiltinFnToFnPtr) | ||||||||
19194 | .get(); | ||||||||
19195 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | ||||||||
19196 | VK_RValue, SourceLocation(), | ||||||||
19197 | FPOptionsOverride()); | ||||||||
19198 | } | ||||||||
19199 | } | ||||||||
19200 | |||||||||
19201 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | ||||||||
19202 | return ExprError(); | ||||||||
19203 | } | ||||||||
19204 | |||||||||
19205 | case BuiltinType::IncompleteMatrixIdx: | ||||||||
19206 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | ||||||||
19207 | ->getRowIdx() | ||||||||
19208 | ->getBeginLoc(), | ||||||||
19209 | diag::err_matrix_incomplete_index); | ||||||||
19210 | return ExprError(); | ||||||||
19211 | |||||||||
19212 | // Expressions of unknown type. | ||||||||
19213 | case BuiltinType::OMPArraySection: | ||||||||
19214 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | ||||||||
19215 | return ExprError(); | ||||||||
19216 | |||||||||
19217 | // Expressions of unknown type. | ||||||||
19218 | case BuiltinType::OMPArrayShaping: | ||||||||
19219 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | ||||||||
19220 | |||||||||
19221 | case BuiltinType::OMPIterator: | ||||||||
19222 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | ||||||||
19223 | |||||||||
19224 | // Everything else should be impossible. | ||||||||
19225 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||||||
19226 | case BuiltinType::Id: | ||||||||
19227 | #include "clang/Basic/OpenCLImageTypes.def" | ||||||||
19228 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||||||
19229 | case BuiltinType::Id: | ||||||||
19230 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||||||
19231 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||||||
19232 | case BuiltinType::Id: | ||||||||
19233 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||||||
19234 | #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ | ||||||||
19235 | case BuiltinType::Id: | ||||||||
19236 | #include "clang/Basic/PPCTypes.def" | ||||||||
19237 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | ||||||||
19238 | #define PLACEHOLDER_TYPE(Id, SingletonId) | ||||||||
19239 | #include "clang/AST/BuiltinTypes.def" | ||||||||
19240 | break; | ||||||||
19241 | } | ||||||||
19242 | |||||||||
19243 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 19243); | ||||||||
19244 | } | ||||||||
19245 | |||||||||
19246 | bool Sema::CheckCaseExpression(Expr *E) { | ||||||||
19247 | if (E->isTypeDependent()) | ||||||||
19248 | return true; | ||||||||
19249 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | ||||||||
19250 | return E->getType()->isIntegralOrEnumerationType(); | ||||||||
19251 | return false; | ||||||||
19252 | } | ||||||||
19253 | |||||||||
19254 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | ||||||||
19255 | ExprResult | ||||||||
19256 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | ||||||||
19257 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 19258, __PRETTY_FUNCTION__)) | ||||||||
19258 | "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaExpr.cpp" , 19258, __PRETTY_FUNCTION__)); | ||||||||
19259 | QualType BoolT = Context.ObjCBuiltinBoolTy; | ||||||||
19260 | if (!Context.getBOOLDecl()) { | ||||||||
19261 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | ||||||||
19262 | Sema::LookupOrdinaryName); | ||||||||
19263 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | ||||||||
19264 | NamedDecl *ND = Result.getFoundDecl(); | ||||||||
19265 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | ||||||||
19266 | Context.setBOOLDecl(TD); | ||||||||
19267 | } | ||||||||
19268 | } | ||||||||
19269 | if (Context.getBOOLDecl()) | ||||||||
19270 | BoolT = Context.getBOOLType(); | ||||||||
19271 | return new (Context) | ||||||||
19272 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | ||||||||
19273 | } | ||||||||
19274 | |||||||||
19275 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | ||||||||
19276 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | ||||||||
19277 | SourceLocation RParen) { | ||||||||
19278 | |||||||||
19279 | StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); | ||||||||
19280 | |||||||||
19281 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||||||
19282 | return Spec.getPlatform() == Platform; | ||||||||
19283 | }); | ||||||||
19284 | |||||||||
19285 | VersionTuple Version; | ||||||||
19286 | if (Spec != AvailSpecs.end()) | ||||||||
19287 | Version = Spec->getVersion(); | ||||||||
19288 | |||||||||
19289 | // The use of `@available` in the enclosing function should be analyzed to | ||||||||
19290 | // warn when it's used inappropriately (i.e. not if(@available)). | ||||||||
19291 | if (getCurFunctionOrMethodDecl()) | ||||||||
19292 | getEnclosingFunction()->HasPotentialAvailabilityViolations = true; | ||||||||
19293 | else if (getCurBlock() || getCurLambda()) | ||||||||
19294 | getCurFunction()->HasPotentialAvailabilityViolations = true; | ||||||||
19295 | |||||||||
19296 | return new (Context) | ||||||||
19297 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | ||||||||
19298 | } | ||||||||
19299 | |||||||||
19300 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | ||||||||
19301 | ArrayRef<Expr *> SubExprs, QualType T) { | ||||||||
19302 | if (!Context.getLangOpts().RecoveryAST) | ||||||||
19303 | return ExprError(); | ||||||||
19304 | |||||||||
19305 | if (isSFINAEContext()) | ||||||||
19306 | return ExprError(); | ||||||||
19307 | |||||||||
19308 | if (T.isNull() || !Context.getLangOpts().RecoveryASTType) | ||||||||
19309 | // We don't know the concrete type, fallback to dependent type. | ||||||||
19310 | T = Context.DependentTy; | ||||||||
19311 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | ||||||||
19312 | } |
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 Type; |
65 | |
66 | enum { |
67 | TypeAlignmentInBits = 4, |
68 | TypeAlignment = 1 << TypeAlignmentInBits |
69 | }; |
70 | |
71 | namespace serialization { |
72 | template <class T> class AbstractTypeReader; |
73 | template <class T> class AbstractTypeWriter; |
74 | } |
75 | |
76 | } // namespace clang |
77 | |
78 | namespace llvm { |
79 | |
80 | template <typename T> |
81 | struct PointerLikeTypeTraits; |
82 | template<> |
83 | struct PointerLikeTypeTraits< ::clang::Type*> { |
84 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
85 | |
86 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
87 | return static_cast< ::clang::Type*>(P); |
88 | } |
89 | |
90 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
91 | }; |
92 | |
93 | template<> |
94 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
95 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
96 | |
97 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
98 | return static_cast< ::clang::ExtQuals*>(P); |
99 | } |
100 | |
101 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
102 | }; |
103 | |
104 | } // namespace llvm |
105 | |
106 | namespace clang { |
107 | |
108 | class ASTContext; |
109 | template <typename> class CanQual; |
110 | class CXXRecordDecl; |
111 | class DeclContext; |
112 | class EnumDecl; |
113 | class Expr; |
114 | class ExtQualsTypeCommonBase; |
115 | class FunctionDecl; |
116 | class IdentifierInfo; |
117 | class NamedDecl; |
118 | class ObjCInterfaceDecl; |
119 | class ObjCProtocolDecl; |
120 | class ObjCTypeParamDecl; |
121 | struct PrintingPolicy; |
122 | class RecordDecl; |
123 | class Stmt; |
124 | class TagDecl; |
125 | class TemplateArgument; |
126 | class TemplateArgumentListInfo; |
127 | class TemplateArgumentLoc; |
128 | class TemplateTypeParmDecl; |
129 | class TypedefNameDecl; |
130 | class UnresolvedUsingTypenameDecl; |
131 | |
132 | using CanQualType = CanQual<Type>; |
133 | |
134 | // Provide forward declarations for all of the *Type classes. |
135 | #define TYPE(Class, Base) class Class##Type; |
136 | #include "clang/AST/TypeNodes.inc" |
137 | |
138 | /// The collection of all-type qualifiers we support. |
139 | /// Clang supports five independent qualifiers: |
140 | /// * C99: const, volatile, and restrict |
141 | /// * MS: __unaligned |
142 | /// * Embedded C (TR18037): address spaces |
143 | /// * Objective C: the GC attributes (none, weak, or strong) |
144 | class Qualifiers { |
145 | public: |
146 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
147 | Const = 0x1, |
148 | Restrict = 0x2, |
149 | Volatile = 0x4, |
150 | CVRMask = Const | Volatile | Restrict |
151 | }; |
152 | |
153 | enum GC { |
154 | GCNone = 0, |
155 | Weak, |
156 | Strong |
157 | }; |
158 | |
159 | enum ObjCLifetime { |
160 | /// There is no lifetime qualification on this type. |
161 | OCL_None, |
162 | |
163 | /// This object can be modified without requiring retains or |
164 | /// releases. |
165 | OCL_ExplicitNone, |
166 | |
167 | /// Assigning into this object requires the old value to be |
168 | /// released and the new value to be retained. The timing of the |
169 | /// release of the old value is inexact: it may be moved to |
170 | /// immediately after the last known point where the value is |
171 | /// live. |
172 | OCL_Strong, |
173 | |
174 | /// Reading or writing from this object requires a barrier call. |
175 | OCL_Weak, |
176 | |
177 | /// Assigning into this object requires a lifetime extension. |
178 | OCL_Autoreleasing |
179 | }; |
180 | |
181 | enum { |
182 | /// The maximum supported address space number. |
183 | /// 23 bits should be enough for anyone. |
184 | MaxAddressSpace = 0x7fffffu, |
185 | |
186 | /// The width of the "fast" qualifier mask. |
187 | FastWidth = 3, |
188 | |
189 | /// The fast qualifier mask. |
190 | FastMask = (1 << FastWidth) - 1 |
191 | }; |
192 | |
193 | /// Returns the common set of qualifiers while removing them from |
194 | /// the given sets. |
195 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
196 | // If both are only CVR-qualified, bit operations are sufficient. |
197 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
198 | Qualifiers Q; |
199 | Q.Mask = L.Mask & R.Mask; |
200 | L.Mask &= ~Q.Mask; |
201 | R.Mask &= ~Q.Mask; |
202 | return Q; |
203 | } |
204 | |
205 | Qualifiers Q; |
206 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
207 | Q.addCVRQualifiers(CommonCRV); |
208 | L.removeCVRQualifiers(CommonCRV); |
209 | R.removeCVRQualifiers(CommonCRV); |
210 | |
211 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
212 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
213 | L.removeObjCGCAttr(); |
214 | R.removeObjCGCAttr(); |
215 | } |
216 | |
217 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
218 | Q.setObjCLifetime(L.getObjCLifetime()); |
219 | L.removeObjCLifetime(); |
220 | R.removeObjCLifetime(); |
221 | } |
222 | |
223 | if (L.getAddressSpace() == R.getAddressSpace()) { |
224 | Q.setAddressSpace(L.getAddressSpace()); |
225 | L.removeAddressSpace(); |
226 | R.removeAddressSpace(); |
227 | } |
228 | return Q; |
229 | } |
230 | |
231 | static Qualifiers fromFastMask(unsigned Mask) { |
232 | Qualifiers Qs; |
233 | Qs.addFastQualifiers(Mask); |
234 | return Qs; |
235 | } |
236 | |
237 | static Qualifiers fromCVRMask(unsigned CVR) { |
238 | Qualifiers Qs; |
239 | Qs.addCVRQualifiers(CVR); |
240 | return Qs; |
241 | } |
242 | |
243 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
244 | Qualifiers Qs; |
245 | Qs.addCVRUQualifiers(CVRU); |
246 | return Qs; |
247 | } |
248 | |
249 | // Deserialize qualifiers from an opaque representation. |
250 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
251 | Qualifiers Qs; |
252 | Qs.Mask = opaque; |
253 | return Qs; |
254 | } |
255 | |
256 | // Serialize these qualifiers into an opaque representation. |
257 | unsigned getAsOpaqueValue() const { |
258 | return Mask; |
259 | } |
260 | |
261 | bool hasConst() const { return Mask & Const; } |
262 | bool hasOnlyConst() const { return Mask == Const; } |
263 | void removeConst() { Mask &= ~Const; } |
264 | void addConst() { Mask |= Const; } |
265 | |
266 | bool hasVolatile() const { return Mask & Volatile; } |
267 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
268 | void removeVolatile() { Mask &= ~Volatile; } |
269 | void addVolatile() { Mask |= Volatile; } |
270 | |
271 | bool hasRestrict() const { return Mask & Restrict; } |
272 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
273 | void removeRestrict() { Mask &= ~Restrict; } |
274 | void addRestrict() { Mask |= Restrict; } |
275 | |
276 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
277 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
278 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
279 | |
280 | void setCVRQualifiers(unsigned mask) { |
281 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 281, __PRETTY_FUNCTION__)); |
282 | Mask = (Mask & ~CVRMask) | mask; |
283 | } |
284 | void removeCVRQualifiers(unsigned mask) { |
285 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 285, __PRETTY_FUNCTION__)); |
286 | Mask &= ~mask; |
287 | } |
288 | void removeCVRQualifiers() { |
289 | removeCVRQualifiers(CVRMask); |
290 | } |
291 | void addCVRQualifiers(unsigned mask) { |
292 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 292, __PRETTY_FUNCTION__)); |
293 | Mask |= mask; |
294 | } |
295 | void addCVRUQualifiers(unsigned mask) { |
296 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 296, __PRETTY_FUNCTION__)); |
297 | Mask |= mask; |
298 | } |
299 | |
300 | bool hasUnaligned() const { return Mask & UMask; } |
301 | void setUnaligned(bool flag) { |
302 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
303 | } |
304 | void removeUnaligned() { Mask &= ~UMask; } |
305 | void addUnaligned() { Mask |= UMask; } |
306 | |
307 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
308 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
309 | void setObjCGCAttr(GC type) { |
310 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
311 | } |
312 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
313 | void addObjCGCAttr(GC type) { |
314 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 314, __PRETTY_FUNCTION__)); |
315 | setObjCGCAttr(type); |
316 | } |
317 | Qualifiers withoutObjCGCAttr() const { |
318 | Qualifiers qs = *this; |
319 | qs.removeObjCGCAttr(); |
320 | return qs; |
321 | } |
322 | Qualifiers withoutObjCLifetime() const { |
323 | Qualifiers qs = *this; |
324 | qs.removeObjCLifetime(); |
325 | return qs; |
326 | } |
327 | Qualifiers withoutAddressSpace() const { |
328 | Qualifiers qs = *this; |
329 | qs.removeAddressSpace(); |
330 | return qs; |
331 | } |
332 | |
333 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
334 | ObjCLifetime getObjCLifetime() const { |
335 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
336 | } |
337 | void setObjCLifetime(ObjCLifetime type) { |
338 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
339 | } |
340 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
341 | void addObjCLifetime(ObjCLifetime type) { |
342 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 342, __PRETTY_FUNCTION__)); |
343 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 343, __PRETTY_FUNCTION__)); |
344 | Mask |= (type << LifetimeShift); |
345 | } |
346 | |
347 | /// True if the lifetime is neither None or ExplicitNone. |
348 | bool hasNonTrivialObjCLifetime() const { |
349 | ObjCLifetime lifetime = getObjCLifetime(); |
350 | return (lifetime > OCL_ExplicitNone); |
351 | } |
352 | |
353 | /// True if the lifetime is either strong or weak. |
354 | bool hasStrongOrWeakObjCLifetime() const { |
355 | ObjCLifetime lifetime = getObjCLifetime(); |
356 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
357 | } |
358 | |
359 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
360 | LangAS getAddressSpace() const { |
361 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
362 | } |
363 | bool hasTargetSpecificAddressSpace() const { |
364 | return isTargetAddressSpace(getAddressSpace()); |
365 | } |
366 | /// Get the address space attribute value to be printed by diagnostics. |
367 | unsigned getAddressSpaceAttributePrintValue() const { |
368 | auto Addr = getAddressSpace(); |
369 | // This function is not supposed to be used with language specific |
370 | // address spaces. If that happens, the diagnostic message should consider |
371 | // printing the QualType instead of the address space value. |
372 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 372, __PRETTY_FUNCTION__)); |
373 | if (Addr != LangAS::Default) |
374 | return toTargetAddressSpace(Addr); |
375 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
376 | // since it cannot differentiate the situation where 0 denotes the default |
377 | // address space or user specified __attribute__((address_space(0))). |
378 | return 0; |
379 | } |
380 | void setAddressSpace(LangAS space) { |
381 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 381, __PRETTY_FUNCTION__)); |
382 | Mask = (Mask & ~AddressSpaceMask) |
383 | | (((uint32_t) space) << AddressSpaceShift); |
384 | } |
385 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
386 | void addAddressSpace(LangAS space) { |
387 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 387, __PRETTY_FUNCTION__)); |
388 | setAddressSpace(space); |
389 | } |
390 | |
391 | // Fast qualifiers are those that can be allocated directly |
392 | // on a QualType object. |
393 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
394 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
395 | void setFastQualifiers(unsigned mask) { |
396 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 396, __PRETTY_FUNCTION__)); |
397 | Mask = (Mask & ~FastMask) | mask; |
398 | } |
399 | void removeFastQualifiers(unsigned mask) { |
400 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 400, __PRETTY_FUNCTION__)); |
401 | Mask &= ~mask; |
402 | } |
403 | void removeFastQualifiers() { |
404 | removeFastQualifiers(FastMask); |
405 | } |
406 | void addFastQualifiers(unsigned mask) { |
407 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 407, __PRETTY_FUNCTION__)); |
408 | Mask |= mask; |
409 | } |
410 | |
411 | /// Return true if the set contains any qualifiers which require an ExtQuals |
412 | /// node to be allocated. |
413 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
414 | Qualifiers getNonFastQualifiers() const { |
415 | Qualifiers Quals = *this; |
416 | Quals.setFastQualifiers(0); |
417 | return Quals; |
418 | } |
419 | |
420 | /// Return true if the set contains any qualifiers. |
421 | bool hasQualifiers() const { return Mask; } |
422 | bool empty() const { return !Mask; } |
423 | |
424 | /// Add the qualifiers from the given set to this set. |
425 | void addQualifiers(Qualifiers Q) { |
426 | // If the other set doesn't have any non-boolean qualifiers, just |
427 | // bit-or it in. |
428 | if (!(Q.Mask & ~CVRMask)) |
429 | Mask |= Q.Mask; |
430 | else { |
431 | Mask |= (Q.Mask & CVRMask); |
432 | if (Q.hasAddressSpace()) |
433 | addAddressSpace(Q.getAddressSpace()); |
434 | if (Q.hasObjCGCAttr()) |
435 | addObjCGCAttr(Q.getObjCGCAttr()); |
436 | if (Q.hasObjCLifetime()) |
437 | addObjCLifetime(Q.getObjCLifetime()); |
438 | } |
439 | } |
440 | |
441 | /// Remove the qualifiers from the given set from this set. |
442 | void removeQualifiers(Qualifiers Q) { |
443 | // If the other set doesn't have any non-boolean qualifiers, just |
444 | // bit-and the inverse in. |
445 | if (!(Q.Mask & ~CVRMask)) |
446 | Mask &= ~Q.Mask; |
447 | else { |
448 | Mask &= ~(Q.Mask & CVRMask); |
449 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
450 | removeObjCGCAttr(); |
451 | if (getObjCLifetime() == Q.getObjCLifetime()) |
452 | removeObjCLifetime(); |
453 | if (getAddressSpace() == Q.getAddressSpace()) |
454 | removeAddressSpace(); |
455 | } |
456 | } |
457 | |
458 | /// Add the qualifiers from the given set to this set, given that |
459 | /// they don't conflict. |
460 | void addConsistentQualifiers(Qualifiers qs) { |
461 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 462, __PRETTY_FUNCTION__)) |
462 | !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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 462, __PRETTY_FUNCTION__)); |
463 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 464, __PRETTY_FUNCTION__)) |
464 | !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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 464, __PRETTY_FUNCTION__)); |
465 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 466, __PRETTY_FUNCTION__)) |
466 | !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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 466, __PRETTY_FUNCTION__)); |
467 | Mask |= qs.Mask; |
468 | } |
469 | |
470 | /// Returns true if address space A is equal to or a superset of B. |
471 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
472 | /// overlapping address spaces. |
473 | /// CL1.1 or CL1.2: |
474 | /// every address space is a superset of itself. |
475 | /// CL2.0 adds: |
476 | /// __generic is a superset of any address space except for __constant. |
477 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
478 | // Address spaces must match exactly. |
479 | return A == B || |
480 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
481 | // for __constant can be used as __generic. |
482 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || |
483 | // We also define global_device and global_host address spaces, |
484 | // to distinguish global pointers allocated on host from pointers |
485 | // allocated on device, which are a subset of __global. |
486 | (A == LangAS::opencl_global && (B == LangAS::opencl_global_device || |
487 | B == LangAS::opencl_global_host)) || |
488 | // Consider pointer size address spaces to be equivalent to default. |
489 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
490 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)); |
491 | } |
492 | |
493 | /// Returns true if the address space in these qualifiers is equal to or |
494 | /// a superset of the address space in the argument qualifiers. |
495 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
496 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
497 | } |
498 | |
499 | /// Determines if these qualifiers compatibly include another set. |
500 | /// Generally this answers the question of whether an object with the other |
501 | /// qualifiers can be safely used as an object with these qualifiers. |
502 | bool compatiblyIncludes(Qualifiers other) const { |
503 | return isAddressSpaceSupersetOf(other) && |
504 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
505 | // be changed. |
506 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
507 | !other.hasObjCGCAttr()) && |
508 | // ObjC lifetime qualifiers must match exactly. |
509 | getObjCLifetime() == other.getObjCLifetime() && |
510 | // CVR qualifiers may subset. |
511 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
512 | // U qualifier may superset. |
513 | (!other.hasUnaligned() || hasUnaligned()); |
514 | } |
515 | |
516 | /// Determines if these qualifiers compatibly include another set of |
517 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
518 | /// |
519 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
520 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
521 | /// including set also contains the 'const' qualifier, or both are non-__weak |
522 | /// and one is None (which can only happen in non-ARC modes). |
523 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
524 | if (getObjCLifetime() == other.getObjCLifetime()) |
525 | return true; |
526 | |
527 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
528 | return false; |
529 | |
530 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
531 | return true; |
532 | |
533 | return hasConst(); |
534 | } |
535 | |
536 | /// Determine whether this set of qualifiers is a strict superset of |
537 | /// another set of qualifiers, not considering qualifier compatibility. |
538 | bool isStrictSupersetOf(Qualifiers Other) const; |
539 | |
540 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
541 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
542 | |
543 | explicit operator bool() const { return hasQualifiers(); } |
544 | |
545 | Qualifiers &operator+=(Qualifiers R) { |
546 | addQualifiers(R); |
547 | return *this; |
548 | } |
549 | |
550 | // Union two qualifier sets. If an enumerated qualifier appears |
551 | // in both sets, use the one from the right. |
552 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
553 | L += R; |
554 | return L; |
555 | } |
556 | |
557 | Qualifiers &operator-=(Qualifiers R) { |
558 | removeQualifiers(R); |
559 | return *this; |
560 | } |
561 | |
562 | /// Compute the difference between two qualifier sets. |
563 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
564 | L -= R; |
565 | return L; |
566 | } |
567 | |
568 | std::string getAsString() const; |
569 | std::string getAsString(const PrintingPolicy &Policy) const; |
570 | |
571 | static std::string getAddrSpaceAsString(LangAS AS); |
572 | |
573 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
574 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
575 | bool appendSpaceIfNonEmpty = false) const; |
576 | |
577 | void Profile(llvm::FoldingSetNodeID &ID) const { |
578 | ID.AddInteger(Mask); |
579 | } |
580 | |
581 | private: |
582 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
583 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
584 | uint32_t Mask = 0; |
585 | |
586 | static const uint32_t UMask = 0x8; |
587 | static const uint32_t UShift = 3; |
588 | static const uint32_t GCAttrMask = 0x30; |
589 | static const uint32_t GCAttrShift = 4; |
590 | static const uint32_t LifetimeMask = 0x1C0; |
591 | static const uint32_t LifetimeShift = 6; |
592 | static const uint32_t AddressSpaceMask = |
593 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
594 | static const uint32_t AddressSpaceShift = 9; |
595 | }; |
596 | |
597 | /// A std::pair-like structure for storing a qualified type split |
598 | /// into its local qualifiers and its locally-unqualified type. |
599 | struct SplitQualType { |
600 | /// The locally-unqualified type. |
601 | const Type *Ty = nullptr; |
602 | |
603 | /// The local qualifiers. |
604 | Qualifiers Quals; |
605 | |
606 | SplitQualType() = default; |
607 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
608 | |
609 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
610 | |
611 | // Make std::tie work. |
612 | std::pair<const Type *,Qualifiers> asPair() const { |
613 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
614 | } |
615 | |
616 | friend bool operator==(SplitQualType a, SplitQualType b) { |
617 | return a.Ty == b.Ty && a.Quals == b.Quals; |
618 | } |
619 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
620 | return a.Ty != b.Ty || a.Quals != b.Quals; |
621 | } |
622 | }; |
623 | |
624 | /// The kind of type we are substituting Objective-C type arguments into. |
625 | /// |
626 | /// The kind of substitution affects the replacement of type parameters when |
627 | /// no concrete type information is provided, e.g., when dealing with an |
628 | /// unspecialized type. |
629 | enum class ObjCSubstitutionContext { |
630 | /// An ordinary type. |
631 | Ordinary, |
632 | |
633 | /// The result type of a method or function. |
634 | Result, |
635 | |
636 | /// The parameter type of a method or function. |
637 | Parameter, |
638 | |
639 | /// The type of a property. |
640 | Property, |
641 | |
642 | /// The superclass of a type. |
643 | Superclass, |
644 | }; |
645 | |
646 | /// A (possibly-)qualified type. |
647 | /// |
648 | /// For efficiency, we don't store CV-qualified types as nodes on their |
649 | /// own: instead each reference to a type stores the qualifiers. This |
650 | /// greatly reduces the number of nodes we need to allocate for types (for |
651 | /// example we only need one for 'int', 'const int', 'volatile int', |
652 | /// 'const volatile int', etc). |
653 | /// |
654 | /// As an added efficiency bonus, instead of making this a pair, we |
655 | /// just store the two bits we care about in the low bits of the |
656 | /// pointer. To handle the packing/unpacking, we make QualType be a |
657 | /// simple wrapper class that acts like a smart pointer. A third bit |
658 | /// indicates whether there are extended qualifiers present, in which |
659 | /// case the pointer points to a special structure. |
660 | class QualType { |
661 | friend class QualifierCollector; |
662 | |
663 | // Thankfully, these are efficiently composable. |
664 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
665 | Qualifiers::FastWidth> Value; |
666 | |
667 | const ExtQuals *getExtQualsUnsafe() const { |
668 | return Value.getPointer().get<const ExtQuals*>(); |
669 | } |
670 | |
671 | const Type *getTypePtrUnsafe() const { |
672 | return Value.getPointer().get<const Type*>(); |
673 | } |
674 | |
675 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
676 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 676, __PRETTY_FUNCTION__)); |
677 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
678 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
679 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
680 | } |
681 | |
682 | public: |
683 | QualType() = default; |
684 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
685 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
686 | |
687 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
688 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
689 | |
690 | /// Retrieves a pointer to the underlying (unqualified) type. |
691 | /// |
692 | /// This function requires that the type not be NULL. If the type might be |
693 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
694 | const Type *getTypePtr() const; |
695 | |
696 | const Type *getTypePtrOrNull() const; |
697 | |
698 | /// Retrieves a pointer to the name of the base type. |
699 | const IdentifierInfo *getBaseTypeIdentifier() const; |
700 | |
701 | /// Divides a QualType into its unqualified type and a set of local |
702 | /// qualifiers. |
703 | SplitQualType split() const; |
704 | |
705 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
706 | |
707 | static QualType getFromOpaquePtr(const void *Ptr) { |
708 | QualType T; |
709 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
710 | return T; |
711 | } |
712 | |
713 | const Type &operator*() const { |
714 | return *getTypePtr(); |
715 | } |
716 | |
717 | const Type *operator->() const { |
718 | return getTypePtr(); |
719 | } |
720 | |
721 | bool isCanonical() const; |
722 | bool isCanonicalAsParam() const; |
723 | |
724 | /// Return true if this QualType doesn't point to a type yet. |
725 | bool isNull() const { |
726 | return Value.getPointer().isNull(); |
727 | } |
728 | |
729 | /// Determine whether this particular QualType instance has the |
730 | /// "const" qualifier set, without looking through typedefs that may have |
731 | /// added "const" at a different level. |
732 | bool isLocalConstQualified() const { |
733 | return (getLocalFastQualifiers() & Qualifiers::Const); |
734 | } |
735 | |
736 | /// Determine whether this type is const-qualified. |
737 | bool isConstQualified() const; |
738 | |
739 | /// Determine whether this particular QualType instance has the |
740 | /// "restrict" qualifier set, without looking through typedefs that may have |
741 | /// added "restrict" at a different level. |
742 | bool isLocalRestrictQualified() const { |
743 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
744 | } |
745 | |
746 | /// Determine whether this type is restrict-qualified. |
747 | bool isRestrictQualified() const; |
748 | |
749 | /// Determine whether this particular QualType instance has the |
750 | /// "volatile" qualifier set, without looking through typedefs that may have |
751 | /// added "volatile" at a different level. |
752 | bool isLocalVolatileQualified() const { |
753 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
754 | } |
755 | |
756 | /// Determine whether this type is volatile-qualified. |
757 | bool isVolatileQualified() const; |
758 | |
759 | /// Determine whether this particular QualType instance has any |
760 | /// qualifiers, without looking through any typedefs that might add |
761 | /// qualifiers at a different level. |
762 | bool hasLocalQualifiers() const { |
763 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
764 | } |
765 | |
766 | /// Determine whether this type has any qualifiers. |
767 | bool hasQualifiers() const; |
768 | |
769 | /// Determine whether this particular QualType instance has any |
770 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
771 | /// instance. |
772 | bool hasLocalNonFastQualifiers() const { |
773 | return Value.getPointer().is<const ExtQuals*>(); |
774 | } |
775 | |
776 | /// Retrieve the set of qualifiers local to this particular QualType |
777 | /// instance, not including any qualifiers acquired through typedefs or |
778 | /// other sugar. |
779 | Qualifiers getLocalQualifiers() const; |
780 | |
781 | /// Retrieve the set of qualifiers applied to this type. |
782 | Qualifiers getQualifiers() const; |
783 | |
784 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
785 | /// local to this particular QualType instance, not including any qualifiers |
786 | /// acquired through typedefs or other sugar. |
787 | unsigned getLocalCVRQualifiers() const { |
788 | return getLocalFastQualifiers(); |
789 | } |
790 | |
791 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
792 | /// applied to this type. |
793 | unsigned getCVRQualifiers() const; |
794 | |
795 | bool isConstant(const ASTContext& Ctx) const { |
796 | return QualType::isConstant(*this, Ctx); |
797 | } |
798 | |
799 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
800 | bool isPODType(const ASTContext &Context) const; |
801 | |
802 | /// Return true if this is a POD type according to the rules of the C++98 |
803 | /// standard, regardless of the current compilation's language. |
804 | bool isCXX98PODType(const ASTContext &Context) const; |
805 | |
806 | /// Return true if this is a POD type according to the more relaxed rules |
807 | /// of the C++11 standard, regardless of the current compilation's language. |
808 | /// (C++0x [basic.types]p9). Note that, unlike |
809 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
810 | bool isCXX11PODType(const ASTContext &Context) const; |
811 | |
812 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
813 | bool isTrivialType(const ASTContext &Context) const; |
814 | |
815 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
816 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
817 | |
818 | |
819 | /// Returns true if it is a class and it might be dynamic. |
820 | bool mayBeDynamicClass() const; |
821 | |
822 | /// Returns true if it is not a class or if the class might not be dynamic. |
823 | bool mayBeNotDynamicClass() const; |
824 | |
825 | // Don't promise in the API that anything besides 'const' can be |
826 | // easily added. |
827 | |
828 | /// Add the `const` type qualifier to this QualType. |
829 | void addConst() { |
830 | addFastQualifiers(Qualifiers::Const); |
831 | } |
832 | QualType withConst() const { |
833 | return withFastQualifiers(Qualifiers::Const); |
834 | } |
835 | |
836 | /// Add the `volatile` type qualifier to this QualType. |
837 | void addVolatile() { |
838 | addFastQualifiers(Qualifiers::Volatile); |
839 | } |
840 | QualType withVolatile() const { |
841 | return withFastQualifiers(Qualifiers::Volatile); |
842 | } |
843 | |
844 | /// Add the `restrict` qualifier to this QualType. |
845 | void addRestrict() { |
846 | addFastQualifiers(Qualifiers::Restrict); |
847 | } |
848 | QualType withRestrict() const { |
849 | return withFastQualifiers(Qualifiers::Restrict); |
850 | } |
851 | |
852 | QualType withCVRQualifiers(unsigned CVR) const { |
853 | return withFastQualifiers(CVR); |
854 | } |
855 | |
856 | void addFastQualifiers(unsigned TQs) { |
857 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 858, __PRETTY_FUNCTION__)) |
858 | && "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 858, __PRETTY_FUNCTION__)); |
859 | Value.setInt(Value.getInt() | TQs); |
860 | } |
861 | |
862 | void removeLocalConst(); |
863 | void removeLocalVolatile(); |
864 | void removeLocalRestrict(); |
865 | void removeLocalCVRQualifiers(unsigned Mask); |
866 | |
867 | void removeLocalFastQualifiers() { Value.setInt(0); } |
868 | void removeLocalFastQualifiers(unsigned Mask) { |
869 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 869, __PRETTY_FUNCTION__)); |
870 | Value.setInt(Value.getInt() & ~Mask); |
871 | } |
872 | |
873 | // Creates a type with the given qualifiers in addition to any |
874 | // qualifiers already on this type. |
875 | QualType withFastQualifiers(unsigned TQs) const { |
876 | QualType T = *this; |
877 | T.addFastQualifiers(TQs); |
878 | return T; |
879 | } |
880 | |
881 | // Creates a type with exactly the given fast qualifiers, removing |
882 | // any existing fast qualifiers. |
883 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
884 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
885 | } |
886 | |
887 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
888 | QualType withoutLocalFastQualifiers() const { |
889 | QualType T = *this; |
890 | T.removeLocalFastQualifiers(); |
891 | return T; |
892 | } |
893 | |
894 | QualType getCanonicalType() const; |
895 | |
896 | /// Return this type with all of the instance-specific qualifiers |
897 | /// removed, but without removing any qualifiers that may have been applied |
898 | /// through typedefs. |
899 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
900 | |
901 | /// Retrieve the unqualified variant of the given type, |
902 | /// removing as little sugar as possible. |
903 | /// |
904 | /// This routine looks through various kinds of sugar to find the |
905 | /// least-desugared type that is unqualified. For example, given: |
906 | /// |
907 | /// \code |
908 | /// typedef int Integer; |
909 | /// typedef const Integer CInteger; |
910 | /// typedef CInteger DifferenceType; |
911 | /// \endcode |
912 | /// |
913 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
914 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
915 | /// |
916 | /// The resulting type might still be qualified if it's sugar for an array |
917 | /// type. To strip qualifiers even from within a sugared array type, use |
918 | /// ASTContext::getUnqualifiedArrayType. |
919 | inline QualType getUnqualifiedType() const; |
920 | |
921 | /// Retrieve the unqualified variant of the given type, removing as little |
922 | /// sugar as possible. |
923 | /// |
924 | /// Like getUnqualifiedType(), but also returns the set of |
925 | /// qualifiers that were built up. |
926 | /// |
927 | /// The resulting type might still be qualified if it's sugar for an array |
928 | /// type. To strip qualifiers even from within a sugared array type, use |
929 | /// ASTContext::getUnqualifiedArrayType. |
930 | inline SplitQualType getSplitUnqualifiedType() const; |
931 | |
932 | /// Determine whether this type is more qualified than the other |
933 | /// given type, requiring exact equality for non-CVR qualifiers. |
934 | bool isMoreQualifiedThan(QualType Other) const; |
935 | |
936 | /// Determine whether this type is at least as qualified as the other |
937 | /// given type, requiring exact equality for non-CVR qualifiers. |
938 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
939 | |
940 | QualType getNonReferenceType() const; |
941 | |
942 | /// Determine the type of a (typically non-lvalue) expression with the |
943 | /// specified result type. |
944 | /// |
945 | /// This routine should be used for expressions for which the return type is |
946 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
947 | /// an lvalue. It removes a top-level reference (since there are no |
948 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
949 | /// from non-class types (in C++) or all types (in C). |
950 | QualType getNonLValueExprType(const ASTContext &Context) const; |
951 | |
952 | /// Remove an outer pack expansion type (if any) from this type. Used as part |
953 | /// of converting the type of a declaration to the type of an expression that |
954 | /// references that expression. It's meaningless for an expression to have a |
955 | /// pack expansion type. |
956 | QualType getNonPackExpansionType() const; |
957 | |
958 | /// Return the specified type with any "sugar" removed from |
959 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
960 | /// the type is already concrete, it returns it unmodified. This is similar |
961 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
962 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
963 | /// concrete. |
964 | /// |
965 | /// Qualifiers are left in place. |
966 | QualType getDesugaredType(const ASTContext &Context) const { |
967 | return getDesugaredType(*this, Context); |
968 | } |
969 | |
970 | SplitQualType getSplitDesugaredType() const { |
971 | return getSplitDesugaredType(*this); |
972 | } |
973 | |
974 | /// Return the specified type with one level of "sugar" removed from |
975 | /// the type. |
976 | /// |
977 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
978 | /// of the type is already concrete, it returns it unmodified. |
979 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
980 | return getSingleStepDesugaredTypeImpl(*this, Context); |
981 | } |
982 | |
983 | /// Returns the specified type after dropping any |
984 | /// outer-level parentheses. |
985 | QualType IgnoreParens() const { |
986 | if (isa<ParenType>(*this)) |
987 | return QualType::IgnoreParens(*this); |
988 | return *this; |
989 | } |
990 | |
991 | /// Indicate whether the specified types and qualifiers are identical. |
992 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
993 | return LHS.Value == RHS.Value; |
994 | } |
995 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
996 | return LHS.Value != RHS.Value; |
997 | } |
998 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
999 | return LHS.Value < RHS.Value; |
1000 | } |
1001 | |
1002 | static std::string getAsString(SplitQualType split, |
1003 | const PrintingPolicy &Policy) { |
1004 | return getAsString(split.Ty, split.Quals, Policy); |
1005 | } |
1006 | static std::string getAsString(const Type *ty, Qualifiers qs, |
1007 | const PrintingPolicy &Policy); |
1008 | |
1009 | std::string getAsString() const; |
1010 | std::string getAsString(const PrintingPolicy &Policy) const; |
1011 | |
1012 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1013 | const Twine &PlaceHolder = Twine(), |
1014 | unsigned Indentation = 0) const; |
1015 | |
1016 | static void print(SplitQualType split, raw_ostream &OS, |
1017 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1018 | unsigned Indentation = 0) { |
1019 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1020 | } |
1021 | |
1022 | static void print(const Type *ty, Qualifiers qs, |
1023 | raw_ostream &OS, const PrintingPolicy &policy, |
1024 | const Twine &PlaceHolder, |
1025 | unsigned Indentation = 0); |
1026 | |
1027 | void getAsStringInternal(std::string &Str, |
1028 | const PrintingPolicy &Policy) const; |
1029 | |
1030 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1031 | const PrintingPolicy &policy) { |
1032 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1033 | } |
1034 | |
1035 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1036 | std::string &out, |
1037 | const PrintingPolicy &policy); |
1038 | |
1039 | class StreamedQualTypeHelper { |
1040 | const QualType &T; |
1041 | const PrintingPolicy &Policy; |
1042 | const Twine &PlaceHolder; |
1043 | unsigned Indentation; |
1044 | |
1045 | public: |
1046 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1047 | const Twine &PlaceHolder, unsigned Indentation) |
1048 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1049 | Indentation(Indentation) {} |
1050 | |
1051 | friend raw_ostream &operator<<(raw_ostream &OS, |
1052 | const StreamedQualTypeHelper &SQT) { |
1053 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1054 | return OS; |
1055 | } |
1056 | }; |
1057 | |
1058 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1059 | const Twine &PlaceHolder = Twine(), |
1060 | unsigned Indentation = 0) const { |
1061 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1062 | } |
1063 | |
1064 | void dump(const char *s) const; |
1065 | void dump() const; |
1066 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
1067 | |
1068 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1069 | ID.AddPointer(getAsOpaquePtr()); |
1070 | } |
1071 | |
1072 | /// Check if this type has any address space qualifier. |
1073 | inline bool hasAddressSpace() const; |
1074 | |
1075 | /// Return the address space of this type. |
1076 | inline LangAS getAddressSpace() const; |
1077 | |
1078 | /// Returns true if address space qualifiers overlap with T address space |
1079 | /// qualifiers. |
1080 | /// OpenCL C defines conversion rules for pointers to different address spaces |
1081 | /// and notion of overlapping address spaces. |
1082 | /// CL1.1 or CL1.2: |
1083 | /// address spaces overlap iff they are they same. |
1084 | /// OpenCL C v2.0 s6.5.5 adds: |
1085 | /// __generic overlaps with any address space except for __constant. |
1086 | bool isAddressSpaceOverlapping(QualType T) const { |
1087 | Qualifiers Q = getQualifiers(); |
1088 | Qualifiers TQ = T.getQualifiers(); |
1089 | // Address spaces overlap if at least one of them is a superset of another |
1090 | return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); |
1091 | } |
1092 | |
1093 | /// Returns gc attribute of this type. |
1094 | inline Qualifiers::GC getObjCGCAttr() const; |
1095 | |
1096 | /// true when Type is objc's weak. |
1097 | bool isObjCGCWeak() const { |
1098 | return getObjCGCAttr() == Qualifiers::Weak; |
1099 | } |
1100 | |
1101 | /// true when Type is objc's strong. |
1102 | bool isObjCGCStrong() const { |
1103 | return getObjCGCAttr() == Qualifiers::Strong; |
1104 | } |
1105 | |
1106 | /// Returns lifetime attribute of this type. |
1107 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1108 | return getQualifiers().getObjCLifetime(); |
1109 | } |
1110 | |
1111 | bool hasNonTrivialObjCLifetime() const { |
1112 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1113 | } |
1114 | |
1115 | bool hasStrongOrWeakObjCLifetime() const { |
1116 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1117 | } |
1118 | |
1119 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1120 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1121 | |
1122 | enum PrimitiveDefaultInitializeKind { |
1123 | /// The type does not fall into any of the following categories. Note that |
1124 | /// this case is zero-valued so that values of this enum can be used as a |
1125 | /// boolean condition for non-triviality. |
1126 | PDIK_Trivial, |
1127 | |
1128 | /// The type is an Objective-C retainable pointer type that is qualified |
1129 | /// with the ARC __strong qualifier. |
1130 | PDIK_ARCStrong, |
1131 | |
1132 | /// The type is an Objective-C retainable pointer type that is qualified |
1133 | /// with the ARC __weak qualifier. |
1134 | PDIK_ARCWeak, |
1135 | |
1136 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1137 | PDIK_Struct |
1138 | }; |
1139 | |
1140 | /// Functions to query basic properties of non-trivial C struct types. |
1141 | |
1142 | /// Check if this is a non-trivial type that would cause a C struct |
1143 | /// transitively containing this type to be non-trivial to default initialize |
1144 | /// and return the kind. |
1145 | PrimitiveDefaultInitializeKind |
1146 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1147 | |
1148 | enum PrimitiveCopyKind { |
1149 | /// The type does not fall into any of the following categories. Note that |
1150 | /// this case is zero-valued so that values of this enum can be used as a |
1151 | /// boolean condition for non-triviality. |
1152 | PCK_Trivial, |
1153 | |
1154 | /// The type would be trivial except that it is volatile-qualified. Types |
1155 | /// that fall into one of the other non-trivial cases may additionally be |
1156 | /// volatile-qualified. |
1157 | PCK_VolatileTrivial, |
1158 | |
1159 | /// The type is an Objective-C retainable pointer type that is qualified |
1160 | /// with the ARC __strong qualifier. |
1161 | PCK_ARCStrong, |
1162 | |
1163 | /// The type is an Objective-C retainable pointer type that is qualified |
1164 | /// with the ARC __weak qualifier. |
1165 | PCK_ARCWeak, |
1166 | |
1167 | /// The type is a struct containing a field whose type is neither |
1168 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1169 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1170 | /// semantics are too complex to express here, in part because they depend |
1171 | /// on the exact constructor or assignment operator that is chosen by |
1172 | /// overload resolution to do the copy. |
1173 | PCK_Struct |
1174 | }; |
1175 | |
1176 | /// Check if this is a non-trivial type that would cause a C struct |
1177 | /// transitively containing this type to be non-trivial to copy and return the |
1178 | /// kind. |
1179 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1180 | |
1181 | /// Check if this is a non-trivial type that would cause a C struct |
1182 | /// transitively containing this type to be non-trivial to destructively |
1183 | /// move and return the kind. Destructive move in this context is a C++-style |
1184 | /// move in which the source object is placed in a valid but unspecified state |
1185 | /// after it is moved, as opposed to a truly destructive move in which the |
1186 | /// source object is placed in an uninitialized state. |
1187 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1188 | |
1189 | enum DestructionKind { |
1190 | DK_none, |
1191 | DK_cxx_destructor, |
1192 | DK_objc_strong_lifetime, |
1193 | DK_objc_weak_lifetime, |
1194 | DK_nontrivial_c_struct |
1195 | }; |
1196 | |
1197 | /// Returns a nonzero value if objects of this type require |
1198 | /// non-trivial work to clean up after. Non-zero because it's |
1199 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1200 | /// something require destruction. |
1201 | DestructionKind isDestructedType() const { |
1202 | return isDestructedTypeImpl(*this); |
1203 | } |
1204 | |
1205 | /// Check if this is or contains a C union that is non-trivial to |
1206 | /// default-initialize, which is a union that has a member that is non-trivial |
1207 | /// to default-initialize. If this returns true, |
1208 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1209 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1210 | |
1211 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1212 | /// which is a union that has a member that is non-trivial to destruct. If |
1213 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1214 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1215 | |
1216 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1217 | /// is a union that has a member that is non-trivial to copy. If this returns |
1218 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1219 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1220 | |
1221 | /// Determine whether expressions of the given type are forbidden |
1222 | /// from being lvalues in C. |
1223 | /// |
1224 | /// The expression types that are forbidden to be lvalues are: |
1225 | /// - 'void', but not qualified void |
1226 | /// - function types |
1227 | /// |
1228 | /// The exact rule here is C99 6.3.2.1: |
1229 | /// An lvalue is an expression with an object type or an incomplete |
1230 | /// type other than void. |
1231 | bool isCForbiddenLValueType() const; |
1232 | |
1233 | /// Substitute type arguments for the Objective-C type parameters used in the |
1234 | /// subject type. |
1235 | /// |
1236 | /// \param ctx ASTContext in which the type exists. |
1237 | /// |
1238 | /// \param typeArgs The type arguments that will be substituted for the |
1239 | /// Objective-C type parameters in the subject type, which are generally |
1240 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1241 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1242 | /// for the context. |
1243 | /// |
1244 | /// \param context The context in which the subject type was written. |
1245 | /// |
1246 | /// \returns the resulting type. |
1247 | QualType substObjCTypeArgs(ASTContext &ctx, |
1248 | ArrayRef<QualType> typeArgs, |
1249 | ObjCSubstitutionContext context) const; |
1250 | |
1251 | /// Substitute type arguments from an object type for the Objective-C type |
1252 | /// parameters used in the subject type. |
1253 | /// |
1254 | /// This operation combines the computation of type arguments for |
1255 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1256 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1257 | /// callers that need to perform a single substitution in isolation. |
1258 | /// |
1259 | /// \param objectType The type of the object whose member type we're |
1260 | /// substituting into. For example, this might be the receiver of a message |
1261 | /// or the base of a property access. |
1262 | /// |
1263 | /// \param dc The declaration context from which the subject type was |
1264 | /// retrieved, which indicates (for example) which type parameters should |
1265 | /// be substituted. |
1266 | /// |
1267 | /// \param context The context in which the subject type was written. |
1268 | /// |
1269 | /// \returns the subject type after replacing all of the Objective-C type |
1270 | /// parameters with their corresponding arguments. |
1271 | QualType substObjCMemberType(QualType objectType, |
1272 | const DeclContext *dc, |
1273 | ObjCSubstitutionContext context) const; |
1274 | |
1275 | /// Strip Objective-C "__kindof" types from the given type. |
1276 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1277 | |
1278 | /// Remove all qualifiers including _Atomic. |
1279 | QualType getAtomicUnqualifiedType() const; |
1280 | |
1281 | private: |
1282 | // These methods are implemented in a separate translation unit; |
1283 | // "static"-ize them to avoid creating temporary QualTypes in the |
1284 | // caller. |
1285 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1286 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1287 | static SplitQualType getSplitDesugaredType(QualType T); |
1288 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1289 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1290 | const ASTContext &C); |
1291 | static QualType IgnoreParens(QualType T); |
1292 | static DestructionKind isDestructedTypeImpl(QualType type); |
1293 | |
1294 | /// Check if \param RD is or contains a non-trivial C union. |
1295 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1296 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1297 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1298 | }; |
1299 | |
1300 | } // namespace clang |
1301 | |
1302 | namespace llvm { |
1303 | |
1304 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1305 | /// to a specific Type class. |
1306 | template<> struct simplify_type< ::clang::QualType> { |
1307 | using SimpleType = const ::clang::Type *; |
1308 | |
1309 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1310 | return Val.getTypePtr(); |
1311 | } |
1312 | }; |
1313 | |
1314 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1315 | template<> |
1316 | struct PointerLikeTypeTraits<clang::QualType> { |
1317 | static inline void *getAsVoidPointer(clang::QualType P) { |
1318 | return P.getAsOpaquePtr(); |
1319 | } |
1320 | |
1321 | static inline clang::QualType getFromVoidPointer(void *P) { |
1322 | return clang::QualType::getFromOpaquePtr(P); |
1323 | } |
1324 | |
1325 | // Various qualifiers go in low bits. |
1326 | static constexpr int NumLowBitsAvailable = 0; |
1327 | }; |
1328 | |
1329 | } // namespace llvm |
1330 | |
1331 | namespace clang { |
1332 | |
1333 | /// Base class that is common to both the \c ExtQuals and \c Type |
1334 | /// classes, which allows \c QualType to access the common fields between the |
1335 | /// two. |
1336 | class ExtQualsTypeCommonBase { |
1337 | friend class ExtQuals; |
1338 | friend class QualType; |
1339 | friend class Type; |
1340 | |
1341 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1342 | /// a self-referential pointer (for \c Type). |
1343 | /// |
1344 | /// This pointer allows an efficient mapping from a QualType to its |
1345 | /// underlying type pointer. |
1346 | const Type *const BaseType; |
1347 | |
1348 | /// The canonical type of this type. A QualType. |
1349 | QualType CanonicalType; |
1350 | |
1351 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1352 | : BaseType(baseType), CanonicalType(canon) {} |
1353 | }; |
1354 | |
1355 | /// We can encode up to four bits in the low bits of a |
1356 | /// type pointer, but there are many more type qualifiers that we want |
1357 | /// to be able to apply to an arbitrary type. Therefore we have this |
1358 | /// struct, intended to be heap-allocated and used by QualType to |
1359 | /// store qualifiers. |
1360 | /// |
1361 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1362 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1363 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1364 | /// Objective-C GC attributes) are much more rare. |
1365 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1366 | // NOTE: changing the fast qualifiers should be straightforward as |
1367 | // long as you don't make 'const' non-fast. |
1368 | // 1. Qualifiers: |
1369 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1370 | // Fast qualifiers must occupy the low-order bits. |
1371 | // b) Update Qualifiers::FastWidth and FastMask. |
1372 | // 2. QualType: |
1373 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1374 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1375 | // this header. |
1376 | // 3. ASTContext: |
1377 | // a) Update get{Volatile,Restrict}Type. |
1378 | |
1379 | /// The immutable set of qualifiers applied by this node. Always contains |
1380 | /// extended qualifiers. |
1381 | Qualifiers Quals; |
1382 | |
1383 | ExtQuals *this_() { return this; } |
1384 | |
1385 | public: |
1386 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1387 | : ExtQualsTypeCommonBase(baseType, |
1388 | canon.isNull() ? QualType(this_(), 0) : canon), |
1389 | Quals(quals) { |
1390 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1391, __PRETTY_FUNCTION__)) |
1391 | && "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1391, __PRETTY_FUNCTION__)); |
1392 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1393, __PRETTY_FUNCTION__)) |
1393 | && "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1393, __PRETTY_FUNCTION__)); |
1394 | } |
1395 | |
1396 | Qualifiers getQualifiers() const { return Quals; } |
1397 | |
1398 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1399 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1400 | |
1401 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1402 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1403 | return Quals.getObjCLifetime(); |
1404 | } |
1405 | |
1406 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1407 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1408 | |
1409 | const Type *getBaseType() const { return BaseType; } |
1410 | |
1411 | public: |
1412 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1413 | Profile(ID, getBaseType(), Quals); |
1414 | } |
1415 | |
1416 | static void Profile(llvm::FoldingSetNodeID &ID, |
1417 | const Type *BaseType, |
1418 | Qualifiers Quals) { |
1419 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1419, __PRETTY_FUNCTION__)); |
1420 | ID.AddPointer(BaseType); |
1421 | Quals.Profile(ID); |
1422 | } |
1423 | }; |
1424 | |
1425 | /// The kind of C++11 ref-qualifier associated with a function type. |
1426 | /// This determines whether a member function's "this" object can be an |
1427 | /// lvalue, rvalue, or neither. |
1428 | enum RefQualifierKind { |
1429 | /// No ref-qualifier was provided. |
1430 | RQ_None = 0, |
1431 | |
1432 | /// An lvalue ref-qualifier was provided (\c &). |
1433 | RQ_LValue, |
1434 | |
1435 | /// An rvalue ref-qualifier was provided (\c &&). |
1436 | RQ_RValue |
1437 | }; |
1438 | |
1439 | /// Which keyword(s) were used to create an AutoType. |
1440 | enum class AutoTypeKeyword { |
1441 | /// auto |
1442 | Auto, |
1443 | |
1444 | /// decltype(auto) |
1445 | DecltypeAuto, |
1446 | |
1447 | /// __auto_type (GNU extension) |
1448 | GNUAutoType |
1449 | }; |
1450 | |
1451 | /// The base class of the type hierarchy. |
1452 | /// |
1453 | /// A central concept with types is that each type always has a canonical |
1454 | /// type. A canonical type is the type with any typedef names stripped out |
1455 | /// of it or the types it references. For example, consider: |
1456 | /// |
1457 | /// typedef int foo; |
1458 | /// typedef foo* bar; |
1459 | /// 'int *' 'foo *' 'bar' |
1460 | /// |
1461 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1462 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1463 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1464 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1465 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1466 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1467 | /// is also 'int*'. |
1468 | /// |
1469 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1470 | /// information about typedefs being used. Canonical types are useful for type |
1471 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1472 | /// about whether something has a particular form (e.g. is a function type), |
1473 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1474 | /// |
1475 | /// Types, once created, are immutable. |
1476 | /// |
1477 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1478 | public: |
1479 | enum TypeClass { |
1480 | #define TYPE(Class, Base) Class, |
1481 | #define LAST_TYPE(Class) TypeLast = Class |
1482 | #define ABSTRACT_TYPE(Class, Base) |
1483 | #include "clang/AST/TypeNodes.inc" |
1484 | }; |
1485 | |
1486 | private: |
1487 | /// Bitfields required by the Type class. |
1488 | class TypeBitfields { |
1489 | friend class Type; |
1490 | template <class T> friend class TypePropertyCache; |
1491 | |
1492 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1493 | unsigned TC : 8; |
1494 | |
1495 | /// Store information on the type dependency. |
1496 | unsigned Dependence : llvm::BitWidth<TypeDependence>; |
1497 | |
1498 | /// True if the cache (i.e. the bitfields here starting with |
1499 | /// 'Cache') is valid. |
1500 | mutable unsigned CacheValid : 1; |
1501 | |
1502 | /// Linkage of this type. |
1503 | mutable unsigned CachedLinkage : 3; |
1504 | |
1505 | /// Whether this type involves and local or unnamed types. |
1506 | mutable unsigned CachedLocalOrUnnamed : 1; |
1507 | |
1508 | /// Whether this type comes from an AST file. |
1509 | mutable unsigned FromAST : 1; |
1510 | |
1511 | bool isCacheValid() const { |
1512 | return CacheValid; |
1513 | } |
1514 | |
1515 | Linkage getLinkage() const { |
1516 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1516, __PRETTY_FUNCTION__)); |
1517 | return static_cast<Linkage>(CachedLinkage); |
1518 | } |
1519 | |
1520 | bool hasLocalOrUnnamedType() const { |
1521 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 1521, __PRETTY_FUNCTION__)); |
1522 | return CachedLocalOrUnnamed; |
1523 | } |
1524 | }; |
1525 | enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; |
1526 | |
1527 | protected: |
1528 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1529 | // into Type. |
1530 | |
1531 | class ArrayTypeBitfields { |
1532 | friend class ArrayType; |
1533 | |
1534 | unsigned : NumTypeBits; |
1535 | |
1536 | /// CVR qualifiers from declarations like |
1537 | /// 'int X[static restrict 4]'. For function parameters only. |
1538 | unsigned IndexTypeQuals : 3; |
1539 | |
1540 | /// Storage class qualifiers from declarations like |
1541 | /// 'int X[static restrict 4]'. For function parameters only. |
1542 | /// Actually an ArrayType::ArraySizeModifier. |
1543 | unsigned SizeModifier : 3; |
1544 | }; |
1545 | |
1546 | class ConstantArrayTypeBitfields { |
1547 | friend class ConstantArrayType; |
1548 | |
1549 | unsigned : NumTypeBits + 3 + 3; |
1550 | |
1551 | /// Whether we have a stored size expression. |
1552 | unsigned HasStoredSizeExpr : 1; |
1553 | }; |
1554 | |
1555 | class BuiltinTypeBitfields { |
1556 | friend class BuiltinType; |
1557 | |
1558 | unsigned : NumTypeBits; |
1559 | |
1560 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1561 | unsigned Kind : 8; |
1562 | }; |
1563 | |
1564 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1565 | /// Only common bits are stored here. Additional uncommon bits are stored |
1566 | /// in a trailing object after FunctionProtoType. |
1567 | class FunctionTypeBitfields { |
1568 | friend class FunctionProtoType; |
1569 | friend class FunctionType; |
1570 | |
1571 | unsigned : NumTypeBits; |
1572 | |
1573 | /// Extra information which affects how the function is called, like |
1574 | /// regparm and the calling convention. |
1575 | unsigned ExtInfo : 13; |
1576 | |
1577 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1578 | /// |
1579 | /// This is a value of type \c RefQualifierKind. |
1580 | unsigned RefQualifier : 2; |
1581 | |
1582 | /// Used only by FunctionProtoType, put here to pack with the |
1583 | /// other bitfields. |
1584 | /// The qualifiers are part of FunctionProtoType because... |
1585 | /// |
1586 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1587 | /// cv-qualifier-seq, [...], are part of the function type. |
1588 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1589 | /// Whether this function has extended Qualifiers. |
1590 | unsigned HasExtQuals : 1; |
1591 | |
1592 | /// The number of parameters this function has, not counting '...'. |
1593 | /// According to [implimits] 8 bits should be enough here but this is |
1594 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1595 | /// keep NumParams as wide as reasonably possible. |
1596 | unsigned NumParams : 16; |
1597 | |
1598 | /// The type of exception specification this function has. |
1599 | unsigned ExceptionSpecType : 4; |
1600 | |
1601 | /// Whether this function has extended parameter information. |
1602 | unsigned HasExtParameterInfos : 1; |
1603 | |
1604 | /// Whether the function is variadic. |
1605 | unsigned Variadic : 1; |
1606 | |
1607 | /// Whether this function has a trailing return type. |
1608 | unsigned HasTrailingReturn : 1; |
1609 | }; |
1610 | |
1611 | class ObjCObjectTypeBitfields { |
1612 | friend class ObjCObjectType; |
1613 | |
1614 | unsigned : NumTypeBits; |
1615 | |
1616 | /// The number of type arguments stored directly on this object type. |
1617 | unsigned NumTypeArgs : 7; |
1618 | |
1619 | /// The number of protocols stored directly on this object type. |
1620 | unsigned NumProtocols : 6; |
1621 | |
1622 | /// Whether this is a "kindof" type. |
1623 | unsigned IsKindOf : 1; |
1624 | }; |
1625 | |
1626 | class ReferenceTypeBitfields { |
1627 | friend class ReferenceType; |
1628 | |
1629 | unsigned : NumTypeBits; |
1630 | |
1631 | /// True if the type was originally spelled with an lvalue sigil. |
1632 | /// This is never true of rvalue references but can also be false |
1633 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1634 | /// as follows: |
1635 | /// |
1636 | /// typedef int &ref; // lvalue, spelled lvalue |
1637 | /// typedef int &&rvref; // rvalue |
1638 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1639 | /// ref &&a; // lvalue, inner ref |
1640 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1641 | /// rvref &&a; // rvalue, inner ref |
1642 | unsigned SpelledAsLValue : 1; |
1643 | |
1644 | /// True if the inner type is a reference type. This only happens |
1645 | /// in non-canonical forms. |
1646 | unsigned InnerRef : 1; |
1647 | }; |
1648 | |
1649 | class TypeWithKeywordBitfields { |
1650 | friend class TypeWithKeyword; |
1651 | |
1652 | unsigned : NumTypeBits; |
1653 | |
1654 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1655 | unsigned Keyword : 8; |
1656 | }; |
1657 | |
1658 | enum { NumTypeWithKeywordBits = 8 }; |
1659 | |
1660 | class ElaboratedTypeBitfields { |
1661 | friend class ElaboratedType; |
1662 | |
1663 | unsigned : NumTypeBits; |
1664 | unsigned : NumTypeWithKeywordBits; |
1665 | |
1666 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1667 | unsigned HasOwnedTagDecl : 1; |
1668 | }; |
1669 | |
1670 | class VectorTypeBitfields { |
1671 | friend class VectorType; |
1672 | friend class DependentVectorType; |
1673 | |
1674 | unsigned : NumTypeBits; |
1675 | |
1676 | /// The kind of vector, either a generic vector type or some |
1677 | /// target-specific vector type such as for AltiVec or Neon. |
1678 | unsigned VecKind : 3; |
1679 | /// The number of elements in the vector. |
1680 | uint32_t NumElements; |
1681 | }; |
1682 | |
1683 | class AttributedTypeBitfields { |
1684 | friend class AttributedType; |
1685 | |
1686 | unsigned : NumTypeBits; |
1687 | |
1688 | /// An AttributedType::Kind |
1689 | unsigned AttrKind : 32 - NumTypeBits; |
1690 | }; |
1691 | |
1692 | class AutoTypeBitfields { |
1693 | friend class AutoType; |
1694 | |
1695 | unsigned : NumTypeBits; |
1696 | |
1697 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1698 | /// or '__auto_type'? AutoTypeKeyword value. |
1699 | unsigned Keyword : 2; |
1700 | |
1701 | /// The number of template arguments in the type-constraints, which is |
1702 | /// expected to be able to hold at least 1024 according to [implimits]. |
1703 | /// However as this limit is somewhat easy to hit with template |
1704 | /// metaprogramming we'd prefer to keep it as large as possible. |
1705 | /// At the moment it has been left as a non-bitfield since this type |
1706 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1707 | /// introduce the performance impact of a bitfield. |
1708 | unsigned NumArgs; |
1709 | }; |
1710 | |
1711 | class SubstTemplateTypeParmPackTypeBitfields { |
1712 | friend class SubstTemplateTypeParmPackType; |
1713 | |
1714 | unsigned : NumTypeBits; |
1715 | |
1716 | /// The number of template arguments in \c Arguments, which is |
1717 | /// expected to be able to hold at least 1024 according to [implimits]. |
1718 | /// However as this limit is somewhat easy to hit with template |
1719 | /// metaprogramming we'd prefer to keep it as large as possible. |
1720 | /// At the moment it has been left as a non-bitfield since this type |
1721 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1722 | /// introduce the performance impact of a bitfield. |
1723 | unsigned NumArgs; |
1724 | }; |
1725 | |
1726 | class TemplateSpecializationTypeBitfields { |
1727 | friend class TemplateSpecializationType; |
1728 | |
1729 | unsigned : NumTypeBits; |
1730 | |
1731 | /// Whether this template specialization type is a substituted type alias. |
1732 | unsigned TypeAlias : 1; |
1733 | |
1734 | /// The number of template arguments named in this class template |
1735 | /// specialization, which is expected to be able to hold at least 1024 |
1736 | /// according to [implimits]. However, as this limit is somewhat easy to |
1737 | /// hit with template metaprogramming we'd prefer to keep it as large |
1738 | /// as possible. At the moment it has been left as a non-bitfield since |
1739 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1740 | /// to introduce the performance impact of a bitfield. |
1741 | unsigned NumArgs; |
1742 | }; |
1743 | |
1744 | class DependentTemplateSpecializationTypeBitfields { |
1745 | friend class DependentTemplateSpecializationType; |
1746 | |
1747 | unsigned : NumTypeBits; |
1748 | unsigned : NumTypeWithKeywordBits; |
1749 | |
1750 | /// The number of template arguments named in this class template |
1751 | /// specialization, which is expected to be able to hold at least 1024 |
1752 | /// according to [implimits]. However, as this limit is somewhat easy to |
1753 | /// hit with template metaprogramming we'd prefer to keep it as large |
1754 | /// as possible. At the moment it has been left as a non-bitfield since |
1755 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1756 | /// to introduce the performance impact of a bitfield. |
1757 | unsigned NumArgs; |
1758 | }; |
1759 | |
1760 | class PackExpansionTypeBitfields { |
1761 | friend class PackExpansionType; |
1762 | |
1763 | unsigned : NumTypeBits; |
1764 | |
1765 | /// The number of expansions that this pack expansion will |
1766 | /// generate when substituted (+1), which is expected to be able to |
1767 | /// hold at least 1024 according to [implimits]. However, as this limit |
1768 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1769 | /// keep it as large as possible. At the moment it has been left as a |
1770 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1771 | /// there is no reason to introduce the performance impact of a bitfield. |
1772 | /// |
1773 | /// This field will only have a non-zero value when some of the parameter |
1774 | /// packs that occur within the pattern have been substituted but others |
1775 | /// have not. |
1776 | unsigned NumExpansions; |
1777 | }; |
1778 | |
1779 | union { |
1780 | TypeBitfields TypeBits; |
1781 | ArrayTypeBitfields ArrayTypeBits; |
1782 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1783 | AttributedTypeBitfields AttributedTypeBits; |
1784 | AutoTypeBitfields AutoTypeBits; |
1785 | BuiltinTypeBitfields BuiltinTypeBits; |
1786 | FunctionTypeBitfields FunctionTypeBits; |
1787 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1788 | ReferenceTypeBitfields ReferenceTypeBits; |
1789 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1790 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1791 | VectorTypeBitfields VectorTypeBits; |
1792 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1793 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1794 | DependentTemplateSpecializationTypeBitfields |
1795 | DependentTemplateSpecializationTypeBits; |
1796 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1797 | }; |
1798 | |
1799 | private: |
1800 | template <class T> friend class TypePropertyCache; |
1801 | |
1802 | /// Set whether this type comes from an AST file. |
1803 | void setFromAST(bool V = true) const { |
1804 | TypeBits.FromAST = V; |
1805 | } |
1806 | |
1807 | protected: |
1808 | friend class ASTContext; |
1809 | |
1810 | Type(TypeClass tc, QualType canon, TypeDependence Dependence) |
1811 | : ExtQualsTypeCommonBase(this, |
1812 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1813 | static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), |
1814 | "changing bitfields changed sizeof(Type)!"); |
1815 | static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, |
1816 | "Insufficient alignment!"); |
1817 | TypeBits.TC = tc; |
1818 | TypeBits.Dependence = static_cast<unsigned>(Dependence); |
1819 | TypeBits.CacheValid = false; |
1820 | TypeBits.CachedLocalOrUnnamed = false; |
1821 | TypeBits.CachedLinkage = NoLinkage; |
1822 | TypeBits.FromAST = false; |
1823 | } |
1824 | |
1825 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1826 | Type *this_() { return this; } |
1827 | |
1828 | void setDependence(TypeDependence D) { |
1829 | TypeBits.Dependence = static_cast<unsigned>(D); |
1830 | } |
1831 | |
1832 | void addDependence(TypeDependence D) { setDependence(getDependence() | D); } |
1833 | |
1834 | public: |
1835 | friend class ASTReader; |
1836 | friend class ASTWriter; |
1837 | template <class T> friend class serialization::AbstractTypeReader; |
1838 | template <class T> friend class serialization::AbstractTypeWriter; |
1839 | |
1840 | Type(const Type &) = delete; |
1841 | Type(Type &&) = delete; |
1842 | Type &operator=(const Type &) = delete; |
1843 | Type &operator=(Type &&) = delete; |
1844 | |
1845 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1846 | |
1847 | /// Whether this type comes from an AST file. |
1848 | bool isFromAST() const { return TypeBits.FromAST; } |
1849 | |
1850 | /// Whether this type is or contains an unexpanded parameter |
1851 | /// pack, used to support C++0x variadic templates. |
1852 | /// |
1853 | /// A type that contains a parameter pack shall be expanded by the |
1854 | /// ellipsis operator at some point. For example, the typedef in the |
1855 | /// following example contains an unexpanded parameter pack 'T': |
1856 | /// |
1857 | /// \code |
1858 | /// template<typename ...T> |
1859 | /// struct X { |
1860 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1861 | /// }; |
1862 | /// \endcode |
1863 | /// |
1864 | /// Note that this routine does not specify which |
1865 | bool containsUnexpandedParameterPack() const { |
1866 | return getDependence() & TypeDependence::UnexpandedPack; |
1867 | } |
1868 | |
1869 | /// Determines if this type would be canonical if it had no further |
1870 | /// qualification. |
1871 | bool isCanonicalUnqualified() const { |
1872 | return CanonicalType == QualType(this, 0); |
1873 | } |
1874 | |
1875 | /// Pull a single level of sugar off of this locally-unqualified type. |
1876 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1877 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1878 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1879 | |
1880 | /// As an extension, we classify types as one of "sized" or "sizeless"; |
1881 | /// every type is one or the other. Standard types are all sized; |
1882 | /// sizeless types are purely an extension. |
1883 | /// |
1884 | /// Sizeless types contain data with no specified size, alignment, |
1885 | /// or layout. |
1886 | bool isSizelessType() const; |
1887 | bool isSizelessBuiltinType() const; |
1888 | |
1889 | /// Determines if this is a sizeless type supported by the |
1890 | /// 'arm_sve_vector_bits' type attribute, which can be applied to a single |
1891 | /// SVE vector or predicate, excluding tuple types such as svint32x4_t. |
1892 | bool isVLSTBuiltinType() const; |
1893 | |
1894 | /// Returns the representative type for the element of an SVE builtin type. |
1895 | /// This is used to represent fixed-length SVE vectors created with the |
1896 | /// 'arm_sve_vector_bits' type attribute as VectorType. |
1897 | QualType getSveEltType(const ASTContext &Ctx) const; |
1898 | |
1899 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1900 | /// object types, function types, and incomplete types. |
1901 | |
1902 | /// Return true if this is an incomplete type. |
1903 | /// A type that can describe objects, but which lacks information needed to |
1904 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1905 | /// routine will need to determine if the size is actually required. |
1906 | /// |
1907 | /// Def If non-null, and the type refers to some kind of declaration |
1908 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1909 | /// class), will be set to the declaration. |
1910 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1911 | |
1912 | /// Return true if this is an incomplete or object |
1913 | /// type, in other words, not a function type. |
1914 | bool isIncompleteOrObjectType() const { |
1915 | return !isFunctionType(); |
1916 | } |
1917 | |
1918 | /// Determine whether this type is an object type. |
1919 | bool isObjectType() const { |
1920 | // C++ [basic.types]p8: |
1921 | // An object type is a (possibly cv-qualified) type that is not a |
1922 | // function type, not a reference type, and not a void type. |
1923 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1924 | } |
1925 | |
1926 | /// Return true if this is a literal type |
1927 | /// (C++11 [basic.types]p10) |
1928 | bool isLiteralType(const ASTContext &Ctx) const; |
1929 | |
1930 | /// Determine if this type is a structural type, per C++20 [temp.param]p7. |
1931 | bool isStructuralType() const; |
1932 | |
1933 | /// Test if this type is a standard-layout type. |
1934 | /// (C++0x [basic.type]p9) |
1935 | bool isStandardLayoutType() const; |
1936 | |
1937 | /// Helper methods to distinguish type categories. All type predicates |
1938 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1939 | |
1940 | /// Returns true if the type is a builtin type. |
1941 | bool isBuiltinType() const; |
1942 | |
1943 | /// Test for a particular builtin type. |
1944 | bool isSpecificBuiltinType(unsigned K) const; |
1945 | |
1946 | /// Test for a type which does not represent an actual type-system type but |
1947 | /// is instead used as a placeholder for various convenient purposes within |
1948 | /// Clang. All such types are BuiltinTypes. |
1949 | bool isPlaceholderType() const; |
1950 | const BuiltinType *getAsPlaceholderType() const; |
1951 | |
1952 | /// Test for a specific placeholder type. |
1953 | bool isSpecificPlaceholderType(unsigned K) const; |
1954 | |
1955 | /// Test for a placeholder type other than Overload; see |
1956 | /// BuiltinType::isNonOverloadPlaceholderType. |
1957 | bool isNonOverloadPlaceholderType() const; |
1958 | |
1959 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1960 | /// isComplexIntegerType() can be used to test for complex integers. |
1961 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1962 | bool isEnumeralType() const; |
1963 | |
1964 | /// Determine whether this type is a scoped enumeration type. |
1965 | bool isScopedEnumeralType() const; |
1966 | bool isBooleanType() const; |
1967 | bool isCharType() const; |
1968 | bool isWideCharType() const; |
1969 | bool isChar8Type() const; |
1970 | bool isChar16Type() const; |
1971 | bool isChar32Type() const; |
1972 | bool isAnyCharacterType() const; |
1973 | bool isIntegralType(const ASTContext &Ctx) const; |
1974 | |
1975 | /// Determine whether this type is an integral or enumeration type. |
1976 | bool isIntegralOrEnumerationType() const; |
1977 | |
1978 | /// Determine whether this type is an integral or unscoped enumeration type. |
1979 | bool isIntegralOrUnscopedEnumerationType() const; |
1980 | bool isUnscopedEnumerationType() const; |
1981 | |
1982 | /// Floating point categories. |
1983 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1984 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1985 | /// isComplexIntegerType() can be used to test for complex integers. |
1986 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1987 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1988 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1989 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1990 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1991 | bool isBFloat16Type() const; |
1992 | bool isFloat128Type() const; |
1993 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1994 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1995 | bool isVoidType() const; // C99 6.2.5p19 |
1996 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1997 | bool isAggregateType() const; |
1998 | bool isFundamentalType() const; |
1999 | bool isCompoundType() const; |
2000 | |
2001 | // Type Predicates: Check to see if this type is structurally the specified |
2002 | // type, ignoring typedefs and qualifiers. |
2003 | bool isFunctionType() const; |
2004 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2005 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2006 | bool isPointerType() const; |
2007 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2008 | bool isBlockPointerType() const; |
2009 | bool isVoidPointerType() const; |
2010 | bool isReferenceType() const; |
2011 | bool isLValueReferenceType() const; |
2012 | bool isRValueReferenceType() const; |
2013 | bool isObjectPointerType() const; |
2014 | bool isFunctionPointerType() const; |
2015 | bool isFunctionReferenceType() const; |
2016 | bool isMemberPointerType() const; |
2017 | bool isMemberFunctionPointerType() const; |
2018 | bool isMemberDataPointerType() const; |
2019 | bool isArrayType() const; |
2020 | bool isConstantArrayType() const; |
2021 | bool isIncompleteArrayType() const; |
2022 | bool isVariableArrayType() const; |
2023 | bool isDependentSizedArrayType() const; |
2024 | bool isRecordType() const; |
2025 | bool isClassType() const; |
2026 | bool isStructureType() const; |
2027 | bool isObjCBoxableRecordType() const; |
2028 | bool isInterfaceType() const; |
2029 | bool isStructureOrClassType() const; |
2030 | bool isUnionType() const; |
2031 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2032 | bool isVectorType() const; // GCC vector type. |
2033 | bool isExtVectorType() const; // Extended vector type. |
2034 | bool isMatrixType() const; // Matrix type. |
2035 | bool isConstantMatrixType() const; // Constant matrix type. |
2036 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2037 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2038 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2039 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2040 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2041 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2042 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2043 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2044 | // for the common case. |
2045 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2046 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2047 | bool isObjCQualifiedIdType() const; // id<foo> |
2048 | bool isObjCQualifiedClassType() const; // Class<foo> |
2049 | bool isObjCObjectOrInterfaceType() const; |
2050 | bool isObjCIdType() const; // id |
2051 | bool isDecltypeType() const; |
2052 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2053 | /// qualifier? |
2054 | /// |
2055 | /// This approximates the answer to the following question: if this |
2056 | /// translation unit were compiled in ARC, would this type be qualified |
2057 | /// with __unsafe_unretained? |
2058 | bool isObjCInertUnsafeUnretainedType() const { |
2059 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2060 | } |
2061 | |
2062 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2063 | /// object type, e.g., __kindof NSView * or __kindof id |
2064 | /// <NSCopying>. |
2065 | /// |
2066 | /// \param bound Will be set to the bound on non-id subtype types, |
2067 | /// which will be (possibly specialized) Objective-C class type, or |
2068 | /// null for 'id. |
2069 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2070 | const ObjCObjectType *&bound) const; |
2071 | |
2072 | bool isObjCClassType() const; // Class |
2073 | |
2074 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2075 | /// Class type, e.g., __kindof Class <NSCopying>. |
2076 | /// |
2077 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2078 | /// here because Objective-C's type system cannot express "a class |
2079 | /// object for a subclass of NSFoo". |
2080 | bool isObjCClassOrClassKindOfType() const; |
2081 | |
2082 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2083 | bool isObjCSelType() const; // Class |
2084 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2085 | bool isObjCARCBridgableType() const; |
2086 | bool isCARCBridgableType() const; |
2087 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2088 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2089 | bool isNothrowT() const; // C++ std::nothrow_t |
2090 | bool isAlignValT() const; // C++17 std::align_val_t |
2091 | bool isStdByteType() const; // C++17 std::byte |
2092 | bool isAtomicType() const; // C11 _Atomic() |
2093 | bool isUndeducedAutoType() const; // C++11 auto or |
2094 | // C++14 decltype(auto) |
2095 | |
2096 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2097 | bool is##Id##Type() const; |
2098 | #include "clang/Basic/OpenCLImageTypes.def" |
2099 | |
2100 | bool isImageType() const; // Any OpenCL image type |
2101 | |
2102 | bool isSamplerT() const; // OpenCL sampler_t |
2103 | bool isEventT() const; // OpenCL event_t |
2104 | bool isClkEventT() const; // OpenCL clk_event_t |
2105 | bool isQueueT() const; // OpenCL queue_t |
2106 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2107 | |
2108 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2109 | bool is##Id##Type() const; |
2110 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2111 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2112 | bool isOCLIntelSubgroupAVCType() const; |
2113 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2114 | |
2115 | bool isPipeType() const; // OpenCL pipe type |
2116 | bool isExtIntType() const; // Extended Int Type |
2117 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2118 | |
2119 | /// Determines if this type, which must satisfy |
2120 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2121 | /// than implicitly __strong. |
2122 | bool isObjCARCImplicitlyUnretainedType() const; |
2123 | |
2124 | /// Check if the type is the CUDA device builtin surface type. |
2125 | bool isCUDADeviceBuiltinSurfaceType() const; |
2126 | /// Check if the type is the CUDA device builtin texture type. |
2127 | bool isCUDADeviceBuiltinTextureType() const; |
2128 | |
2129 | /// Return the implicit lifetime for this type, which must not be dependent. |
2130 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2131 | |
2132 | enum ScalarTypeKind { |
2133 | STK_CPointer, |
2134 | STK_BlockPointer, |
2135 | STK_ObjCObjectPointer, |
2136 | STK_MemberPointer, |
2137 | STK_Bool, |
2138 | STK_Integral, |
2139 | STK_Floating, |
2140 | STK_IntegralComplex, |
2141 | STK_FloatingComplex, |
2142 | STK_FixedPoint |
2143 | }; |
2144 | |
2145 | /// Given that this is a scalar type, classify it. |
2146 | ScalarTypeKind getScalarTypeKind() const; |
2147 | |
2148 | TypeDependence getDependence() const { |
2149 | return static_cast<TypeDependence>(TypeBits.Dependence); |
2150 | } |
2151 | |
2152 | /// Whether this type is an error type. |
2153 | bool containsErrors() const { |
2154 | return getDependence() & TypeDependence::Error; |
2155 | } |
2156 | |
2157 | /// Whether this type is a dependent type, meaning that its definition |
2158 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2159 | bool isDependentType() const { |
2160 | return getDependence() & TypeDependence::Dependent; |
2161 | } |
2162 | |
2163 | /// Determine whether this type is an instantiation-dependent type, |
2164 | /// meaning that the type involves a template parameter (even if the |
2165 | /// definition does not actually depend on the type substituted for that |
2166 | /// template parameter). |
2167 | bool isInstantiationDependentType() const { |
2168 | return getDependence() & TypeDependence::Instantiation; |
2169 | } |
2170 | |
2171 | /// Determine whether this type is an undeduced type, meaning that |
2172 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2173 | /// deduced. |
2174 | bool isUndeducedType() const; |
2175 | |
2176 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2177 | bool isVariablyModifiedType() const { |
2178 | return getDependence() & TypeDependence::VariablyModified; |
2179 | } |
2180 | |
2181 | /// Whether this type involves a variable-length array type |
2182 | /// with a definite size. |
2183 | bool hasSizedVLAType() const; |
2184 | |
2185 | /// Whether this type is or contains a local or unnamed type. |
2186 | bool hasUnnamedOrLocalType() const; |
2187 | |
2188 | bool isOverloadableType() const; |
2189 | |
2190 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2191 | bool isElaboratedTypeSpecifier() const; |
2192 | |
2193 | bool canDecayToPointerType() const; |
2194 | |
2195 | /// Whether this type is represented natively as a pointer. This includes |
2196 | /// pointers, references, block pointers, and Objective-C interface, |
2197 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2198 | bool hasPointerRepresentation() const; |
2199 | |
2200 | /// Whether this type can represent an objective pointer type for the |
2201 | /// purpose of GC'ability |
2202 | bool hasObjCPointerRepresentation() const; |
2203 | |
2204 | /// Determine whether this type has an integer representation |
2205 | /// of some sort, e.g., it is an integer type or a vector. |
2206 | bool hasIntegerRepresentation() const; |
2207 | |
2208 | /// Determine whether this type has an signed integer representation |
2209 | /// of some sort, e.g., it is an signed integer type or a vector. |
2210 | bool hasSignedIntegerRepresentation() const; |
2211 | |
2212 | /// Determine whether this type has an unsigned integer representation |
2213 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2214 | bool hasUnsignedIntegerRepresentation() const; |
2215 | |
2216 | /// Determine whether this type has a floating-point representation |
2217 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2218 | bool hasFloatingRepresentation() const; |
2219 | |
2220 | // Type Checking Functions: Check to see if this type is structurally the |
2221 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2222 | // the best type we can. |
2223 | const RecordType *getAsStructureType() const; |
2224 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2225 | const RecordType *getAsUnionType() const; |
2226 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2227 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2228 | |
2229 | // The following is a convenience method that returns an ObjCObjectPointerType |
2230 | // for object declared using an interface. |
2231 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2232 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2233 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2234 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2235 | |
2236 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2237 | /// because the type is a RecordType or because it is the injected-class-name |
2238 | /// type of a class template or class template partial specialization. |
2239 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2240 | |
2241 | /// Retrieves the RecordDecl this type refers to. |
2242 | RecordDecl *getAsRecordDecl() const; |
2243 | |
2244 | /// Retrieves the TagDecl that this type refers to, either |
2245 | /// because the type is a TagType or because it is the injected-class-name |
2246 | /// type of a class template or class template partial specialization. |
2247 | TagDecl *getAsTagDecl() const; |
2248 | |
2249 | /// If this is a pointer or reference to a RecordType, return the |
2250 | /// CXXRecordDecl that the type refers to. |
2251 | /// |
2252 | /// If this is not a pointer or reference, or the type being pointed to does |
2253 | /// not refer to a CXXRecordDecl, returns NULL. |
2254 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2255 | |
2256 | /// Get the DeducedType whose type will be deduced for a variable with |
2257 | /// an initializer of this type. This looks through declarators like pointer |
2258 | /// types, but not through decltype or typedefs. |
2259 | DeducedType *getContainedDeducedType() const; |
2260 | |
2261 | /// Get the AutoType whose type will be deduced for a variable with |
2262 | /// an initializer of this type. This looks through declarators like pointer |
2263 | /// types, but not through decltype or typedefs. |
2264 | AutoType *getContainedAutoType() const { |
2265 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2266 | } |
2267 | |
2268 | /// Determine whether this type was written with a leading 'auto' |
2269 | /// corresponding to a trailing return type (possibly for a nested |
2270 | /// function type within a pointer to function type or similar). |
2271 | bool hasAutoForTrailingReturnType() const; |
2272 | |
2273 | /// Member-template getAs<specific type>'. Look through sugar for |
2274 | /// an instance of \<specific type>. This scheme will eventually |
2275 | /// replace the specific getAsXXXX methods above. |
2276 | /// |
2277 | /// There are some specializations of this member template listed |
2278 | /// immediately following this class. |
2279 | template <typename T> const T *getAs() const; |
2280 | |
2281 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2282 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2283 | /// This is used when you need to walk over sugar nodes that represent some |
2284 | /// kind of type adjustment from a type that was written as a \<specific type> |
2285 | /// to another type that is still canonically a \<specific type>. |
2286 | template <typename T> const T *getAsAdjusted() const; |
2287 | |
2288 | /// A variant of getAs<> for array types which silently discards |
2289 | /// qualifiers from the outermost type. |
2290 | const ArrayType *getAsArrayTypeUnsafe() const; |
2291 | |
2292 | /// Member-template castAs<specific type>. Look through sugar for |
2293 | /// the underlying instance of \<specific type>. |
2294 | /// |
2295 | /// This method has the same relationship to getAs<T> as cast<T> has |
2296 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2297 | /// have the intended type, and this method will never return null. |
2298 | template <typename T> const T *castAs() const; |
2299 | |
2300 | /// A variant of castAs<> for array type which silently discards |
2301 | /// qualifiers from the outermost type. |
2302 | const ArrayType *castAsArrayTypeUnsafe() const; |
2303 | |
2304 | /// Determine whether this type had the specified attribute applied to it |
2305 | /// (looking through top-level type sugar). |
2306 | bool hasAttr(attr::Kind AK) const; |
2307 | |
2308 | /// Get the base element type of this type, potentially discarding type |
2309 | /// qualifiers. This should never be used when type qualifiers |
2310 | /// are meaningful. |
2311 | const Type *getBaseElementTypeUnsafe() const; |
2312 | |
2313 | /// If this is an array type, return the element type of the array, |
2314 | /// potentially with type qualifiers missing. |
2315 | /// This should never be used when type qualifiers are meaningful. |
2316 | const Type *getArrayElementTypeNoTypeQual() const; |
2317 | |
2318 | /// If this is a pointer type, return the pointee type. |
2319 | /// If this is an array type, return the array element type. |
2320 | /// This should never be used when type qualifiers are meaningful. |
2321 | const Type *getPointeeOrArrayElementType() const; |
2322 | |
2323 | /// If this is a pointer, ObjC object pointer, or block |
2324 | /// pointer, this returns the respective pointee. |
2325 | QualType getPointeeType() const; |
2326 | |
2327 | /// Return the specified type with any "sugar" removed from the type, |
2328 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2329 | const Type *getUnqualifiedDesugaredType() const; |
2330 | |
2331 | /// More type predicates useful for type checking/promotion |
2332 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2333 | |
2334 | /// Return true if this is an integer type that is |
2335 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2336 | /// or an enum decl which has a signed representation. |
2337 | bool isSignedIntegerType() const; |
2338 | |
2339 | /// Return true if this is an integer type that is |
2340 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2341 | /// or an enum decl which has an unsigned representation. |
2342 | bool isUnsignedIntegerType() const; |
2343 | |
2344 | /// Determines whether this is an integer type that is signed or an |
2345 | /// enumeration types whose underlying type is a signed integer type. |
2346 | bool isSignedIntegerOrEnumerationType() const; |
2347 | |
2348 | /// Determines whether this is an integer type that is unsigned or an |
2349 | /// enumeration types whose underlying type is a unsigned integer type. |
2350 | bool isUnsignedIntegerOrEnumerationType() const; |
2351 | |
2352 | /// Return true if this is a fixed point type according to |
2353 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2354 | bool isFixedPointType() const; |
2355 | |
2356 | /// Return true if this is a fixed point or integer type. |
2357 | bool isFixedPointOrIntegerType() const; |
2358 | |
2359 | /// Return true if this is a saturated fixed point type according to |
2360 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2361 | bool isSaturatedFixedPointType() const; |
2362 | |
2363 | /// Return true if this is a saturated fixed point type according to |
2364 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2365 | bool isUnsaturatedFixedPointType() const; |
2366 | |
2367 | /// Return true if this is a fixed point type that is signed according |
2368 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2369 | bool isSignedFixedPointType() const; |
2370 | |
2371 | /// Return true if this is a fixed point type that is unsigned according |
2372 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2373 | bool isUnsignedFixedPointType() const; |
2374 | |
2375 | /// Return true if this is not a variable sized type, |
2376 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2377 | /// incomplete types. |
2378 | bool isConstantSizeType() const; |
2379 | |
2380 | /// Returns true if this type can be represented by some |
2381 | /// set of type specifiers. |
2382 | bool isSpecifierType() const; |
2383 | |
2384 | /// Determine the linkage of this type. |
2385 | Linkage getLinkage() const; |
2386 | |
2387 | /// Determine the visibility of this type. |
2388 | Visibility getVisibility() const { |
2389 | return getLinkageAndVisibility().getVisibility(); |
2390 | } |
2391 | |
2392 | /// Return true if the visibility was explicitly set is the code. |
2393 | bool isVisibilityExplicit() const { |
2394 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2395 | } |
2396 | |
2397 | /// Determine the linkage and visibility of this type. |
2398 | LinkageInfo getLinkageAndVisibility() const; |
2399 | |
2400 | /// True if the computed linkage is valid. Used for consistency |
2401 | /// checking. Should always return true. |
2402 | bool isLinkageValid() const; |
2403 | |
2404 | /// Determine the nullability of the given type. |
2405 | /// |
2406 | /// Note that nullability is only captured as sugar within the type |
2407 | /// system, not as part of the canonical type, so nullability will |
2408 | /// be lost by canonicalization and desugaring. |
2409 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2410 | |
2411 | /// Determine whether the given type can have a nullability |
2412 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2413 | /// |
2414 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2415 | /// this type can have nullability because it is dependent. |
2416 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2417 | |
2418 | /// Retrieve the set of substitutions required when accessing a member |
2419 | /// of the Objective-C receiver type that is declared in the given context. |
2420 | /// |
2421 | /// \c *this is the type of the object we're operating on, e.g., the |
2422 | /// receiver for a message send or the base of a property access, and is |
2423 | /// expected to be of some object or object pointer type. |
2424 | /// |
2425 | /// \param dc The declaration context for which we are building up a |
2426 | /// substitution mapping, which should be an Objective-C class, extension, |
2427 | /// category, or method within. |
2428 | /// |
2429 | /// \returns an array of type arguments that can be substituted for |
2430 | /// the type parameters of the given declaration context in any type described |
2431 | /// within that context, or an empty optional to indicate that no |
2432 | /// substitution is required. |
2433 | Optional<ArrayRef<QualType>> |
2434 | getObjCSubstitutions(const DeclContext *dc) const; |
2435 | |
2436 | /// Determines if this is an ObjC interface type that may accept type |
2437 | /// parameters. |
2438 | bool acceptsObjCTypeParams() const; |
2439 | |
2440 | const char *getTypeClassName() const; |
2441 | |
2442 | QualType getCanonicalTypeInternal() const { |
2443 | return CanonicalType; |
2444 | } |
2445 | |
2446 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2447 | void dump() const; |
2448 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
2449 | }; |
2450 | |
2451 | /// This will check for a TypedefType by removing any existing sugar |
2452 | /// until it reaches a TypedefType or a non-sugared type. |
2453 | template <> const TypedefType *Type::getAs() const; |
2454 | |
2455 | /// This will check for a TemplateSpecializationType by removing any |
2456 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2457 | /// non-sugared type. |
2458 | template <> const TemplateSpecializationType *Type::getAs() const; |
2459 | |
2460 | /// This will check for an AttributedType by removing any existing sugar |
2461 | /// until it reaches an AttributedType or a non-sugared type. |
2462 | template <> const AttributedType *Type::getAs() const; |
2463 | |
2464 | // We can do canonical leaf types faster, because we don't have to |
2465 | // worry about preserving child type decoration. |
2466 | #define TYPE(Class, Base) |
2467 | #define LEAF_TYPE(Class) \ |
2468 | template <> inline const Class##Type *Type::getAs() const { \ |
2469 | return dyn_cast<Class##Type>(CanonicalType); \ |
2470 | } \ |
2471 | template <> inline const Class##Type *Type::castAs() const { \ |
2472 | return cast<Class##Type>(CanonicalType); \ |
2473 | } |
2474 | #include "clang/AST/TypeNodes.inc" |
2475 | |
2476 | /// This class is used for builtin types like 'int'. Builtin |
2477 | /// types are always canonical and have a literal name field. |
2478 | class BuiltinType : public Type { |
2479 | public: |
2480 | enum Kind { |
2481 | // OpenCL image types |
2482 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2483 | #include "clang/Basic/OpenCLImageTypes.def" |
2484 | // OpenCL extension types |
2485 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2486 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2487 | // SVE Types |
2488 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2489 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2490 | // PPC MMA Types |
2491 | #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) Id, |
2492 | #include "clang/Basic/PPCTypes.def" |
2493 | // All other builtin types |
2494 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2495 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2496 | #include "clang/AST/BuiltinTypes.def" |
2497 | }; |
2498 | |
2499 | private: |
2500 | friend class ASTContext; // ASTContext creates these. |
2501 | |
2502 | BuiltinType(Kind K) |
2503 | : Type(Builtin, QualType(), |
2504 | K == Dependent ? TypeDependence::DependentInstantiation |
2505 | : TypeDependence::None) { |
2506 | BuiltinTypeBits.Kind = K; |
2507 | } |
2508 | |
2509 | public: |
2510 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2511 | StringRef getName(const PrintingPolicy &Policy) const; |
2512 | |
2513 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2514 | // The StringRef is null-terminated. |
2515 | StringRef str = getName(Policy); |
2516 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 2516, __PRETTY_FUNCTION__)); |
2517 | return str.data(); |
2518 | } |
2519 | |
2520 | bool isSugared() const { return false; } |
2521 | QualType desugar() const { return QualType(this, 0); } |
2522 | |
2523 | bool isInteger() const { |
2524 | return getKind() >= Bool && getKind() <= Int128; |
2525 | } |
2526 | |
2527 | bool isSignedInteger() const { |
2528 | return getKind() >= Char_S && getKind() <= Int128; |
2529 | } |
2530 | |
2531 | bool isUnsignedInteger() const { |
2532 | return getKind() >= Bool && getKind() <= UInt128; |
2533 | } |
2534 | |
2535 | bool isFloatingPoint() const { |
2536 | return getKind() >= Half && getKind() <= Float128; |
2537 | } |
2538 | |
2539 | /// Determines whether the given kind corresponds to a placeholder type. |
2540 | static bool isPlaceholderTypeKind(Kind K) { |
2541 | return K >= Overload; |
2542 | } |
2543 | |
2544 | /// Determines whether this type is a placeholder type, i.e. a type |
2545 | /// which cannot appear in arbitrary positions in a fully-formed |
2546 | /// expression. |
2547 | bool isPlaceholderType() const { |
2548 | return isPlaceholderTypeKind(getKind()); |
2549 | } |
2550 | |
2551 | /// Determines whether this type is a placeholder type other than |
2552 | /// Overload. Most placeholder types require only syntactic |
2553 | /// information about their context in order to be resolved (e.g. |
2554 | /// whether it is a call expression), which means they can (and |
2555 | /// should) be resolved in an earlier "phase" of analysis. |
2556 | /// Overload expressions sometimes pick up further information |
2557 | /// from their context, like whether the context expects a |
2558 | /// specific function-pointer type, and so frequently need |
2559 | /// special treatment. |
2560 | bool isNonOverloadPlaceholderType() const { |
2561 | return getKind() > Overload; |
2562 | } |
2563 | |
2564 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2565 | }; |
2566 | |
2567 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2568 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2569 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2570 | friend class ASTContext; // ASTContext creates these. |
2571 | |
2572 | QualType ElementType; |
2573 | |
2574 | ComplexType(QualType Element, QualType CanonicalPtr) |
2575 | : Type(Complex, CanonicalPtr, Element->getDependence()), |
2576 | ElementType(Element) {} |
2577 | |
2578 | public: |
2579 | QualType getElementType() const { return ElementType; } |
2580 | |
2581 | bool isSugared() const { return false; } |
2582 | QualType desugar() const { return QualType(this, 0); } |
2583 | |
2584 | void Profile(llvm::FoldingSetNodeID &ID) { |
2585 | Profile(ID, getElementType()); |
2586 | } |
2587 | |
2588 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2589 | ID.AddPointer(Element.getAsOpaquePtr()); |
2590 | } |
2591 | |
2592 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2593 | }; |
2594 | |
2595 | /// Sugar for parentheses used when specifying types. |
2596 | class ParenType : public Type, public llvm::FoldingSetNode { |
2597 | friend class ASTContext; // ASTContext creates these. |
2598 | |
2599 | QualType Inner; |
2600 | |
2601 | ParenType(QualType InnerType, QualType CanonType) |
2602 | : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} |
2603 | |
2604 | public: |
2605 | QualType getInnerType() const { return Inner; } |
2606 | |
2607 | bool isSugared() const { return true; } |
2608 | QualType desugar() const { return getInnerType(); } |
2609 | |
2610 | void Profile(llvm::FoldingSetNodeID &ID) { |
2611 | Profile(ID, getInnerType()); |
2612 | } |
2613 | |
2614 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2615 | Inner.Profile(ID); |
2616 | } |
2617 | |
2618 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2619 | }; |
2620 | |
2621 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2622 | class PointerType : public Type, public llvm::FoldingSetNode { |
2623 | friend class ASTContext; // ASTContext creates these. |
2624 | |
2625 | QualType PointeeType; |
2626 | |
2627 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2628 | : Type(Pointer, CanonicalPtr, Pointee->getDependence()), |
2629 | PointeeType(Pointee) {} |
2630 | |
2631 | public: |
2632 | QualType getPointeeType() const { return PointeeType; } |
2633 | |
2634 | bool isSugared() const { return false; } |
2635 | QualType desugar() const { return QualType(this, 0); } |
2636 | |
2637 | void Profile(llvm::FoldingSetNodeID &ID) { |
2638 | Profile(ID, getPointeeType()); |
2639 | } |
2640 | |
2641 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2642 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2643 | } |
2644 | |
2645 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2646 | }; |
2647 | |
2648 | /// Represents a type which was implicitly adjusted by the semantic |
2649 | /// engine for arbitrary reasons. For example, array and function types can |
2650 | /// decay, and function types can have their calling conventions adjusted. |
2651 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2652 | QualType OriginalTy; |
2653 | QualType AdjustedTy; |
2654 | |
2655 | protected: |
2656 | friend class ASTContext; // ASTContext creates these. |
2657 | |
2658 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2659 | QualType CanonicalPtr) |
2660 | : Type(TC, CanonicalPtr, OriginalTy->getDependence()), |
2661 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2662 | |
2663 | public: |
2664 | QualType getOriginalType() const { return OriginalTy; } |
2665 | QualType getAdjustedType() const { return AdjustedTy; } |
2666 | |
2667 | bool isSugared() const { return true; } |
2668 | QualType desugar() const { return AdjustedTy; } |
2669 | |
2670 | void Profile(llvm::FoldingSetNodeID &ID) { |
2671 | Profile(ID, OriginalTy, AdjustedTy); |
2672 | } |
2673 | |
2674 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2675 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2676 | ID.AddPointer(New.getAsOpaquePtr()); |
2677 | } |
2678 | |
2679 | static bool classof(const Type *T) { |
2680 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2681 | } |
2682 | }; |
2683 | |
2684 | /// Represents a pointer type decayed from an array or function type. |
2685 | class DecayedType : public AdjustedType { |
2686 | friend class ASTContext; // ASTContext creates these. |
2687 | |
2688 | inline |
2689 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2690 | |
2691 | public: |
2692 | QualType getDecayedType() const { return getAdjustedType(); } |
2693 | |
2694 | inline QualType getPointeeType() const; |
2695 | |
2696 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2697 | }; |
2698 | |
2699 | /// Pointer to a block type. |
2700 | /// This type is to represent types syntactically represented as |
2701 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2702 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2703 | friend class ASTContext; // ASTContext creates these. |
2704 | |
2705 | // Block is some kind of pointer type |
2706 | QualType PointeeType; |
2707 | |
2708 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2709 | : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), |
2710 | PointeeType(Pointee) {} |
2711 | |
2712 | public: |
2713 | // Get the pointee type. Pointee is required to always be a function type. |
2714 | QualType getPointeeType() const { return PointeeType; } |
2715 | |
2716 | bool isSugared() const { return false; } |
2717 | QualType desugar() const { return QualType(this, 0); } |
2718 | |
2719 | void Profile(llvm::FoldingSetNodeID &ID) { |
2720 | Profile(ID, getPointeeType()); |
2721 | } |
2722 | |
2723 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2724 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2725 | } |
2726 | |
2727 | static bool classof(const Type *T) { |
2728 | return T->getTypeClass() == BlockPointer; |
2729 | } |
2730 | }; |
2731 | |
2732 | /// Base for LValueReferenceType and RValueReferenceType |
2733 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2734 | QualType PointeeType; |
2735 | |
2736 | protected: |
2737 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2738 | bool SpelledAsLValue) |
2739 | : Type(tc, CanonicalRef, Referencee->getDependence()), |
2740 | PointeeType(Referencee) { |
2741 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2742 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2743 | } |
2744 | |
2745 | public: |
2746 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2747 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2748 | |
2749 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2750 | |
2751 | QualType getPointeeType() const { |
2752 | // FIXME: this might strip inner qualifiers; okay? |
2753 | const ReferenceType *T = this; |
2754 | while (T->isInnerRef()) |
2755 | T = T->PointeeType->castAs<ReferenceType>(); |
2756 | return T->PointeeType; |
2757 | } |
2758 | |
2759 | void Profile(llvm::FoldingSetNodeID &ID) { |
2760 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2761 | } |
2762 | |
2763 | static void Profile(llvm::FoldingSetNodeID &ID, |
2764 | QualType Referencee, |
2765 | bool SpelledAsLValue) { |
2766 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2767 | ID.AddBoolean(SpelledAsLValue); |
2768 | } |
2769 | |
2770 | static bool classof(const Type *T) { |
2771 | return T->getTypeClass() == LValueReference || |
2772 | T->getTypeClass() == RValueReference; |
2773 | } |
2774 | }; |
2775 | |
2776 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2777 | class LValueReferenceType : public ReferenceType { |
2778 | friend class ASTContext; // ASTContext creates these |
2779 | |
2780 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2781 | bool SpelledAsLValue) |
2782 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2783 | SpelledAsLValue) {} |
2784 | |
2785 | public: |
2786 | bool isSugared() const { return false; } |
2787 | QualType desugar() const { return QualType(this, 0); } |
2788 | |
2789 | static bool classof(const Type *T) { |
2790 | return T->getTypeClass() == LValueReference; |
2791 | } |
2792 | }; |
2793 | |
2794 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2795 | class RValueReferenceType : public ReferenceType { |
2796 | friend class ASTContext; // ASTContext creates these |
2797 | |
2798 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2799 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2800 | |
2801 | public: |
2802 | bool isSugared() const { return false; } |
2803 | QualType desugar() const { return QualType(this, 0); } |
2804 | |
2805 | static bool classof(const Type *T) { |
2806 | return T->getTypeClass() == RValueReference; |
2807 | } |
2808 | }; |
2809 | |
2810 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2811 | /// |
2812 | /// This includes both pointers to data members and pointer to member functions. |
2813 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2814 | friend class ASTContext; // ASTContext creates these. |
2815 | |
2816 | QualType PointeeType; |
2817 | |
2818 | /// The class of which the pointee is a member. Must ultimately be a |
2819 | /// RecordType, but could be a typedef or a template parameter too. |
2820 | const Type *Class; |
2821 | |
2822 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2823 | : Type(MemberPointer, CanonicalPtr, |
2824 | (Cls->getDependence() & ~TypeDependence::VariablyModified) | |
2825 | Pointee->getDependence()), |
2826 | PointeeType(Pointee), Class(Cls) {} |
2827 | |
2828 | public: |
2829 | QualType getPointeeType() const { return PointeeType; } |
2830 | |
2831 | /// Returns true if the member type (i.e. the pointee type) is a |
2832 | /// function type rather than a data-member type. |
2833 | bool isMemberFunctionPointer() const { |
2834 | return PointeeType->isFunctionProtoType(); |
2835 | } |
2836 | |
2837 | /// Returns true if the member type (i.e. the pointee type) is a |
2838 | /// data type rather than a function type. |
2839 | bool isMemberDataPointer() const { |
2840 | return !PointeeType->isFunctionProtoType(); |
2841 | } |
2842 | |
2843 | const Type *getClass() const { return Class; } |
2844 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2845 | |
2846 | bool isSugared() const { return false; } |
2847 | QualType desugar() const { return QualType(this, 0); } |
2848 | |
2849 | void Profile(llvm::FoldingSetNodeID &ID) { |
2850 | Profile(ID, getPointeeType(), getClass()); |
2851 | } |
2852 | |
2853 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2854 | const Type *Class) { |
2855 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2856 | ID.AddPointer(Class); |
2857 | } |
2858 | |
2859 | static bool classof(const Type *T) { |
2860 | return T->getTypeClass() == MemberPointer; |
2861 | } |
2862 | }; |
2863 | |
2864 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2865 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2866 | public: |
2867 | /// Capture whether this is a normal array (e.g. int X[4]) |
2868 | /// an array with a static size (e.g. int X[static 4]), or an array |
2869 | /// with a star size (e.g. int X[*]). |
2870 | /// 'static' is only allowed on function parameters. |
2871 | enum ArraySizeModifier { |
2872 | Normal, Static, Star |
2873 | }; |
2874 | |
2875 | private: |
2876 | /// The element type of the array. |
2877 | QualType ElementType; |
2878 | |
2879 | protected: |
2880 | friend class ASTContext; // ASTContext creates these. |
2881 | |
2882 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2883 | unsigned tq, const Expr *sz = nullptr); |
2884 | |
2885 | public: |
2886 | QualType getElementType() const { return ElementType; } |
2887 | |
2888 | ArraySizeModifier getSizeModifier() const { |
2889 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2890 | } |
2891 | |
2892 | Qualifiers getIndexTypeQualifiers() const { |
2893 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2894 | } |
2895 | |
2896 | unsigned getIndexTypeCVRQualifiers() const { |
2897 | return ArrayTypeBits.IndexTypeQuals; |
2898 | } |
2899 | |
2900 | static bool classof(const Type *T) { |
2901 | return T->getTypeClass() == ConstantArray || |
2902 | T->getTypeClass() == VariableArray || |
2903 | T->getTypeClass() == IncompleteArray || |
2904 | T->getTypeClass() == DependentSizedArray; |
2905 | } |
2906 | }; |
2907 | |
2908 | /// Represents the canonical version of C arrays with a specified constant size. |
2909 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2910 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2911 | class ConstantArrayType final |
2912 | : public ArrayType, |
2913 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2914 | friend class ASTContext; // ASTContext creates these. |
2915 | friend TrailingObjects; |
2916 | |
2917 | llvm::APInt Size; // Allows us to unique the type. |
2918 | |
2919 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2920 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2921 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2922 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2923 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2924 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 2924, __PRETTY_FUNCTION__)); |
2925 | *getTrailingObjects<const Expr*>() = sz; |
2926 | } |
2927 | } |
2928 | |
2929 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2930 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2931 | } |
2932 | |
2933 | public: |
2934 | const llvm::APInt &getSize() const { return Size; } |
2935 | const Expr *getSizeExpr() const { |
2936 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2937 | ? *getTrailingObjects<const Expr *>() |
2938 | : nullptr; |
2939 | } |
2940 | bool isSugared() const { return false; } |
2941 | QualType desugar() const { return QualType(this, 0); } |
2942 | |
2943 | /// Determine the number of bits required to address a member of |
2944 | // an array with the given element type and number of elements. |
2945 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2946 | QualType ElementType, |
2947 | const llvm::APInt &NumElements); |
2948 | |
2949 | /// Determine the maximum number of active bits that an array's size |
2950 | /// can require, which limits the maximum size of the array. |
2951 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2952 | |
2953 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2954 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2955 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2956 | } |
2957 | |
2958 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2959 | QualType ET, const llvm::APInt &ArraySize, |
2960 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2961 | unsigned TypeQuals); |
2962 | |
2963 | static bool classof(const Type *T) { |
2964 | return T->getTypeClass() == ConstantArray; |
2965 | } |
2966 | }; |
2967 | |
2968 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2969 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2970 | /// unspecified. |
2971 | class IncompleteArrayType : public ArrayType { |
2972 | friend class ASTContext; // ASTContext creates these. |
2973 | |
2974 | IncompleteArrayType(QualType et, QualType can, |
2975 | ArraySizeModifier sm, unsigned tq) |
2976 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2977 | |
2978 | public: |
2979 | friend class StmtIteratorBase; |
2980 | |
2981 | bool isSugared() const { return false; } |
2982 | QualType desugar() const { return QualType(this, 0); } |
2983 | |
2984 | static bool classof(const Type *T) { |
2985 | return T->getTypeClass() == IncompleteArray; |
2986 | } |
2987 | |
2988 | void Profile(llvm::FoldingSetNodeID &ID) { |
2989 | Profile(ID, getElementType(), getSizeModifier(), |
2990 | getIndexTypeCVRQualifiers()); |
2991 | } |
2992 | |
2993 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2994 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2995 | ID.AddPointer(ET.getAsOpaquePtr()); |
2996 | ID.AddInteger(SizeMod); |
2997 | ID.AddInteger(TypeQuals); |
2998 | } |
2999 | }; |
3000 | |
3001 | /// Represents a C array with a specified size that is not an |
3002 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
3003 | /// Since the size expression is an arbitrary expression, we store it as such. |
3004 | /// |
3005 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3006 | /// should not be: two lexically equivalent variable array types could mean |
3007 | /// different things, for example, these variables do not have the same type |
3008 | /// dynamically: |
3009 | /// |
3010 | /// void foo(int x) { |
3011 | /// int Y[x]; |
3012 | /// ++x; |
3013 | /// int Z[x]; |
3014 | /// } |
3015 | class VariableArrayType : public ArrayType { |
3016 | friend class ASTContext; // ASTContext creates these. |
3017 | |
3018 | /// An assignment-expression. VLA's are only permitted within |
3019 | /// a function block. |
3020 | Stmt *SizeExpr; |
3021 | |
3022 | /// The range spanned by the left and right array brackets. |
3023 | SourceRange Brackets; |
3024 | |
3025 | VariableArrayType(QualType et, QualType can, Expr *e, |
3026 | ArraySizeModifier sm, unsigned tq, |
3027 | SourceRange brackets) |
3028 | : ArrayType(VariableArray, et, can, sm, tq, e), |
3029 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3030 | |
3031 | public: |
3032 | friend class StmtIteratorBase; |
3033 | |
3034 | Expr *getSizeExpr() const { |
3035 | // We use C-style casts instead of cast<> here because we do not wish |
3036 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3037 | return (Expr*) SizeExpr; |
3038 | } |
3039 | |
3040 | SourceRange getBracketsRange() const { return Brackets; } |
3041 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3042 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3043 | |
3044 | bool isSugared() const { return false; } |
3045 | QualType desugar() const { return QualType(this, 0); } |
3046 | |
3047 | static bool classof(const Type *T) { |
3048 | return T->getTypeClass() == VariableArray; |
3049 | } |
3050 | |
3051 | void Profile(llvm::FoldingSetNodeID &ID) { |
3052 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 3052); |
3053 | } |
3054 | }; |
3055 | |
3056 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3057 | /// |
3058 | /// For example: |
3059 | /// \code |
3060 | /// template<typename T, int Size> |
3061 | /// class array { |
3062 | /// T data[Size]; |
3063 | /// }; |
3064 | /// \endcode |
3065 | /// |
3066 | /// For these types, we won't actually know what the array bound is |
3067 | /// until template instantiation occurs, at which point this will |
3068 | /// become either a ConstantArrayType or a VariableArrayType. |
3069 | class DependentSizedArrayType : public ArrayType { |
3070 | friend class ASTContext; // ASTContext creates these. |
3071 | |
3072 | const ASTContext &Context; |
3073 | |
3074 | /// An assignment expression that will instantiate to the |
3075 | /// size of the array. |
3076 | /// |
3077 | /// The expression itself might be null, in which case the array |
3078 | /// type will have its size deduced from an initializer. |
3079 | Stmt *SizeExpr; |
3080 | |
3081 | /// The range spanned by the left and right array brackets. |
3082 | SourceRange Brackets; |
3083 | |
3084 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3085 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3086 | SourceRange brackets); |
3087 | |
3088 | public: |
3089 | friend class StmtIteratorBase; |
3090 | |
3091 | Expr *getSizeExpr() const { |
3092 | // We use C-style casts instead of cast<> here because we do not wish |
3093 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3094 | return (Expr*) SizeExpr; |
3095 | } |
3096 | |
3097 | SourceRange getBracketsRange() const { return Brackets; } |
3098 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3099 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3100 | |
3101 | bool isSugared() const { return false; } |
3102 | QualType desugar() const { return QualType(this, 0); } |
3103 | |
3104 | static bool classof(const Type *T) { |
3105 | return T->getTypeClass() == DependentSizedArray; |
3106 | } |
3107 | |
3108 | void Profile(llvm::FoldingSetNodeID &ID) { |
3109 | Profile(ID, Context, getElementType(), |
3110 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3111 | } |
3112 | |
3113 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3114 | QualType ET, ArraySizeModifier SizeMod, |
3115 | unsigned TypeQuals, Expr *E); |
3116 | }; |
3117 | |
3118 | /// Represents an extended address space qualifier where the input address space |
3119 | /// value is dependent. Non-dependent address spaces are not represented with a |
3120 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3121 | /// |
3122 | /// For example: |
3123 | /// \code |
3124 | /// template<typename T, int AddrSpace> |
3125 | /// class AddressSpace { |
3126 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3127 | /// } |
3128 | /// \endcode |
3129 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3130 | friend class ASTContext; |
3131 | |
3132 | const ASTContext &Context; |
3133 | Expr *AddrSpaceExpr; |
3134 | QualType PointeeType; |
3135 | SourceLocation loc; |
3136 | |
3137 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3138 | QualType can, Expr *AddrSpaceExpr, |
3139 | SourceLocation loc); |
3140 | |
3141 | public: |
3142 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3143 | QualType getPointeeType() const { return PointeeType; } |
3144 | SourceLocation getAttributeLoc() const { return loc; } |
3145 | |
3146 | bool isSugared() const { return false; } |
3147 | QualType desugar() const { return QualType(this, 0); } |
3148 | |
3149 | static bool classof(const Type *T) { |
3150 | return T->getTypeClass() == DependentAddressSpace; |
3151 | } |
3152 | |
3153 | void Profile(llvm::FoldingSetNodeID &ID) { |
3154 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3155 | } |
3156 | |
3157 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3158 | QualType PointeeType, Expr *AddrSpaceExpr); |
3159 | }; |
3160 | |
3161 | /// Represents an extended vector type where either the type or size is |
3162 | /// dependent. |
3163 | /// |
3164 | /// For example: |
3165 | /// \code |
3166 | /// template<typename T, int Size> |
3167 | /// class vector { |
3168 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3169 | /// } |
3170 | /// \endcode |
3171 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3172 | friend class ASTContext; |
3173 | |
3174 | const ASTContext &Context; |
3175 | Expr *SizeExpr; |
3176 | |
3177 | /// The element type of the array. |
3178 | QualType ElementType; |
3179 | |
3180 | SourceLocation loc; |
3181 | |
3182 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3183 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3184 | |
3185 | public: |
3186 | Expr *getSizeExpr() const { return SizeExpr; } |
3187 | QualType getElementType() const { return ElementType; } |
3188 | SourceLocation getAttributeLoc() const { return loc; } |
3189 | |
3190 | bool isSugared() const { return false; } |
3191 | QualType desugar() const { return QualType(this, 0); } |
3192 | |
3193 | static bool classof(const Type *T) { |
3194 | return T->getTypeClass() == DependentSizedExtVector; |
3195 | } |
3196 | |
3197 | void Profile(llvm::FoldingSetNodeID &ID) { |
3198 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3199 | } |
3200 | |
3201 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3202 | QualType ElementType, Expr *SizeExpr); |
3203 | }; |
3204 | |
3205 | |
3206 | /// Represents a GCC generic vector type. This type is created using |
3207 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3208 | /// bytes; or from an Altivec __vector or vector declaration. |
3209 | /// Since the constructor takes the number of vector elements, the |
3210 | /// client is responsible for converting the size into the number of elements. |
3211 | class VectorType : public Type, public llvm::FoldingSetNode { |
3212 | public: |
3213 | enum VectorKind { |
3214 | /// not a target-specific vector type |
3215 | GenericVector, |
3216 | |
3217 | /// is AltiVec vector |
3218 | AltiVecVector, |
3219 | |
3220 | /// is AltiVec 'vector Pixel' |
3221 | AltiVecPixel, |
3222 | |
3223 | /// is AltiVec 'vector bool ...' |
3224 | AltiVecBool, |
3225 | |
3226 | /// is ARM Neon vector |
3227 | NeonVector, |
3228 | |
3229 | /// is ARM Neon polynomial vector |
3230 | NeonPolyVector, |
3231 | |
3232 | /// is AArch64 SVE fixed-length data vector |
3233 | SveFixedLengthDataVector, |
3234 | |
3235 | /// is AArch64 SVE fixed-length predicate vector |
3236 | SveFixedLengthPredicateVector |
3237 | }; |
3238 | |
3239 | protected: |
3240 | friend class ASTContext; // ASTContext creates these. |
3241 | |
3242 | /// The element type of the vector. |
3243 | QualType ElementType; |
3244 | |
3245 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3246 | VectorKind vecKind); |
3247 | |
3248 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3249 | QualType canonType, VectorKind vecKind); |
3250 | |
3251 | public: |
3252 | QualType getElementType() const { return ElementType; } |
3253 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3254 | |
3255 | bool isSugared() const { return false; } |
3256 | QualType desugar() const { return QualType(this, 0); } |
3257 | |
3258 | VectorKind getVectorKind() const { |
3259 | return VectorKind(VectorTypeBits.VecKind); |
3260 | } |
3261 | |
3262 | void Profile(llvm::FoldingSetNodeID &ID) { |
3263 | Profile(ID, getElementType(), getNumElements(), |
3264 | getTypeClass(), getVectorKind()); |
3265 | } |
3266 | |
3267 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3268 | unsigned NumElements, TypeClass TypeClass, |
3269 | VectorKind VecKind) { |
3270 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3271 | ID.AddInteger(NumElements); |
3272 | ID.AddInteger(TypeClass); |
3273 | ID.AddInteger(VecKind); |
3274 | } |
3275 | |
3276 | static bool classof(const Type *T) { |
3277 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3278 | } |
3279 | }; |
3280 | |
3281 | /// Represents a vector type where either the type or size is dependent. |
3282 | //// |
3283 | /// For example: |
3284 | /// \code |
3285 | /// template<typename T, int Size> |
3286 | /// class vector { |
3287 | /// typedef T __attribute__((vector_size(Size))) type; |
3288 | /// } |
3289 | /// \endcode |
3290 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3291 | friend class ASTContext; |
3292 | |
3293 | const ASTContext &Context; |
3294 | QualType ElementType; |
3295 | Expr *SizeExpr; |
3296 | SourceLocation Loc; |
3297 | |
3298 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3299 | QualType CanonType, Expr *SizeExpr, |
3300 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3301 | |
3302 | public: |
3303 | Expr *getSizeExpr() const { return SizeExpr; } |
3304 | QualType getElementType() const { return ElementType; } |
3305 | SourceLocation getAttributeLoc() const { return Loc; } |
3306 | VectorType::VectorKind getVectorKind() const { |
3307 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3308 | } |
3309 | |
3310 | bool isSugared() const { return false; } |
3311 | QualType desugar() const { return QualType(this, 0); } |
3312 | |
3313 | static bool classof(const Type *T) { |
3314 | return T->getTypeClass() == DependentVector; |
3315 | } |
3316 | |
3317 | void Profile(llvm::FoldingSetNodeID &ID) { |
3318 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3319 | } |
3320 | |
3321 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3322 | QualType ElementType, const Expr *SizeExpr, |
3323 | VectorType::VectorKind VecKind); |
3324 | }; |
3325 | |
3326 | /// ExtVectorType - Extended vector type. This type is created using |
3327 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3328 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3329 | /// class enables syntactic extensions, like Vector Components for accessing |
3330 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3331 | /// Shading Language). |
3332 | class ExtVectorType : public VectorType { |
3333 | friend class ASTContext; // ASTContext creates these. |
3334 | |
3335 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3336 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3337 | |
3338 | public: |
3339 | static int getPointAccessorIdx(char c) { |
3340 | switch (c) { |
3341 | default: return -1; |
3342 | case 'x': case 'r': return 0; |
3343 | case 'y': case 'g': return 1; |
3344 | case 'z': case 'b': return 2; |
3345 | case 'w': case 'a': return 3; |
3346 | } |
3347 | } |
3348 | |
3349 | static int getNumericAccessorIdx(char c) { |
3350 | switch (c) { |
3351 | default: return -1; |
3352 | case '0': return 0; |
3353 | case '1': return 1; |
3354 | case '2': return 2; |
3355 | case '3': return 3; |
3356 | case '4': return 4; |
3357 | case '5': return 5; |
3358 | case '6': return 6; |
3359 | case '7': return 7; |
3360 | case '8': return 8; |
3361 | case '9': return 9; |
3362 | case 'A': |
3363 | case 'a': return 10; |
3364 | case 'B': |
3365 | case 'b': return 11; |
3366 | case 'C': |
3367 | case 'c': return 12; |
3368 | case 'D': |
3369 | case 'd': return 13; |
3370 | case 'E': |
3371 | case 'e': return 14; |
3372 | case 'F': |
3373 | case 'f': return 15; |
3374 | } |
3375 | } |
3376 | |
3377 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3378 | if (isNumericAccessor) |
3379 | return getNumericAccessorIdx(c); |
3380 | else |
3381 | return getPointAccessorIdx(c); |
3382 | } |
3383 | |
3384 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3385 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3386 | return unsigned(idx-1) < getNumElements(); |
3387 | return false; |
3388 | } |
3389 | |
3390 | bool isSugared() const { return false; } |
3391 | QualType desugar() const { return QualType(this, 0); } |
3392 | |
3393 | static bool classof(const Type *T) { |
3394 | return T->getTypeClass() == ExtVector; |
3395 | } |
3396 | }; |
3397 | |
3398 | /// Represents a matrix type, as defined in the Matrix Types clang extensions. |
3399 | /// __attribute__((matrix_type(rows, columns))), where "rows" specifies |
3400 | /// number of rows and "columns" specifies the number of columns. |
3401 | class MatrixType : public Type, public llvm::FoldingSetNode { |
3402 | protected: |
3403 | friend class ASTContext; |
3404 | |
3405 | /// The element type of the matrix. |
3406 | QualType ElementType; |
3407 | |
3408 | MatrixType(QualType ElementTy, QualType CanonElementTy); |
3409 | |
3410 | MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, |
3411 | const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); |
3412 | |
3413 | public: |
3414 | /// Returns type of the elements being stored in the matrix |
3415 | QualType getElementType() const { return ElementType; } |
3416 | |
3417 | /// Valid elements types are the following: |
3418 | /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types |
3419 | /// and _Bool |
3420 | /// * the standard floating types float or double |
3421 | /// * a half-precision floating point type, if one is supported on the target |
3422 | static bool isValidElementType(QualType T) { |
3423 | return T->isDependentType() || |
3424 | (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); |
3425 | } |
3426 | |
3427 | bool isSugared() const { return false; } |
3428 | QualType desugar() const { return QualType(this, 0); } |
3429 | |
3430 | static bool classof(const Type *T) { |
3431 | return T->getTypeClass() == ConstantMatrix || |
3432 | T->getTypeClass() == DependentSizedMatrix; |
3433 | } |
3434 | }; |
3435 | |
3436 | /// Represents a concrete matrix type with constant number of rows and columns |
3437 | class ConstantMatrixType final : public MatrixType { |
3438 | protected: |
3439 | friend class ASTContext; |
3440 | |
3441 | /// The element type of the matrix. |
3442 | // FIXME: Appears to be unused? There is also MatrixType::ElementType... |
3443 | QualType ElementType; |
3444 | |
3445 | /// Number of rows and columns. |
3446 | unsigned NumRows; |
3447 | unsigned NumColumns; |
3448 | |
3449 | static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1; |
3450 | |
3451 | ConstantMatrixType(QualType MatrixElementType, unsigned NRows, |
3452 | unsigned NColumns, QualType CanonElementType); |
3453 | |
3454 | ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, |
3455 | unsigned NColumns, QualType CanonElementType); |
3456 | |
3457 | public: |
3458 | /// Returns the number of rows in the matrix. |
3459 | unsigned getNumRows() const { return NumRows; } |
3460 | |
3461 | /// Returns the number of columns in the matrix. |
3462 | unsigned getNumColumns() const { return NumColumns; } |
3463 | |
3464 | /// Returns the number of elements required to embed the matrix into a vector. |
3465 | unsigned getNumElementsFlattened() const { |
3466 | return getNumRows() * getNumColumns(); |
3467 | } |
3468 | |
3469 | /// Returns true if \p NumElements is a valid matrix dimension. |
3470 | static constexpr bool isDimensionValid(size_t NumElements) { |
3471 | return NumElements > 0 && NumElements <= MaxElementsPerDimension; |
3472 | } |
3473 | |
3474 | /// Returns the maximum number of elements per dimension. |
3475 | static constexpr unsigned getMaxElementsPerDimension() { |
3476 | return MaxElementsPerDimension; |
3477 | } |
3478 | |
3479 | void Profile(llvm::FoldingSetNodeID &ID) { |
3480 | Profile(ID, getElementType(), getNumRows(), getNumColumns(), |
3481 | getTypeClass()); |
3482 | } |
3483 | |
3484 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3485 | unsigned NumRows, unsigned NumColumns, |
3486 | TypeClass TypeClass) { |
3487 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3488 | ID.AddInteger(NumRows); |
3489 | ID.AddInteger(NumColumns); |
3490 | ID.AddInteger(TypeClass); |
3491 | } |
3492 | |
3493 | static bool classof(const Type *T) { |
3494 | return T->getTypeClass() == ConstantMatrix; |
3495 | } |
3496 | }; |
3497 | |
3498 | /// Represents a matrix type where the type and the number of rows and columns |
3499 | /// is dependent on a template. |
3500 | class DependentSizedMatrixType final : public MatrixType { |
3501 | friend class ASTContext; |
3502 | |
3503 | const ASTContext &Context; |
3504 | Expr *RowExpr; |
3505 | Expr *ColumnExpr; |
3506 | |
3507 | SourceLocation loc; |
3508 | |
3509 | DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, |
3510 | QualType CanonicalType, Expr *RowExpr, |
3511 | Expr *ColumnExpr, SourceLocation loc); |
3512 | |
3513 | public: |
3514 | QualType getElementType() const { return ElementType; } |
3515 | Expr *getRowExpr() const { return RowExpr; } |
3516 | Expr *getColumnExpr() const { return ColumnExpr; } |
3517 | SourceLocation getAttributeLoc() const { return loc; } |
3518 | |
3519 | bool isSugared() const { return false; } |
3520 | QualType desugar() const { return QualType(this, 0); } |
3521 | |
3522 | static bool classof(const Type *T) { |
3523 | return T->getTypeClass() == DependentSizedMatrix; |
3524 | } |
3525 | |
3526 | void Profile(llvm::FoldingSetNodeID &ID) { |
3527 | Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); |
3528 | } |
3529 | |
3530 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3531 | QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); |
3532 | }; |
3533 | |
3534 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3535 | /// class of FunctionNoProtoType and FunctionProtoType. |
3536 | class FunctionType : public Type { |
3537 | // The type returned by the function. |
3538 | QualType ResultType; |
3539 | |
3540 | public: |
3541 | /// Interesting information about a specific parameter that can't simply |
3542 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3543 | /// but is in FunctionType to make this class available during the |
3544 | /// specification of the bases of FunctionProtoType. |
3545 | /// |
3546 | /// It makes sense to model language features this way when there's some |
3547 | /// sort of parameter-specific override (such as an attribute) that |
3548 | /// affects how the function is called. For example, the ARC ns_consumed |
3549 | /// attribute changes whether a parameter is passed at +0 (the default) |
3550 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3551 | /// but isn't really a change to the parameter type. |
3552 | /// |
3553 | /// One serious disadvantage of modelling language features this way is |
3554 | /// that they generally do not work with language features that attempt |
3555 | /// to destructure types. For example, template argument deduction will |
3556 | /// not be able to match a parameter declared as |
3557 | /// T (*)(U) |
3558 | /// against an argument of type |
3559 | /// void (*)(__attribute__((ns_consumed)) id) |
3560 | /// because the substitution of T=void, U=id into the former will |
3561 | /// not produce the latter. |
3562 | class ExtParameterInfo { |
3563 | enum { |
3564 | ABIMask = 0x0F, |
3565 | IsConsumed = 0x10, |
3566 | HasPassObjSize = 0x20, |
3567 | IsNoEscape = 0x40, |
3568 | }; |
3569 | unsigned char Data = 0; |
3570 | |
3571 | public: |
3572 | ExtParameterInfo() = default; |
3573 | |
3574 | /// Return the ABI treatment of this parameter. |
3575 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3576 | ExtParameterInfo withABI(ParameterABI kind) const { |
3577 | ExtParameterInfo copy = *this; |
3578 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3579 | return copy; |
3580 | } |
3581 | |
3582 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3583 | /// Consumed parameters must have retainable object type. |
3584 | bool isConsumed() const { return (Data & IsConsumed); } |
3585 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3586 | ExtParameterInfo copy = *this; |
3587 | if (consumed) |
3588 | copy.Data |= IsConsumed; |
3589 | else |
3590 | copy.Data &= ~IsConsumed; |
3591 | return copy; |
3592 | } |
3593 | |
3594 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3595 | ExtParameterInfo withHasPassObjectSize() const { |
3596 | ExtParameterInfo Copy = *this; |
3597 | Copy.Data |= HasPassObjSize; |
3598 | return Copy; |
3599 | } |
3600 | |
3601 | bool isNoEscape() const { return Data & IsNoEscape; } |
3602 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3603 | ExtParameterInfo Copy = *this; |
3604 | if (NoEscape) |
3605 | Copy.Data |= IsNoEscape; |
3606 | else |
3607 | Copy.Data &= ~IsNoEscape; |
3608 | return Copy; |
3609 | } |
3610 | |
3611 | unsigned char getOpaqueValue() const { return Data; } |
3612 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3613 | ExtParameterInfo result; |
3614 | result.Data = data; |
3615 | return result; |
3616 | } |
3617 | |
3618 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3619 | return lhs.Data == rhs.Data; |
3620 | } |
3621 | |
3622 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3623 | return lhs.Data != rhs.Data; |
3624 | } |
3625 | }; |
3626 | |
3627 | /// A class which abstracts out some details necessary for |
3628 | /// making a call. |
3629 | /// |
3630 | /// It is not actually used directly for storing this information in |
3631 | /// a FunctionType, although FunctionType does currently use the |
3632 | /// same bit-pattern. |
3633 | /// |
3634 | // If you add a field (say Foo), other than the obvious places (both, |
3635 | // constructors, compile failures), what you need to update is |
3636 | // * Operator== |
3637 | // * getFoo |
3638 | // * withFoo |
3639 | // * functionType. Add Foo, getFoo. |
3640 | // * ASTContext::getFooType |
3641 | // * ASTContext::mergeFunctionTypes |
3642 | // * FunctionNoProtoType::Profile |
3643 | // * FunctionProtoType::Profile |
3644 | // * TypePrinter::PrintFunctionProto |
3645 | // * AST read and write |
3646 | // * Codegen |
3647 | class ExtInfo { |
3648 | friend class FunctionType; |
3649 | |
3650 | // Feel free to rearrange or add bits, but if you go over 16, you'll need to |
3651 | // adjust the Bits field below, and if you add bits, you'll need to adjust |
3652 | // Type::FunctionTypeBitfields::ExtInfo as well. |
3653 | |
3654 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| |
3655 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | |
3656 | // |
3657 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3658 | enum { CallConvMask = 0x1F }; |
3659 | enum { NoReturnMask = 0x20 }; |
3660 | enum { ProducesResultMask = 0x40 }; |
3661 | enum { NoCallerSavedRegsMask = 0x80 }; |
3662 | enum { |
3663 | RegParmMask = 0x700, |
3664 | RegParmOffset = 8 |
3665 | }; |
3666 | enum { NoCfCheckMask = 0x800 }; |
3667 | enum { CmseNSCallMask = 0x1000 }; |
3668 | uint16_t Bits = CC_C; |
3669 | |
3670 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3671 | |
3672 | public: |
3673 | // Constructor with no defaults. Use this when you know that you |
3674 | // have all the elements (when reading an AST file for example). |
3675 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3676 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, |
3677 | bool cmseNSCall) { |
3678 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 3678, __PRETTY_FUNCTION__)); |
3679 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3680 | (producesResult ? ProducesResultMask : 0) | |
3681 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3682 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3683 | (NoCfCheck ? NoCfCheckMask : 0) | |
3684 | (cmseNSCall ? CmseNSCallMask : 0); |
3685 | } |
3686 | |
3687 | // Constructor with all defaults. Use when for example creating a |
3688 | // function known to use defaults. |
3689 | ExtInfo() = default; |
3690 | |
3691 | // Constructor with just the calling convention, which is an important part |
3692 | // of the canonical type. |
3693 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3694 | |
3695 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3696 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3697 | bool getCmseNSCall() const { return Bits & CmseNSCallMask; } |
3698 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3699 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3700 | bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } |
3701 | |
3702 | unsigned getRegParm() const { |
3703 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3704 | if (RegParm > 0) |
3705 | --RegParm; |
3706 | return RegParm; |
3707 | } |
3708 | |
3709 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3710 | |
3711 | bool operator==(ExtInfo Other) const { |
3712 | return Bits == Other.Bits; |
3713 | } |
3714 | bool operator!=(ExtInfo Other) const { |
3715 | return Bits != Other.Bits; |
3716 | } |
3717 | |
3718 | // Note that we don't have setters. That is by design, use |
3719 | // the following with methods instead of mutating these objects. |
3720 | |
3721 | ExtInfo withNoReturn(bool noReturn) const { |
3722 | if (noReturn) |
3723 | return ExtInfo(Bits | NoReturnMask); |
3724 | else |
3725 | return ExtInfo(Bits & ~NoReturnMask); |
3726 | } |
3727 | |
3728 | ExtInfo withProducesResult(bool producesResult) const { |
3729 | if (producesResult) |
3730 | return ExtInfo(Bits | ProducesResultMask); |
3731 | else |
3732 | return ExtInfo(Bits & ~ProducesResultMask); |
3733 | } |
3734 | |
3735 | ExtInfo withCmseNSCall(bool cmseNSCall) const { |
3736 | if (cmseNSCall) |
3737 | return ExtInfo(Bits | CmseNSCallMask); |
3738 | else |
3739 | return ExtInfo(Bits & ~CmseNSCallMask); |
3740 | } |
3741 | |
3742 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3743 | if (noCallerSavedRegs) |
3744 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3745 | else |
3746 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3747 | } |
3748 | |
3749 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3750 | if (noCfCheck) |
3751 | return ExtInfo(Bits | NoCfCheckMask); |
3752 | else |
3753 | return ExtInfo(Bits & ~NoCfCheckMask); |
3754 | } |
3755 | |
3756 | ExtInfo withRegParm(unsigned RegParm) const { |
3757 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 3757, __PRETTY_FUNCTION__)); |
3758 | return ExtInfo((Bits & ~RegParmMask) | |
3759 | ((RegParm + 1) << RegParmOffset)); |
3760 | } |
3761 | |
3762 | ExtInfo withCallingConv(CallingConv cc) const { |
3763 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3764 | } |
3765 | |
3766 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3767 | ID.AddInteger(Bits); |
3768 | } |
3769 | }; |
3770 | |
3771 | /// A simple holder for a QualType representing a type in an |
3772 | /// exception specification. Unfortunately needed by FunctionProtoType |
3773 | /// because TrailingObjects cannot handle repeated types. |
3774 | struct ExceptionType { QualType Type; }; |
3775 | |
3776 | /// A simple holder for various uncommon bits which do not fit in |
3777 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3778 | /// alignment of subsequent objects in TrailingObjects. You must update |
3779 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3780 | struct alignas(void *) FunctionTypeExtraBitfields { |
3781 | /// The number of types in the exception specification. |
3782 | /// A whole unsigned is not needed here and according to |
3783 | /// [implimits] 8 bits would be enough here. |
3784 | unsigned NumExceptionType; |
3785 | }; |
3786 | |
3787 | protected: |
3788 | FunctionType(TypeClass tc, QualType res, QualType Canonical, |
3789 | TypeDependence Dependence, ExtInfo Info) |
3790 | : Type(tc, Canonical, Dependence), ResultType(res) { |
3791 | FunctionTypeBits.ExtInfo = Info.Bits; |
3792 | } |
3793 | |
3794 | Qualifiers getFastTypeQuals() const { |
3795 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3796 | } |
3797 | |
3798 | public: |
3799 | QualType getReturnType() const { return ResultType; } |
3800 | |
3801 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3802 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3803 | |
3804 | /// Determine whether this function type includes the GNU noreturn |
3805 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3806 | /// type. |
3807 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3808 | |
3809 | bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } |
3810 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3811 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3812 | |
3813 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3814 | "Const, volatile and restrict are assumed to be a subset of " |
3815 | "the fast qualifiers."); |
3816 | |
3817 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3818 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3819 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3820 | |
3821 | /// Determine the type of an expression that calls a function of |
3822 | /// this type. |
3823 | QualType getCallResultType(const ASTContext &Context) const { |
3824 | return getReturnType().getNonLValueExprType(Context); |
3825 | } |
3826 | |
3827 | static StringRef getNameForCallConv(CallingConv CC); |
3828 | |
3829 | static bool classof(const Type *T) { |
3830 | return T->getTypeClass() == FunctionNoProto || |
3831 | T->getTypeClass() == FunctionProto; |
3832 | } |
3833 | }; |
3834 | |
3835 | /// Represents a K&R-style 'int foo()' function, which has |
3836 | /// no information available about its arguments. |
3837 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3838 | friend class ASTContext; // ASTContext creates these. |
3839 | |
3840 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3841 | : FunctionType(FunctionNoProto, Result, Canonical, |
3842 | Result->getDependence() & |
3843 | ~(TypeDependence::DependentInstantiation | |
3844 | TypeDependence::UnexpandedPack), |
3845 | Info) {} |
3846 | |
3847 | public: |
3848 | // No additional state past what FunctionType provides. |
3849 | |
3850 | bool isSugared() const { return false; } |
3851 | QualType desugar() const { return QualType(this, 0); } |
3852 | |
3853 | void Profile(llvm::FoldingSetNodeID &ID) { |
3854 | Profile(ID, getReturnType(), getExtInfo()); |
3855 | } |
3856 | |
3857 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3858 | ExtInfo Info) { |
3859 | Info.Profile(ID); |
3860 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3861 | } |
3862 | |
3863 | static bool classof(const Type *T) { |
3864 | return T->getTypeClass() == FunctionNoProto; |
3865 | } |
3866 | }; |
3867 | |
3868 | /// Represents a prototype with parameter type info, e.g. |
3869 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3870 | /// parameters, not as having a single void parameter. Such a type can have |
3871 | /// an exception specification, but this specification is not part of the |
3872 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3873 | /// which optional. For more information about the trailing objects see |
3874 | /// the first comment inside FunctionProtoType. |
3875 | class FunctionProtoType final |
3876 | : public FunctionType, |
3877 | public llvm::FoldingSetNode, |
3878 | private llvm::TrailingObjects< |
3879 | FunctionProtoType, QualType, SourceLocation, |
3880 | FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, |
3881 | Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { |
3882 | friend class ASTContext; // ASTContext creates these. |
3883 | friend TrailingObjects; |
3884 | |
3885 | // FunctionProtoType is followed by several trailing objects, some of |
3886 | // which optional. They are in order: |
3887 | // |
3888 | // * An array of getNumParams() QualType holding the parameter types. |
3889 | // Always present. Note that for the vast majority of FunctionProtoType, |
3890 | // these will be the only trailing objects. |
3891 | // |
3892 | // * Optionally if the function is variadic, the SourceLocation of the |
3893 | // ellipsis. |
3894 | // |
3895 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3896 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3897 | // a single FunctionTypeExtraBitfields. Present if and only if |
3898 | // hasExtraBitfields() is true. |
3899 | // |
3900 | // * Optionally exactly one of: |
3901 | // * an array of getNumExceptions() ExceptionType, |
3902 | // * a single Expr *, |
3903 | // * a pair of FunctionDecl *, |
3904 | // * a single FunctionDecl * |
3905 | // used to store information about the various types of exception |
3906 | // specification. See getExceptionSpecSize for the details. |
3907 | // |
3908 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3909 | // an ExtParameterInfo for each of the parameters. Present if and |
3910 | // only if hasExtParameterInfos() is true. |
3911 | // |
3912 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3913 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3914 | // if hasExtQualifiers() is true. |
3915 | // |
3916 | // The optional FunctionTypeExtraBitfields has to be before the data |
3917 | // related to the exception specification since it contains the number |
3918 | // of exception types. |
3919 | // |
3920 | // We put the ExtParameterInfos last. If all were equal, it would make |
3921 | // more sense to put these before the exception specification, because |
3922 | // it's much easier to skip past them compared to the elaborate switch |
3923 | // required to skip the exception specification. However, all is not |
3924 | // equal; ExtParameterInfos are used to model very uncommon features, |
3925 | // and it's better not to burden the more common paths. |
3926 | |
3927 | public: |
3928 | /// Holds information about the various types of exception specification. |
3929 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3930 | /// used to group together the various bits of information about the |
3931 | /// exception specification. |
3932 | struct ExceptionSpecInfo { |
3933 | /// The kind of exception specification this is. |
3934 | ExceptionSpecificationType Type = EST_None; |
3935 | |
3936 | /// Explicitly-specified list of exception types. |
3937 | ArrayRef<QualType> Exceptions; |
3938 | |
3939 | /// Noexcept expression, if this is a computed noexcept specification. |
3940 | Expr *NoexceptExpr = nullptr; |
3941 | |
3942 | /// The function whose exception specification this is, for |
3943 | /// EST_Unevaluated and EST_Uninstantiated. |
3944 | FunctionDecl *SourceDecl = nullptr; |
3945 | |
3946 | /// The function template whose exception specification this is instantiated |
3947 | /// from, for EST_Uninstantiated. |
3948 | FunctionDecl *SourceTemplate = nullptr; |
3949 | |
3950 | ExceptionSpecInfo() = default; |
3951 | |
3952 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3953 | }; |
3954 | |
3955 | /// Extra information about a function prototype. ExtProtoInfo is not |
3956 | /// stored as such in FunctionProtoType but is used to group together |
3957 | /// the various bits of extra information about a function prototype. |
3958 | struct ExtProtoInfo { |
3959 | FunctionType::ExtInfo ExtInfo; |
3960 | bool Variadic : 1; |
3961 | bool HasTrailingReturn : 1; |
3962 | Qualifiers TypeQuals; |
3963 | RefQualifierKind RefQualifier = RQ_None; |
3964 | ExceptionSpecInfo ExceptionSpec; |
3965 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3966 | SourceLocation EllipsisLoc; |
3967 | |
3968 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3969 | |
3970 | ExtProtoInfo(CallingConv CC) |
3971 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3972 | |
3973 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3974 | ExtProtoInfo Result(*this); |
3975 | Result.ExceptionSpec = ESI; |
3976 | return Result; |
3977 | } |
3978 | }; |
3979 | |
3980 | private: |
3981 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3982 | return getNumParams(); |
3983 | } |
3984 | |
3985 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
3986 | return isVariadic(); |
3987 | } |
3988 | |
3989 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3990 | return hasExtraBitfields(); |
3991 | } |
3992 | |
3993 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3994 | return getExceptionSpecSize().NumExceptionType; |
3995 | } |
3996 | |
3997 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
3998 | return getExceptionSpecSize().NumExprPtr; |
3999 | } |
4000 | |
4001 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
4002 | return getExceptionSpecSize().NumFunctionDeclPtr; |
4003 | } |
4004 | |
4005 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
4006 | return hasExtParameterInfos() ? getNumParams() : 0; |
4007 | } |
4008 | |
4009 | /// Determine whether there are any argument types that |
4010 | /// contain an unexpanded parameter pack. |
4011 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
4012 | unsigned numArgs) { |
4013 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
4014 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
4015 | return true; |
4016 | |
4017 | return false; |
4018 | } |
4019 | |
4020 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
4021 | QualType canonical, const ExtProtoInfo &epi); |
4022 | |
4023 | /// This struct is returned by getExceptionSpecSize and is used to |
4024 | /// translate an ExceptionSpecificationType to the number and kind |
4025 | /// of trailing objects related to the exception specification. |
4026 | struct ExceptionSpecSizeHolder { |
4027 | unsigned NumExceptionType; |
4028 | unsigned NumExprPtr; |
4029 | unsigned NumFunctionDeclPtr; |
4030 | }; |
4031 | |
4032 | /// Return the number and kind of trailing objects |
4033 | /// related to the exception specification. |
4034 | static ExceptionSpecSizeHolder |
4035 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
4036 | switch (EST) { |
4037 | case EST_None: |
4038 | case EST_DynamicNone: |
4039 | case EST_MSAny: |
4040 | case EST_BasicNoexcept: |
4041 | case EST_Unparsed: |
4042 | case EST_NoThrow: |
4043 | return {0, 0, 0}; |
4044 | |
4045 | case EST_Dynamic: |
4046 | return {NumExceptions, 0, 0}; |
4047 | |
4048 | case EST_DependentNoexcept: |
4049 | case EST_NoexceptFalse: |
4050 | case EST_NoexceptTrue: |
4051 | return {0, 1, 0}; |
4052 | |
4053 | case EST_Uninstantiated: |
4054 | return {0, 0, 2}; |
4055 | |
4056 | case EST_Unevaluated: |
4057 | return {0, 0, 1}; |
4058 | } |
4059 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4059); |
4060 | } |
4061 | |
4062 | /// Return the number and kind of trailing objects |
4063 | /// related to the exception specification. |
4064 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
4065 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
4066 | } |
4067 | |
4068 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4069 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
4070 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
4071 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
4072 | return EST == EST_Dynamic; |
4073 | } |
4074 | |
4075 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4076 | bool hasExtraBitfields() const { |
4077 | return hasExtraBitfields(getExceptionSpecType()); |
4078 | } |
4079 | |
4080 | bool hasExtQualifiers() const { |
4081 | return FunctionTypeBits.HasExtQuals; |
4082 | } |
4083 | |
4084 | public: |
4085 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
4086 | |
4087 | QualType getParamType(unsigned i) const { |
4088 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4088, __PRETTY_FUNCTION__)); |
4089 | return param_type_begin()[i]; |
4090 | } |
4091 | |
4092 | ArrayRef<QualType> getParamTypes() const { |
4093 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
4094 | } |
4095 | |
4096 | ExtProtoInfo getExtProtoInfo() const { |
4097 | ExtProtoInfo EPI; |
4098 | EPI.ExtInfo = getExtInfo(); |
4099 | EPI.Variadic = isVariadic(); |
4100 | EPI.EllipsisLoc = getEllipsisLoc(); |
4101 | EPI.HasTrailingReturn = hasTrailingReturn(); |
4102 | EPI.ExceptionSpec = getExceptionSpecInfo(); |
4103 | EPI.TypeQuals = getMethodQuals(); |
4104 | EPI.RefQualifier = getRefQualifier(); |
4105 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
4106 | return EPI; |
4107 | } |
4108 | |
4109 | /// Get the kind of exception specification on this function. |
4110 | ExceptionSpecificationType getExceptionSpecType() const { |
4111 | return static_cast<ExceptionSpecificationType>( |
4112 | FunctionTypeBits.ExceptionSpecType); |
4113 | } |
4114 | |
4115 | /// Return whether this function has any kind of exception spec. |
4116 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
4117 | |
4118 | /// Return whether this function has a dynamic (throw) exception spec. |
4119 | bool hasDynamicExceptionSpec() const { |
4120 | return isDynamicExceptionSpec(getExceptionSpecType()); |
4121 | } |
4122 | |
4123 | /// Return whether this function has a noexcept exception spec. |
4124 | bool hasNoexceptExceptionSpec() const { |
4125 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
4126 | } |
4127 | |
4128 | /// Return whether this function has a dependent exception spec. |
4129 | bool hasDependentExceptionSpec() const; |
4130 | |
4131 | /// Return whether this function has an instantiation-dependent exception |
4132 | /// spec. |
4133 | bool hasInstantiationDependentExceptionSpec() const; |
4134 | |
4135 | /// Return all the available information about this type's exception spec. |
4136 | ExceptionSpecInfo getExceptionSpecInfo() const { |
4137 | ExceptionSpecInfo Result; |
4138 | Result.Type = getExceptionSpecType(); |
4139 | if (Result.Type == EST_Dynamic) { |
4140 | Result.Exceptions = exceptions(); |
4141 | } else if (isComputedNoexcept(Result.Type)) { |
4142 | Result.NoexceptExpr = getNoexceptExpr(); |
4143 | } else if (Result.Type == EST_Uninstantiated) { |
4144 | Result.SourceDecl = getExceptionSpecDecl(); |
4145 | Result.SourceTemplate = getExceptionSpecTemplate(); |
4146 | } else if (Result.Type == EST_Unevaluated) { |
4147 | Result.SourceDecl = getExceptionSpecDecl(); |
4148 | } |
4149 | return Result; |
4150 | } |
4151 | |
4152 | /// Return the number of types in the exception specification. |
4153 | unsigned getNumExceptions() const { |
4154 | return getExceptionSpecType() == EST_Dynamic |
4155 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
4156 | ->NumExceptionType |
4157 | : 0; |
4158 | } |
4159 | |
4160 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
4161 | QualType getExceptionType(unsigned i) const { |
4162 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4162, __PRETTY_FUNCTION__)); |
4163 | return exception_begin()[i]; |
4164 | } |
4165 | |
4166 | /// Return the expression inside noexcept(expression), or a null pointer |
4167 | /// if there is none (because the exception spec is not of this form). |
4168 | Expr *getNoexceptExpr() const { |
4169 | if (!isComputedNoexcept(getExceptionSpecType())) |
4170 | return nullptr; |
4171 | return *getTrailingObjects<Expr *>(); |
4172 | } |
4173 | |
4174 | /// If this function type has an exception specification which hasn't |
4175 | /// been determined yet (either because it has not been evaluated or because |
4176 | /// it has not been instantiated), this is the function whose exception |
4177 | /// specification is represented by this type. |
4178 | FunctionDecl *getExceptionSpecDecl() const { |
4179 | if (getExceptionSpecType() != EST_Uninstantiated && |
4180 | getExceptionSpecType() != EST_Unevaluated) |
4181 | return nullptr; |
4182 | return getTrailingObjects<FunctionDecl *>()[0]; |
4183 | } |
4184 | |
4185 | /// If this function type has an uninstantiated exception |
4186 | /// specification, this is the function whose exception specification |
4187 | /// should be instantiated to find the exception specification for |
4188 | /// this type. |
4189 | FunctionDecl *getExceptionSpecTemplate() const { |
4190 | if (getExceptionSpecType() != EST_Uninstantiated) |
4191 | return nullptr; |
4192 | return getTrailingObjects<FunctionDecl *>()[1]; |
4193 | } |
4194 | |
4195 | /// Determine whether this function type has a non-throwing exception |
4196 | /// specification. |
4197 | CanThrowResult canThrow() const; |
4198 | |
4199 | /// Determine whether this function type has a non-throwing exception |
4200 | /// specification. If this depends on template arguments, returns |
4201 | /// \c ResultIfDependent. |
4202 | bool isNothrow(bool ResultIfDependent = false) const { |
4203 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4204 | } |
4205 | |
4206 | /// Whether this function prototype is variadic. |
4207 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4208 | |
4209 | SourceLocation getEllipsisLoc() const { |
4210 | return isVariadic() ? *getTrailingObjects<SourceLocation>() |
4211 | : SourceLocation(); |
4212 | } |
4213 | |
4214 | /// Determines whether this function prototype contains a |
4215 | /// parameter pack at the end. |
4216 | /// |
4217 | /// A function template whose last parameter is a parameter pack can be |
4218 | /// called with an arbitrary number of arguments, much like a variadic |
4219 | /// function. |
4220 | bool isTemplateVariadic() const; |
4221 | |
4222 | /// Whether this function prototype has a trailing return type. |
4223 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4224 | |
4225 | Qualifiers getMethodQuals() const { |
4226 | if (hasExtQualifiers()) |
4227 | return *getTrailingObjects<Qualifiers>(); |
4228 | else |
4229 | return getFastTypeQuals(); |
4230 | } |
4231 | |
4232 | /// Retrieve the ref-qualifier associated with this function type. |
4233 | RefQualifierKind getRefQualifier() const { |
4234 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4235 | } |
4236 | |
4237 | using param_type_iterator = const QualType *; |
4238 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4239 | |
4240 | param_type_range param_types() const { |
4241 | return param_type_range(param_type_begin(), param_type_end()); |
4242 | } |
4243 | |
4244 | param_type_iterator param_type_begin() const { |
4245 | return getTrailingObjects<QualType>(); |
4246 | } |
4247 | |
4248 | param_type_iterator param_type_end() const { |
4249 | return param_type_begin() + getNumParams(); |
4250 | } |
4251 | |
4252 | using exception_iterator = const QualType *; |
4253 | |
4254 | ArrayRef<QualType> exceptions() const { |
4255 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4256 | } |
4257 | |
4258 | exception_iterator exception_begin() const { |
4259 | return reinterpret_cast<exception_iterator>( |
4260 | getTrailingObjects<ExceptionType>()); |
4261 | } |
4262 | |
4263 | exception_iterator exception_end() const { |
4264 | return exception_begin() + getNumExceptions(); |
4265 | } |
4266 | |
4267 | /// Is there any interesting extra information for any of the parameters |
4268 | /// of this function type? |
4269 | bool hasExtParameterInfos() const { |
4270 | return FunctionTypeBits.HasExtParameterInfos; |
4271 | } |
4272 | |
4273 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4274 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4274, __PRETTY_FUNCTION__)); |
4275 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4276 | getNumParams()); |
4277 | } |
4278 | |
4279 | /// Return a pointer to the beginning of the array of extra parameter |
4280 | /// information, if present, or else null if none of the parameters |
4281 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4282 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4283 | if (!hasExtParameterInfos()) |
4284 | return nullptr; |
4285 | return getTrailingObjects<ExtParameterInfo>(); |
4286 | } |
4287 | |
4288 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4289 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4289, __PRETTY_FUNCTION__)); |
4290 | if (hasExtParameterInfos()) |
4291 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4292 | return ExtParameterInfo(); |
4293 | } |
4294 | |
4295 | ParameterABI getParameterABI(unsigned I) const { |
4296 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4296, __PRETTY_FUNCTION__)); |
4297 | if (hasExtParameterInfos()) |
4298 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4299 | return ParameterABI::Ordinary; |
4300 | } |
4301 | |
4302 | bool isParamConsumed(unsigned I) const { |
4303 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4303, __PRETTY_FUNCTION__)); |
4304 | if (hasExtParameterInfos()) |
4305 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4306 | return false; |
4307 | } |
4308 | |
4309 | bool isSugared() const { return false; } |
4310 | QualType desugar() const { return QualType(this, 0); } |
4311 | |
4312 | void printExceptionSpecification(raw_ostream &OS, |
4313 | const PrintingPolicy &Policy) const; |
4314 | |
4315 | static bool classof(const Type *T) { |
4316 | return T->getTypeClass() == FunctionProto; |
4317 | } |
4318 | |
4319 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4320 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4321 | param_type_iterator ArgTys, unsigned NumArgs, |
4322 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4323 | bool Canonical); |
4324 | }; |
4325 | |
4326 | /// Represents the dependent type named by a dependently-scoped |
4327 | /// typename using declaration, e.g. |
4328 | /// using typename Base<T>::foo; |
4329 | /// |
4330 | /// Template instantiation turns these into the underlying type. |
4331 | class UnresolvedUsingType : public Type { |
4332 | friend class ASTContext; // ASTContext creates these. |
4333 | |
4334 | UnresolvedUsingTypenameDecl *Decl; |
4335 | |
4336 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4337 | : Type(UnresolvedUsing, QualType(), |
4338 | TypeDependence::DependentInstantiation), |
4339 | Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {} |
4340 | |
4341 | public: |
4342 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4343 | |
4344 | bool isSugared() const { return false; } |
4345 | QualType desugar() const { return QualType(this, 0); } |
4346 | |
4347 | static bool classof(const Type *T) { |
4348 | return T->getTypeClass() == UnresolvedUsing; |
4349 | } |
4350 | |
4351 | void Profile(llvm::FoldingSetNodeID &ID) { |
4352 | return Profile(ID, Decl); |
4353 | } |
4354 | |
4355 | static void Profile(llvm::FoldingSetNodeID &ID, |
4356 | UnresolvedUsingTypenameDecl *D) { |
4357 | ID.AddPointer(D); |
4358 | } |
4359 | }; |
4360 | |
4361 | class TypedefType : public Type { |
4362 | TypedefNameDecl *Decl; |
4363 | |
4364 | protected: |
4365 | friend class ASTContext; // ASTContext creates these. |
4366 | |
4367 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can); |
4368 | |
4369 | public: |
4370 | TypedefNameDecl *getDecl() const { return Decl; } |
4371 | |
4372 | bool isSugared() const { return true; } |
4373 | QualType desugar() const; |
4374 | |
4375 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4376 | }; |
4377 | |
4378 | /// Sugar type that represents a type that was qualified by a qualifier written |
4379 | /// as a macro invocation. |
4380 | class MacroQualifiedType : public Type { |
4381 | friend class ASTContext; // ASTContext creates these. |
4382 | |
4383 | QualType UnderlyingTy; |
4384 | const IdentifierInfo *MacroII; |
4385 | |
4386 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4387 | const IdentifierInfo *MacroII) |
4388 | : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()), |
4389 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4390 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4391, __PRETTY_FUNCTION__)) |
4391 | "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4391, __PRETTY_FUNCTION__)); |
4392 | } |
4393 | |
4394 | public: |
4395 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4396 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4397 | |
4398 | /// Return this attributed type's modified type with no qualifiers attached to |
4399 | /// it. |
4400 | QualType getModifiedType() const; |
4401 | |
4402 | bool isSugared() const { return true; } |
4403 | QualType desugar() const; |
4404 | |
4405 | static bool classof(const Type *T) { |
4406 | return T->getTypeClass() == MacroQualified; |
4407 | } |
4408 | }; |
4409 | |
4410 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4411 | class TypeOfExprType : public Type { |
4412 | Expr *TOExpr; |
4413 | |
4414 | protected: |
4415 | friend class ASTContext; // ASTContext creates these. |
4416 | |
4417 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4418 | |
4419 | public: |
4420 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4421 | |
4422 | /// Remove a single level of sugar. |
4423 | QualType desugar() const; |
4424 | |
4425 | /// Returns whether this type directly provides sugar. |
4426 | bool isSugared() const; |
4427 | |
4428 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4429 | }; |
4430 | |
4431 | /// Internal representation of canonical, dependent |
4432 | /// `typeof(expr)` types. |
4433 | /// |
4434 | /// This class is used internally by the ASTContext to manage |
4435 | /// canonical, dependent types, only. Clients will only see instances |
4436 | /// of this class via TypeOfExprType nodes. |
4437 | class DependentTypeOfExprType |
4438 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4439 | const ASTContext &Context; |
4440 | |
4441 | public: |
4442 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4443 | : TypeOfExprType(E), Context(Context) {} |
4444 | |
4445 | void Profile(llvm::FoldingSetNodeID &ID) { |
4446 | Profile(ID, Context, getUnderlyingExpr()); |
4447 | } |
4448 | |
4449 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4450 | Expr *E); |
4451 | }; |
4452 | |
4453 | /// Represents `typeof(type)`, a GCC extension. |
4454 | class TypeOfType : public Type { |
4455 | friend class ASTContext; // ASTContext creates these. |
4456 | |
4457 | QualType TOType; |
4458 | |
4459 | TypeOfType(QualType T, QualType can) |
4460 | : Type(TypeOf, can, T->getDependence()), TOType(T) { |
4461 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4461, __PRETTY_FUNCTION__)); |
4462 | } |
4463 | |
4464 | public: |
4465 | QualType getUnderlyingType() const { return TOType; } |
4466 | |
4467 | /// Remove a single level of sugar. |
4468 | QualType desugar() const { return getUnderlyingType(); } |
4469 | |
4470 | /// Returns whether this type directly provides sugar. |
4471 | bool isSugared() const { return true; } |
4472 | |
4473 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4474 | }; |
4475 | |
4476 | /// Represents the type `decltype(expr)` (C++11). |
4477 | class DecltypeType : public Type { |
4478 | Expr *E; |
4479 | QualType UnderlyingType; |
4480 | |
4481 | protected: |
4482 | friend class ASTContext; // ASTContext creates these. |
4483 | |
4484 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4485 | |
4486 | public: |
4487 | Expr *getUnderlyingExpr() const { return E; } |
4488 | QualType getUnderlyingType() const { return UnderlyingType; } |
4489 | |
4490 | /// Remove a single level of sugar. |
4491 | QualType desugar() const; |
4492 | |
4493 | /// Returns whether this type directly provides sugar. |
4494 | bool isSugared() const; |
4495 | |
4496 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4497 | }; |
4498 | |
4499 | /// Internal representation of canonical, dependent |
4500 | /// decltype(expr) types. |
4501 | /// |
4502 | /// This class is used internally by the ASTContext to manage |
4503 | /// canonical, dependent types, only. Clients will only see instances |
4504 | /// of this class via DecltypeType nodes. |
4505 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4506 | const ASTContext &Context; |
4507 | |
4508 | public: |
4509 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4510 | |
4511 | void Profile(llvm::FoldingSetNodeID &ID) { |
4512 | Profile(ID, Context, getUnderlyingExpr()); |
4513 | } |
4514 | |
4515 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4516 | Expr *E); |
4517 | }; |
4518 | |
4519 | /// A unary type transform, which is a type constructed from another. |
4520 | class UnaryTransformType : public Type { |
4521 | public: |
4522 | enum UTTKind { |
4523 | EnumUnderlyingType |
4524 | }; |
4525 | |
4526 | private: |
4527 | /// The untransformed type. |
4528 | QualType BaseType; |
4529 | |
4530 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4531 | QualType UnderlyingType; |
4532 | |
4533 | UTTKind UKind; |
4534 | |
4535 | protected: |
4536 | friend class ASTContext; |
4537 | |
4538 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4539 | QualType CanonicalTy); |
4540 | |
4541 | public: |
4542 | bool isSugared() const { return !isDependentType(); } |
4543 | QualType desugar() const { return UnderlyingType; } |
4544 | |
4545 | QualType getUnderlyingType() const { return UnderlyingType; } |
4546 | QualType getBaseType() const { return BaseType; } |
4547 | |
4548 | UTTKind getUTTKind() const { return UKind; } |
4549 | |
4550 | static bool classof(const Type *T) { |
4551 | return T->getTypeClass() == UnaryTransform; |
4552 | } |
4553 | }; |
4554 | |
4555 | /// Internal representation of canonical, dependent |
4556 | /// __underlying_type(type) types. |
4557 | /// |
4558 | /// This class is used internally by the ASTContext to manage |
4559 | /// canonical, dependent types, only. Clients will only see instances |
4560 | /// of this class via UnaryTransformType nodes. |
4561 | class DependentUnaryTransformType : public UnaryTransformType, |
4562 | public llvm::FoldingSetNode { |
4563 | public: |
4564 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4565 | UTTKind UKind); |
4566 | |
4567 | void Profile(llvm::FoldingSetNodeID &ID) { |
4568 | Profile(ID, getBaseType(), getUTTKind()); |
4569 | } |
4570 | |
4571 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4572 | UTTKind UKind) { |
4573 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4574 | ID.AddInteger((unsigned)UKind); |
4575 | } |
4576 | }; |
4577 | |
4578 | class TagType : public Type { |
4579 | friend class ASTReader; |
4580 | template <class T> friend class serialization::AbstractTypeReader; |
4581 | |
4582 | /// Stores the TagDecl associated with this type. The decl may point to any |
4583 | /// TagDecl that declares the entity. |
4584 | TagDecl *decl; |
4585 | |
4586 | protected: |
4587 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4588 | |
4589 | public: |
4590 | TagDecl *getDecl() const; |
4591 | |
4592 | /// Determines whether this type is in the process of being defined. |
4593 | bool isBeingDefined() const; |
4594 | |
4595 | static bool classof(const Type *T) { |
4596 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4597 | } |
4598 | }; |
4599 | |
4600 | /// A helper class that allows the use of isa/cast/dyncast |
4601 | /// to detect TagType objects of structs/unions/classes. |
4602 | class RecordType : public TagType { |
4603 | protected: |
4604 | friend class ASTContext; // ASTContext creates these. |
4605 | |
4606 | explicit RecordType(const RecordDecl *D) |
4607 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4608 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4609 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4610 | |
4611 | public: |
4612 | RecordDecl *getDecl() const { |
4613 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4614 | } |
4615 | |
4616 | /// Recursively check all fields in the record for const-ness. If any field |
4617 | /// is declared const, return true. Otherwise, return false. |
4618 | bool hasConstFields() const; |
4619 | |
4620 | bool isSugared() const { return false; } |
4621 | QualType desugar() const { return QualType(this, 0); } |
4622 | |
4623 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4624 | }; |
4625 | |
4626 | /// A helper class that allows the use of isa/cast/dyncast |
4627 | /// to detect TagType objects of enums. |
4628 | class EnumType : public TagType { |
4629 | friend class ASTContext; // ASTContext creates these. |
4630 | |
4631 | explicit EnumType(const EnumDecl *D) |
4632 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4633 | |
4634 | public: |
4635 | EnumDecl *getDecl() const { |
4636 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4637 | } |
4638 | |
4639 | bool isSugared() const { return false; } |
4640 | QualType desugar() const { return QualType(this, 0); } |
4641 | |
4642 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4643 | }; |
4644 | |
4645 | /// An attributed type is a type to which a type attribute has been applied. |
4646 | /// |
4647 | /// The "modified type" is the fully-sugared type to which the attributed |
4648 | /// type was applied; generally it is not canonically equivalent to the |
4649 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4650 | /// which the type is canonically equivalent to. |
4651 | /// |
4652 | /// For example, in the following attributed type: |
4653 | /// int32_t __attribute__((vector_size(16))) |
4654 | /// - the modified type is the TypedefType for int32_t |
4655 | /// - the equivalent type is VectorType(16, int32_t) |
4656 | /// - the canonical type is VectorType(16, int) |
4657 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4658 | public: |
4659 | using Kind = attr::Kind; |
4660 | |
4661 | private: |
4662 | friend class ASTContext; // ASTContext creates these |
4663 | |
4664 | QualType ModifiedType; |
4665 | QualType EquivalentType; |
4666 | |
4667 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4668 | QualType equivalent) |
4669 | : Type(Attributed, canon, equivalent->getDependence()), |
4670 | ModifiedType(modified), EquivalentType(equivalent) { |
4671 | AttributedTypeBits.AttrKind = attrKind; |
4672 | } |
4673 | |
4674 | public: |
4675 | Kind getAttrKind() const { |
4676 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4677 | } |
4678 | |
4679 | QualType getModifiedType() const { return ModifiedType; } |
4680 | QualType getEquivalentType() const { return EquivalentType; } |
4681 | |
4682 | bool isSugared() const { return true; } |
4683 | QualType desugar() const { return getEquivalentType(); } |
4684 | |
4685 | /// Does this attribute behave like a type qualifier? |
4686 | /// |
4687 | /// A type qualifier adjusts a type to provide specialized rules for |
4688 | /// a specific object, like the standard const and volatile qualifiers. |
4689 | /// This includes attributes controlling things like nullability, |
4690 | /// address spaces, and ARC ownership. The value of the object is still |
4691 | /// largely described by the modified type. |
4692 | /// |
4693 | /// In contrast, many type attributes "rewrite" their modified type to |
4694 | /// produce a fundamentally different type, not necessarily related in any |
4695 | /// formalizable way to the original type. For example, calling convention |
4696 | /// and vector attributes are not simple type qualifiers. |
4697 | /// |
4698 | /// Type qualifiers are often, but not always, reflected in the canonical |
4699 | /// type. |
4700 | bool isQualifier() const; |
4701 | |
4702 | bool isMSTypeSpec() const; |
4703 | |
4704 | bool isCallingConv() const; |
4705 | |
4706 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4707 | |
4708 | /// Retrieve the attribute kind corresponding to the given |
4709 | /// nullability kind. |
4710 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4711 | switch (kind) { |
4712 | case NullabilityKind::NonNull: |
4713 | return attr::TypeNonNull; |
4714 | |
4715 | case NullabilityKind::Nullable: |
4716 | return attr::TypeNullable; |
4717 | |
4718 | case NullabilityKind::Unspecified: |
4719 | return attr::TypeNullUnspecified; |
4720 | } |
4721 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 4721); |
4722 | } |
4723 | |
4724 | /// Strip off the top-level nullability annotation on the given |
4725 | /// type, if it's there. |
4726 | /// |
4727 | /// \param T The type to strip. If the type is exactly an |
4728 | /// AttributedType specifying nullability (without looking through |
4729 | /// type sugar), the nullability is returned and this type changed |
4730 | /// to the underlying modified type. |
4731 | /// |
4732 | /// \returns the top-level nullability, if present. |
4733 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4734 | |
4735 | void Profile(llvm::FoldingSetNodeID &ID) { |
4736 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4737 | } |
4738 | |
4739 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4740 | QualType modified, QualType equivalent) { |
4741 | ID.AddInteger(attrKind); |
4742 | ID.AddPointer(modified.getAsOpaquePtr()); |
4743 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4744 | } |
4745 | |
4746 | static bool classof(const Type *T) { |
4747 | return T->getTypeClass() == Attributed; |
4748 | } |
4749 | }; |
4750 | |
4751 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4752 | friend class ASTContext; // ASTContext creates these |
4753 | |
4754 | // Helper data collector for canonical types. |
4755 | struct CanonicalTTPTInfo { |
4756 | unsigned Depth : 15; |
4757 | unsigned ParameterPack : 1; |
4758 | unsigned Index : 16; |
4759 | }; |
4760 | |
4761 | union { |
4762 | // Info for the canonical type. |
4763 | CanonicalTTPTInfo CanTTPTInfo; |
4764 | |
4765 | // Info for the non-canonical type. |
4766 | TemplateTypeParmDecl *TTPDecl; |
4767 | }; |
4768 | |
4769 | /// Build a non-canonical type. |
4770 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4771 | : Type(TemplateTypeParm, Canon, |
4772 | TypeDependence::DependentInstantiation | |
4773 | (Canon->getDependence() & TypeDependence::UnexpandedPack)), |
4774 | TTPDecl(TTPDecl) {} |
4775 | |
4776 | /// Build the canonical type. |
4777 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4778 | : Type(TemplateTypeParm, QualType(this, 0), |
4779 | TypeDependence::DependentInstantiation | |
4780 | (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) { |
4781 | CanTTPTInfo.Depth = D; |
4782 | CanTTPTInfo.Index = I; |
4783 | CanTTPTInfo.ParameterPack = PP; |
4784 | } |
4785 | |
4786 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4787 | QualType Can = getCanonicalTypeInternal(); |
4788 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4789 | } |
4790 | |
4791 | public: |
4792 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4793 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4794 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4795 | |
4796 | TemplateTypeParmDecl *getDecl() const { |
4797 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4798 | } |
4799 | |
4800 | IdentifierInfo *getIdentifier() const; |
4801 | |
4802 | bool isSugared() const { return false; } |
4803 | QualType desugar() const { return QualType(this, 0); } |
4804 | |
4805 | void Profile(llvm::FoldingSetNodeID &ID) { |
4806 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4807 | } |
4808 | |
4809 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4810 | unsigned Index, bool ParameterPack, |
4811 | TemplateTypeParmDecl *TTPDecl) { |
4812 | ID.AddInteger(Depth); |
4813 | ID.AddInteger(Index); |
4814 | ID.AddBoolean(ParameterPack); |
4815 | ID.AddPointer(TTPDecl); |
4816 | } |
4817 | |
4818 | static bool classof(const Type *T) { |
4819 | return T->getTypeClass() == TemplateTypeParm; |
4820 | } |
4821 | }; |
4822 | |
4823 | /// Represents the result of substituting a type for a template |
4824 | /// type parameter. |
4825 | /// |
4826 | /// Within an instantiated template, all template type parameters have |
4827 | /// been replaced with these. They are used solely to record that a |
4828 | /// type was originally written as a template type parameter; |
4829 | /// therefore they are never canonical. |
4830 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4831 | friend class ASTContext; |
4832 | |
4833 | // The original type parameter. |
4834 | const TemplateTypeParmType *Replaced; |
4835 | |
4836 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4837 | : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), |
4838 | Replaced(Param) {} |
4839 | |
4840 | public: |
4841 | /// Gets the template parameter that was substituted for. |
4842 | const TemplateTypeParmType *getReplacedParameter() const { |
4843 | return Replaced; |
4844 | } |
4845 | |
4846 | /// Gets the type that was substituted for the template |
4847 | /// parameter. |
4848 | QualType getReplacementType() const { |
4849 | return getCanonicalTypeInternal(); |
4850 | } |
4851 | |
4852 | bool isSugared() const { return true; } |
4853 | QualType desugar() const { return getReplacementType(); } |
4854 | |
4855 | void Profile(llvm::FoldingSetNodeID &ID) { |
4856 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4857 | } |
4858 | |
4859 | static void Profile(llvm::FoldingSetNodeID &ID, |
4860 | const TemplateTypeParmType *Replaced, |
4861 | QualType Replacement) { |
4862 | ID.AddPointer(Replaced); |
4863 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4864 | } |
4865 | |
4866 | static bool classof(const Type *T) { |
4867 | return T->getTypeClass() == SubstTemplateTypeParm; |
4868 | } |
4869 | }; |
4870 | |
4871 | /// Represents the result of substituting a set of types for a template |
4872 | /// type parameter pack. |
4873 | /// |
4874 | /// When a pack expansion in the source code contains multiple parameter packs |
4875 | /// and those parameter packs correspond to different levels of template |
4876 | /// parameter lists, this type node is used to represent a template type |
4877 | /// parameter pack from an outer level, which has already had its argument pack |
4878 | /// substituted but that still lives within a pack expansion that itself |
4879 | /// could not be instantiated. When actually performing a substitution into |
4880 | /// that pack expansion (e.g., when all template parameters have corresponding |
4881 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4882 | /// at the current pack substitution index. |
4883 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4884 | friend class ASTContext; |
4885 | |
4886 | /// The original type parameter. |
4887 | const TemplateTypeParmType *Replaced; |
4888 | |
4889 | /// A pointer to the set of template arguments that this |
4890 | /// parameter pack is instantiated with. |
4891 | const TemplateArgument *Arguments; |
4892 | |
4893 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4894 | QualType Canon, |
4895 | const TemplateArgument &ArgPack); |
4896 | |
4897 | public: |
4898 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4899 | |
4900 | /// Gets the template parameter that was substituted for. |
4901 | const TemplateTypeParmType *getReplacedParameter() const { |
4902 | return Replaced; |
4903 | } |
4904 | |
4905 | unsigned getNumArgs() const { |
4906 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4907 | } |
4908 | |
4909 | bool isSugared() const { return false; } |
4910 | QualType desugar() const { return QualType(this, 0); } |
4911 | |
4912 | TemplateArgument getArgumentPack() const; |
4913 | |
4914 | void Profile(llvm::FoldingSetNodeID &ID); |
4915 | static void Profile(llvm::FoldingSetNodeID &ID, |
4916 | const TemplateTypeParmType *Replaced, |
4917 | const TemplateArgument &ArgPack); |
4918 | |
4919 | static bool classof(const Type *T) { |
4920 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4921 | } |
4922 | }; |
4923 | |
4924 | /// Common base class for placeholders for types that get replaced by |
4925 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4926 | /// class template types, and constrained type names. |
4927 | /// |
4928 | /// These types are usually a placeholder for a deduced type. However, before |
4929 | /// the initializer is attached, or (usually) if the initializer is |
4930 | /// type-dependent, there is no deduced type and the type is canonical. In |
4931 | /// the latter case, it is also a dependent type. |
4932 | class DeducedType : public Type { |
4933 | protected: |
4934 | DeducedType(TypeClass TC, QualType DeducedAsType, |
4935 | TypeDependence ExtraDependence) |
4936 | : Type(TC, |
4937 | // FIXME: Retain the sugared deduced type? |
4938 | DeducedAsType.isNull() ? QualType(this, 0) |
4939 | : DeducedAsType.getCanonicalType(), |
4940 | ExtraDependence | (DeducedAsType.isNull() |
4941 | ? TypeDependence::None |
4942 | : DeducedAsType->getDependence() & |
4943 | ~TypeDependence::VariablyModified)) {} |
4944 | |
4945 | public: |
4946 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4947 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4948 | |
4949 | /// Get the type deduced for this placeholder type, or null if it's |
4950 | /// either not been deduced or was deduced to a dependent type. |
4951 | QualType getDeducedType() const { |
4952 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4953 | } |
4954 | bool isDeduced() const { |
4955 | return !isCanonicalUnqualified() || isDependentType(); |
4956 | } |
4957 | |
4958 | static bool classof(const Type *T) { |
4959 | return T->getTypeClass() == Auto || |
4960 | T->getTypeClass() == DeducedTemplateSpecialization; |
4961 | } |
4962 | }; |
4963 | |
4964 | /// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained |
4965 | /// by a type-constraint. |
4966 | class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode { |
4967 | friend class ASTContext; // ASTContext creates these |
4968 | |
4969 | ConceptDecl *TypeConstraintConcept; |
4970 | |
4971 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4972 | TypeDependence ExtraDependence, ConceptDecl *CD, |
4973 | ArrayRef<TemplateArgument> TypeConstraintArgs); |
4974 | |
4975 | const TemplateArgument *getArgBuffer() const { |
4976 | return reinterpret_cast<const TemplateArgument*>(this+1); |
4977 | } |
4978 | |
4979 | TemplateArgument *getArgBuffer() { |
4980 | return reinterpret_cast<TemplateArgument*>(this+1); |
4981 | } |
4982 | |
4983 | public: |
4984 | /// Retrieve the template arguments. |
4985 | const TemplateArgument *getArgs() const { |
4986 | return getArgBuffer(); |
4987 | } |
4988 | |
4989 | /// Retrieve the number of template arguments. |
4990 | unsigned getNumArgs() const { |
4991 | return AutoTypeBits.NumArgs; |
4992 | } |
4993 | |
4994 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4995 | |
4996 | ArrayRef<TemplateArgument> getTypeConstraintArguments() const { |
4997 | return {getArgs(), getNumArgs()}; |
4998 | } |
4999 | |
5000 | ConceptDecl *getTypeConstraintConcept() const { |
5001 | return TypeConstraintConcept; |
5002 | } |
5003 | |
5004 | bool isConstrained() const { |
5005 | return TypeConstraintConcept != nullptr; |
5006 | } |
5007 | |
5008 | bool isDecltypeAuto() const { |
5009 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
5010 | } |
5011 | |
5012 | AutoTypeKeyword getKeyword() const { |
5013 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
5014 | } |
5015 | |
5016 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5017 | Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), |
5018 | getTypeConstraintConcept(), getTypeConstraintArguments()); |
5019 | } |
5020 | |
5021 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
5022 | QualType Deduced, AutoTypeKeyword Keyword, |
5023 | bool IsDependent, ConceptDecl *CD, |
5024 | ArrayRef<TemplateArgument> Arguments); |
5025 | |
5026 | static bool classof(const Type *T) { |
5027 | return T->getTypeClass() == Auto; |
5028 | } |
5029 | }; |
5030 | |
5031 | /// Represents a C++17 deduced template specialization type. |
5032 | class DeducedTemplateSpecializationType : public DeducedType, |
5033 | public llvm::FoldingSetNode { |
5034 | friend class ASTContext; // ASTContext creates these |
5035 | |
5036 | /// The name of the template whose arguments will be deduced. |
5037 | TemplateName Template; |
5038 | |
5039 | DeducedTemplateSpecializationType(TemplateName Template, |
5040 | QualType DeducedAsType, |
5041 | bool IsDeducedAsDependent) |
5042 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
5043 | toTypeDependence(Template.getDependence()) | |
5044 | (IsDeducedAsDependent |
5045 | ? TypeDependence::DependentInstantiation |
5046 | : TypeDependence::None)), |
5047 | Template(Template) {} |
5048 | |
5049 | public: |
5050 | /// Retrieve the name of the template that we are deducing. |
5051 | TemplateName getTemplateName() const { return Template;} |
5052 | |
5053 | void Profile(llvm::FoldingSetNodeID &ID) { |
5054 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
5055 | } |
5056 | |
5057 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
5058 | QualType Deduced, bool IsDependent) { |
5059 | Template.Profile(ID); |
5060 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
5061 | ID.AddBoolean(IsDependent); |
5062 | } |
5063 | |
5064 | static bool classof(const Type *T) { |
5065 | return T->getTypeClass() == DeducedTemplateSpecialization; |
5066 | } |
5067 | }; |
5068 | |
5069 | /// Represents a type template specialization; the template |
5070 | /// must be a class template, a type alias template, or a template |
5071 | /// template parameter. A template which cannot be resolved to one of |
5072 | /// these, e.g. because it is written with a dependent scope |
5073 | /// specifier, is instead represented as a |
5074 | /// @c DependentTemplateSpecializationType. |
5075 | /// |
5076 | /// A non-dependent template specialization type is always "sugar", |
5077 | /// typically for a \c RecordType. For example, a class template |
5078 | /// specialization type of \c vector<int> will refer to a tag type for |
5079 | /// the instantiation \c std::vector<int, std::allocator<int>> |
5080 | /// |
5081 | /// Template specializations are dependent if either the template or |
5082 | /// any of the template arguments are dependent, in which case the |
5083 | /// type may also be canonical. |
5084 | /// |
5085 | /// Instances of this type are allocated with a trailing array of |
5086 | /// TemplateArguments, followed by a QualType representing the |
5087 | /// non-canonical aliased type when the template is a type alias |
5088 | /// template. |
5089 | class alignas(8) TemplateSpecializationType |
5090 | : public Type, |
5091 | public llvm::FoldingSetNode { |
5092 | friend class ASTContext; // ASTContext creates these |
5093 | |
5094 | /// The name of the template being specialized. This is |
5095 | /// either a TemplateName::Template (in which case it is a |
5096 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
5097 | /// TypeAliasTemplateDecl*), a |
5098 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
5099 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
5100 | /// replacement must, recursively, be one of these). |
5101 | TemplateName Template; |
5102 | |
5103 | TemplateSpecializationType(TemplateName T, |
5104 | ArrayRef<TemplateArgument> Args, |
5105 | QualType Canon, |
5106 | QualType Aliased); |
5107 | |
5108 | public: |
5109 | /// Determine whether any of the given template arguments are dependent. |
5110 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
5111 | bool &InstantiationDependent); |
5112 | |
5113 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
5114 | bool &InstantiationDependent); |
5115 | |
5116 | /// True if this template specialization type matches a current |
5117 | /// instantiation in the context in which it is found. |
5118 | bool isCurrentInstantiation() const { |
5119 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
5120 | } |
5121 | |
5122 | /// Determine if this template specialization type is for a type alias |
5123 | /// template that has been substituted. |
5124 | /// |
5125 | /// Nearly every template specialization type whose template is an alias |
5126 | /// template will be substituted. However, this is not the case when |
5127 | /// the specialization contains a pack expansion but the template alias |
5128 | /// does not have a corresponding parameter pack, e.g., |
5129 | /// |
5130 | /// \code |
5131 | /// template<typename T, typename U, typename V> struct S; |
5132 | /// template<typename T, typename U> using A = S<T, int, U>; |
5133 | /// template<typename... Ts> struct X { |
5134 | /// typedef A<Ts...> type; // not a type alias |
5135 | /// }; |
5136 | /// \endcode |
5137 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
5138 | |
5139 | /// Get the aliased type, if this is a specialization of a type alias |
5140 | /// template. |
5141 | QualType getAliasedType() const { |
5142 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5142, __PRETTY_FUNCTION__)); |
5143 | return *reinterpret_cast<const QualType*>(end()); |
5144 | } |
5145 | |
5146 | using iterator = const TemplateArgument *; |
5147 | |
5148 | iterator begin() const { return getArgs(); } |
5149 | iterator end() const; // defined inline in TemplateBase.h |
5150 | |
5151 | /// Retrieve the name of the template that we are specializing. |
5152 | TemplateName getTemplateName() const { return Template; } |
5153 | |
5154 | /// Retrieve the template arguments. |
5155 | const TemplateArgument *getArgs() const { |
5156 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
5157 | } |
5158 | |
5159 | /// Retrieve the number of template arguments. |
5160 | unsigned getNumArgs() const { |
5161 | return TemplateSpecializationTypeBits.NumArgs; |
5162 | } |
5163 | |
5164 | /// Retrieve a specific template argument as a type. |
5165 | /// \pre \c isArgType(Arg) |
5166 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5167 | |
5168 | ArrayRef<TemplateArgument> template_arguments() const { |
5169 | return {getArgs(), getNumArgs()}; |
5170 | } |
5171 | |
5172 | bool isSugared() const { |
5173 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5174 | } |
5175 | |
5176 | QualType desugar() const { |
5177 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5178 | } |
5179 | |
5180 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5181 | Profile(ID, Template, template_arguments(), Ctx); |
5182 | if (isTypeAlias()) |
5183 | getAliasedType().Profile(ID); |
5184 | } |
5185 | |
5186 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5187 | ArrayRef<TemplateArgument> Args, |
5188 | const ASTContext &Context); |
5189 | |
5190 | static bool classof(const Type *T) { |
5191 | return T->getTypeClass() == TemplateSpecialization; |
5192 | } |
5193 | }; |
5194 | |
5195 | /// Print a template argument list, including the '<' and '>' |
5196 | /// enclosing the template arguments. |
5197 | void printTemplateArgumentList(raw_ostream &OS, |
5198 | ArrayRef<TemplateArgument> Args, |
5199 | const PrintingPolicy &Policy); |
5200 | |
5201 | void printTemplateArgumentList(raw_ostream &OS, |
5202 | ArrayRef<TemplateArgumentLoc> Args, |
5203 | const PrintingPolicy &Policy); |
5204 | |
5205 | void printTemplateArgumentList(raw_ostream &OS, |
5206 | const TemplateArgumentListInfo &Args, |
5207 | const PrintingPolicy &Policy); |
5208 | |
5209 | /// The injected class name of a C++ class template or class |
5210 | /// template partial specialization. Used to record that a type was |
5211 | /// spelled with a bare identifier rather than as a template-id; the |
5212 | /// equivalent for non-templated classes is just RecordType. |
5213 | /// |
5214 | /// Injected class name types are always dependent. Template |
5215 | /// instantiation turns these into RecordTypes. |
5216 | /// |
5217 | /// Injected class name types are always canonical. This works |
5218 | /// because it is impossible to compare an injected class name type |
5219 | /// with the corresponding non-injected template type, for the same |
5220 | /// reason that it is impossible to directly compare template |
5221 | /// parameters from different dependent contexts: injected class name |
5222 | /// types can only occur within the scope of a particular templated |
5223 | /// declaration, and within that scope every template specialization |
5224 | /// will canonicalize to the injected class name (when appropriate |
5225 | /// according to the rules of the language). |
5226 | class InjectedClassNameType : public Type { |
5227 | friend class ASTContext; // ASTContext creates these. |
5228 | friend class ASTNodeImporter; |
5229 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5230 | // currently suitable for AST reading, too much |
5231 | // interdependencies. |
5232 | template <class T> friend class serialization::AbstractTypeReader; |
5233 | |
5234 | CXXRecordDecl *Decl; |
5235 | |
5236 | /// The template specialization which this type represents. |
5237 | /// For example, in |
5238 | /// template <class T> class A { ... }; |
5239 | /// this is A<T>, whereas in |
5240 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5241 | /// this is A<B<X,Y> >. |
5242 | /// |
5243 | /// It is always unqualified, always a template specialization type, |
5244 | /// and always dependent. |
5245 | QualType InjectedType; |
5246 | |
5247 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5248 | : Type(InjectedClassName, QualType(), |
5249 | TypeDependence::DependentInstantiation), |
5250 | Decl(D), InjectedType(TST) { |
5251 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5251, __PRETTY_FUNCTION__)); |
5252 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5252, __PRETTY_FUNCTION__)); |
5253 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5253, __PRETTY_FUNCTION__)); |
5254 | } |
5255 | |
5256 | public: |
5257 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5258 | |
5259 | const TemplateSpecializationType *getInjectedTST() const { |
5260 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5261 | } |
5262 | |
5263 | TemplateName getTemplateName() const { |
5264 | return getInjectedTST()->getTemplateName(); |
5265 | } |
5266 | |
5267 | CXXRecordDecl *getDecl() const; |
5268 | |
5269 | bool isSugared() const { return false; } |
5270 | QualType desugar() const { return QualType(this, 0); } |
5271 | |
5272 | static bool classof(const Type *T) { |
5273 | return T->getTypeClass() == InjectedClassName; |
5274 | } |
5275 | }; |
5276 | |
5277 | /// The kind of a tag type. |
5278 | enum TagTypeKind { |
5279 | /// The "struct" keyword. |
5280 | TTK_Struct, |
5281 | |
5282 | /// The "__interface" keyword. |
5283 | TTK_Interface, |
5284 | |
5285 | /// The "union" keyword. |
5286 | TTK_Union, |
5287 | |
5288 | /// The "class" keyword. |
5289 | TTK_Class, |
5290 | |
5291 | /// The "enum" keyword. |
5292 | TTK_Enum |
5293 | }; |
5294 | |
5295 | /// The elaboration keyword that precedes a qualified type name or |
5296 | /// introduces an elaborated-type-specifier. |
5297 | enum ElaboratedTypeKeyword { |
5298 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5299 | ETK_Struct, |
5300 | |
5301 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5302 | ETK_Interface, |
5303 | |
5304 | /// The "union" keyword introduces the elaborated-type-specifier. |
5305 | ETK_Union, |
5306 | |
5307 | /// The "class" keyword introduces the elaborated-type-specifier. |
5308 | ETK_Class, |
5309 | |
5310 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5311 | ETK_Enum, |
5312 | |
5313 | /// The "typename" keyword precedes the qualified type name, e.g., |
5314 | /// \c typename T::type. |
5315 | ETK_Typename, |
5316 | |
5317 | /// No keyword precedes the qualified type name. |
5318 | ETK_None |
5319 | }; |
5320 | |
5321 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5322 | /// The keyword in stored in the free bits of the base class. |
5323 | /// Also provides a few static helpers for converting and printing |
5324 | /// elaborated type keyword and tag type kind enumerations. |
5325 | class TypeWithKeyword : public Type { |
5326 | protected: |
5327 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5328 | QualType Canonical, TypeDependence Dependence) |
5329 | : Type(tc, Canonical, Dependence) { |
5330 | TypeWithKeywordBits.Keyword = Keyword; |
5331 | } |
5332 | |
5333 | public: |
5334 | ElaboratedTypeKeyword getKeyword() const { |
5335 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5336 | } |
5337 | |
5338 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5339 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5340 | |
5341 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5342 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5343 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5344 | |
5345 | /// Converts a TagTypeKind into an elaborated type keyword. |
5346 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5347 | |
5348 | /// Converts an elaborated type keyword into a TagTypeKind. |
5349 | /// It is an error to provide an elaborated type keyword |
5350 | /// which *isn't* a tag kind here. |
5351 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5352 | |
5353 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5354 | |
5355 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5356 | |
5357 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5358 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5359 | } |
5360 | |
5361 | class CannotCastToThisType {}; |
5362 | static CannotCastToThisType classof(const Type *); |
5363 | }; |
5364 | |
5365 | /// Represents a type that was referred to using an elaborated type |
5366 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5367 | /// or both. |
5368 | /// |
5369 | /// This type is used to keep track of a type name as written in the |
5370 | /// source code, including tag keywords and any nested-name-specifiers. |
5371 | /// The type itself is always "sugar", used to express what was written |
5372 | /// in the source code but containing no additional semantic information. |
5373 | class ElaboratedType final |
5374 | : public TypeWithKeyword, |
5375 | public llvm::FoldingSetNode, |
5376 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5377 | friend class ASTContext; // ASTContext creates these |
5378 | friend TrailingObjects; |
5379 | |
5380 | /// The nested name specifier containing the qualifier. |
5381 | NestedNameSpecifier *NNS; |
5382 | |
5383 | /// The type that this qualified name refers to. |
5384 | QualType NamedType; |
5385 | |
5386 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5387 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5388 | /// it, or obtain a null pointer if there is none. |
5389 | |
5390 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5391 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5392 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5393 | NamedType->getDependence()), |
5394 | NNS(NNS), NamedType(NamedType) { |
5395 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5396 | if (OwnedTagDecl) { |
5397 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5398 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5399 | } |
5400 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5402, __PRETTY_FUNCTION__)) |
5401 | "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5402, __PRETTY_FUNCTION__)) |
5402 | "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5402, __PRETTY_FUNCTION__)); |
5403 | } |
5404 | |
5405 | public: |
5406 | /// Retrieve the qualification on this type. |
5407 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5408 | |
5409 | /// Retrieve the type named by the qualified-id. |
5410 | QualType getNamedType() const { return NamedType; } |
5411 | |
5412 | /// Remove a single level of sugar. |
5413 | QualType desugar() const { return getNamedType(); } |
5414 | |
5415 | /// Returns whether this type directly provides sugar. |
5416 | bool isSugared() const { return true; } |
5417 | |
5418 | /// Return the (re)declaration of this type owned by this occurrence of this |
5419 | /// type, or nullptr if there is none. |
5420 | TagDecl *getOwnedTagDecl() const { |
5421 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5422 | : nullptr; |
5423 | } |
5424 | |
5425 | void Profile(llvm::FoldingSetNodeID &ID) { |
5426 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5427 | } |
5428 | |
5429 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5430 | NestedNameSpecifier *NNS, QualType NamedType, |
5431 | TagDecl *OwnedTagDecl) { |
5432 | ID.AddInteger(Keyword); |
5433 | ID.AddPointer(NNS); |
5434 | NamedType.Profile(ID); |
5435 | ID.AddPointer(OwnedTagDecl); |
5436 | } |
5437 | |
5438 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5439 | }; |
5440 | |
5441 | /// Represents a qualified type name for which the type name is |
5442 | /// dependent. |
5443 | /// |
5444 | /// DependentNameType represents a class of dependent types that involve a |
5445 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5446 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5447 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5448 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5449 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5450 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5451 | /// mode, this type is used with non-dependent names to delay name lookup until |
5452 | /// instantiation. |
5453 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5454 | friend class ASTContext; // ASTContext creates these |
5455 | |
5456 | /// The nested name specifier containing the qualifier. |
5457 | NestedNameSpecifier *NNS; |
5458 | |
5459 | /// The type that this typename specifier refers to. |
5460 | const IdentifierInfo *Name; |
5461 | |
5462 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5463 | const IdentifierInfo *Name, QualType CanonType) |
5464 | : TypeWithKeyword(Keyword, DependentName, CanonType, |
5465 | TypeDependence::DependentInstantiation | |
5466 | toTypeDependence(NNS->getDependence())), |
5467 | NNS(NNS), Name(Name) {} |
5468 | |
5469 | public: |
5470 | /// Retrieve the qualification on this type. |
5471 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5472 | |
5473 | /// Retrieve the type named by the typename specifier as an identifier. |
5474 | /// |
5475 | /// This routine will return a non-NULL identifier pointer when the |
5476 | /// form of the original typename was terminated by an identifier, |
5477 | /// e.g., "typename T::type". |
5478 | const IdentifierInfo *getIdentifier() const { |
5479 | return Name; |
5480 | } |
5481 | |
5482 | bool isSugared() const { return false; } |
5483 | QualType desugar() const { return QualType(this, 0); } |
5484 | |
5485 | void Profile(llvm::FoldingSetNodeID &ID) { |
5486 | Profile(ID, getKeyword(), NNS, Name); |
5487 | } |
5488 | |
5489 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5490 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5491 | ID.AddInteger(Keyword); |
5492 | ID.AddPointer(NNS); |
5493 | ID.AddPointer(Name); |
5494 | } |
5495 | |
5496 | static bool classof(const Type *T) { |
5497 | return T->getTypeClass() == DependentName; |
5498 | } |
5499 | }; |
5500 | |
5501 | /// Represents a template specialization type whose template cannot be |
5502 | /// resolved, e.g. |
5503 | /// A<T>::template B<T> |
5504 | class alignas(8) DependentTemplateSpecializationType |
5505 | : public TypeWithKeyword, |
5506 | public llvm::FoldingSetNode { |
5507 | friend class ASTContext; // ASTContext creates these |
5508 | |
5509 | /// The nested name specifier containing the qualifier. |
5510 | NestedNameSpecifier *NNS; |
5511 | |
5512 | /// The identifier of the template. |
5513 | const IdentifierInfo *Name; |
5514 | |
5515 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5516 | NestedNameSpecifier *NNS, |
5517 | const IdentifierInfo *Name, |
5518 | ArrayRef<TemplateArgument> Args, |
5519 | QualType Canon); |
5520 | |
5521 | const TemplateArgument *getArgBuffer() const { |
5522 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5523 | } |
5524 | |
5525 | TemplateArgument *getArgBuffer() { |
5526 | return reinterpret_cast<TemplateArgument*>(this+1); |
5527 | } |
5528 | |
5529 | public: |
5530 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5531 | const IdentifierInfo *getIdentifier() const { return Name; } |
5532 | |
5533 | /// Retrieve the template arguments. |
5534 | const TemplateArgument *getArgs() const { |
5535 | return getArgBuffer(); |
5536 | } |
5537 | |
5538 | /// Retrieve the number of template arguments. |
5539 | unsigned getNumArgs() const { |
5540 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5541 | } |
5542 | |
5543 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5544 | |
5545 | ArrayRef<TemplateArgument> template_arguments() const { |
5546 | return {getArgs(), getNumArgs()}; |
5547 | } |
5548 | |
5549 | using iterator = const TemplateArgument *; |
5550 | |
5551 | iterator begin() const { return getArgs(); } |
5552 | iterator end() const; // inline in TemplateBase.h |
5553 | |
5554 | bool isSugared() const { return false; } |
5555 | QualType desugar() const { return QualType(this, 0); } |
5556 | |
5557 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5558 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5559 | } |
5560 | |
5561 | static void Profile(llvm::FoldingSetNodeID &ID, |
5562 | const ASTContext &Context, |
5563 | ElaboratedTypeKeyword Keyword, |
5564 | NestedNameSpecifier *Qualifier, |
5565 | const IdentifierInfo *Name, |
5566 | ArrayRef<TemplateArgument> Args); |
5567 | |
5568 | static bool classof(const Type *T) { |
5569 | return T->getTypeClass() == DependentTemplateSpecialization; |
5570 | } |
5571 | }; |
5572 | |
5573 | /// Represents a pack expansion of types. |
5574 | /// |
5575 | /// Pack expansions are part of C++11 variadic templates. A pack |
5576 | /// expansion contains a pattern, which itself contains one or more |
5577 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5578 | /// produces a series of types, each instantiated from the pattern of |
5579 | /// the expansion, where the Ith instantiation of the pattern uses the |
5580 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5581 | /// pack expansion is considered to "expand" these unexpanded |
5582 | /// parameter packs. |
5583 | /// |
5584 | /// \code |
5585 | /// template<typename ...Types> struct tuple; |
5586 | /// |
5587 | /// template<typename ...Types> |
5588 | /// struct tuple_of_references { |
5589 | /// typedef tuple<Types&...> type; |
5590 | /// }; |
5591 | /// \endcode |
5592 | /// |
5593 | /// Here, the pack expansion \c Types&... is represented via a |
5594 | /// PackExpansionType whose pattern is Types&. |
5595 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5596 | friend class ASTContext; // ASTContext creates these |
5597 | |
5598 | /// The pattern of the pack expansion. |
5599 | QualType Pattern; |
5600 | |
5601 | PackExpansionType(QualType Pattern, QualType Canon, |
5602 | Optional<unsigned> NumExpansions) |
5603 | : Type(PackExpansion, Canon, |
5604 | (Pattern->getDependence() | TypeDependence::Dependent | |
5605 | TypeDependence::Instantiation) & |
5606 | ~TypeDependence::UnexpandedPack), |
5607 | Pattern(Pattern) { |
5608 | PackExpansionTypeBits.NumExpansions = |
5609 | NumExpansions ? *NumExpansions + 1 : 0; |
5610 | } |
5611 | |
5612 | public: |
5613 | /// Retrieve the pattern of this pack expansion, which is the |
5614 | /// type that will be repeatedly instantiated when instantiating the |
5615 | /// pack expansion itself. |
5616 | QualType getPattern() const { return Pattern; } |
5617 | |
5618 | /// Retrieve the number of expansions that this pack expansion will |
5619 | /// generate, if known. |
5620 | Optional<unsigned> getNumExpansions() const { |
5621 | if (PackExpansionTypeBits.NumExpansions) |
5622 | return PackExpansionTypeBits.NumExpansions - 1; |
5623 | return None; |
5624 | } |
5625 | |
5626 | bool isSugared() const { return false; } |
5627 | QualType desugar() const { return QualType(this, 0); } |
5628 | |
5629 | void Profile(llvm::FoldingSetNodeID &ID) { |
5630 | Profile(ID, getPattern(), getNumExpansions()); |
5631 | } |
5632 | |
5633 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5634 | Optional<unsigned> NumExpansions) { |
5635 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5636 | ID.AddBoolean(NumExpansions.hasValue()); |
5637 | if (NumExpansions) |
5638 | ID.AddInteger(*NumExpansions); |
5639 | } |
5640 | |
5641 | static bool classof(const Type *T) { |
5642 | return T->getTypeClass() == PackExpansion; |
5643 | } |
5644 | }; |
5645 | |
5646 | /// This class wraps the list of protocol qualifiers. For types that can |
5647 | /// take ObjC protocol qualifers, they can subclass this class. |
5648 | template <class T> |
5649 | class ObjCProtocolQualifiers { |
5650 | protected: |
5651 | ObjCProtocolQualifiers() = default; |
5652 | |
5653 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5654 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5655 | } |
5656 | |
5657 | ObjCProtocolDecl **getProtocolStorage() { |
5658 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5659 | } |
5660 | |
5661 | void setNumProtocols(unsigned N) { |
5662 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5663 | } |
5664 | |
5665 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5666 | setNumProtocols(protocols.size()); |
5667 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5668, __PRETTY_FUNCTION__)) |
5668 | "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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5668, __PRETTY_FUNCTION__)); |
5669 | if (!protocols.empty()) |
5670 | memcpy(getProtocolStorage(), protocols.data(), |
5671 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5672 | } |
5673 | |
5674 | public: |
5675 | using qual_iterator = ObjCProtocolDecl * const *; |
5676 | using qual_range = llvm::iterator_range<qual_iterator>; |
5677 | |
5678 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5679 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5680 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5681 | |
5682 | bool qual_empty() const { return getNumProtocols() == 0; } |
5683 | |
5684 | /// Return the number of qualifying protocols in this type, or 0 if |
5685 | /// there are none. |
5686 | unsigned getNumProtocols() const { |
5687 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5688 | } |
5689 | |
5690 | /// Fetch a protocol by index. |
5691 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5692 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5692, __PRETTY_FUNCTION__)); |
5693 | return qual_begin()[I]; |
5694 | } |
5695 | |
5696 | /// Retrieve all of the protocol qualifiers. |
5697 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5698 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5699 | } |
5700 | }; |
5701 | |
5702 | /// Represents a type parameter type in Objective C. It can take |
5703 | /// a list of protocols. |
5704 | class ObjCTypeParamType : public Type, |
5705 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5706 | public llvm::FoldingSetNode { |
5707 | friend class ASTContext; |
5708 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5709 | |
5710 | /// The number of protocols stored on this type. |
5711 | unsigned NumProtocols : 6; |
5712 | |
5713 | ObjCTypeParamDecl *OTPDecl; |
5714 | |
5715 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5716 | /// canonical type, the list of protocols are sorted alphabetically |
5717 | /// and uniqued. |
5718 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5719 | |
5720 | /// Return the number of qualifying protocols in this interface type, |
5721 | /// or 0 if there are none. |
5722 | unsigned getNumProtocolsImpl() const { |
5723 | return NumProtocols; |
5724 | } |
5725 | |
5726 | void setNumProtocolsImpl(unsigned N) { |
5727 | NumProtocols = N; |
5728 | } |
5729 | |
5730 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5731 | QualType can, |
5732 | ArrayRef<ObjCProtocolDecl *> protocols); |
5733 | |
5734 | public: |
5735 | bool isSugared() const { return true; } |
5736 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5737 | |
5738 | static bool classof(const Type *T) { |
5739 | return T->getTypeClass() == ObjCTypeParam; |
5740 | } |
5741 | |
5742 | void Profile(llvm::FoldingSetNodeID &ID); |
5743 | static void Profile(llvm::FoldingSetNodeID &ID, |
5744 | const ObjCTypeParamDecl *OTPDecl, |
5745 | QualType CanonicalType, |
5746 | ArrayRef<ObjCProtocolDecl *> protocols); |
5747 | |
5748 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5749 | }; |
5750 | |
5751 | /// Represents a class type in Objective C. |
5752 | /// |
5753 | /// Every Objective C type is a combination of a base type, a set of |
5754 | /// type arguments (optional, for parameterized classes) and a list of |
5755 | /// protocols. |
5756 | /// |
5757 | /// Given the following declarations: |
5758 | /// \code |
5759 | /// \@class C<T>; |
5760 | /// \@protocol P; |
5761 | /// \endcode |
5762 | /// |
5763 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5764 | /// with base C and no protocols. |
5765 | /// |
5766 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5767 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5768 | /// protocol list. |
5769 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5770 | /// and protocol list [P]. |
5771 | /// |
5772 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5773 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5774 | /// and no protocols. |
5775 | /// |
5776 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5777 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5778 | /// this should get its own sugar class to better represent the source. |
5779 | class ObjCObjectType : public Type, |
5780 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5781 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5782 | |
5783 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5784 | // after the ObjCObjectPointerType node. |
5785 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5786 | // after the type arguments of ObjCObjectPointerType node. |
5787 | // |
5788 | // These protocols are those written directly on the type. If |
5789 | // protocol qualifiers ever become additive, the iterators will need |
5790 | // to get kindof complicated. |
5791 | // |
5792 | // In the canonical object type, these are sorted alphabetically |
5793 | // and uniqued. |
5794 | |
5795 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5796 | QualType BaseType; |
5797 | |
5798 | /// Cached superclass type. |
5799 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5800 | CachedSuperClassType; |
5801 | |
5802 | QualType *getTypeArgStorage(); |
5803 | const QualType *getTypeArgStorage() const { |
5804 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5805 | } |
5806 | |
5807 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5808 | /// Return the number of qualifying protocols in this interface type, |
5809 | /// or 0 if there are none. |
5810 | unsigned getNumProtocolsImpl() const { |
5811 | return ObjCObjectTypeBits.NumProtocols; |
5812 | } |
5813 | void setNumProtocolsImpl(unsigned N) { |
5814 | ObjCObjectTypeBits.NumProtocols = N; |
5815 | } |
5816 | |
5817 | protected: |
5818 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5819 | |
5820 | ObjCObjectType(QualType Canonical, QualType Base, |
5821 | ArrayRef<QualType> typeArgs, |
5822 | ArrayRef<ObjCProtocolDecl *> protocols, |
5823 | bool isKindOf); |
5824 | |
5825 | ObjCObjectType(enum Nonce_ObjCInterface) |
5826 | : Type(ObjCInterface, QualType(), TypeDependence::None), |
5827 | BaseType(QualType(this_(), 0)) { |
5828 | ObjCObjectTypeBits.NumProtocols = 0; |
5829 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5830 | ObjCObjectTypeBits.IsKindOf = 0; |
5831 | } |
5832 | |
5833 | void computeSuperClassTypeSlow() const; |
5834 | |
5835 | public: |
5836 | /// Gets the base type of this object type. This is always (possibly |
5837 | /// sugar for) one of: |
5838 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5839 | /// user, which is a typedef for an ObjCObjectPointerType) |
5840 | /// - the 'Class' builtin type (same caveat) |
5841 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5842 | QualType getBaseType() const { return BaseType; } |
5843 | |
5844 | bool isObjCId() const { |
5845 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5846 | } |
5847 | |
5848 | bool isObjCClass() const { |
5849 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5850 | } |
5851 | |
5852 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5853 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5854 | bool isObjCUnqualifiedIdOrClass() const { |
5855 | if (!qual_empty()) return false; |
5856 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5857 | return T->getKind() == BuiltinType::ObjCId || |
5858 | T->getKind() == BuiltinType::ObjCClass; |
5859 | return false; |
5860 | } |
5861 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5862 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5863 | |
5864 | /// Gets the interface declaration for this object type, if the base type |
5865 | /// really is an interface. |
5866 | ObjCInterfaceDecl *getInterface() const; |
5867 | |
5868 | /// Determine whether this object type is "specialized", meaning |
5869 | /// that it has type arguments. |
5870 | bool isSpecialized() const; |
5871 | |
5872 | /// Determine whether this object type was written with type arguments. |
5873 | bool isSpecializedAsWritten() const { |
5874 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5875 | } |
5876 | |
5877 | /// Determine whether this object type is "unspecialized", meaning |
5878 | /// that it has no type arguments. |
5879 | bool isUnspecialized() const { return !isSpecialized(); } |
5880 | |
5881 | /// Determine whether this object type is "unspecialized" as |
5882 | /// written, meaning that it has no type arguments. |
5883 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5884 | |
5885 | /// Retrieve the type arguments of this object type (semantically). |
5886 | ArrayRef<QualType> getTypeArgs() const; |
5887 | |
5888 | /// Retrieve the type arguments of this object type as they were |
5889 | /// written. |
5890 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5891 | return llvm::makeArrayRef(getTypeArgStorage(), |
5892 | ObjCObjectTypeBits.NumTypeArgs); |
5893 | } |
5894 | |
5895 | /// Whether this is a "__kindof" type as written. |
5896 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5897 | |
5898 | /// Whether this ia a "__kindof" type (semantically). |
5899 | bool isKindOfType() const; |
5900 | |
5901 | /// Retrieve the type of the superclass of this object type. |
5902 | /// |
5903 | /// This operation substitutes any type arguments into the |
5904 | /// superclass of the current class type, potentially producing a |
5905 | /// specialization of the superclass type. Produces a null type if |
5906 | /// there is no superclass. |
5907 | QualType getSuperClassType() const { |
5908 | if (!CachedSuperClassType.getInt()) |
5909 | computeSuperClassTypeSlow(); |
5910 | |
5911 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 5911, __PRETTY_FUNCTION__)); |
5912 | return QualType(CachedSuperClassType.getPointer(), 0); |
5913 | } |
5914 | |
5915 | /// Strip off the Objective-C "kindof" type and (with it) any |
5916 | /// protocol qualifiers. |
5917 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5918 | |
5919 | bool isSugared() const { return false; } |
5920 | QualType desugar() const { return QualType(this, 0); } |
5921 | |
5922 | static bool classof(const Type *T) { |
5923 | return T->getTypeClass() == ObjCObject || |
5924 | T->getTypeClass() == ObjCInterface; |
5925 | } |
5926 | }; |
5927 | |
5928 | /// A class providing a concrete implementation |
5929 | /// of ObjCObjectType, so as to not increase the footprint of |
5930 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5931 | /// system should not reference this type. |
5932 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5933 | friend class ASTContext; |
5934 | |
5935 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5936 | // will need to be modified. |
5937 | |
5938 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5939 | ArrayRef<QualType> typeArgs, |
5940 | ArrayRef<ObjCProtocolDecl *> protocols, |
5941 | bool isKindOf) |
5942 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5943 | |
5944 | public: |
5945 | void Profile(llvm::FoldingSetNodeID &ID); |
5946 | static void Profile(llvm::FoldingSetNodeID &ID, |
5947 | QualType Base, |
5948 | ArrayRef<QualType> typeArgs, |
5949 | ArrayRef<ObjCProtocolDecl *> protocols, |
5950 | bool isKindOf); |
5951 | }; |
5952 | |
5953 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5954 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5955 | } |
5956 | |
5957 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5958 | return reinterpret_cast<ObjCProtocolDecl**>( |
5959 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5960 | } |
5961 | |
5962 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5963 | return reinterpret_cast<ObjCProtocolDecl**>( |
5964 | static_cast<ObjCTypeParamType*>(this)+1); |
5965 | } |
5966 | |
5967 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5968 | /// They basically correspond to C++ classes. There are two kinds of interface |
5969 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5970 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5971 | /// |
5972 | /// ObjCInterfaceType guarantees the following properties when considered |
5973 | /// as a subtype of its superclass, ObjCObjectType: |
5974 | /// - There are no protocol qualifiers. To reinforce this, code which |
5975 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5976 | /// fail to compile. |
5977 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5978 | /// T->getBaseType() == QualType(T, 0). |
5979 | class ObjCInterfaceType : public ObjCObjectType { |
5980 | friend class ASTContext; // ASTContext creates these. |
5981 | friend class ASTReader; |
5982 | friend class ObjCInterfaceDecl; |
5983 | template <class T> friend class serialization::AbstractTypeReader; |
5984 | |
5985 | mutable ObjCInterfaceDecl *Decl; |
5986 | |
5987 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5988 | : ObjCObjectType(Nonce_ObjCInterface), |
5989 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5990 | |
5991 | public: |
5992 | /// Get the declaration of this interface. |
5993 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5994 | |
5995 | bool isSugared() const { return false; } |
5996 | QualType desugar() const { return QualType(this, 0); } |
5997 | |
5998 | static bool classof(const Type *T) { |
5999 | return T->getTypeClass() == ObjCInterface; |
6000 | } |
6001 | |
6002 | // Nonsense to "hide" certain members of ObjCObjectType within this |
6003 | // class. People asking for protocols on an ObjCInterfaceType are |
6004 | // not going to get what they want: ObjCInterfaceTypes are |
6005 | // guaranteed to have no protocols. |
6006 | enum { |
6007 | qual_iterator, |
6008 | qual_begin, |
6009 | qual_end, |
6010 | getNumProtocols, |
6011 | getProtocol |
6012 | }; |
6013 | }; |
6014 | |
6015 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
6016 | QualType baseType = getBaseType(); |
6017 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
6018 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
6019 | return T->getDecl(); |
6020 | |
6021 | baseType = ObjT->getBaseType(); |
6022 | } |
6023 | |
6024 | return nullptr; |
6025 | } |
6026 | |
6027 | /// Represents a pointer to an Objective C object. |
6028 | /// |
6029 | /// These are constructed from pointer declarators when the pointee type is |
6030 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
6031 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
6032 | /// and 'Class<P>' are translated into these. |
6033 | /// |
6034 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
6035 | /// only the first level of pointer gets it own type implementation. |
6036 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
6037 | friend class ASTContext; // ASTContext creates these. |
6038 | |
6039 | QualType PointeeType; |
6040 | |
6041 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
6042 | : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()), |
6043 | PointeeType(Pointee) {} |
6044 | |
6045 | public: |
6046 | /// Gets the type pointed to by this ObjC pointer. |
6047 | /// The result will always be an ObjCObjectType or sugar thereof. |
6048 | QualType getPointeeType() const { return PointeeType; } |
6049 | |
6050 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
6051 | /// |
6052 | /// This method is equivalent to getPointeeType() except that |
6053 | /// it discards any typedefs (or other sugar) between this |
6054 | /// type and the "outermost" object type. So for: |
6055 | /// \code |
6056 | /// \@class A; \@protocol P; \@protocol Q; |
6057 | /// typedef A<P> AP; |
6058 | /// typedef A A1; |
6059 | /// typedef A1<P> A1P; |
6060 | /// typedef A1P<Q> A1PQ; |
6061 | /// \endcode |
6062 | /// For 'A*', getObjectType() will return 'A'. |
6063 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
6064 | /// For 'AP*', getObjectType() will return 'A<P>'. |
6065 | /// For 'A1*', getObjectType() will return 'A'. |
6066 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
6067 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
6068 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
6069 | /// adding protocols to a protocol-qualified base discards the |
6070 | /// old qualifiers (for now). But if it didn't, getObjectType() |
6071 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
6072 | /// qualifiers more complicated). |
6073 | const ObjCObjectType *getObjectType() const { |
6074 | return PointeeType->castAs<ObjCObjectType>(); |
6075 | } |
6076 | |
6077 | /// If this pointer points to an Objective C |
6078 | /// \@interface type, gets the type for that interface. Any protocol |
6079 | /// qualifiers on the interface are ignored. |
6080 | /// |
6081 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6082 | const ObjCInterfaceType *getInterfaceType() const; |
6083 | |
6084 | /// If this pointer points to an Objective \@interface |
6085 | /// type, gets the declaration for that interface. |
6086 | /// |
6087 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6088 | ObjCInterfaceDecl *getInterfaceDecl() const { |
6089 | return getObjectType()->getInterface(); |
6090 | } |
6091 | |
6092 | /// True if this is equivalent to the 'id' type, i.e. if |
6093 | /// its object type is the primitive 'id' type with no protocols. |
6094 | bool isObjCIdType() const { |
6095 | return getObjectType()->isObjCUnqualifiedId(); |
6096 | } |
6097 | |
6098 | /// True if this is equivalent to the 'Class' type, |
6099 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
6100 | bool isObjCClassType() const { |
6101 | return getObjectType()->isObjCUnqualifiedClass(); |
6102 | } |
6103 | |
6104 | /// True if this is equivalent to the 'id' or 'Class' type, |
6105 | bool isObjCIdOrClassType() const { |
6106 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
6107 | } |
6108 | |
6109 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
6110 | /// protocols. |
6111 | bool isObjCQualifiedIdType() const { |
6112 | return getObjectType()->isObjCQualifiedId(); |
6113 | } |
6114 | |
6115 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
6116 | /// protocols. |
6117 | bool isObjCQualifiedClassType() const { |
6118 | return getObjectType()->isObjCQualifiedClass(); |
6119 | } |
6120 | |
6121 | /// Whether this is a "__kindof" type. |
6122 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
6123 | |
6124 | /// Whether this type is specialized, meaning that it has type arguments. |
6125 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
6126 | |
6127 | /// Whether this type is specialized, meaning that it has type arguments. |
6128 | bool isSpecializedAsWritten() const { |
6129 | return getObjectType()->isSpecializedAsWritten(); |
6130 | } |
6131 | |
6132 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
6133 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
6134 | |
6135 | /// Determine whether this object type is "unspecialized" as |
6136 | /// written, meaning that it has no type arguments. |
6137 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
6138 | |
6139 | /// Retrieve the type arguments for this type. |
6140 | ArrayRef<QualType> getTypeArgs() const { |
6141 | return getObjectType()->getTypeArgs(); |
6142 | } |
6143 | |
6144 | /// Retrieve the type arguments for this type. |
6145 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
6146 | return getObjectType()->getTypeArgsAsWritten(); |
6147 | } |
6148 | |
6149 | /// An iterator over the qualifiers on the object type. Provided |
6150 | /// for convenience. This will always iterate over the full set of |
6151 | /// protocols on a type, not just those provided directly. |
6152 | using qual_iterator = ObjCObjectType::qual_iterator; |
6153 | using qual_range = llvm::iterator_range<qual_iterator>; |
6154 | |
6155 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
6156 | |
6157 | qual_iterator qual_begin() const { |
6158 | return getObjectType()->qual_begin(); |
6159 | } |
6160 | |
6161 | qual_iterator qual_end() const { |
6162 | return getObjectType()->qual_end(); |
6163 | } |
6164 | |
6165 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6166 | |
6167 | /// Return the number of qualifying protocols on the object type. |
6168 | unsigned getNumProtocols() const { |
6169 | return getObjectType()->getNumProtocols(); |
6170 | } |
6171 | |
6172 | /// Retrieve a qualifying protocol by index on the object type. |
6173 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6174 | return getObjectType()->getProtocol(I); |
6175 | } |
6176 | |
6177 | bool isSugared() const { return false; } |
6178 | QualType desugar() const { return QualType(this, 0); } |
6179 | |
6180 | /// Retrieve the type of the superclass of this object pointer type. |
6181 | /// |
6182 | /// This operation substitutes any type arguments into the |
6183 | /// superclass of the current class type, potentially producing a |
6184 | /// pointer to a specialization of the superclass type. Produces a |
6185 | /// null type if there is no superclass. |
6186 | QualType getSuperClassType() const; |
6187 | |
6188 | /// Strip off the Objective-C "kindof" type and (with it) any |
6189 | /// protocol qualifiers. |
6190 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6191 | const ASTContext &ctx) const; |
6192 | |
6193 | void Profile(llvm::FoldingSetNodeID &ID) { |
6194 | Profile(ID, getPointeeType()); |
6195 | } |
6196 | |
6197 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6198 | ID.AddPointer(T.getAsOpaquePtr()); |
6199 | } |
6200 | |
6201 | static bool classof(const Type *T) { |
6202 | return T->getTypeClass() == ObjCObjectPointer; |
6203 | } |
6204 | }; |
6205 | |
6206 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6207 | friend class ASTContext; // ASTContext creates these. |
6208 | |
6209 | QualType ValueType; |
6210 | |
6211 | AtomicType(QualType ValTy, QualType Canonical) |
6212 | : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {} |
6213 | |
6214 | public: |
6215 | /// Gets the type contained by this atomic type, i.e. |
6216 | /// the type returned by performing an atomic load of this atomic type. |
6217 | QualType getValueType() const { return ValueType; } |
6218 | |
6219 | bool isSugared() const { return false; } |
6220 | QualType desugar() const { return QualType(this, 0); } |
6221 | |
6222 | void Profile(llvm::FoldingSetNodeID &ID) { |
6223 | Profile(ID, getValueType()); |
6224 | } |
6225 | |
6226 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6227 | ID.AddPointer(T.getAsOpaquePtr()); |
6228 | } |
6229 | |
6230 | static bool classof(const Type *T) { |
6231 | return T->getTypeClass() == Atomic; |
6232 | } |
6233 | }; |
6234 | |
6235 | /// PipeType - OpenCL20. |
6236 | class PipeType : public Type, public llvm::FoldingSetNode { |
6237 | friend class ASTContext; // ASTContext creates these. |
6238 | |
6239 | QualType ElementType; |
6240 | bool isRead; |
6241 | |
6242 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6243 | : Type(Pipe, CanonicalPtr, elemType->getDependence()), |
6244 | ElementType(elemType), isRead(isRead) {} |
6245 | |
6246 | public: |
6247 | QualType getElementType() const { return ElementType; } |
6248 | |
6249 | bool isSugared() const { return false; } |
6250 | |
6251 | QualType desugar() const { return QualType(this, 0); } |
6252 | |
6253 | void Profile(llvm::FoldingSetNodeID &ID) { |
6254 | Profile(ID, getElementType(), isReadOnly()); |
6255 | } |
6256 | |
6257 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6258 | ID.AddPointer(T.getAsOpaquePtr()); |
6259 | ID.AddBoolean(isRead); |
6260 | } |
6261 | |
6262 | static bool classof(const Type *T) { |
6263 | return T->getTypeClass() == Pipe; |
6264 | } |
6265 | |
6266 | bool isReadOnly() const { return isRead; } |
6267 | }; |
6268 | |
6269 | /// A fixed int type of a specified bitwidth. |
6270 | class ExtIntType final : public Type, public llvm::FoldingSetNode { |
6271 | friend class ASTContext; |
6272 | unsigned IsUnsigned : 1; |
6273 | unsigned NumBits : 24; |
6274 | |
6275 | protected: |
6276 | ExtIntType(bool isUnsigned, unsigned NumBits); |
6277 | |
6278 | public: |
6279 | bool isUnsigned() const { return IsUnsigned; } |
6280 | bool isSigned() const { return !IsUnsigned; } |
6281 | unsigned getNumBits() const { return NumBits; } |
6282 | |
6283 | bool isSugared() const { return false; } |
6284 | QualType desugar() const { return QualType(this, 0); } |
6285 | |
6286 | void Profile(llvm::FoldingSetNodeID &ID) { |
6287 | Profile(ID, isUnsigned(), getNumBits()); |
6288 | } |
6289 | |
6290 | static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned, |
6291 | unsigned NumBits) { |
6292 | ID.AddBoolean(IsUnsigned); |
6293 | ID.AddInteger(NumBits); |
6294 | } |
6295 | |
6296 | static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; } |
6297 | }; |
6298 | |
6299 | class DependentExtIntType final : public Type, public llvm::FoldingSetNode { |
6300 | friend class ASTContext; |
6301 | const ASTContext &Context; |
6302 | llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned; |
6303 | |
6304 | protected: |
6305 | DependentExtIntType(const ASTContext &Context, bool IsUnsigned, |
6306 | Expr *NumBits); |
6307 | |
6308 | public: |
6309 | bool isUnsigned() const; |
6310 | bool isSigned() const { return !isUnsigned(); } |
6311 | Expr *getNumBitsExpr() const; |
6312 | |
6313 | bool isSugared() const { return false; } |
6314 | QualType desugar() const { return QualType(this, 0); } |
6315 | |
6316 | void Profile(llvm::FoldingSetNodeID &ID) { |
6317 | Profile(ID, Context, isUnsigned(), getNumBitsExpr()); |
6318 | } |
6319 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
6320 | bool IsUnsigned, Expr *NumBitsExpr); |
6321 | |
6322 | static bool classof(const Type *T) { |
6323 | return T->getTypeClass() == DependentExtInt; |
6324 | } |
6325 | }; |
6326 | |
6327 | /// A qualifier set is used to build a set of qualifiers. |
6328 | class QualifierCollector : public Qualifiers { |
6329 | public: |
6330 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6331 | |
6332 | /// Collect any qualifiers on the given type and return an |
6333 | /// unqualified type. The qualifiers are assumed to be consistent |
6334 | /// with those already in the type. |
6335 | const Type *strip(QualType type) { |
6336 | addFastQualifiers(type.getLocalFastQualifiers()); |
6337 | if (!type.hasLocalNonFastQualifiers()) |
6338 | return type.getTypePtrUnsafe(); |
6339 | |
6340 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6341 | addConsistentQualifiers(extQuals->getQualifiers()); |
6342 | return extQuals->getBaseType(); |
6343 | } |
6344 | |
6345 | /// Apply the collected qualifiers to the given type. |
6346 | QualType apply(const ASTContext &Context, QualType QT) const; |
6347 | |
6348 | /// Apply the collected qualifiers to the given type. |
6349 | QualType apply(const ASTContext &Context, const Type* T) const; |
6350 | }; |
6351 | |
6352 | /// A container of type source information. |
6353 | /// |
6354 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
6355 | /// @code |
6356 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
6357 | /// TL.getBeginLoc().print(OS, SrcMgr); |
6358 | /// @endcode |
6359 | class alignas(8) TypeSourceInfo { |
6360 | // Contains a memory block after the class, used for type source information, |
6361 | // allocated by ASTContext. |
6362 | friend class ASTContext; |
6363 | |
6364 | QualType Ty; |
6365 | |
6366 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
6367 | |
6368 | public: |
6369 | /// Return the type wrapped by this type source info. |
6370 | QualType getType() const { return Ty; } |
6371 | |
6372 | /// Return the TypeLoc wrapper for the type source info. |
6373 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
6374 | |
6375 | /// Override the type stored in this TypeSourceInfo. Use with caution! |
6376 | void overrideType(QualType T) { Ty = T; } |
6377 | }; |
6378 | |
6379 | // Inline function definitions. |
6380 | |
6381 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6382 | SplitQualType desugar = |
6383 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6384 | desugar.Quals.addConsistentQualifiers(Quals); |
6385 | return desugar; |
6386 | } |
6387 | |
6388 | inline const Type *QualType::getTypePtr() const { |
6389 | return getCommonPtr()->BaseType; |
6390 | } |
6391 | |
6392 | inline const Type *QualType::getTypePtrOrNull() const { |
6393 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6394 | } |
6395 | |
6396 | inline SplitQualType QualType::split() const { |
6397 | if (!hasLocalNonFastQualifiers()) |
6398 | return SplitQualType(getTypePtrUnsafe(), |
6399 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6400 | |
6401 | const ExtQuals *eq = getExtQualsUnsafe(); |
6402 | Qualifiers qs = eq->getQualifiers(); |
6403 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6404 | return SplitQualType(eq->getBaseType(), qs); |
6405 | } |
6406 | |
6407 | inline Qualifiers QualType::getLocalQualifiers() const { |
6408 | Qualifiers Quals; |
6409 | if (hasLocalNonFastQualifiers()) |
6410 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6411 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6412 | return Quals; |
6413 | } |
6414 | |
6415 | inline Qualifiers QualType::getQualifiers() const { |
6416 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6417 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6418 | return quals; |
6419 | } |
6420 | |
6421 | inline unsigned QualType::getCVRQualifiers() const { |
6422 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6423 | cvr |= getLocalCVRQualifiers(); |
6424 | return cvr; |
6425 | } |
6426 | |
6427 | inline QualType QualType::getCanonicalType() const { |
6428 | QualType canon = getCommonPtr()->CanonicalType; |
6429 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6430 | } |
6431 | |
6432 | inline bool QualType::isCanonical() const { |
6433 | return getTypePtr()->isCanonicalUnqualified(); |
6434 | } |
6435 | |
6436 | inline bool QualType::isCanonicalAsParam() const { |
6437 | if (!isCanonical()) return false; |
6438 | if (hasLocalQualifiers()) return false; |
6439 | |
6440 | const Type *T = getTypePtr(); |
6441 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6442 | return false; |
6443 | |
6444 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6445 | } |
6446 | |
6447 | inline bool QualType::isConstQualified() const { |
6448 | return isLocalConstQualified() || |
6449 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6450 | } |
6451 | |
6452 | inline bool QualType::isRestrictQualified() const { |
6453 | return isLocalRestrictQualified() || |
6454 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6455 | } |
6456 | |
6457 | |
6458 | inline bool QualType::isVolatileQualified() const { |
6459 | return isLocalVolatileQualified() || |
6460 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6461 | } |
6462 | |
6463 | inline bool QualType::hasQualifiers() const { |
6464 | return hasLocalQualifiers() || |
6465 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6466 | } |
6467 | |
6468 | inline QualType QualType::getUnqualifiedType() const { |
6469 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6470 | return QualType(getTypePtr(), 0); |
6471 | |
6472 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6473 | } |
6474 | |
6475 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6476 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6477 | return split(); |
6478 | |
6479 | return getSplitUnqualifiedTypeImpl(*this); |
6480 | } |
6481 | |
6482 | inline void QualType::removeLocalConst() { |
6483 | removeLocalFastQualifiers(Qualifiers::Const); |
6484 | } |
6485 | |
6486 | inline void QualType::removeLocalRestrict() { |
6487 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6488 | } |
6489 | |
6490 | inline void QualType::removeLocalVolatile() { |
6491 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6492 | } |
6493 | |
6494 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6495 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 6495, __PRETTY_FUNCTION__)); |
6496 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6497 | "Fast bits differ from CVR bits!"); |
6498 | |
6499 | // Fast path: we don't need to touch the slow qualifiers. |
6500 | removeLocalFastQualifiers(Mask); |
6501 | } |
6502 | |
6503 | /// Check if this type has any address space qualifier. |
6504 | inline bool QualType::hasAddressSpace() const { |
6505 | return getQualifiers().hasAddressSpace(); |
6506 | } |
6507 | |
6508 | /// Return the address space of this type. |
6509 | inline LangAS QualType::getAddressSpace() const { |
6510 | return getQualifiers().getAddressSpace(); |
6511 | } |
6512 | |
6513 | /// Return the gc attribute of this type. |
6514 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6515 | return getQualifiers().getObjCGCAttr(); |
6516 | } |
6517 | |
6518 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6519 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6520 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6521 | return false; |
6522 | } |
6523 | |
6524 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6525 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6526 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6527 | return false; |
6528 | } |
6529 | |
6530 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6531 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6532 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6533 | return false; |
6534 | } |
6535 | |
6536 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6537 | if (const auto *PT = t.getAs<PointerType>()) { |
6538 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6539 | return FT->getExtInfo(); |
6540 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6541 | return FT->getExtInfo(); |
6542 | |
6543 | return FunctionType::ExtInfo(); |
6544 | } |
6545 | |
6546 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6547 | return getFunctionExtInfo(*t); |
6548 | } |
6549 | |
6550 | /// Determine whether this type is more |
6551 | /// qualified than the Other type. For example, "const volatile int" |
6552 | /// is more qualified than "const int", "volatile int", and |
6553 | /// "int". However, it is not more qualified than "const volatile |
6554 | /// int". |
6555 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6556 | Qualifiers MyQuals = getQualifiers(); |
6557 | Qualifiers OtherQuals = other.getQualifiers(); |
6558 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6559 | } |
6560 | |
6561 | /// Determine whether this type is at last |
6562 | /// as qualified as the Other type. For example, "const volatile |
6563 | /// int" is at least as qualified as "const int", "volatile int", |
6564 | /// "int", and "const volatile int". |
6565 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6566 | Qualifiers OtherQuals = other.getQualifiers(); |
6567 | |
6568 | // Ignore __unaligned qualifier if this type is a void. |
6569 | if (getUnqualifiedType()->isVoidType()) |
6570 | OtherQuals.removeUnaligned(); |
6571 | |
6572 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6573 | } |
6574 | |
6575 | /// If Type is a reference type (e.g., const |
6576 | /// int&), returns the type that the reference refers to ("const |
6577 | /// int"). Otherwise, returns the type itself. This routine is used |
6578 | /// throughout Sema to implement C++ 5p6: |
6579 | /// |
6580 | /// If an expression initially has the type "reference to T" (8.3.2, |
6581 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6582 | /// analysis, the expression designates the object or function |
6583 | /// denoted by the reference, and the expression is an lvalue. |
6584 | inline QualType QualType::getNonReferenceType() const { |
6585 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6586 | return RefType->getPointeeType(); |
6587 | else |
6588 | return *this; |
6589 | } |
6590 | |
6591 | inline bool QualType::isCForbiddenLValueType() const { |
6592 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6593 | getTypePtr()->isFunctionType()); |
6594 | } |
6595 | |
6596 | /// Tests whether the type is categorized as a fundamental type. |
6597 | /// |
6598 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6599 | inline bool Type::isFundamentalType() const { |
6600 | return isVoidType() || |
6601 | isNullPtrType() || |
6602 | // FIXME: It's really annoying that we don't have an |
6603 | // 'isArithmeticType()' which agrees with the standard definition. |
6604 | (isArithmeticType() && !isEnumeralType()); |
6605 | } |
6606 | |
6607 | /// Tests whether the type is categorized as a compound type. |
6608 | /// |
6609 | /// \returns True for types specified in C++0x [basic.compound]. |
6610 | inline bool Type::isCompoundType() const { |
6611 | // C++0x [basic.compound]p1: |
6612 | // Compound types can be constructed in the following ways: |
6613 | // -- arrays of objects of a given type [...]; |
6614 | return isArrayType() || |
6615 | // -- functions, which have parameters of given types [...]; |
6616 | isFunctionType() || |
6617 | // -- pointers to void or objects or functions [...]; |
6618 | isPointerType() || |
6619 | // -- references to objects or functions of a given type. [...] |
6620 | isReferenceType() || |
6621 | // -- classes containing a sequence of objects of various types, [...]; |
6622 | isRecordType() || |
6623 | // -- unions, which are classes capable of containing objects of different |
6624 | // types at different times; |
6625 | isUnionType() || |
6626 | // -- enumerations, which comprise a set of named constant values. [...]; |
6627 | isEnumeralType() || |
6628 | // -- pointers to non-static class members, [...]. |
6629 | isMemberPointerType(); |
6630 | } |
6631 | |
6632 | inline bool Type::isFunctionType() const { |
6633 | return isa<FunctionType>(CanonicalType); |
6634 | } |
6635 | |
6636 | inline bool Type::isPointerType() const { |
6637 | return isa<PointerType>(CanonicalType); |
6638 | } |
6639 | |
6640 | inline bool Type::isAnyPointerType() const { |
6641 | return isPointerType() || isObjCObjectPointerType(); |
6642 | } |
6643 | |
6644 | inline bool Type::isBlockPointerType() const { |
6645 | return isa<BlockPointerType>(CanonicalType); |
6646 | } |
6647 | |
6648 | inline bool Type::isReferenceType() const { |
6649 | return isa<ReferenceType>(CanonicalType); |
6650 | } |
6651 | |
6652 | inline bool Type::isLValueReferenceType() const { |
6653 | return isa<LValueReferenceType>(CanonicalType); |
6654 | } |
6655 | |
6656 | inline bool Type::isRValueReferenceType() const { |
6657 | return isa<RValueReferenceType>(CanonicalType); |
6658 | } |
6659 | |
6660 | inline bool Type::isObjectPointerType() const { |
6661 | // Note: an "object pointer type" is not the same thing as a pointer to an |
6662 | // object type; rather, it is a pointer to an object type or a pointer to cv |
6663 | // void. |
6664 | if (const auto *T = getAs<PointerType>()) |
6665 | return !T->getPointeeType()->isFunctionType(); |
6666 | else |
6667 | return false; |
6668 | } |
6669 | |
6670 | inline bool Type::isFunctionPointerType() const { |
6671 | if (const auto *T = getAs<PointerType>()) |
6672 | return T->getPointeeType()->isFunctionType(); |
6673 | else |
6674 | return false; |
6675 | } |
6676 | |
6677 | inline bool Type::isFunctionReferenceType() const { |
6678 | if (const auto *T = getAs<ReferenceType>()) |
6679 | return T->getPointeeType()->isFunctionType(); |
6680 | else |
6681 | return false; |
6682 | } |
6683 | |
6684 | inline bool Type::isMemberPointerType() const { |
6685 | return isa<MemberPointerType>(CanonicalType); |
6686 | } |
6687 | |
6688 | inline bool Type::isMemberFunctionPointerType() const { |
6689 | if (const auto *T = getAs<MemberPointerType>()) |
6690 | return T->isMemberFunctionPointer(); |
6691 | else |
6692 | return false; |
6693 | } |
6694 | |
6695 | inline bool Type::isMemberDataPointerType() const { |
6696 | if (const auto *T = getAs<MemberPointerType>()) |
6697 | return T->isMemberDataPointer(); |
6698 | else |
6699 | return false; |
6700 | } |
6701 | |
6702 | inline bool Type::isArrayType() const { |
6703 | return isa<ArrayType>(CanonicalType); |
6704 | } |
6705 | |
6706 | inline bool Type::isConstantArrayType() const { |
6707 | return isa<ConstantArrayType>(CanonicalType); |
6708 | } |
6709 | |
6710 | inline bool Type::isIncompleteArrayType() const { |
6711 | return isa<IncompleteArrayType>(CanonicalType); |
6712 | } |
6713 | |
6714 | inline bool Type::isVariableArrayType() const { |
6715 | return isa<VariableArrayType>(CanonicalType); |
6716 | } |
6717 | |
6718 | inline bool Type::isDependentSizedArrayType() const { |
6719 | return isa<DependentSizedArrayType>(CanonicalType); |
6720 | } |
6721 | |
6722 | inline bool Type::isBuiltinType() const { |
6723 | return isa<BuiltinType>(CanonicalType); |
6724 | } |
6725 | |
6726 | inline bool Type::isRecordType() const { |
6727 | return isa<RecordType>(CanonicalType); |
6728 | } |
6729 | |
6730 | inline bool Type::isEnumeralType() const { |
6731 | return isa<EnumType>(CanonicalType); |
6732 | } |
6733 | |
6734 | inline bool Type::isAnyComplexType() const { |
6735 | return isa<ComplexType>(CanonicalType); |
6736 | } |
6737 | |
6738 | inline bool Type::isVectorType() const { |
6739 | return isa<VectorType>(CanonicalType); |
6740 | } |
6741 | |
6742 | inline bool Type::isExtVectorType() const { |
6743 | return isa<ExtVectorType>(CanonicalType); |
6744 | } |
6745 | |
6746 | inline bool Type::isMatrixType() const { |
6747 | return isa<MatrixType>(CanonicalType); |
6748 | } |
6749 | |
6750 | inline bool Type::isConstantMatrixType() const { |
6751 | return isa<ConstantMatrixType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isDependentAddressSpaceType() const { |
6755 | return isa<DependentAddressSpaceType>(CanonicalType); |
6756 | } |
6757 | |
6758 | inline bool Type::isObjCObjectPointerType() const { |
6759 | return isa<ObjCObjectPointerType>(CanonicalType); |
6760 | } |
6761 | |
6762 | inline bool Type::isObjCObjectType() const { |
6763 | return isa<ObjCObjectType>(CanonicalType); |
6764 | } |
6765 | |
6766 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6767 | return isa<ObjCInterfaceType>(CanonicalType) || |
6768 | isa<ObjCObjectType>(CanonicalType); |
6769 | } |
6770 | |
6771 | inline bool Type::isAtomicType() const { |
6772 | return isa<AtomicType>(CanonicalType); |
6773 | } |
6774 | |
6775 | inline bool Type::isUndeducedAutoType() const { |
6776 | return isa<AutoType>(CanonicalType); |
6777 | } |
6778 | |
6779 | inline bool Type::isObjCQualifiedIdType() const { |
6780 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6781 | return OPT->isObjCQualifiedIdType(); |
6782 | return false; |
6783 | } |
6784 | |
6785 | inline bool Type::isObjCQualifiedClassType() const { |
6786 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6787 | return OPT->isObjCQualifiedClassType(); |
6788 | return false; |
6789 | } |
6790 | |
6791 | inline bool Type::isObjCIdType() const { |
6792 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6793 | return OPT->isObjCIdType(); |
6794 | return false; |
6795 | } |
6796 | |
6797 | inline bool Type::isObjCClassType() const { |
6798 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6799 | return OPT->isObjCClassType(); |
6800 | return false; |
6801 | } |
6802 | |
6803 | inline bool Type::isObjCSelType() const { |
6804 | if (const auto *OPT = getAs<PointerType>()) |
6805 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6806 | return false; |
6807 | } |
6808 | |
6809 | inline bool Type::isObjCBuiltinType() const { |
6810 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6811 | } |
6812 | |
6813 | inline bool Type::isDecltypeType() const { |
6814 | return isa<DecltypeType>(this); |
6815 | } |
6816 | |
6817 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6818 | inline bool Type::is##Id##Type() const { \ |
6819 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6820 | } |
6821 | #include "clang/Basic/OpenCLImageTypes.def" |
6822 | |
6823 | inline bool Type::isSamplerT() const { |
6824 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6825 | } |
6826 | |
6827 | inline bool Type::isEventT() const { |
6828 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6829 | } |
6830 | |
6831 | inline bool Type::isClkEventT() const { |
6832 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6833 | } |
6834 | |
6835 | inline bool Type::isQueueT() const { |
6836 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6837 | } |
6838 | |
6839 | inline bool Type::isReserveIDT() const { |
6840 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6841 | } |
6842 | |
6843 | inline bool Type::isImageType() const { |
6844 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6845 | return |
6846 | #include "clang/Basic/OpenCLImageTypes.def" |
6847 | false; // end boolean or operation |
6848 | } |
6849 | |
6850 | inline bool Type::isPipeType() const { |
6851 | return isa<PipeType>(CanonicalType); |
6852 | } |
6853 | |
6854 | inline bool Type::isExtIntType() const { |
6855 | return isa<ExtIntType>(CanonicalType); |
6856 | } |
6857 | |
6858 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6859 | inline bool Type::is##Id##Type() const { \ |
6860 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6861 | } |
6862 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6863 | |
6864 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6865 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6866 | isOCLIntelSubgroupAVC##Id##Type() || |
6867 | return |
6868 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6869 | false; // end of boolean or operation |
6870 | } |
6871 | |
6872 | inline bool Type::isOCLExtOpaqueType() const { |
6873 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6874 | return |
6875 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6876 | false; // end of boolean or operation |
6877 | } |
6878 | |
6879 | inline bool Type::isOpenCLSpecificType() const { |
6880 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6881 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6882 | } |
6883 | |
6884 | inline bool Type::isTemplateTypeParmType() const { |
6885 | return isa<TemplateTypeParmType>(CanonicalType); |
6886 | } |
6887 | |
6888 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6889 | if (const BuiltinType *BT = getAs<BuiltinType>()) { |
6890 | return BT->getKind() == static_cast<BuiltinType::Kind>(K); |
6891 | } |
6892 | return false; |
6893 | } |
6894 | |
6895 | inline bool Type::isPlaceholderType() const { |
6896 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6897 | return BT->isPlaceholderType(); |
6898 | return false; |
6899 | } |
6900 | |
6901 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6902 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6903 | if (BT->isPlaceholderType()) |
6904 | return BT; |
6905 | return nullptr; |
6906 | } |
6907 | |
6908 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6909 | 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-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 6909, __PRETTY_FUNCTION__)); |
6910 | return isSpecificBuiltinType(K); |
6911 | } |
6912 | |
6913 | inline bool Type::isNonOverloadPlaceholderType() const { |
6914 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6915 | return BT->isNonOverloadPlaceholderType(); |
6916 | return false; |
6917 | } |
6918 | |
6919 | inline bool Type::isVoidType() const { |
6920 | return isSpecificBuiltinType(BuiltinType::Void); |
6921 | } |
6922 | |
6923 | inline bool Type::isHalfType() const { |
6924 | // FIXME: Should we allow complex __fp16? Probably not. |
6925 | return isSpecificBuiltinType(BuiltinType::Half); |
6926 | } |
6927 | |
6928 | inline bool Type::isFloat16Type() const { |
6929 | return isSpecificBuiltinType(BuiltinType::Float16); |
6930 | } |
6931 | |
6932 | inline bool Type::isBFloat16Type() const { |
6933 | return isSpecificBuiltinType(BuiltinType::BFloat16); |
6934 | } |
6935 | |
6936 | inline bool Type::isFloat128Type() const { |
6937 | return isSpecificBuiltinType(BuiltinType::Float128); |
6938 | } |
6939 | |
6940 | inline bool Type::isNullPtrType() const { |
6941 | return isSpecificBuiltinType(BuiltinType::NullPtr); |
6942 | } |
6943 | |
6944 | bool IsEnumDeclComplete(EnumDecl *); |
6945 | bool IsEnumDeclScoped(EnumDecl *); |
6946 | |
6947 | inline bool Type::isIntegerType() const { |
6948 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6949 | return BT->getKind() >= BuiltinType::Bool && |
6950 | BT->getKind() <= BuiltinType::Int128; |
6951 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6952 | // Incomplete enum types are not treated as integer types. |
6953 | // FIXME: In C++, enum types are never integer types. |
6954 | return IsEnumDeclComplete(ET->getDecl()) && |
6955 | !IsEnumDeclScoped(ET->getDecl()); |
6956 | } |
6957 | return isExtIntType(); |
6958 | } |
6959 | |
6960 | inline bool Type::isFixedPointType() const { |
6961 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6962 | return BT->getKind() >= BuiltinType::ShortAccum && |
6963 | BT->getKind() <= BuiltinType::SatULongFract; |
6964 | } |
6965 | return false; |
6966 | } |
6967 | |
6968 | inline bool Type::isFixedPointOrIntegerType() const { |
6969 | return isFixedPointType() || isIntegerType(); |
6970 | } |
6971 | |
6972 | inline bool Type::isSaturatedFixedPointType() const { |
6973 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6974 | return BT->getKind() >= BuiltinType::SatShortAccum && |
6975 | BT->getKind() <= BuiltinType::SatULongFract; |
6976 | } |
6977 | return false; |
6978 | } |
6979 | |
6980 | inline bool Type::isUnsaturatedFixedPointType() const { |
6981 | return isFixedPointType() && !isSaturatedFixedPointType(); |
6982 | } |
6983 | |
6984 | inline bool Type::isSignedFixedPointType() const { |
6985 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6986 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
6987 | BT->getKind() <= BuiltinType::LongAccum) || |
6988 | (BT->getKind() >= BuiltinType::ShortFract && |
6989 | BT->getKind() <= BuiltinType::LongFract) || |
6990 | (BT->getKind() >= BuiltinType::SatShortAccum && |
6991 | BT->getKind() <= BuiltinType::SatLongAccum) || |
6992 | (BT->getKind() >= BuiltinType::SatShortFract && |
6993 | BT->getKind() <= BuiltinType::SatLongFract)); |
6994 | } |
6995 | return false; |
6996 | } |
6997 | |
6998 | inline bool Type::isUnsignedFixedPointType() const { |
6999 | return isFixedPointType() && !isSignedFixedPointType(); |
7000 | } |
7001 | |
7002 | inline bool Type::isScalarType() const { |
7003 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7004 | return BT->getKind() > BuiltinType::Void && |
7005 | BT->getKind() <= BuiltinType::NullPtr; |
7006 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
7007 | // Enums are scalar types, but only if they are defined. Incomplete enums |
7008 | // are not treated as scalar types. |
7009 | return IsEnumDeclComplete(ET->getDecl()); |
7010 | return isa<PointerType>(CanonicalType) || |
7011 | isa<BlockPointerType>(CanonicalType) || |
7012 | isa<MemberPointerType>(CanonicalType) || |
7013 | isa<ComplexType>(CanonicalType) || |
7014 | isa<ObjCObjectPointerType>(CanonicalType) || |
7015 | isExtIntType(); |
7016 | } |
7017 | |
7018 | inline bool Type::isIntegralOrEnumerationType() const { |
7019 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7020 | return BT->getKind() >= BuiltinType::Bool && |
7021 | BT->getKind() <= BuiltinType::Int128; |
7022 | |
7023 | // Check for a complete enum type; incomplete enum types are not properly an |
7024 | // enumeration type in the sense required here. |
7025 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
7026 | return IsEnumDeclComplete(ET->getDecl()); |
7027 | |
7028 | return isExtIntType(); |
7029 | } |
7030 | |
7031 | inline bool Type::isBooleanType() const { |
7032 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7033 | return BT->getKind() == BuiltinType::Bool; |
7034 | return false; |
7035 | } |
7036 | |
7037 | inline bool Type::isUndeducedType() const { |
7038 | auto *DT = getContainedDeducedType(); |
7039 | return DT && !DT->isDeduced(); |
7040 | } |
7041 | |
7042 | /// Determines whether this is a type for which one can define |
7043 | /// an overloaded operator. |
7044 | inline bool Type::isOverloadableType() const { |
7045 | return isDependentType() || isRecordType() || isEnumeralType(); |
7046 | } |
7047 | |
7048 | /// Determines whether this type can decay to a pointer type. |
7049 | inline bool Type::canDecayToPointerType() const { |
7050 | return isFunctionType() || isArrayType(); |
7051 | } |
7052 | |
7053 | inline bool Type::hasPointerRepresentation() const { |
7054 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
7055 | isObjCObjectPointerType() || isNullPtrType()); |
7056 | } |
7057 | |
7058 | inline bool Type::hasObjCPointerRepresentation() const { |
7059 | return isObjCObjectPointerType(); |
7060 | } |
7061 | |
7062 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
7063 | const Type *type = this; |
7064 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
7065 | type = arrayType->getElementType().getTypePtr(); |
7066 | return type; |
7067 | } |
7068 | |
7069 | inline const Type *Type::getPointeeOrArrayElementType() const { |
7070 | const Type *type = this; |
7071 | if (type->isAnyPointerType()) |
7072 | return type->getPointeeType().getTypePtr(); |
7073 | else if (type->isArrayType()) |
7074 | return type->getBaseElementTypeUnsafe(); |
7075 | return type; |
7076 | } |
7077 | /// Insertion operator for partial diagnostics. This allows sending adress |
7078 | /// spaces into a diagnostic with <<. |
7079 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7080 | LangAS AS) { |
7081 | PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), |
7082 | DiagnosticsEngine::ArgumentKind::ak_addrspace); |
7083 | return PD; |
7084 | } |
7085 | |
7086 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
7087 | /// into a diagnostic with <<. |
7088 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7089 | Qualifiers Q) { |
7090 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
7091 | DiagnosticsEngine::ArgumentKind::ak_qual); |
7092 | return PD; |
7093 | } |
7094 | |
7095 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
7096 | /// into a diagnostic with <<. |
7097 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7098 | QualType T) { |
7099 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
7100 | DiagnosticsEngine::ak_qualtype); |
7101 | return PD; |
7102 | } |
7103 | |
7104 | // Helper class template that is used by Type::getAs to ensure that one does |
7105 | // not try to look through a qualified type to get to an array type. |
7106 | template <typename T> |
7107 | using TypeIsArrayType = |
7108 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
7109 | std::is_base_of<ArrayType, T>::value>; |
7110 | |
7111 | // Member-template getAs<specific type>'. |
7112 | template <typename T> const T *Type::getAs() const { |
7113 | static_assert(!TypeIsArrayType<T>::value, |
7114 | "ArrayType cannot be used with getAs!"); |
7115 | |
7116 | // If this is directly a T type, return it. |
7117 | if (const auto *Ty = dyn_cast<T>(this)) |
7118 | return Ty; |
7119 | |
7120 | // If the canonical form of this type isn't the right kind, reject it. |
7121 | if (!isa<T>(CanonicalType)) |
7122 | return nullptr; |
7123 | |
7124 | // If this is a typedef for the type, strip the typedef off without |
7125 | // losing all typedef information. |
7126 | return cast<T>(getUnqualifiedDesugaredType()); |
7127 | } |
7128 | |
7129 | template <typename T> const T *Type::getAsAdjusted() const { |
7130 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
7131 | |
7132 | // If this is directly a T type, return it. |
7133 | if (const auto *Ty = dyn_cast<T>(this)) |
7134 | return Ty; |
7135 | |
7136 | // If the canonical form of this type isn't the right kind, reject it. |
7137 | if (!isa<T>(CanonicalType)) |
7138 | return nullptr; |
7139 | |
7140 | // Strip off type adjustments that do not modify the underlying nature of the |
7141 | // type. |
7142 | const Type *Ty = this; |
7143 | while (Ty) { |
7144 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
7145 | Ty = A->getModifiedType().getTypePtr(); |
7146 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
7147 | Ty = E->desugar().getTypePtr(); |
7148 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
7149 | Ty = P->desugar().getTypePtr(); |
7150 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
7151 | Ty = A->desugar().getTypePtr(); |
7152 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
7153 | Ty = M->desugar().getTypePtr(); |
7154 | else |
7155 | break; |
7156 | } |
7157 | |
7158 | // Just because the canonical type is correct does not mean we can use cast<>, |
7159 | // since we may not have stripped off all the sugar down to the base type. |
7160 | return dyn_cast<T>(Ty); |
7161 | } |
7162 | |
7163 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
7164 | // If this is directly an array type, return it. |
7165 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
7166 | return arr; |
7167 | |
7168 | // If the canonical form of this type isn't the right kind, reject it. |
7169 | if (!isa<ArrayType>(CanonicalType)) |
7170 | return nullptr; |
7171 | |
7172 | // If this is a typedef for the type, strip the typedef off without |
7173 | // losing all typedef information. |
7174 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7175 | } |
7176 | |
7177 | template <typename T> const T *Type::castAs() const { |
7178 | static_assert(!TypeIsArrayType<T>::value, |
7179 | "ArrayType cannot be used with castAs!"); |
7180 | |
7181 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
7182 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 7182, __PRETTY_FUNCTION__)); |
7183 | return cast<T>(getUnqualifiedDesugaredType()); |
7184 | } |
7185 | |
7186 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
7187 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 7187, __PRETTY_FUNCTION__)); |
7188 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
7189 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7190 | } |
7191 | |
7192 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
7193 | QualType CanonicalPtr) |
7194 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
7195 | #ifndef NDEBUG |
7196 | QualType Adjusted = getAdjustedType(); |
7197 | (void)AttributedType::stripOuterNullability(Adjusted); |
7198 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h" , 7198, __PRETTY_FUNCTION__)); |
7199 | #endif |
7200 | } |
7201 | |
7202 | QualType DecayedType::getPointeeType() const { |
7203 | QualType Decayed = getDecayedType(); |
7204 | (void)AttributedType::stripOuterNullability(Decayed); |
7205 | return cast<PointerType>(Decayed)->getPointeeType(); |
7206 | } |
7207 | |
7208 | // Get the decimal string representation of a fixed point type, represented |
7209 | // as a scaled integer. |
7210 | // TODO: At some point, we should change the arguments to instead just accept an |
7211 | // APFixedPoint instead of APSInt and scale. |
7212 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
7213 | unsigned Scale); |
7214 | |
7215 | } // namespace clang |
7216 | |
7217 | #endif // LLVM_CLANG_AST_TYPE_H |
1 | //===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the PointerIntPair class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_ADT_POINTERINTPAIR_H |
14 | #define LLVM_ADT_POINTERINTPAIR_H |
15 | |
16 | #include "llvm/Support/Compiler.h" |
17 | #include "llvm/Support/PointerLikeTypeTraits.h" |
18 | #include "llvm/Support/type_traits.h" |
19 | #include <cassert> |
20 | #include <cstdint> |
21 | #include <limits> |
22 | |
23 | namespace llvm { |
24 | |
25 | template <typename T> struct DenseMapInfo; |
26 | template <typename PointerT, unsigned IntBits, typename PtrTraits> |
27 | struct PointerIntPairInfo; |
28 | |
29 | /// PointerIntPair - This class implements a pair of a pointer and small |
30 | /// integer. It is designed to represent this in the space required by one |
31 | /// pointer by bitmangling the integer into the low part of the pointer. This |
32 | /// can only be done for small integers: typically up to 3 bits, but it depends |
33 | /// on the number of bits available according to PointerLikeTypeTraits for the |
34 | /// type. |
35 | /// |
36 | /// Note that PointerIntPair always puts the IntVal part in the highest bits |
37 | /// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for |
38 | /// the bool into bit #2, not bit #0, which allows the low two bits to be used |
39 | /// for something else. For example, this allows: |
40 | /// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool> |
41 | /// ... and the two bools will land in different bits. |
42 | template <typename PointerTy, unsigned IntBits, typename IntType = unsigned, |
43 | typename PtrTraits = PointerLikeTypeTraits<PointerTy>, |
44 | typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>> |
45 | class PointerIntPair { |
46 | // Used by MSVC visualizer and generally helpful for debugging/visualizing. |
47 | using InfoTy = Info; |
48 | intptr_t Value = 0; |
49 | |
50 | public: |
51 | constexpr PointerIntPair() = default; |
52 | |
53 | PointerIntPair(PointerTy PtrVal, IntType IntVal) { |
54 | setPointerAndInt(PtrVal, IntVal); |
55 | } |
56 | |
57 | explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); } |
58 | |
59 | PointerTy getPointer() const { return Info::getPointer(Value); } |
60 | |
61 | IntType getInt() const { return (IntType)Info::getInt(Value); } |
62 | |
63 | void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& { |
64 | Value = Info::updatePointer(Value, PtrVal); |
65 | } |
66 | |
67 | void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& { |
68 | Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal)); |
69 | } |
70 | |
71 | void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& { |
72 | Value = Info::updatePointer(0, PtrVal); |
73 | } |
74 | |
75 | void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& { |
76 | Value = Info::updateInt(Info::updatePointer(0, PtrVal), |
77 | static_cast<intptr_t>(IntVal)); |
78 | } |
79 | |
80 | PointerTy const *getAddrOfPointer() const { |
81 | return const_cast<PointerIntPair *>(this)->getAddrOfPointer(); |
82 | } |
83 | |
84 | PointerTy *getAddrOfPointer() { |
85 | assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer" ) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h" , 87, __PRETTY_FUNCTION__)) |
86 | "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer" ) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h" , 87, __PRETTY_FUNCTION__)) |
87 | "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer" ) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h" , 87, __PRETTY_FUNCTION__)); |
88 | return reinterpret_cast<PointerTy *>(&Value); |
89 | } |
90 | |
91 | void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); } |
92 | |
93 | void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& { |
94 | Value = reinterpret_cast<intptr_t>(Val); |
95 | } |
96 | |
97 | static PointerIntPair getFromOpaqueValue(void *V) { |
98 | PointerIntPair P; |
99 | P.setFromOpaqueValue(V); |
100 | return P; |
101 | } |
102 | |
103 | // Allow PointerIntPairs to be created from const void * if and only if the |
104 | // pointer type could be created from a const void *. |
105 | static PointerIntPair getFromOpaqueValue(const void *V) { |
106 | (void)PtrTraits::getFromVoidPointer(V); |
107 | return getFromOpaqueValue(const_cast<void *>(V)); |
108 | } |
109 | |
110 | bool operator==(const PointerIntPair &RHS) const { |
111 | return Value == RHS.Value; |
112 | } |
113 | |
114 | bool operator!=(const PointerIntPair &RHS) const { |
115 | return Value != RHS.Value; |
116 | } |
117 | |
118 | bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; } |
119 | bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; } |
120 | |
121 | bool operator<=(const PointerIntPair &RHS) const { |
122 | return Value <= RHS.Value; |
123 | } |
124 | |
125 | bool operator>=(const PointerIntPair &RHS) const { |
126 | return Value >= RHS.Value; |
127 | } |
128 | }; |
129 | |
130 | // Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable |
131 | // when compiled with gcc 4.9. |
132 | template <typename PointerTy, unsigned IntBits, typename IntType, |
133 | typename PtrTraits, |
134 | typename Info> |
135 | struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type { |
136 | #ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE |
137 | static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value, |
138 | "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable"); |
139 | #endif |
140 | }; |
141 | |
142 | |
143 | template <typename PointerT, unsigned IntBits, typename PtrTraits> |
144 | struct PointerIntPairInfo { |
145 | static_assert(PtrTraits::NumLowBitsAvailable < |
146 | std::numeric_limits<uintptr_t>::digits, |
147 | "cannot use a pointer type that has all bits free"); |
148 | static_assert(IntBits <= PtrTraits::NumLowBitsAvailable, |
149 | "PointerIntPair with integer size too large for pointer"); |
150 | enum MaskAndShiftConstants : uintptr_t { |
151 | /// PointerBitMask - The bits that come from the pointer. |
152 | PointerBitMask = |
153 | ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1), |
154 | |
155 | /// IntShift - The number of low bits that we reserve for other uses, and |
156 | /// keep zero. |
157 | IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits, |
158 | |
159 | /// IntMask - This is the unshifted mask for valid bits of the int type. |
160 | IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1), |
161 | |
162 | // ShiftedIntMask - This is the bits for the integer shifted in place. |
163 | ShiftedIntMask = (uintptr_t)(IntMask << IntShift) |
164 | }; |
165 | |
166 | static PointerT getPointer(intptr_t Value) { |
167 | return PtrTraits::getFromVoidPointer( |
168 | reinterpret_cast<void *>(Value & PointerBitMask)); |
169 | } |
170 | |
171 | static intptr_t getInt(intptr_t Value) { |
172 | return (Value >> IntShift) & IntMask; |
173 | } |
174 | |
175 | static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) { |
176 | intptr_t PtrWord = |
177 | reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr)); |
178 | assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned" ) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h" , 179, __PRETTY_FUNCTION__)) |
179 | "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned" ) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h" , 179, __PRETTY_FUNCTION__)); |
180 | // Preserve all low bits, just update the pointer. |
181 | return PtrWord | (OrigValue & ~PointerBitMask); |
182 | } |
183 | |
184 | static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) { |
185 | intptr_t IntWord = static_cast<intptr_t>(Int); |
186 | assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field" ) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h" , 186, __PRETTY_FUNCTION__)); |
187 | |
188 | // Preserve all bits other than the ones we are updating. |
189 | return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift; |
190 | } |
191 | }; |
192 | |
193 | // Provide specialization of DenseMapInfo for PointerIntPair. |
194 | template <typename PointerTy, unsigned IntBits, typename IntType> |
195 | struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> { |
196 | using Ty = PointerIntPair<PointerTy, IntBits, IntType>; |
197 | |
198 | static Ty getEmptyKey() { |
199 | uintptr_t Val = static_cast<uintptr_t>(-1); |
200 | Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable; |
201 | return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val)); |
202 | } |
203 | |
204 | static Ty getTombstoneKey() { |
205 | uintptr_t Val = static_cast<uintptr_t>(-2); |
206 | Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable; |
207 | return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val)); |
208 | } |
209 | |
210 | static unsigned getHashValue(Ty V) { |
211 | uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue()); |
212 | return unsigned(IV) ^ unsigned(IV >> 9); |
213 | } |
214 | |
215 | static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; } |
216 | }; |
217 | |
218 | // Teach SmallPtrSet that PointerIntPair is "basically a pointer". |
219 | template <typename PointerTy, unsigned IntBits, typename IntType, |
220 | typename PtrTraits> |
221 | struct PointerLikeTypeTraits< |
222 | PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> { |
223 | static inline void * |
224 | getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) { |
225 | return P.getOpaqueValue(); |
226 | } |
227 | |
228 | static inline PointerIntPair<PointerTy, IntBits, IntType> |
229 | getFromVoidPointer(void *P) { |
230 | return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P); |
231 | } |
232 | |
233 | static inline PointerIntPair<PointerTy, IntBits, IntType> |
234 | getFromVoidPointer(const void *P) { |
235 | return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P); |
236 | } |
237 | |
238 | static constexpr int NumLowBitsAvailable = |
239 | PtrTraits::NumLowBitsAvailable - IntBits; |
240 | }; |
241 | |
242 | } // end namespace llvm |
243 | |
244 | #endif // LLVM_ADT_POINTERINTPAIR_H |
1 | //===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(), |
10 | // and dyn_cast_or_null<X>() templates. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_SUPPORT_CASTING_H |
15 | #define LLVM_SUPPORT_CASTING_H |
16 | |
17 | #include "llvm/Support/Compiler.h" |
18 | #include "llvm/Support/type_traits.h" |
19 | #include <cassert> |
20 | #include <memory> |
21 | #include <type_traits> |
22 | |
23 | namespace llvm { |
24 | |
25 | //===----------------------------------------------------------------------===// |
26 | // isa<x> Support Templates |
27 | //===----------------------------------------------------------------------===// |
28 | |
29 | // Define a template that can be specialized by smart pointers to reflect the |
30 | // fact that they are automatically dereferenced, and are not involved with the |
31 | // template selection process... the default implementation is a noop. |
32 | // |
33 | template<typename From> struct simplify_type { |
34 | using SimpleType = From; // The real type this represents... |
35 | |
36 | // An accessor to get the real value... |
37 | static SimpleType &getSimplifiedValue(From &Val) { return Val; } |
38 | }; |
39 | |
40 | template<typename From> struct simplify_type<const From> { |
41 | using NonConstSimpleType = typename simplify_type<From>::SimpleType; |
42 | using SimpleType = |
43 | typename add_const_past_pointer<NonConstSimpleType>::type; |
44 | using RetType = |
45 | typename add_lvalue_reference_if_not_pointer<SimpleType>::type; |
46 | |
47 | static RetType getSimplifiedValue(const From& Val) { |
48 | return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val)); |
49 | } |
50 | }; |
51 | |
52 | // The core of the implementation of isa<X> is here; To and From should be |
53 | // the names of classes. This template can be specialized to customize the |
54 | // implementation of isa<> without rewriting it from scratch. |
55 | template <typename To, typename From, typename Enabler = void> |
56 | struct isa_impl { |
57 | static inline bool doit(const From &Val) { |
58 | return To::classof(&Val); |
59 | } |
60 | }; |
61 | |
62 | /// Always allow upcasts, and perform no dynamic check for them. |
63 | template <typename To, typename From> |
64 | struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> { |
65 | static inline bool doit(const From &) { return true; } |
66 | }; |
67 | |
68 | template <typename To, typename From> struct isa_impl_cl { |
69 | static inline bool doit(const From &Val) { |
70 | return isa_impl<To, From>::doit(Val); |
71 | } |
72 | }; |
73 | |
74 | template <typename To, typename From> struct isa_impl_cl<To, const From> { |
75 | static inline bool doit(const From &Val) { |
76 | return isa_impl<To, From>::doit(Val); |
77 | } |
78 | }; |
79 | |
80 | template <typename To, typename From> |
81 | struct isa_impl_cl<To, const std::unique_ptr<From>> { |
82 | static inline bool doit(const std::unique_ptr<From> &Val) { |
83 | assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast <void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 83, __PRETTY_FUNCTION__)); |
84 | return isa_impl_cl<To, From>::doit(*Val); |
85 | } |
86 | }; |
87 | |
88 | template <typename To, typename From> struct isa_impl_cl<To, From*> { |
89 | static inline bool doit(const From *Val) { |
90 | assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast <void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 90, __PRETTY_FUNCTION__)); |
91 | return isa_impl<To, From>::doit(*Val); |
92 | } |
93 | }; |
94 | |
95 | template <typename To, typename From> struct isa_impl_cl<To, From*const> { |
96 | static inline bool doit(const From *Val) { |
97 | assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast <void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 97, __PRETTY_FUNCTION__)); |
98 | return isa_impl<To, From>::doit(*Val); |
99 | } |
100 | }; |
101 | |
102 | template <typename To, typename From> struct isa_impl_cl<To, const From*> { |
103 | static inline bool doit(const From *Val) { |
104 | assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast <void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 104, __PRETTY_FUNCTION__)); |
105 | return isa_impl<To, From>::doit(*Val); |
106 | } |
107 | }; |
108 | |
109 | template <typename To, typename From> struct isa_impl_cl<To, const From*const> { |
110 | static inline bool doit(const From *Val) { |
111 | assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast <void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 111, __PRETTY_FUNCTION__)); |
112 | return isa_impl<To, From>::doit(*Val); |
113 | } |
114 | }; |
115 | |
116 | template<typename To, typename From, typename SimpleFrom> |
117 | struct isa_impl_wrap { |
118 | // When From != SimplifiedType, we can simplify the type some more by using |
119 | // the simplify_type template. |
120 | static bool doit(const From &Val) { |
121 | return isa_impl_wrap<To, SimpleFrom, |
122 | typename simplify_type<SimpleFrom>::SimpleType>::doit( |
123 | simplify_type<const From>::getSimplifiedValue(Val)); |
124 | } |
125 | }; |
126 | |
127 | template<typename To, typename FromTy> |
128 | struct isa_impl_wrap<To, FromTy, FromTy> { |
129 | // When From == SimpleType, we are as simple as we are going to get. |
130 | static bool doit(const FromTy &Val) { |
131 | return isa_impl_cl<To,FromTy>::doit(Val); |
132 | } |
133 | }; |
134 | |
135 | // isa<X> - Return true if the parameter to the template is an instance of one |
136 | // of the template type arguments. Used like this: |
137 | // |
138 | // if (isa<Type>(myVal)) { ... } |
139 | // if (isa<Type0, Type1, Type2>(myVal)) { ... } |
140 | // |
141 | template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) { |
142 | return isa_impl_wrap<X, const Y, |
143 | typename simplify_type<const Y>::SimpleType>::doit(Val); |
144 | } |
145 | |
146 | template <typename First, typename Second, typename... Rest, typename Y> |
147 | LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) { |
148 | return isa<First>(Val) || isa<Second, Rest...>(Val); |
149 | } |
150 | |
151 | // isa_and_nonnull<X> - Functionally identical to isa, except that a null value |
152 | // is accepted. |
153 | // |
154 | template <typename... X, class Y> |
155 | LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) { |
156 | if (!Val) |
157 | return false; |
158 | return isa<X...>(Val); |
159 | } |
160 | |
161 | //===----------------------------------------------------------------------===// |
162 | // cast<x> Support Templates |
163 | //===----------------------------------------------------------------------===// |
164 | |
165 | template<class To, class From> struct cast_retty; |
166 | |
167 | // Calculate what type the 'cast' function should return, based on a requested |
168 | // type of To and a source type of From. |
169 | template<class To, class From> struct cast_retty_impl { |
170 | using ret_type = To &; // Normal case, return Ty& |
171 | }; |
172 | template<class To, class From> struct cast_retty_impl<To, const From> { |
173 | using ret_type = const To &; // Normal case, return Ty& |
174 | }; |
175 | |
176 | template<class To, class From> struct cast_retty_impl<To, From*> { |
177 | using ret_type = To *; // Pointer arg case, return Ty* |
178 | }; |
179 | |
180 | template<class To, class From> struct cast_retty_impl<To, const From*> { |
181 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
182 | }; |
183 | |
184 | template<class To, class From> struct cast_retty_impl<To, const From*const> { |
185 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
186 | }; |
187 | |
188 | template <class To, class From> |
189 | struct cast_retty_impl<To, std::unique_ptr<From>> { |
190 | private: |
191 | using PointerType = typename cast_retty_impl<To, From *>::ret_type; |
192 | using ResultType = std::remove_pointer_t<PointerType>; |
193 | |
194 | public: |
195 | using ret_type = std::unique_ptr<ResultType>; |
196 | }; |
197 | |
198 | template<class To, class From, class SimpleFrom> |
199 | struct cast_retty_wrap { |
200 | // When the simplified type and the from type are not the same, use the type |
201 | // simplifier to reduce the type, then reuse cast_retty_impl to get the |
202 | // resultant type. |
203 | using ret_type = typename cast_retty<To, SimpleFrom>::ret_type; |
204 | }; |
205 | |
206 | template<class To, class FromTy> |
207 | struct cast_retty_wrap<To, FromTy, FromTy> { |
208 | // When the simplified type is equal to the from type, use it directly. |
209 | using ret_type = typename cast_retty_impl<To,FromTy>::ret_type; |
210 | }; |
211 | |
212 | template<class To, class From> |
213 | struct cast_retty { |
214 | using ret_type = typename cast_retty_wrap< |
215 | To, From, typename simplify_type<From>::SimpleType>::ret_type; |
216 | }; |
217 | |
218 | // Ensure the non-simple values are converted using the simplify_type template |
219 | // that may be specialized by smart pointers... |
220 | // |
221 | template<class To, class From, class SimpleFrom> struct cast_convert_val { |
222 | // This is not a simple type, use the template to simplify it... |
223 | static typename cast_retty<To, From>::ret_type doit(From &Val) { |
224 | return cast_convert_val<To, SimpleFrom, |
225 | typename simplify_type<SimpleFrom>::SimpleType>::doit( |
226 | simplify_type<From>::getSimplifiedValue(Val)); |
227 | } |
228 | }; |
229 | |
230 | template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> { |
231 | // This _is_ a simple type, just cast it. |
232 | static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) { |
233 | typename cast_retty<To, FromTy>::ret_type Res2 |
234 | = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val); |
235 | return Res2; |
236 | } |
237 | }; |
238 | |
239 | template <class X> struct is_simple_type { |
240 | static const bool value = |
241 | std::is_same<X, typename simplify_type<X>::SimpleType>::value; |
242 | }; |
243 | |
244 | // cast<X> - Return the argument parameter cast to the specified type. This |
245 | // casting operator asserts that the type is correct, so it does not return null |
246 | // on failure. It does not allow a null argument (use cast_or_null for that). |
247 | // It is typically used like this: |
248 | // |
249 | // cast<Instruction>(myVal)->getParent() |
250 | // |
251 | template <class X, class Y> |
252 | inline std::enable_if_t<!is_simple_type<Y>::value, |
253 | typename cast_retty<X, const Y>::ret_type> |
254 | cast(const Y &Val) { |
255 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 255, __PRETTY_FUNCTION__)); |
256 | return cast_convert_val< |
257 | X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val); |
258 | } |
259 | |
260 | template <class X, class Y> |
261 | inline typename cast_retty<X, Y>::ret_type cast(Y &Val) { |
262 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 262, __PRETTY_FUNCTION__)); |
263 | return cast_convert_val<X, Y, |
264 | typename simplify_type<Y>::SimpleType>::doit(Val); |
265 | } |
266 | |
267 | template <class X, class Y> |
268 | inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) { |
269 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 269, __PRETTY_FUNCTION__)); |
270 | return cast_convert_val<X, Y*, |
271 | typename simplify_type<Y*>::SimpleType>::doit(Val); |
272 | } |
273 | |
274 | template <class X, class Y> |
275 | inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type |
276 | cast(std::unique_ptr<Y> &&Val) { |
277 | assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 277, __PRETTY_FUNCTION__)); |
278 | using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type; |
279 | return ret_type( |
280 | cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit( |
281 | Val.release())); |
282 | } |
283 | |
284 | // cast_or_null<X> - Functionally identical to cast, except that a null value is |
285 | // accepted. |
286 | // |
287 | template <class X, class Y> |
288 | LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t< |
289 | !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type> |
290 | cast_or_null(const Y &Val) { |
291 | if (!Val) |
292 | return nullptr; |
293 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 293, __PRETTY_FUNCTION__)); |
294 | return cast<X>(Val); |
295 | } |
296 | |
297 | template <class X, class Y> |
298 | LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value, |
299 | typename cast_retty<X, Y>::ret_type> |
300 | cast_or_null(Y &Val) { |
301 | if (!Val) |
302 | return nullptr; |
303 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 303, __PRETTY_FUNCTION__)); |
304 | return cast<X>(Val); |
305 | } |
306 | |
307 | template <class X, class Y> |
308 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type |
309 | cast_or_null(Y *Val) { |
310 | if (!Val) return nullptr; |
311 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/Support/Casting.h" , 311, __PRETTY_FUNCTION__)); |
312 | return cast<X>(Val); |
313 | } |
314 | |
315 | template <class X, class Y> |
316 | inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type |
317 | cast_or_null(std::unique_ptr<Y> &&Val) { |
318 | if (!Val) |
319 | return nullptr; |
320 | return cast<X>(std::move(Val)); |
321 | } |
322 | |
323 | // dyn_cast<X> - Return the argument parameter cast to the specified type. This |
324 | // casting operator returns null if the argument is of the wrong type, so it can |
325 | // be used to test for a type as well as cast if successful. This should be |
326 | // used in the context of an if statement like this: |
327 | // |
328 | // if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... } |
329 | // |
330 | |
331 | template <class X, class Y> |
332 | LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t< |
333 | !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type> |
334 | dyn_cast(const Y &Val) { |
335 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
336 | } |
337 | |
338 | template <class X, class Y> |
339 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) { |
340 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
341 | } |
342 | |
343 | template <class X, class Y> |
344 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) { |
345 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
346 | } |
347 | |
348 | // dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null |
349 | // value is accepted. |
350 | // |
351 | template <class X, class Y> |
352 | LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t< |
353 | !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type> |
354 | dyn_cast_or_null(const Y &Val) { |
355 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
356 | } |
357 | |
358 | template <class X, class Y> |
359 | LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value, |
360 | typename cast_retty<X, Y>::ret_type> |
361 | dyn_cast_or_null(Y &Val) { |
362 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
363 | } |
364 | |
365 | template <class X, class Y> |
366 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type |
367 | dyn_cast_or_null(Y *Val) { |
368 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
369 | } |
370 | |
371 | // unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>, |
372 | // taking ownership of the input pointer iff isa<X>(Val) is true. If the |
373 | // cast is successful, From refers to nullptr on exit and the casted value |
374 | // is returned. If the cast is unsuccessful, the function returns nullptr |
375 | // and From is unchanged. |
376 | template <class X, class Y> |
377 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val) |
378 | -> decltype(cast<X>(Val)) { |
379 | if (!isa<X>(Val)) |
380 | return nullptr; |
381 | return cast<X>(std::move(Val)); |
382 | } |
383 | |
384 | template <class X, class Y> |
385 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) { |
386 | return unique_dyn_cast<X, Y>(Val); |
387 | } |
388 | |
389 | // dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that |
390 | // a null value is accepted. |
391 | template <class X, class Y> |
392 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) |
393 | -> decltype(cast<X>(Val)) { |
394 | if (!Val) |
395 | return nullptr; |
396 | return unique_dyn_cast<X, Y>(Val); |
397 | } |
398 | |
399 | template <class X, class Y> |
400 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) { |
401 | return unique_dyn_cast_or_null<X, Y>(Val); |
402 | } |
403 | |
404 | } // end namespace llvm |
405 | |
406 | #endif // LLVM_SUPPORT_CASTING_H |