File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 5947, 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 "clang/AST/ASTConsumer.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/ASTLambda.h" | |||
17 | #include "clang/AST/ASTMutationListener.h" | |||
18 | #include "clang/AST/CXXInheritance.h" | |||
19 | #include "clang/AST/DeclObjC.h" | |||
20 | #include "clang/AST/DeclTemplate.h" | |||
21 | #include "clang/AST/EvaluatedExprVisitor.h" | |||
22 | #include "clang/AST/Expr.h" | |||
23 | #include "clang/AST/ExprCXX.h" | |||
24 | #include "clang/AST/ExprObjC.h" | |||
25 | #include "clang/AST/ExprOpenMP.h" | |||
26 | #include "clang/AST/RecursiveASTVisitor.h" | |||
27 | #include "clang/AST/TypeLoc.h" | |||
28 | #include "clang/Basic/FixedPoint.h" | |||
29 | #include "clang/Basic/PartialDiagnostic.h" | |||
30 | #include "clang/Basic/SourceManager.h" | |||
31 | #include "clang/Basic/TargetInfo.h" | |||
32 | #include "clang/Lex/LiteralSupport.h" | |||
33 | #include "clang/Lex/Preprocessor.h" | |||
34 | #include "clang/Sema/AnalysisBasedWarnings.h" | |||
35 | #include "clang/Sema/DeclSpec.h" | |||
36 | #include "clang/Sema/DelayedDiagnostic.h" | |||
37 | #include "clang/Sema/Designator.h" | |||
38 | #include "clang/Sema/Initialization.h" | |||
39 | #include "clang/Sema/Lookup.h" | |||
40 | #include "clang/Sema/Overload.h" | |||
41 | #include "clang/Sema/ParsedTemplate.h" | |||
42 | #include "clang/Sema/Scope.h" | |||
43 | #include "clang/Sema/ScopeInfo.h" | |||
44 | #include "clang/Sema/SemaFixItUtils.h" | |||
45 | #include "clang/Sema/SemaInternal.h" | |||
46 | #include "clang/Sema/Template.h" | |||
47 | #include "llvm/Support/ConvertUTF.h" | |||
48 | using namespace clang; | |||
49 | using namespace sema; | |||
50 | ||||
51 | /// Determine whether the use of this declaration is valid, without | |||
52 | /// emitting diagnostics. | |||
53 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | |||
54 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
55 | if (ParsingInitForAutoVars.count(D)) | |||
56 | return false; | |||
57 | ||||
58 | // See if this is a deleted function. | |||
59 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
60 | if (FD->isDeleted()) | |||
61 | return false; | |||
62 | ||||
63 | // If the function has a deduced return type, and we can't deduce it, | |||
64 | // then we can't use it either. | |||
65 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
66 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | |||
67 | return false; | |||
68 | ||||
69 | // See if this is an aligned allocation/deallocation function that is | |||
70 | // unavailable. | |||
71 | if (TreatUnavailableAsInvalid && | |||
72 | isUnavailableAlignedAllocationFunction(*FD)) | |||
73 | return false; | |||
74 | } | |||
75 | ||||
76 | // See if this function is unavailable. | |||
77 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | |||
78 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | |||
79 | return false; | |||
80 | ||||
81 | return true; | |||
82 | } | |||
83 | ||||
84 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | |||
85 | // Warn if this is used but marked unused. | |||
86 | if (const auto *A = D->getAttr<UnusedAttr>()) { | |||
87 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | |||
88 | // should diagnose them. | |||
89 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | |||
90 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | |||
91 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | |||
92 | if (DC && !DC->hasAttr<UnusedAttr>()) | |||
93 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); | |||
94 | } | |||
95 | } | |||
96 | } | |||
97 | ||||
98 | /// Emit a note explaining that this function is deleted. | |||
99 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | |||
100 | assert(Decl->isDeleted())((Decl->isDeleted()) ? static_cast<void> (0) : __assert_fail ("Decl->isDeleted()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 100, __PRETTY_FUNCTION__)); | |||
101 | ||||
102 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); | |||
103 | ||||
104 | if (Method && Method->isDeleted() && Method->isDefaulted()) { | |||
105 | // If the method was explicitly defaulted, point at that declaration. | |||
106 | if (!Method->isImplicit()) | |||
107 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | |||
108 | ||||
109 | // Try to diagnose why this special member function was implicitly | |||
110 | // deleted. This might fail, if that reason no longer applies. | |||
111 | CXXSpecialMember CSM = getSpecialMember(Method); | |||
112 | if (CSM != CXXInvalid) | |||
113 | ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); | |||
114 | ||||
115 | return; | |||
116 | } | |||
117 | ||||
118 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | |||
119 | if (Ctor && Ctor->isInheritingConstructor()) | |||
120 | return NoteDeletedInheritingConstructor(Ctor); | |||
121 | ||||
122 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | |||
123 | << Decl << 1; | |||
124 | } | |||
125 | ||||
126 | /// Determine whether a FunctionDecl was ever declared with an | |||
127 | /// explicit storage class. | |||
128 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | |||
129 | for (auto I : D->redecls()) { | |||
130 | if (I->getStorageClass() != SC_None) | |||
131 | return true; | |||
132 | } | |||
133 | return false; | |||
134 | } | |||
135 | ||||
136 | /// Check whether we're in an extern inline function and referring to a | |||
137 | /// variable or function with internal linkage (C11 6.7.4p3). | |||
138 | /// | |||
139 | /// This is only a warning because we used to silently accept this code, but | |||
140 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | |||
141 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | |||
142 | /// and so while there may still be user mistakes, most of the time we can't | |||
143 | /// prove that there are errors. | |||
144 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | |||
145 | const NamedDecl *D, | |||
146 | SourceLocation Loc) { | |||
147 | // This is disabled under C++; there are too many ways for this to fire in | |||
148 | // contexts where the warning is a false positive, or where it is technically | |||
149 | // correct but benign. | |||
150 | if (S.getLangOpts().CPlusPlus) | |||
151 | return; | |||
152 | ||||
153 | // Check if this is an inlined function or method. | |||
154 | FunctionDecl *Current = S.getCurFunctionDecl(); | |||
155 | if (!Current) | |||
156 | return; | |||
157 | if (!Current->isInlined()) | |||
158 | return; | |||
159 | if (!Current->isExternallyVisible()) | |||
160 | return; | |||
161 | ||||
162 | // Check if the decl has internal linkage. | |||
163 | if (D->getFormalLinkage() != InternalLinkage) | |||
164 | return; | |||
165 | ||||
166 | // Downgrade from ExtWarn to Extension if | |||
167 | // (1) the supposedly external inline function is in the main file, | |||
168 | // and probably won't be included anywhere else. | |||
169 | // (2) the thing we're referencing is a pure function. | |||
170 | // (3) the thing we're referencing is another inline function. | |||
171 | // This last can give us false negatives, but it's better than warning on | |||
172 | // wrappers for simple C library functions. | |||
173 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | |||
174 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | |||
175 | if (!DowngradeWarning && UsedFn) | |||
176 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | |||
177 | ||||
178 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | |||
179 | : diag::ext_internal_in_extern_inline) | |||
180 | << /*IsVar=*/!UsedFn << D; | |||
181 | ||||
182 | S.MaybeSuggestAddingStaticToDecl(Current); | |||
183 | ||||
184 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | |||
185 | << D; | |||
186 | } | |||
187 | ||||
188 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | |||
189 | const FunctionDecl *First = Cur->getFirstDecl(); | |||
190 | ||||
191 | // Suggest "static" on the function, if possible. | |||
192 | if (!hasAnyExplicitStorageClass(First)) { | |||
193 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | |||
194 | Diag(DeclBegin, diag::note_convert_inline_to_static) | |||
195 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | |||
196 | } | |||
197 | } | |||
198 | ||||
199 | /// Determine whether the use of this declaration is valid, and | |||
200 | /// emit any corresponding diagnostics. | |||
201 | /// | |||
202 | /// This routine diagnoses various problems with referencing | |||
203 | /// declarations that can occur when using a declaration. For example, | |||
204 | /// it might warn if a deprecated or unavailable declaration is being | |||
205 | /// used, or produce an error (and return true) if a C++0x deleted | |||
206 | /// function is being used. | |||
207 | /// | |||
208 | /// \returns true if there was an error (this declaration cannot be | |||
209 | /// referenced), false otherwise. | |||
210 | /// | |||
211 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | |||
212 | const ObjCInterfaceDecl *UnknownObjCClass, | |||
213 | bool ObjCPropertyAccess, | |||
214 | bool AvoidPartialAvailabilityChecks, | |||
215 | ObjCInterfaceDecl *ClassReceiver) { | |||
216 | SourceLocation Loc = Locs.front(); | |||
217 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | |||
218 | // If there were any diagnostics suppressed by template argument deduction, | |||
219 | // emit them now. | |||
220 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | |||
221 | if (Pos != SuppressedDiagnostics.end()) { | |||
222 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | |||
223 | Diag(Suppressed.first, Suppressed.second); | |||
224 | ||||
225 | // Clear out the list of suppressed diagnostics, so that we don't emit | |||
226 | // them again for this specialization. However, we don't obsolete this | |||
227 | // entry from the table, because we want to avoid ever emitting these | |||
228 | // diagnostics again. | |||
229 | Pos->second.clear(); | |||
230 | } | |||
231 | ||||
232 | // C++ [basic.start.main]p3: | |||
233 | // The function 'main' shall not be used within a program. | |||
234 | if (cast<FunctionDecl>(D)->isMain()) | |||
235 | Diag(Loc, diag::ext_main_used); | |||
236 | ||||
237 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | |||
238 | } | |||
239 | ||||
240 | // See if this is an auto-typed variable whose initializer we are parsing. | |||
241 | if (ParsingInitForAutoVars.count(D)) { | |||
242 | if (isa<BindingDecl>(D)) { | |||
243 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | |||
244 | << D->getDeclName(); | |||
245 | } else { | |||
246 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | |||
247 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | |||
248 | } | |||
249 | return true; | |||
250 | } | |||
251 | ||||
252 | // See if this is a deleted function. | |||
253 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
254 | if (FD->isDeleted()) { | |||
255 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | |||
256 | if (Ctor && Ctor->isInheritingConstructor()) | |||
257 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | |||
258 | << Ctor->getParent() | |||
259 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | |||
260 | else | |||
261 | Diag(Loc, diag::err_deleted_function_use); | |||
262 | NoteDeletedFunction(FD); | |||
263 | return true; | |||
264 | } | |||
265 | ||||
266 | // If the function has a deduced return type, and we can't deduce it, | |||
267 | // then we can't use it either. | |||
268 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
269 | DeduceReturnType(FD, Loc)) | |||
270 | return true; | |||
271 | ||||
272 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | |||
273 | return true; | |||
274 | } | |||
275 | ||||
276 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
277 | // Lambdas are only default-constructible or assignable in C++2a onwards. | |||
278 | if (MD->getParent()->isLambda() && | |||
279 | ((isa<CXXConstructorDecl>(MD) && | |||
280 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | |||
281 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | |||
282 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | |||
283 | << !isa<CXXConstructorDecl>(MD); | |||
284 | } | |||
285 | } | |||
286 | ||||
287 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | |||
288 | const ObjCPropertyDecl * { | |||
289 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | |||
290 | return MD->findPropertyDecl(); | |||
291 | return nullptr; | |||
292 | }; | |||
293 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | |||
294 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | |||
295 | return true; | |||
296 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | |||
297 | return true; | |||
298 | } | |||
299 | ||||
300 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | |||
301 | // Only the variables omp_in and omp_out are allowed in the combiner. | |||
302 | // Only the variables omp_priv and omp_orig are allowed in the | |||
303 | // initializer-clause. | |||
304 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | |||
305 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | |||
306 | isa<VarDecl>(D)) { | |||
307 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | |||
308 | << getCurFunction()->HasOMPDeclareReductionCombiner; | |||
309 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
310 | return true; | |||
311 | } | |||
312 | ||||
313 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | |||
314 | // List-items in map clauses on this construct may only refer to the declared | |||
315 | // variable var and entities that could be referenced by a procedure defined | |||
316 | // at the same location | |||
317 | auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); | |||
318 | if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && | |||
319 | isa<VarDecl>(D)) { | |||
320 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | |||
321 | << DMD->getVarName().getAsString(); | |||
322 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | |||
323 | return true; | |||
324 | } | |||
325 | ||||
326 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | |||
327 | AvoidPartialAvailabilityChecks, ClassReceiver); | |||
328 | ||||
329 | DiagnoseUnusedOfDecl(*this, D, Loc); | |||
330 | ||||
331 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | |||
332 | ||||
333 | return false; | |||
334 | } | |||
335 | ||||
336 | /// DiagnoseSentinelCalls - This routine checks whether a call or | |||
337 | /// message-send is to a declaration with the sentinel attribute, and | |||
338 | /// if so, it checks that the requirements of the sentinel are | |||
339 | /// satisfied. | |||
340 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | |||
341 | ArrayRef<Expr *> Args) { | |||
342 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | |||
343 | if (!attr) | |||
344 | return; | |||
345 | ||||
346 | // The number of formal parameters of the declaration. | |||
347 | unsigned numFormalParams; | |||
348 | ||||
349 | // The kind of declaration. This is also an index into a %select in | |||
350 | // the diagnostic. | |||
351 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | |||
352 | ||||
353 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | |||
354 | numFormalParams = MD->param_size(); | |||
355 | calleeType = CT_Method; | |||
356 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
357 | numFormalParams = FD->param_size(); | |||
358 | calleeType = CT_Function; | |||
359 | } else if (isa<VarDecl>(D)) { | |||
360 | QualType type = cast<ValueDecl>(D)->getType(); | |||
361 | const FunctionType *fn = nullptr; | |||
362 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
363 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | |||
364 | if (!fn) return; | |||
365 | calleeType = CT_Function; | |||
366 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | |||
367 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | |||
368 | calleeType = CT_Block; | |||
369 | } else { | |||
370 | return; | |||
371 | } | |||
372 | ||||
373 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | |||
374 | numFormalParams = proto->getNumParams(); | |||
375 | } else { | |||
376 | numFormalParams = 0; | |||
377 | } | |||
378 | } else { | |||
379 | return; | |||
380 | } | |||
381 | ||||
382 | // "nullPos" is the number of formal parameters at the end which | |||
383 | // effectively count as part of the variadic arguments. This is | |||
384 | // useful if you would prefer to not have *any* formal parameters, | |||
385 | // but the language forces you to have at least one. | |||
386 | unsigned nullPos = attr->getNullPos(); | |||
387 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 387, __PRETTY_FUNCTION__)); | |||
388 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | |||
389 | ||||
390 | // The number of arguments which should follow the sentinel. | |||
391 | unsigned numArgsAfterSentinel = attr->getSentinel(); | |||
392 | ||||
393 | // If there aren't enough arguments for all the formal parameters, | |||
394 | // the sentinel, and the args after the sentinel, complain. | |||
395 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | |||
396 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | |||
397 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
398 | return; | |||
399 | } | |||
400 | ||||
401 | // Otherwise, find the sentinel expression. | |||
402 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | |||
403 | if (!sentinelExpr) return; | |||
404 | if (sentinelExpr->isValueDependent()) return; | |||
405 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | |||
406 | ||||
407 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | |||
408 | // or 'NULL' if those are actually defined in the context. Only use | |||
409 | // 'nil' for ObjC methods, where it's much more likely that the | |||
410 | // variadic arguments form a list of object pointers. | |||
411 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | |||
412 | std::string NullValue; | |||
413 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | |||
414 | NullValue = "nil"; | |||
415 | else if (getLangOpts().CPlusPlus11) | |||
416 | NullValue = "nullptr"; | |||
417 | else if (PP.isMacroDefined("NULL")) | |||
418 | NullValue = "NULL"; | |||
419 | else | |||
420 | NullValue = "(void*) 0"; | |||
421 | ||||
422 | if (MissingNilLoc.isInvalid()) | |||
423 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | |||
424 | else | |||
425 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | |||
426 | << int(calleeType) | |||
427 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | |||
428 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | |||
429 | } | |||
430 | ||||
431 | SourceRange Sema::getExprRange(Expr *E) const { | |||
432 | return E ? E->getSourceRange() : SourceRange(); | |||
433 | } | |||
434 | ||||
435 | //===----------------------------------------------------------------------===// | |||
436 | // Standard Promotions and Conversions | |||
437 | //===----------------------------------------------------------------------===// | |||
438 | ||||
439 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | |||
440 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | |||
441 | // Handle any placeholder expressions which made it here. | |||
442 | if (E->getType()->isPlaceholderType()) { | |||
443 | ExprResult result = CheckPlaceholderExpr(E); | |||
444 | if (result.isInvalid()) return ExprError(); | |||
445 | E = result.get(); | |||
446 | } | |||
447 | ||||
448 | QualType Ty = E->getType(); | |||
449 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 449, __PRETTY_FUNCTION__)); | |||
450 | ||||
451 | if (Ty->isFunctionType()) { | |||
452 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | |||
453 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | |||
454 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | |||
455 | return ExprError(); | |||
456 | ||||
457 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
458 | CK_FunctionToPointerDecay).get(); | |||
459 | } else if (Ty->isArrayType()) { | |||
460 | // In C90 mode, arrays only promote to pointers if the array expression is | |||
461 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | |||
462 | // type 'array of type' is converted to an expression that has type 'pointer | |||
463 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | |||
464 | // that has type 'array of type' ...". The relevant change is "an lvalue" | |||
465 | // (C90) to "an expression" (C99). | |||
466 | // | |||
467 | // C++ 4.2p1: | |||
468 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | |||
469 | // T" can be converted to an rvalue of type "pointer to T". | |||
470 | // | |||
471 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | |||
472 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | |||
473 | CK_ArrayToPointerDecay).get(); | |||
474 | } | |||
475 | return E; | |||
476 | } | |||
477 | ||||
478 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | |||
479 | // Check to see if we are dereferencing a null pointer. If so, | |||
480 | // and if not volatile-qualified, this is undefined behavior that the | |||
481 | // optimizer will delete, so warn about it. People sometimes try to use this | |||
482 | // to get a deterministic trap and are surprised by clang's behavior. This | |||
483 | // only handles the pattern "*null", which is a very syntactic check. | |||
484 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | |||
485 | if (UO && UO->getOpcode() == UO_Deref && | |||
486 | UO->getSubExpr()->getType()->isPointerType()) { | |||
487 | const LangAS AS = | |||
488 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | |||
489 | if ((!isTargetAddressSpace(AS) || | |||
490 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | |||
491 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | |||
492 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | |||
493 | !UO->getType().isVolatileQualified()) { | |||
494 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
495 | S.PDiag(diag::warn_indirection_through_null) | |||
496 | << UO->getSubExpr()->getSourceRange()); | |||
497 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
498 | S.PDiag(diag::note_indirection_through_null)); | |||
499 | } | |||
500 | } | |||
501 | } | |||
502 | ||||
503 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | |||
504 | SourceLocation AssignLoc, | |||
505 | const Expr* RHS) { | |||
506 | const ObjCIvarDecl *IV = OIRE->getDecl(); | |||
507 | if (!IV) | |||
508 | return; | |||
509 | ||||
510 | DeclarationName MemberName = IV->getDeclName(); | |||
511 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | |||
512 | if (!Member || !Member->isStr("isa")) | |||
513 | return; | |||
514 | ||||
515 | const Expr *Base = OIRE->getBase(); | |||
516 | QualType BaseType = Base->getType(); | |||
517 | if (OIRE->isArrow()) | |||
518 | BaseType = BaseType->getPointeeType(); | |||
519 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | |||
520 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | |||
521 | ObjCInterfaceDecl *ClassDeclared = nullptr; | |||
522 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | |||
523 | if (!ClassDeclared->getSuperClass() | |||
524 | && (*ClassDeclared->ivar_begin()) == IV) { | |||
525 | if (RHS) { | |||
526 | NamedDecl *ObjectSetClass = | |||
527 | S.LookupSingleName(S.TUScope, | |||
528 | &S.Context.Idents.get("object_setClass"), | |||
529 | SourceLocation(), S.LookupOrdinaryName); | |||
530 | if (ObjectSetClass) { | |||
531 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | |||
532 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | |||
533 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | |||
534 | "object_setClass(") | |||
535 | << FixItHint::CreateReplacement( | |||
536 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | |||
537 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | |||
538 | } | |||
539 | else | |||
540 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | |||
541 | } else { | |||
542 | NamedDecl *ObjectGetClass = | |||
543 | S.LookupSingleName(S.TUScope, | |||
544 | &S.Context.Idents.get("object_getClass"), | |||
545 | SourceLocation(), S.LookupOrdinaryName); | |||
546 | if (ObjectGetClass) | |||
547 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | |||
548 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | |||
549 | "object_getClass(") | |||
550 | << FixItHint::CreateReplacement( | |||
551 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | |||
552 | else | |||
553 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | |||
554 | } | |||
555 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | |||
556 | } | |||
557 | } | |||
558 | } | |||
559 | ||||
560 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | |||
561 | // Handle any placeholder expressions which made it here. | |||
562 | if (E->getType()->isPlaceholderType()) { | |||
563 | ExprResult result = CheckPlaceholderExpr(E); | |||
564 | if (result.isInvalid()) return ExprError(); | |||
565 | E = result.get(); | |||
566 | } | |||
567 | ||||
568 | // C++ [conv.lval]p1: | |||
569 | // A glvalue of a non-function, non-array type T can be | |||
570 | // converted to a prvalue. | |||
571 | if (!E->isGLValue()) return E; | |||
572 | ||||
573 | QualType T = E->getType(); | |||
574 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 574, __PRETTY_FUNCTION__)); | |||
575 | ||||
576 | // We don't want to throw lvalue-to-rvalue casts on top of | |||
577 | // expressions of certain types in C++. | |||
578 | if (getLangOpts().CPlusPlus && | |||
579 | (E->getType() == Context.OverloadTy || | |||
580 | T->isDependentType() || | |||
581 | T->isRecordType())) | |||
582 | return E; | |||
583 | ||||
584 | // The C standard is actually really unclear on this point, and | |||
585 | // DR106 tells us what the result should be but not why. It's | |||
586 | // generally best to say that void types just doesn't undergo | |||
587 | // lvalue-to-rvalue at all. Note that expressions of unqualified | |||
588 | // 'void' type are never l-values, but qualified void can be. | |||
589 | if (T->isVoidType()) | |||
590 | return E; | |||
591 | ||||
592 | // OpenCL usually rejects direct accesses to values of 'half' type. | |||
593 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | |||
594 | T->isHalfType()) { | |||
595 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | |||
596 | << 0 << T; | |||
597 | return ExprError(); | |||
598 | } | |||
599 | ||||
600 | CheckForNullPointerDereference(*this, E); | |||
601 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | |||
602 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | |||
603 | &Context.Idents.get("object_getClass"), | |||
604 | SourceLocation(), LookupOrdinaryName); | |||
605 | if (ObjectGetClass) | |||
606 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | |||
607 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | |||
608 | << FixItHint::CreateReplacement( | |||
609 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | |||
610 | else | |||
611 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | |||
612 | } | |||
613 | else if (const ObjCIvarRefExpr *OIRE = | |||
614 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | |||
615 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | |||
616 | ||||
617 | // C++ [conv.lval]p1: | |||
618 | // [...] If T is a non-class type, the type of the prvalue is the | |||
619 | // cv-unqualified version of T. Otherwise, the type of the | |||
620 | // rvalue is T. | |||
621 | // | |||
622 | // C99 6.3.2.1p2: | |||
623 | // If the lvalue has qualified type, the value has the unqualified | |||
624 | // version of the type of the lvalue; otherwise, the value has the | |||
625 | // type of the lvalue. | |||
626 | if (T.hasQualifiers()) | |||
627 | T = T.getUnqualifiedType(); | |||
628 | ||||
629 | // Under the MS ABI, lock down the inheritance model now. | |||
630 | if (T->isMemberPointerType() && | |||
631 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
632 | (void)isCompleteType(E->getExprLoc(), T); | |||
633 | ||||
634 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | |||
635 | if (Res.isInvalid()) | |||
636 | return Res; | |||
637 | E = Res.get(); | |||
638 | ||||
639 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | |||
640 | // balance that. | |||
641 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
642 | Cleanup.setExprNeedsCleanups(true); | |||
643 | ||||
644 | // C++ [conv.lval]p3: | |||
645 | // If T is cv std::nullptr_t, the result is a null pointer constant. | |||
646 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | |||
647 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); | |||
648 | ||||
649 | // C11 6.3.2.1p2: | |||
650 | // ... if the lvalue has atomic type, the value has the non-atomic version | |||
651 | // of the type of the lvalue ... | |||
652 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | |||
653 | T = Atomic->getValueType().getUnqualifiedType(); | |||
654 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | |||
655 | nullptr, VK_RValue); | |||
656 | } | |||
657 | ||||
658 | return Res; | |||
659 | } | |||
660 | ||||
661 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | |||
662 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | |||
663 | if (Res.isInvalid()) | |||
664 | return ExprError(); | |||
665 | Res = DefaultLvalueConversion(Res.get()); | |||
666 | if (Res.isInvalid()) | |||
667 | return ExprError(); | |||
668 | return Res; | |||
669 | } | |||
670 | ||||
671 | /// CallExprUnaryConversions - a special case of an unary conversion | |||
672 | /// performed on a function designator of a call expression. | |||
673 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | |||
674 | QualType Ty = E->getType(); | |||
675 | ExprResult Res = E; | |||
676 | // Only do implicit cast for a function type, but not for a pointer | |||
677 | // to function type. | |||
678 | if (Ty->isFunctionType()) { | |||
679 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | |||
680 | CK_FunctionToPointerDecay).get(); | |||
681 | if (Res.isInvalid()) | |||
682 | return ExprError(); | |||
683 | } | |||
684 | Res = DefaultLvalueConversion(Res.get()); | |||
685 | if (Res.isInvalid()) | |||
686 | return ExprError(); | |||
687 | return Res.get(); | |||
688 | } | |||
689 | ||||
690 | /// UsualUnaryConversions - Performs various conversions that are common to most | |||
691 | /// operators (C99 6.3). The conversions of array and function types are | |||
692 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | |||
693 | /// apply if the array is an argument to the sizeof or address (&) operators. | |||
694 | /// In these instances, this routine should *not* be called. | |||
695 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | |||
696 | // First, convert to an r-value. | |||
697 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
698 | if (Res.isInvalid()) | |||
699 | return ExprError(); | |||
700 | E = Res.get(); | |||
701 | ||||
702 | QualType Ty = E->getType(); | |||
703 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 703, __PRETTY_FUNCTION__)); | |||
704 | ||||
705 | // Half FP have to be promoted to float unless it is natively supported | |||
706 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | |||
707 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | |||
708 | ||||
709 | // Try to perform integral promotions if the object has a theoretically | |||
710 | // promotable type. | |||
711 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | |||
712 | // C99 6.3.1.1p2: | |||
713 | // | |||
714 | // The following may be used in an expression wherever an int or | |||
715 | // unsigned int may be used: | |||
716 | // - an object or expression with an integer type whose integer | |||
717 | // conversion rank is less than or equal to the rank of int | |||
718 | // and unsigned int. | |||
719 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | |||
720 | // | |||
721 | // If an int can represent all values of the original type, the | |||
722 | // value is converted to an int; otherwise, it is converted to an | |||
723 | // unsigned int. These are called the integer promotions. All | |||
724 | // other types are unchanged by the integer promotions. | |||
725 | ||||
726 | QualType PTy = Context.isPromotableBitField(E); | |||
727 | if (!PTy.isNull()) { | |||
728 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | |||
729 | return E; | |||
730 | } | |||
731 | if (Ty->isPromotableIntegerType()) { | |||
732 | QualType PT = Context.getPromotedIntegerType(Ty); | |||
733 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | |||
734 | return E; | |||
735 | } | |||
736 | } | |||
737 | return E; | |||
738 | } | |||
739 | ||||
740 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | |||
741 | /// do not have a prototype. Arguments that have type float or __fp16 | |||
742 | /// are promoted to double. All other argument types are converted by | |||
743 | /// UsualUnaryConversions(). | |||
744 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | |||
745 | QualType Ty = E->getType(); | |||
746 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 746, __PRETTY_FUNCTION__)); | |||
747 | ||||
748 | ExprResult Res = UsualUnaryConversions(E); | |||
749 | if (Res.isInvalid()) | |||
750 | return ExprError(); | |||
751 | E = Res.get(); | |||
752 | ||||
753 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | |||
754 | // promote to double. | |||
755 | // Note that default argument promotion applies only to float (and | |||
756 | // half/fp16); it does not apply to _Float16. | |||
757 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
758 | if (BTy && (BTy->getKind() == BuiltinType::Half || | |||
759 | BTy->getKind() == BuiltinType::Float)) { | |||
760 | if (getLangOpts().OpenCL && | |||
761 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | |||
762 | if (BTy->getKind() == BuiltinType::Half) { | |||
763 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | |||
764 | } | |||
765 | } else { | |||
766 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | |||
767 | } | |||
768 | } | |||
769 | ||||
770 | // C++ performs lvalue-to-rvalue conversion as a default argument | |||
771 | // promotion, even on class types, but note: | |||
772 | // C++11 [conv.lval]p2: | |||
773 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | |||
774 | // operand or a subexpression thereof the value contained in the | |||
775 | // referenced object is not accessed. Otherwise, if the glvalue | |||
776 | // has a class type, the conversion copy-initializes a temporary | |||
777 | // of type T from the glvalue and the result of the conversion | |||
778 | // is a prvalue for the temporary. | |||
779 | // FIXME: add some way to gate this entire thing for correctness in | |||
780 | // potentially potentially evaluated contexts. | |||
781 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | |||
782 | ExprResult Temp = PerformCopyInitialization( | |||
783 | InitializedEntity::InitializeTemporary(E->getType()), | |||
784 | E->getExprLoc(), E); | |||
785 | if (Temp.isInvalid()) | |||
786 | return ExprError(); | |||
787 | E = Temp.get(); | |||
788 | } | |||
789 | ||||
790 | return E; | |||
791 | } | |||
792 | ||||
793 | /// Determine the degree of POD-ness for an expression. | |||
794 | /// Incomplete types are considered POD, since this check can be performed | |||
795 | /// when we're in an unevaluated context. | |||
796 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | |||
797 | if (Ty->isIncompleteType()) { | |||
798 | // C++11 [expr.call]p7: | |||
799 | // After these conversions, if the argument does not have arithmetic, | |||
800 | // enumeration, pointer, pointer to member, or class type, the program | |||
801 | // is ill-formed. | |||
802 | // | |||
803 | // Since we've already performed array-to-pointer and function-to-pointer | |||
804 | // decay, the only such type in C++ is cv void. This also handles | |||
805 | // initializer lists as variadic arguments. | |||
806 | if (Ty->isVoidType()) | |||
807 | return VAK_Invalid; | |||
808 | ||||
809 | if (Ty->isObjCObjectType()) | |||
810 | return VAK_Invalid; | |||
811 | return VAK_Valid; | |||
812 | } | |||
813 | ||||
814 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
815 | return VAK_Invalid; | |||
816 | ||||
817 | if (Ty.isCXX98PODType(Context)) | |||
818 | return VAK_Valid; | |||
819 | ||||
820 | // C++11 [expr.call]p7: | |||
821 | // Passing a potentially-evaluated argument of class type (Clause 9) | |||
822 | // having a non-trivial copy constructor, a non-trivial move constructor, | |||
823 | // or a non-trivial destructor, with no corresponding parameter, | |||
824 | // is conditionally-supported with implementation-defined semantics. | |||
825 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | |||
826 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | |||
827 | if (!Record->hasNonTrivialCopyConstructor() && | |||
828 | !Record->hasNonTrivialMoveConstructor() && | |||
829 | !Record->hasNonTrivialDestructor()) | |||
830 | return VAK_ValidInCXX11; | |||
831 | ||||
832 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | |||
833 | return VAK_Valid; | |||
834 | ||||
835 | if (Ty->isObjCObjectType()) | |||
836 | return VAK_Invalid; | |||
837 | ||||
838 | if (getLangOpts().MSVCCompat) | |||
839 | return VAK_MSVCUndefined; | |||
840 | ||||
841 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | |||
842 | // permitted to reject them. We should consider doing so. | |||
843 | return VAK_Undefined; | |||
844 | } | |||
845 | ||||
846 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | |||
847 | // Don't allow one to pass an Objective-C interface to a vararg. | |||
848 | const QualType &Ty = E->getType(); | |||
849 | VarArgKind VAK = isValidVarArgType(Ty); | |||
850 | ||||
851 | // Complain about passing non-POD types through varargs. | |||
852 | switch (VAK) { | |||
853 | case VAK_ValidInCXX11: | |||
854 | DiagRuntimeBehavior( | |||
855 | E->getBeginLoc(), nullptr, | |||
856 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | |||
857 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
858 | case VAK_Valid: | |||
859 | if (Ty->isRecordType()) { | |||
860 | // This is unlikely to be what the user intended. If the class has a | |||
861 | // 'c_str' member function, the user probably meant to call that. | |||
862 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
863 | PDiag(diag::warn_pass_class_arg_to_vararg) | |||
864 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | |||
865 | } | |||
866 | break; | |||
867 | ||||
868 | case VAK_Undefined: | |||
869 | case VAK_MSVCUndefined: | |||
870 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
871 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | |||
872 | << getLangOpts().CPlusPlus11 << Ty << CT); | |||
873 | break; | |||
874 | ||||
875 | case VAK_Invalid: | |||
876 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
877 | Diag(E->getBeginLoc(), | |||
878 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | |||
879 | << Ty << CT; | |||
880 | else if (Ty->isObjCObjectType()) | |||
881 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | |||
882 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | |||
883 | << Ty << CT); | |||
884 | else | |||
885 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | |||
886 | << isa<InitListExpr>(E) << Ty << CT; | |||
887 | break; | |||
888 | } | |||
889 | } | |||
890 | ||||
891 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | |||
892 | /// will create a trap if the resulting type is not a POD type. | |||
893 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | |||
894 | FunctionDecl *FDecl) { | |||
895 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | |||
896 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
897 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | |||
898 | (CT == VariadicMethod || | |||
899 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | |||
900 | E = stripARCUnbridgedCast(E); | |||
901 | ||||
902 | // Otherwise, do normal placeholder checking. | |||
903 | } else { | |||
904 | ExprResult ExprRes = CheckPlaceholderExpr(E); | |||
905 | if (ExprRes.isInvalid()) | |||
906 | return ExprError(); | |||
907 | E = ExprRes.get(); | |||
908 | } | |||
909 | } | |||
910 | ||||
911 | ExprResult ExprRes = DefaultArgumentPromotion(E); | |||
912 | if (ExprRes.isInvalid()) | |||
913 | return ExprError(); | |||
914 | E = ExprRes.get(); | |||
915 | ||||
916 | // Diagnostics regarding non-POD argument types are | |||
917 | // emitted along with format string checking in Sema::CheckFunctionCall(). | |||
918 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | |||
919 | // Turn this into a trap. | |||
920 | CXXScopeSpec SS; | |||
921 | SourceLocation TemplateKWLoc; | |||
922 | UnqualifiedId Name; | |||
923 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | |||
924 | E->getBeginLoc()); | |||
925 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | |||
926 | /*HasTrailingLParen=*/true, | |||
927 | /*IsAddressOfOperand=*/false); | |||
928 | if (TrapFn.isInvalid()) | |||
929 | return ExprError(); | |||
930 | ||||
931 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | |||
932 | None, E->getEndLoc()); | |||
933 | if (Call.isInvalid()) | |||
934 | return ExprError(); | |||
935 | ||||
936 | ExprResult Comma = | |||
937 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | |||
938 | if (Comma.isInvalid()) | |||
939 | return ExprError(); | |||
940 | return Comma.get(); | |||
941 | } | |||
942 | ||||
943 | if (!getLangOpts().CPlusPlus && | |||
944 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
945 | diag::err_call_incomplete_argument)) | |||
946 | return ExprError(); | |||
947 | ||||
948 | return E; | |||
949 | } | |||
950 | ||||
951 | /// Converts an integer to complex float type. Helper function of | |||
952 | /// UsualArithmeticConversions() | |||
953 | /// | |||
954 | /// \return false if the integer expression is an integer type and is | |||
955 | /// successfully converted to the complex type. | |||
956 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | |||
957 | ExprResult &ComplexExpr, | |||
958 | QualType IntTy, | |||
959 | QualType ComplexTy, | |||
960 | bool SkipCast) { | |||
961 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | |||
962 | if (SkipCast) return false; | |||
963 | if (IntTy->isIntegerType()) { | |||
964 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | |||
965 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | |||
966 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
967 | CK_FloatingRealToComplex); | |||
968 | } else { | |||
969 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 969, __PRETTY_FUNCTION__)); | |||
970 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | |||
971 | CK_IntegralComplexToFloatingComplex); | |||
972 | } | |||
973 | return false; | |||
974 | } | |||
975 | ||||
976 | /// Handle arithmetic conversion with complex types. Helper function of | |||
977 | /// UsualArithmeticConversions() | |||
978 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | |||
979 | ExprResult &RHS, QualType LHSType, | |||
980 | QualType RHSType, | |||
981 | bool IsCompAssign) { | |||
982 | // if we have an integer operand, the result is the complex type. | |||
983 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
984 | /*skipCast*/false)) | |||
985 | return LHSType; | |||
986 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
987 | /*skipCast*/IsCompAssign)) | |||
988 | return RHSType; | |||
989 | ||||
990 | // This handles complex/complex, complex/float, or float/complex. | |||
991 | // When both operands are complex, the shorter operand is converted to the | |||
992 | // type of the longer, and that is the type of the result. This corresponds | |||
993 | // to what is done when combining two real floating-point operands. | |||
994 | // The fun begins when size promotion occur across type domains. | |||
995 | // From H&S 6.3.4: When one operand is complex and the other is a real | |||
996 | // floating-point type, the less precise type is converted, within it's | |||
997 | // real or complex domain, to the precision of the other type. For example, | |||
998 | // when combining a "long double" with a "double _Complex", the | |||
999 | // "double _Complex" is promoted to "long double _Complex". | |||
1000 | ||||
1001 | // Compute the rank of the two types, regardless of whether they are complex. | |||
1002 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1003 | ||||
1004 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | |||
1005 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | |||
1006 | QualType LHSElementType = | |||
1007 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | |||
1008 | QualType RHSElementType = | |||
1009 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | |||
1010 | ||||
1011 | QualType ResultType = S.Context.getComplexType(LHSElementType); | |||
1012 | if (Order < 0) { | |||
1013 | // Promote the precision of the LHS if not an assignment. | |||
1014 | ResultType = S.Context.getComplexType(RHSElementType); | |||
1015 | if (!IsCompAssign) { | |||
1016 | if (LHSComplexType) | |||
1017 | LHS = | |||
1018 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | |||
1019 | else | |||
1020 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | |||
1021 | } | |||
1022 | } else if (Order > 0) { | |||
1023 | // Promote the precision of the RHS. | |||
1024 | if (RHSComplexType) | |||
1025 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | |||
1026 | else | |||
1027 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | |||
1028 | } | |||
1029 | return ResultType; | |||
1030 | } | |||
1031 | ||||
1032 | /// Handle arithmetic conversion from integer to float. Helper function | |||
1033 | /// of UsualArithmeticConversions() | |||
1034 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | |||
1035 | ExprResult &IntExpr, | |||
1036 | QualType FloatTy, QualType IntTy, | |||
1037 | bool ConvertFloat, bool ConvertInt) { | |||
1038 | if (IntTy->isIntegerType()) { | |||
1039 | if (ConvertInt) | |||
1040 | // Convert intExpr to the lhs floating point type. | |||
1041 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | |||
1042 | CK_IntegralToFloating); | |||
1043 | return FloatTy; | |||
1044 | } | |||
1045 | ||||
1046 | // Convert both sides to the appropriate complex float. | |||
1047 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1047, __PRETTY_FUNCTION__)); | |||
1048 | QualType result = S.Context.getComplexType(FloatTy); | |||
1049 | ||||
1050 | // _Complex int -> _Complex float | |||
1051 | if (ConvertInt) | |||
1052 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | |||
1053 | CK_IntegralComplexToFloatingComplex); | |||
1054 | ||||
1055 | // float -> _Complex float | |||
1056 | if (ConvertFloat) | |||
1057 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | |||
1058 | CK_FloatingRealToComplex); | |||
1059 | ||||
1060 | return result; | |||
1061 | } | |||
1062 | ||||
1063 | /// Handle arithmethic conversion with floating point types. Helper | |||
1064 | /// function of UsualArithmeticConversions() | |||
1065 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | |||
1066 | ExprResult &RHS, QualType LHSType, | |||
1067 | QualType RHSType, bool IsCompAssign) { | |||
1068 | bool LHSFloat = LHSType->isRealFloatingType(); | |||
1069 | bool RHSFloat = RHSType->isRealFloatingType(); | |||
1070 | ||||
1071 | // If we have two real floating types, convert the smaller operand | |||
1072 | // to the bigger result. | |||
1073 | if (LHSFloat && RHSFloat) { | |||
1074 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | |||
1075 | if (order > 0) { | |||
1076 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | |||
1077 | return LHSType; | |||
1078 | } | |||
1079 | ||||
1080 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1080, __PRETTY_FUNCTION__)); | |||
1081 | if (!IsCompAssign) | |||
1082 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | |||
1083 | return RHSType; | |||
1084 | } | |||
1085 | ||||
1086 | if (LHSFloat) { | |||
1087 | // Half FP has to be promoted to float unless it is natively supported | |||
1088 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | |||
1089 | LHSType = S.Context.FloatTy; | |||
1090 | ||||
1091 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | |||
1092 | /*ConvertFloat=*/!IsCompAssign, | |||
1093 | /*ConvertInt=*/ true); | |||
1094 | } | |||
1095 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1095, __PRETTY_FUNCTION__)); | |||
1096 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | |||
1097 | /*convertInt=*/ true, | |||
1098 | /*convertFloat=*/!IsCompAssign); | |||
1099 | } | |||
1100 | ||||
1101 | /// Diagnose attempts to convert between __float128 and long double if | |||
1102 | /// there is no support for such conversion. Helper function of | |||
1103 | /// UsualArithmeticConversions(). | |||
1104 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | |||
1105 | QualType RHSType) { | |||
1106 | /* No issue converting if at least one of the types is not a floating point | |||
1107 | type or the two types have the same rank. | |||
1108 | */ | |||
1109 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | |||
1110 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | |||
1111 | return false; | |||
1112 | ||||
1113 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1114, __PRETTY_FUNCTION__)) | |||
1114 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1114, __PRETTY_FUNCTION__)); | |||
1115 | ||||
1116 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | |||
1117 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | |||
1118 | ||||
1119 | QualType LHSElemType = LHSComplex ? | |||
1120 | LHSComplex->getElementType() : LHSType; | |||
1121 | QualType RHSElemType = RHSComplex ? | |||
1122 | RHSComplex->getElementType() : RHSType; | |||
1123 | ||||
1124 | // No issue if the two types have the same representation | |||
1125 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | |||
1126 | &S.Context.getFloatTypeSemantics(RHSElemType)) | |||
1127 | return false; | |||
1128 | ||||
1129 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | |||
1130 | RHSElemType == S.Context.LongDoubleTy); | |||
1131 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | |||
1132 | RHSElemType == S.Context.Float128Ty); | |||
1133 | ||||
1134 | // We've handled the situation where __float128 and long double have the same | |||
1135 | // representation. We allow all conversions for all possible long double types | |||
1136 | // except PPC's double double. | |||
1137 | return Float128AndLongDouble && | |||
1138 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | |||
1139 | &llvm::APFloat::PPCDoubleDouble()); | |||
1140 | } | |||
1141 | ||||
1142 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | |||
1143 | ||||
1144 | namespace { | |||
1145 | /// These helper callbacks are placed in an anonymous namespace to | |||
1146 | /// permit their use as function template parameters. | |||
1147 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1148 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | |||
1149 | } | |||
1150 | ||||
1151 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | |||
1152 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | |||
1153 | CK_IntegralComplexCast); | |||
1154 | } | |||
1155 | } | |||
1156 | ||||
1157 | /// Handle integer arithmetic conversions. Helper function of | |||
1158 | /// UsualArithmeticConversions() | |||
1159 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | |||
1160 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | |||
1161 | ExprResult &RHS, QualType LHSType, | |||
1162 | QualType RHSType, bool IsCompAssign) { | |||
1163 | // The rules for this case are in C99 6.3.1.8 | |||
1164 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | |||
1165 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | |||
1166 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | |||
1167 | if (LHSSigned == RHSSigned) { | |||
1168 | // Same signedness; use the higher-ranked type | |||
1169 | if (order >= 0) { | |||
1170 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1171 | return LHSType; | |||
1172 | } else if (!IsCompAssign) | |||
1173 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1174 | return RHSType; | |||
1175 | } else if (order != (LHSSigned ? 1 : -1)) { | |||
1176 | // The unsigned type has greater than or equal rank to the | |||
1177 | // signed type, so use the unsigned type | |||
1178 | if (RHSSigned) { | |||
1179 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1180 | return LHSType; | |||
1181 | } else if (!IsCompAssign) | |||
1182 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1183 | return RHSType; | |||
1184 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | |||
1185 | // The two types are different widths; if we are here, that | |||
1186 | // means the signed type is larger than the unsigned type, so | |||
1187 | // use the signed type. | |||
1188 | if (LHSSigned) { | |||
1189 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | |||
1190 | return LHSType; | |||
1191 | } else if (!IsCompAssign) | |||
1192 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | |||
1193 | return RHSType; | |||
1194 | } else { | |||
1195 | // The signed type is higher-ranked than the unsigned type, | |||
1196 | // but isn't actually any bigger (like unsigned int and long | |||
1197 | // on most 32-bit systems). Use the unsigned type corresponding | |||
1198 | // to the signed type. | |||
1199 | QualType result = | |||
1200 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | |||
1201 | RHS = (*doRHSCast)(S, RHS.get(), result); | |||
1202 | if (!IsCompAssign) | |||
1203 | LHS = (*doLHSCast)(S, LHS.get(), result); | |||
1204 | return result; | |||
1205 | } | |||
1206 | } | |||
1207 | ||||
1208 | /// Handle conversions with GCC complex int extension. Helper function | |||
1209 | /// of UsualArithmeticConversions() | |||
1210 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | |||
1211 | ExprResult &RHS, QualType LHSType, | |||
1212 | QualType RHSType, | |||
1213 | bool IsCompAssign) { | |||
1214 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | |||
1215 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | |||
1216 | ||||
1217 | if (LHSComplexInt && RHSComplexInt) { | |||
1218 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1219 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1220 | QualType ScalarType = | |||
1221 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | |||
1222 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | |||
1223 | ||||
1224 | return S.Context.getComplexType(ScalarType); | |||
1225 | } | |||
1226 | ||||
1227 | if (LHSComplexInt) { | |||
1228 | QualType LHSEltType = LHSComplexInt->getElementType(); | |||
1229 | QualType ScalarType = | |||
1230 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | |||
1231 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | |||
1232 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1233 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | |||
1234 | CK_IntegralRealToComplex); | |||
1235 | ||||
1236 | return ComplexType; | |||
1237 | } | |||
1238 | ||||
1239 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1239, __PRETTY_FUNCTION__)); | |||
1240 | ||||
1241 | QualType RHSEltType = RHSComplexInt->getElementType(); | |||
1242 | QualType ScalarType = | |||
1243 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | |||
1244 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | |||
1245 | QualType ComplexType = S.Context.getComplexType(ScalarType); | |||
1246 | ||||
1247 | if (!IsCompAssign) | |||
1248 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | |||
1249 | CK_IntegralRealToComplex); | |||
1250 | return ComplexType; | |||
1251 | } | |||
1252 | ||||
1253 | /// Return the rank of a given fixed point or integer type. The value itself | |||
1254 | /// doesn't matter, but the values must be increasing with proper increasing | |||
1255 | /// rank as described in N1169 4.1.1. | |||
1256 | static unsigned GetFixedPointRank(QualType Ty) { | |||
1257 | const auto *BTy = Ty->getAs<BuiltinType>(); | |||
1258 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1258, __PRETTY_FUNCTION__)); | |||
1259 | ||||
1260 | switch (BTy->getKind()) { | |||
1261 | case BuiltinType::ShortFract: | |||
1262 | case BuiltinType::UShortFract: | |||
1263 | case BuiltinType::SatShortFract: | |||
1264 | case BuiltinType::SatUShortFract: | |||
1265 | return 1; | |||
1266 | case BuiltinType::Fract: | |||
1267 | case BuiltinType::UFract: | |||
1268 | case BuiltinType::SatFract: | |||
1269 | case BuiltinType::SatUFract: | |||
1270 | return 2; | |||
1271 | case BuiltinType::LongFract: | |||
1272 | case BuiltinType::ULongFract: | |||
1273 | case BuiltinType::SatLongFract: | |||
1274 | case BuiltinType::SatULongFract: | |||
1275 | return 3; | |||
1276 | case BuiltinType::ShortAccum: | |||
1277 | case BuiltinType::UShortAccum: | |||
1278 | case BuiltinType::SatShortAccum: | |||
1279 | case BuiltinType::SatUShortAccum: | |||
1280 | return 4; | |||
1281 | case BuiltinType::Accum: | |||
1282 | case BuiltinType::UAccum: | |||
1283 | case BuiltinType::SatAccum: | |||
1284 | case BuiltinType::SatUAccum: | |||
1285 | return 5; | |||
1286 | case BuiltinType::LongAccum: | |||
1287 | case BuiltinType::ULongAccum: | |||
1288 | case BuiltinType::SatLongAccum: | |||
1289 | case BuiltinType::SatULongAccum: | |||
1290 | return 6; | |||
1291 | default: | |||
1292 | if (BTy->isInteger()) | |||
1293 | return 0; | |||
1294 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1294); | |||
1295 | } | |||
1296 | } | |||
1297 | ||||
1298 | /// handleFixedPointConversion - Fixed point operations between fixed | |||
1299 | /// point types and integers or other fixed point types do not fall under | |||
1300 | /// usual arithmetic conversion since these conversions could result in loss | |||
1301 | /// of precsision (N1169 4.1.4). These operations should be calculated with | |||
1302 | /// the full precision of their result type (N1169 4.1.6.2.1). | |||
1303 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | |||
1304 | QualType RHSTy) { | |||
1305 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1306, __PRETTY_FUNCTION__)) | |||
1306 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1306, __PRETTY_FUNCTION__)); | |||
1307 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1310, __PRETTY_FUNCTION__)) | |||
1308 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1310, __PRETTY_FUNCTION__)) | |||
1309 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1310, __PRETTY_FUNCTION__)) | |||
1310 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1310, __PRETTY_FUNCTION__)); | |||
1311 | ||||
1312 | // If one operand has signed fixed-point type and the other operand has | |||
1313 | // unsigned fixed-point type, then the unsigned fixed-point operand is | |||
1314 | // converted to its corresponding signed fixed-point type and the resulting | |||
1315 | // type is the type of the converted operand. | |||
1316 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | |||
1317 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | |||
1318 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | |||
1319 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | |||
1320 | ||||
1321 | // The result type is the type with the highest rank, whereby a fixed-point | |||
1322 | // conversion rank is always greater than an integer conversion rank; if the | |||
1323 | // type of either of the operands is a saturating fixedpoint type, the result | |||
1324 | // type shall be the saturating fixed-point type corresponding to the type | |||
1325 | // with the highest rank; the resulting value is converted (taking into | |||
1326 | // account rounding and overflow) to the precision of the resulting type. | |||
1327 | // Same ranks between signed and unsigned types are resolved earlier, so both | |||
1328 | // types are either signed or both unsigned at this point. | |||
1329 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | |||
1330 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | |||
1331 | ||||
1332 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | |||
1333 | ||||
1334 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | |||
1335 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | |||
1336 | ||||
1337 | return ResultTy; | |||
1338 | } | |||
1339 | ||||
1340 | /// UsualArithmeticConversions - Performs various conversions that are common to | |||
1341 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | |||
1342 | /// routine returns the first non-arithmetic type found. The client is | |||
1343 | /// responsible for emitting appropriate error diagnostics. | |||
1344 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | |||
1345 | bool IsCompAssign) { | |||
1346 | if (!IsCompAssign) { | |||
1347 | LHS = UsualUnaryConversions(LHS.get()); | |||
1348 | if (LHS.isInvalid()) | |||
1349 | return QualType(); | |||
1350 | } | |||
1351 | ||||
1352 | RHS = UsualUnaryConversions(RHS.get()); | |||
1353 | if (RHS.isInvalid()) | |||
1354 | return QualType(); | |||
1355 | ||||
1356 | // For conversion purposes, we ignore any qualifiers. | |||
1357 | // For example, "const float" and "float" are equivalent. | |||
1358 | QualType LHSType = | |||
1359 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | |||
1360 | QualType RHSType = | |||
1361 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | |||
1362 | ||||
1363 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | |||
1364 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | |||
1365 | LHSType = AtomicLHS->getValueType(); | |||
1366 | ||||
1367 | // If both types are identical, no conversion is needed. | |||
1368 | if (LHSType == RHSType) | |||
1369 | return LHSType; | |||
1370 | ||||
1371 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | |||
1372 | // The caller can deal with this (e.g. pointer + int). | |||
1373 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | |||
1374 | return QualType(); | |||
1375 | ||||
1376 | // Apply unary and bitfield promotions to the LHS's type. | |||
1377 | QualType LHSUnpromotedType = LHSType; | |||
1378 | if (LHSType->isPromotableIntegerType()) | |||
1379 | LHSType = Context.getPromotedIntegerType(LHSType); | |||
1380 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | |||
1381 | if (!LHSBitfieldPromoteTy.isNull()) | |||
1382 | LHSType = LHSBitfieldPromoteTy; | |||
1383 | if (LHSType != LHSUnpromotedType && !IsCompAssign) | |||
1384 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | |||
1385 | ||||
1386 | // If both types are identical, no conversion is needed. | |||
1387 | if (LHSType == RHSType) | |||
1388 | return LHSType; | |||
1389 | ||||
1390 | // At this point, we have two different arithmetic types. | |||
1391 | ||||
1392 | // Diagnose attempts to convert between __float128 and long double where | |||
1393 | // such conversions currently can't be handled. | |||
1394 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | |||
1395 | return QualType(); | |||
1396 | ||||
1397 | // Handle complex types first (C99 6.3.1.8p1). | |||
1398 | if (LHSType->isComplexType() || RHSType->isComplexType()) | |||
1399 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1400 | IsCompAssign); | |||
1401 | ||||
1402 | // Now handle "real" floating types (i.e. float, double, long double). | |||
1403 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | |||
1404 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1405 | IsCompAssign); | |||
1406 | ||||
1407 | // Handle GCC complex int extension. | |||
1408 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | |||
1409 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | |||
1410 | IsCompAssign); | |||
1411 | ||||
1412 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | |||
1413 | return handleFixedPointConversion(*this, LHSType, RHSType); | |||
1414 | ||||
1415 | // Finally, we have two differing integer types. | |||
1416 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | |||
1417 | (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); | |||
1418 | } | |||
1419 | ||||
1420 | //===----------------------------------------------------------------------===// | |||
1421 | // Semantic Analysis for various Expression Types | |||
1422 | //===----------------------------------------------------------------------===// | |||
1423 | ||||
1424 | ||||
1425 | ExprResult | |||
1426 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | |||
1427 | SourceLocation DefaultLoc, | |||
1428 | SourceLocation RParenLoc, | |||
1429 | Expr *ControllingExpr, | |||
1430 | ArrayRef<ParsedType> ArgTypes, | |||
1431 | ArrayRef<Expr *> ArgExprs) { | |||
1432 | unsigned NumAssocs = ArgTypes.size(); | |||
1433 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1433, __PRETTY_FUNCTION__)); | |||
1434 | ||||
1435 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | |||
1436 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1437 | if (ArgTypes[i]) | |||
1438 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | |||
1439 | else | |||
1440 | Types[i] = nullptr; | |||
1441 | } | |||
1442 | ||||
1443 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | |||
1444 | ControllingExpr, | |||
1445 | llvm::makeArrayRef(Types, NumAssocs), | |||
1446 | ArgExprs); | |||
1447 | delete [] Types; | |||
1448 | return ER; | |||
1449 | } | |||
1450 | ||||
1451 | ExprResult | |||
1452 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | |||
1453 | SourceLocation DefaultLoc, | |||
1454 | SourceLocation RParenLoc, | |||
1455 | Expr *ControllingExpr, | |||
1456 | ArrayRef<TypeSourceInfo *> Types, | |||
1457 | ArrayRef<Expr *> Exprs) { | |||
1458 | unsigned NumAssocs = Types.size(); | |||
1459 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1459, __PRETTY_FUNCTION__)); | |||
1460 | ||||
1461 | // Decay and strip qualifiers for the controlling expression type, and handle | |||
1462 | // placeholder type replacement. See committee discussion from WG14 DR423. | |||
1463 | { | |||
1464 | EnterExpressionEvaluationContext Unevaluated( | |||
1465 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
1466 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | |||
1467 | if (R.isInvalid()) | |||
1468 | return ExprError(); | |||
1469 | ControllingExpr = R.get(); | |||
1470 | } | |||
1471 | ||||
1472 | // The controlling expression is an unevaluated operand, so side effects are | |||
1473 | // likely unintended. | |||
1474 | if (!inTemplateInstantiation() && | |||
1475 | ControllingExpr->HasSideEffects(Context, false)) | |||
1476 | Diag(ControllingExpr->getExprLoc(), | |||
1477 | diag::warn_side_effects_unevaluated_context); | |||
1478 | ||||
1479 | bool TypeErrorFound = false, | |||
1480 | IsResultDependent = ControllingExpr->isTypeDependent(), | |||
1481 | ContainsUnexpandedParameterPack | |||
1482 | = ControllingExpr->containsUnexpandedParameterPack(); | |||
1483 | ||||
1484 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1485 | if (Exprs[i]->containsUnexpandedParameterPack()) | |||
1486 | ContainsUnexpandedParameterPack = true; | |||
1487 | ||||
1488 | if (Types[i]) { | |||
1489 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | |||
1490 | ContainsUnexpandedParameterPack = true; | |||
1491 | ||||
1492 | if (Types[i]->getType()->isDependentType()) { | |||
1493 | IsResultDependent = true; | |||
1494 | } else { | |||
1495 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | |||
1496 | // complete object type other than a variably modified type." | |||
1497 | unsigned D = 0; | |||
1498 | if (Types[i]->getType()->isIncompleteType()) | |||
1499 | D = diag::err_assoc_type_incomplete; | |||
1500 | else if (!Types[i]->getType()->isObjectType()) | |||
1501 | D = diag::err_assoc_type_nonobject; | |||
1502 | else if (Types[i]->getType()->isVariablyModifiedType()) | |||
1503 | D = diag::err_assoc_type_variably_modified; | |||
1504 | ||||
1505 | if (D != 0) { | |||
1506 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | |||
1507 | << Types[i]->getTypeLoc().getSourceRange() | |||
1508 | << Types[i]->getType(); | |||
1509 | TypeErrorFound = true; | |||
1510 | } | |||
1511 | ||||
1512 | // C11 6.5.1.1p2 "No two generic associations in the same generic | |||
1513 | // selection shall specify compatible types." | |||
1514 | for (unsigned j = i+1; j < NumAssocs; ++j) | |||
1515 | if (Types[j] && !Types[j]->getType()->isDependentType() && | |||
1516 | Context.typesAreCompatible(Types[i]->getType(), | |||
1517 | Types[j]->getType())) { | |||
1518 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | |||
1519 | diag::err_assoc_compatible_types) | |||
1520 | << Types[j]->getTypeLoc().getSourceRange() | |||
1521 | << Types[j]->getType() | |||
1522 | << Types[i]->getType(); | |||
1523 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | |||
1524 | diag::note_compat_assoc) | |||
1525 | << Types[i]->getTypeLoc().getSourceRange() | |||
1526 | << Types[i]->getType(); | |||
1527 | TypeErrorFound = true; | |||
1528 | } | |||
1529 | } | |||
1530 | } | |||
1531 | } | |||
1532 | if (TypeErrorFound) | |||
1533 | return ExprError(); | |||
1534 | ||||
1535 | // If we determined that the generic selection is result-dependent, don't | |||
1536 | // try to compute the result expression. | |||
1537 | if (IsResultDependent) | |||
1538 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | |||
1539 | Exprs, DefaultLoc, RParenLoc, | |||
1540 | ContainsUnexpandedParameterPack); | |||
1541 | ||||
1542 | SmallVector<unsigned, 1> CompatIndices; | |||
1543 | unsigned DefaultIndex = -1U; | |||
1544 | for (unsigned i = 0; i < NumAssocs; ++i) { | |||
1545 | if (!Types[i]) | |||
1546 | DefaultIndex = i; | |||
1547 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | |||
1548 | Types[i]->getType())) | |||
1549 | CompatIndices.push_back(i); | |||
1550 | } | |||
1551 | ||||
1552 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | |||
1553 | // type compatible with at most one of the types named in its generic | |||
1554 | // association list." | |||
1555 | if (CompatIndices.size() > 1) { | |||
1556 | // We strip parens here because the controlling expression is typically | |||
1557 | // parenthesized in macro definitions. | |||
1558 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1559 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | |||
1560 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | |||
1561 | << (unsigned)CompatIndices.size(); | |||
1562 | for (unsigned I : CompatIndices) { | |||
1563 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | |||
1564 | diag::note_compat_assoc) | |||
1565 | << Types[I]->getTypeLoc().getSourceRange() | |||
1566 | << Types[I]->getType(); | |||
1567 | } | |||
1568 | return ExprError(); | |||
1569 | } | |||
1570 | ||||
1571 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | |||
1572 | // its controlling expression shall have type compatible with exactly one of | |||
1573 | // the types named in its generic association list." | |||
1574 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | |||
1575 | // We strip parens here because the controlling expression is typically | |||
1576 | // parenthesized in macro definitions. | |||
1577 | ControllingExpr = ControllingExpr->IgnoreParens(); | |||
1578 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | |||
1579 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | |||
1580 | return ExprError(); | |||
1581 | } | |||
1582 | ||||
1583 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | |||
1584 | // type name that is compatible with the type of the controlling expression, | |||
1585 | // then the result expression of the generic selection is the expression | |||
1586 | // in that generic association. Otherwise, the result expression of the | |||
1587 | // generic selection is the expression in the default generic association." | |||
1588 | unsigned ResultIndex = | |||
1589 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | |||
1590 | ||||
1591 | return GenericSelectionExpr::Create( | |||
1592 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | |||
1593 | ContainsUnexpandedParameterPack, ResultIndex); | |||
1594 | } | |||
1595 | ||||
1596 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | |||
1597 | /// location of the token and the offset of the ud-suffix within it. | |||
1598 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | |||
1599 | unsigned Offset) { | |||
1600 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | |||
1601 | S.getLangOpts()); | |||
1602 | } | |||
1603 | ||||
1604 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | |||
1605 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | |||
1606 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | |||
1607 | IdentifierInfo *UDSuffix, | |||
1608 | SourceLocation UDSuffixLoc, | |||
1609 | ArrayRef<Expr*> Args, | |||
1610 | SourceLocation LitEndLoc) { | |||
1611 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1611, __PRETTY_FUNCTION__)); | |||
1612 | ||||
1613 | QualType ArgTy[2]; | |||
1614 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | |||
1615 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | |||
1616 | if (ArgTy[ArgIdx]->isArrayType()) | |||
1617 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | |||
1618 | } | |||
1619 | ||||
1620 | DeclarationName OpName = | |||
1621 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1622 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1623 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1624 | ||||
1625 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | |||
1626 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | |||
1627 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | |||
1628 | /*AllowStringTemplate*/ false, | |||
1629 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | |||
1630 | return ExprError(); | |||
1631 | ||||
1632 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | |||
1633 | } | |||
1634 | ||||
1635 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | |||
1636 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | |||
1637 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | |||
1638 | /// multiple tokens. However, the common case is that StringToks points to one | |||
1639 | /// string. | |||
1640 | /// | |||
1641 | ExprResult | |||
1642 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | |||
1643 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1643, __PRETTY_FUNCTION__)); | |||
1644 | ||||
1645 | StringLiteralParser Literal(StringToks, PP); | |||
1646 | if (Literal.hadError) | |||
1647 | return ExprError(); | |||
1648 | ||||
1649 | SmallVector<SourceLocation, 4> StringTokLocs; | |||
1650 | for (const Token &Tok : StringToks) | |||
1651 | StringTokLocs.push_back(Tok.getLocation()); | |||
1652 | ||||
1653 | QualType CharTy = Context.CharTy; | |||
1654 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | |||
1655 | if (Literal.isWide()) { | |||
1656 | CharTy = Context.getWideCharType(); | |||
1657 | Kind = StringLiteral::Wide; | |||
1658 | } else if (Literal.isUTF8()) { | |||
1659 | if (getLangOpts().Char8) | |||
1660 | CharTy = Context.Char8Ty; | |||
1661 | Kind = StringLiteral::UTF8; | |||
1662 | } else if (Literal.isUTF16()) { | |||
1663 | CharTy = Context.Char16Ty; | |||
1664 | Kind = StringLiteral::UTF16; | |||
1665 | } else if (Literal.isUTF32()) { | |||
1666 | CharTy = Context.Char32Ty; | |||
1667 | Kind = StringLiteral::UTF32; | |||
1668 | } else if (Literal.isPascal()) { | |||
1669 | CharTy = Context.UnsignedCharTy; | |||
1670 | } | |||
1671 | ||||
1672 | // Warn on initializing an array of char from a u8 string literal; this | |||
1673 | // becomes ill-formed in C++2a. | |||
1674 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && | |||
1675 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | |||
1676 | Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); | |||
1677 | ||||
1678 | // Create removals for all 'u8' prefixes in the string literal(s). This | |||
1679 | // ensures C++2a compatibility (but may change the program behavior when | |||
1680 | // built by non-Clang compilers for which the execution character set is | |||
1681 | // not always UTF-8). | |||
1682 | auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); | |||
1683 | SourceLocation RemovalDiagLoc; | |||
1684 | for (const Token &Tok : StringToks) { | |||
1685 | if (Tok.getKind() == tok::utf8_string_literal) { | |||
1686 | if (RemovalDiagLoc.isInvalid()) | |||
1687 | RemovalDiagLoc = Tok.getLocation(); | |||
1688 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | |||
1689 | Tok.getLocation(), | |||
1690 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | |||
1691 | getSourceManager(), getLangOpts()))); | |||
1692 | } | |||
1693 | } | |||
1694 | Diag(RemovalDiagLoc, RemovalDiag); | |||
1695 | } | |||
1696 | ||||
1697 | QualType StrTy = | |||
1698 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | |||
1699 | ||||
1700 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | |||
1701 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | |||
1702 | Kind, Literal.Pascal, StrTy, | |||
1703 | &StringTokLocs[0], | |||
1704 | StringTokLocs.size()); | |||
1705 | if (Literal.getUDSuffix().empty()) | |||
1706 | return Lit; | |||
1707 | ||||
1708 | // We're building a user-defined literal. | |||
1709 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
1710 | SourceLocation UDSuffixLoc = | |||
1711 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | |||
1712 | Literal.getUDSuffixOffset()); | |||
1713 | ||||
1714 | // Make sure we're allowed user-defined literals here. | |||
1715 | if (!UDLScope) | |||
1716 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | |||
1717 | ||||
1718 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | |||
1719 | // operator "" X (str, len) | |||
1720 | QualType SizeType = Context.getSizeType(); | |||
1721 | ||||
1722 | DeclarationName OpName = | |||
1723 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
1724 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
1725 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
1726 | ||||
1727 | QualType ArgTy[] = { | |||
1728 | Context.getArrayDecayedType(StrTy), SizeType | |||
1729 | }; | |||
1730 | ||||
1731 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
1732 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | |||
1733 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | |||
1734 | /*AllowStringTemplate*/ true, | |||
1735 | /*DiagnoseMissing*/ true)) { | |||
1736 | ||||
1737 | case LOLR_Cooked: { | |||
1738 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | |||
1739 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | |||
1740 | StringTokLocs[0]); | |||
1741 | Expr *Args[] = { Lit, LenArg }; | |||
1742 | ||||
1743 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | |||
1744 | } | |||
1745 | ||||
1746 | case LOLR_StringTemplate: { | |||
1747 | TemplateArgumentListInfo ExplicitArgs; | |||
1748 | ||||
1749 | unsigned CharBits = Context.getIntWidth(CharTy); | |||
1750 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | |||
1751 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
1752 | ||||
1753 | TemplateArgument TypeArg(CharTy); | |||
1754 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | |||
1755 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | |||
1756 | ||||
1757 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | |||
1758 | Value = Lit->getCodeUnit(I); | |||
1759 | TemplateArgument Arg(Context, Value, CharTy); | |||
1760 | TemplateArgumentLocInfo ArgInfo; | |||
1761 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
1762 | } | |||
1763 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | |||
1764 | &ExplicitArgs); | |||
1765 | } | |||
1766 | case LOLR_Raw: | |||
1767 | case LOLR_Template: | |||
1768 | case LOLR_ErrorNoDiagnostic: | |||
1769 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1769); | |||
1770 | case LOLR_Error: | |||
1771 | return ExprError(); | |||
1772 | } | |||
1773 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 1773); | |||
1774 | } | |||
1775 | ||||
1776 | DeclRefExpr * | |||
1777 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1778 | SourceLocation Loc, | |||
1779 | const CXXScopeSpec *SS) { | |||
1780 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | |||
1781 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | |||
1782 | } | |||
1783 | ||||
1784 | DeclRefExpr * | |||
1785 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1786 | const DeclarationNameInfo &NameInfo, | |||
1787 | const CXXScopeSpec *SS, NamedDecl *FoundD, | |||
1788 | SourceLocation TemplateKWLoc, | |||
1789 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1790 | NestedNameSpecifierLoc NNS = | |||
1791 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | |||
1792 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | |||
1793 | TemplateArgs); | |||
1794 | } | |||
1795 | ||||
1796 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | |||
1797 | // A declaration named in an unevaluated operand never constitutes an odr-use. | |||
1798 | if (isUnevaluatedContext()) | |||
1799 | return NOUR_Unevaluated; | |||
1800 | ||||
1801 | // C++2a [basic.def.odr]p4: | |||
1802 | // A variable x whose name appears as a potentially-evaluated expression e | |||
1803 | // is odr-used by e unless [...] x is a reference that is usable in | |||
1804 | // constant expressions. | |||
1805 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1806 | if (VD->getType()->isReferenceType() && | |||
1807 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | |||
1808 | VD->isUsableInConstantExpressions(Context)) | |||
1809 | return NOUR_Constant; | |||
1810 | } | |||
1811 | ||||
1812 | // All remaining non-variable cases constitute an odr-use. For variables, we | |||
1813 | // need to wait and see how the expression is used. | |||
1814 | return NOUR_None; | |||
1815 | } | |||
1816 | ||||
1817 | /// BuildDeclRefExpr - Build an expression that references a | |||
1818 | /// declaration that does not require a closure capture. | |||
1819 | DeclRefExpr * | |||
1820 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
1821 | const DeclarationNameInfo &NameInfo, | |||
1822 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | |||
1823 | SourceLocation TemplateKWLoc, | |||
1824 | const TemplateArgumentListInfo *TemplateArgs) { | |||
1825 | bool RefersToCapturedVariable = | |||
1826 | isa<VarDecl>(D) && | |||
1827 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | |||
1828 | ||||
1829 | DeclRefExpr *E = DeclRefExpr::Create( | |||
1830 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | |||
1831 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | |||
1832 | MarkDeclRefReferenced(E); | |||
1833 | ||||
1834 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | |||
1835 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | |||
1836 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | |||
1837 | getCurFunction()->recordUseOfWeak(E); | |||
1838 | ||||
1839 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
1840 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | |||
1841 | FD = IFD->getAnonField(); | |||
1842 | if (FD) { | |||
1843 | UnusedPrivateFields.remove(FD); | |||
1844 | // Just in case we're building an illegal pointer-to-member. | |||
1845 | if (FD->isBitField()) | |||
1846 | E->setObjectKind(OK_BitField); | |||
1847 | } | |||
1848 | ||||
1849 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | |||
1850 | // designates a bit-field. | |||
1851 | if (auto *BD = dyn_cast<BindingDecl>(D)) | |||
1852 | if (auto *BE = BD->getBinding()) | |||
1853 | E->setObjectKind(BE->getObjectKind()); | |||
1854 | ||||
1855 | return E; | |||
1856 | } | |||
1857 | ||||
1858 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | |||
1859 | /// possibly a list of template arguments. | |||
1860 | /// | |||
1861 | /// If this produces template arguments, it is permitted to call | |||
1862 | /// DecomposeTemplateName. | |||
1863 | /// | |||
1864 | /// This actually loses a lot of source location information for | |||
1865 | /// non-standard name kinds; we should consider preserving that in | |||
1866 | /// some way. | |||
1867 | void | |||
1868 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | |||
1869 | TemplateArgumentListInfo &Buffer, | |||
1870 | DeclarationNameInfo &NameInfo, | |||
1871 | const TemplateArgumentListInfo *&TemplateArgs) { | |||
1872 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
1873 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | |||
1874 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | |||
1875 | ||||
1876 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | |||
1877 | Id.TemplateId->NumArgs); | |||
1878 | translateTemplateArguments(TemplateArgsPtr, Buffer); | |||
1879 | ||||
1880 | TemplateName TName = Id.TemplateId->Template.get(); | |||
1881 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | |||
1882 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | |||
1883 | TemplateArgs = &Buffer; | |||
1884 | } else { | |||
1885 | NameInfo = GetNameFromUnqualifiedId(Id); | |||
1886 | TemplateArgs = nullptr; | |||
1887 | } | |||
1888 | } | |||
1889 | ||||
1890 | static void emitEmptyLookupTypoDiagnostic( | |||
1891 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | |||
1892 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | |||
1893 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | |||
1894 | DeclContext *Ctx = | |||
1895 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | |||
1896 | if (!TC) { | |||
1897 | // Emit a special diagnostic for failed member lookups. | |||
1898 | // FIXME: computing the declaration context might fail here (?) | |||
1899 | if (Ctx) | |||
1900 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | |||
1901 | << SS.getRange(); | |||
1902 | else | |||
1903 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | |||
1904 | return; | |||
1905 | } | |||
1906 | ||||
1907 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | |||
1908 | bool DroppedSpecifier = | |||
1909 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | |||
1910 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | |||
1911 | ? diag::note_implicit_param_decl | |||
1912 | : diag::note_previous_decl; | |||
1913 | if (!Ctx) | |||
1914 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | |||
1915 | SemaRef.PDiag(NoteID)); | |||
1916 | else | |||
1917 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | |||
1918 | << Typo << Ctx << DroppedSpecifier | |||
1919 | << SS.getRange(), | |||
1920 | SemaRef.PDiag(NoteID)); | |||
1921 | } | |||
1922 | ||||
1923 | /// Diagnose an empty lookup. | |||
1924 | /// | |||
1925 | /// \return false if new lookup candidates were found | |||
1926 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | |||
1927 | CorrectionCandidateCallback &CCC, | |||
1928 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
1929 | ArrayRef<Expr *> Args, TypoExpr **Out) { | |||
1930 | DeclarationName Name = R.getLookupName(); | |||
1931 | ||||
1932 | unsigned diagnostic = diag::err_undeclared_var_use; | |||
1933 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | |||
1934 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | |||
1935 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | |||
1936 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
1937 | diagnostic = diag::err_undeclared_use; | |||
1938 | diagnostic_suggest = diag::err_undeclared_use_suggest; | |||
1939 | } | |||
1940 | ||||
1941 | // If the original lookup was an unqualified lookup, fake an | |||
1942 | // unqualified lookup. This is useful when (for example) the | |||
1943 | // original lookup would not have found something because it was a | |||
1944 | // dependent name. | |||
1945 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | |||
1946 | while (DC) { | |||
1947 | if (isa<CXXRecordDecl>(DC)) { | |||
1948 | LookupQualifiedName(R, DC); | |||
1949 | ||||
1950 | if (!R.empty()) { | |||
1951 | // Don't give errors about ambiguities in this lookup. | |||
1952 | R.suppressDiagnostics(); | |||
1953 | ||||
1954 | // During a default argument instantiation the CurContext points | |||
1955 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | |||
1956 | // function parameter list, hence add an explicit check. | |||
1957 | bool isDefaultArgument = | |||
1958 | !CodeSynthesisContexts.empty() && | |||
1959 | CodeSynthesisContexts.back().Kind == | |||
1960 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | |||
1961 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | |||
1962 | bool isInstance = CurMethod && | |||
1963 | CurMethod->isInstance() && | |||
1964 | DC == CurMethod->getParent() && !isDefaultArgument; | |||
1965 | ||||
1966 | // Give a code modification hint to insert 'this->'. | |||
1967 | // TODO: fixit for inserting 'Base<T>::' in the other cases. | |||
1968 | // Actually quite difficult! | |||
1969 | if (getLangOpts().MSVCCompat) | |||
1970 | diagnostic = diag::ext_found_via_dependent_bases_lookup; | |||
1971 | if (isInstance) { | |||
1972 | Diag(R.getNameLoc(), diagnostic) << Name | |||
1973 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | |||
1974 | CheckCXXThisCapture(R.getNameLoc()); | |||
1975 | } else { | |||
1976 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
1977 | } | |||
1978 | ||||
1979 | // Do we really want to note all of these? | |||
1980 | for (NamedDecl *D : R) | |||
1981 | Diag(D->getLocation(), diag::note_dependent_var_use); | |||
1982 | ||||
1983 | // Return true if we are inside a default argument instantiation | |||
1984 | // and the found name refers to an instance member function, otherwise | |||
1985 | // the function calling DiagnoseEmptyLookup will try to create an | |||
1986 | // implicit member call and this is wrong for default argument. | |||
1987 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | |||
1988 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | |||
1989 | return true; | |||
1990 | } | |||
1991 | ||||
1992 | // Tell the callee to try to recover. | |||
1993 | return false; | |||
1994 | } | |||
1995 | ||||
1996 | R.clear(); | |||
1997 | } | |||
1998 | ||||
1999 | DC = DC->getLookupParent(); | |||
2000 | } | |||
2001 | ||||
2002 | // We didn't find anything, so try to correct for a typo. | |||
2003 | TypoCorrection Corrected; | |||
2004 | if (S && Out) { | |||
2005 | SourceLocation TypoLoc = R.getNameLoc(); | |||
2006 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2007, __PRETTY_FUNCTION__)) | |||
2007 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2007, __PRETTY_FUNCTION__)); | |||
2008 | *Out = CorrectTypoDelayed( | |||
2009 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | |||
2010 | [=](const TypoCorrection &TC) { | |||
2011 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | |||
2012 | diagnostic, diagnostic_suggest); | |||
2013 | }, | |||
2014 | nullptr, CTK_ErrorRecovery); | |||
2015 | if (*Out) | |||
2016 | return true; | |||
2017 | } else if (S && | |||
2018 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | |||
2019 | S, &SS, CCC, CTK_ErrorRecovery))) { | |||
2020 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
2021 | bool DroppedSpecifier = | |||
2022 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | |||
2023 | R.setLookupName(Corrected.getCorrection()); | |||
2024 | ||||
2025 | bool AcceptableWithRecovery = false; | |||
2026 | bool AcceptableWithoutRecovery = false; | |||
2027 | NamedDecl *ND = Corrected.getFoundDecl(); | |||
2028 | if (ND) { | |||
2029 | if (Corrected.isOverloaded()) { | |||
2030 | OverloadCandidateSet OCS(R.getNameLoc(), | |||
2031 | OverloadCandidateSet::CSK_Normal); | |||
2032 | OverloadCandidateSet::iterator Best; | |||
2033 | for (NamedDecl *CD : Corrected) { | |||
2034 | if (FunctionTemplateDecl *FTD = | |||
2035 | dyn_cast<FunctionTemplateDecl>(CD)) | |||
2036 | AddTemplateOverloadCandidate( | |||
2037 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | |||
2038 | Args, OCS); | |||
2039 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
2040 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | |||
2041 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | |||
2042 | Args, OCS); | |||
2043 | } | |||
2044 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | |||
2045 | case OR_Success: | |||
2046 | ND = Best->FoundDecl; | |||
2047 | Corrected.setCorrectionDecl(ND); | |||
2048 | break; | |||
2049 | default: | |||
2050 | // FIXME: Arbitrarily pick the first declaration for the note. | |||
2051 | Corrected.setCorrectionDecl(ND); | |||
2052 | break; | |||
2053 | } | |||
2054 | } | |||
2055 | R.addDecl(ND); | |||
2056 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | |||
2057 | CXXRecordDecl *Record = nullptr; | |||
2058 | if (Corrected.getCorrectionSpecifier()) { | |||
2059 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | |||
2060 | Record = Ty->getAsCXXRecordDecl(); | |||
2061 | } | |||
2062 | if (!Record) | |||
2063 | Record = cast<CXXRecordDecl>( | |||
2064 | ND->getDeclContext()->getRedeclContext()); | |||
2065 | R.setNamingClass(Record); | |||
2066 | } | |||
2067 | ||||
2068 | auto *UnderlyingND = ND->getUnderlyingDecl(); | |||
2069 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | |||
2070 | isa<FunctionTemplateDecl>(UnderlyingND); | |||
2071 | // FIXME: If we ended up with a typo for a type name or | |||
2072 | // Objective-C class name, we're in trouble because the parser | |||
2073 | // is in the wrong place to recover. Suggest the typo | |||
2074 | // correction, but don't make it a fix-it since we're not going | |||
2075 | // to recover well anyway. | |||
2076 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | |||
2077 | getAsTypeTemplateDecl(UnderlyingND) || | |||
2078 | isa<ObjCInterfaceDecl>(UnderlyingND); | |||
2079 | } else { | |||
2080 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | |||
2081 | // because we aren't able to recover. | |||
2082 | AcceptableWithoutRecovery = true; | |||
2083 | } | |||
2084 | ||||
2085 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | |||
2086 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | |||
2087 | ? diag::note_implicit_param_decl | |||
2088 | : diag::note_previous_decl; | |||
2089 | if (SS.isEmpty()) | |||
2090 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | |||
2091 | PDiag(NoteID), AcceptableWithRecovery); | |||
2092 | else | |||
2093 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
2094 | << Name << computeDeclContext(SS, false) | |||
2095 | << DroppedSpecifier << SS.getRange(), | |||
2096 | PDiag(NoteID), AcceptableWithRecovery); | |||
2097 | ||||
2098 | // Tell the callee whether to try to recover. | |||
2099 | return !AcceptableWithRecovery; | |||
2100 | } | |||
2101 | } | |||
2102 | R.clear(); | |||
2103 | ||||
2104 | // Emit a special diagnostic for failed member lookups. | |||
2105 | // FIXME: computing the declaration context might fail here (?) | |||
2106 | if (!SS.isEmpty()) { | |||
2107 | Diag(R.getNameLoc(), diag::err_no_member) | |||
2108 | << Name << computeDeclContext(SS, false) | |||
2109 | << SS.getRange(); | |||
2110 | return true; | |||
2111 | } | |||
2112 | ||||
2113 | // Give up, we can't recover. | |||
2114 | Diag(R.getNameLoc(), diagnostic) << Name; | |||
2115 | return true; | |||
2116 | } | |||
2117 | ||||
2118 | /// In Microsoft mode, if we are inside a template class whose parent class has | |||
2119 | /// dependent base classes, and we can't resolve an unqualified identifier, then | |||
2120 | /// assume the identifier is a member of a dependent base class. We can only | |||
2121 | /// recover successfully in static methods, instance methods, and other contexts | |||
2122 | /// where 'this' is available. This doesn't precisely match MSVC's | |||
2123 | /// instantiation model, but it's close enough. | |||
2124 | static Expr * | |||
2125 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | |||
2126 | DeclarationNameInfo &NameInfo, | |||
2127 | SourceLocation TemplateKWLoc, | |||
2128 | const TemplateArgumentListInfo *TemplateArgs) { | |||
2129 | // Only try to recover from lookup into dependent bases in static methods or | |||
2130 | // contexts where 'this' is available. | |||
2131 | QualType ThisType = S.getCurrentThisType(); | |||
2132 | const CXXRecordDecl *RD = nullptr; | |||
2133 | if (!ThisType.isNull()) | |||
2134 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | |||
2135 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | |||
2136 | RD = MD->getParent(); | |||
2137 | if (!RD || !RD->hasAnyDependentBases()) | |||
2138 | return nullptr; | |||
2139 | ||||
2140 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | |||
2141 | // is available, suggest inserting 'this->' as a fixit. | |||
2142 | SourceLocation Loc = NameInfo.getLoc(); | |||
2143 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | |||
2144 | DB << NameInfo.getName() << RD; | |||
2145 | ||||
2146 | if (!ThisType.isNull()) { | |||
2147 | DB << FixItHint::CreateInsertion(Loc, "this->"); | |||
2148 | return CXXDependentScopeMemberExpr::Create( | |||
2149 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | |||
2150 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | |||
2151 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | |||
2152 | } | |||
2153 | ||||
2154 | // Synthesize a fake NNS that points to the derived class. This will | |||
2155 | // perform name lookup during template instantiation. | |||
2156 | CXXScopeSpec SS; | |||
2157 | auto *NNS = | |||
2158 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | |||
2159 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | |||
2160 | return DependentScopeDeclRefExpr::Create( | |||
2161 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | |||
2162 | TemplateArgs); | |||
2163 | } | |||
2164 | ||||
2165 | ExprResult | |||
2166 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | |||
2167 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | |||
2168 | bool HasTrailingLParen, bool IsAddressOfOperand, | |||
2169 | CorrectionCandidateCallback *CCC, | |||
2170 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | |||
2171 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2172, __PRETTY_FUNCTION__)) | |||
2172 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2172, __PRETTY_FUNCTION__)); | |||
2173 | if (SS.isInvalid()) | |||
2174 | return ExprError(); | |||
2175 | ||||
2176 | TemplateArgumentListInfo TemplateArgsBuffer; | |||
2177 | ||||
2178 | // Decompose the UnqualifiedId into the following data. | |||
2179 | DeclarationNameInfo NameInfo; | |||
2180 | const TemplateArgumentListInfo *TemplateArgs; | |||
2181 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | |||
2182 | ||||
2183 | DeclarationName Name = NameInfo.getName(); | |||
2184 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
2185 | SourceLocation NameLoc = NameInfo.getLoc(); | |||
2186 | ||||
2187 | if (II && II->isEditorPlaceholder()) { | |||
2188 | // FIXME: When typed placeholders are supported we can create a typed | |||
2189 | // placeholder expression node. | |||
2190 | return ExprError(); | |||
2191 | } | |||
2192 | ||||
2193 | // C++ [temp.dep.expr]p3: | |||
2194 | // An id-expression is type-dependent if it contains: | |||
2195 | // -- an identifier that was declared with a dependent type, | |||
2196 | // (note: handled after lookup) | |||
2197 | // -- a template-id that is dependent, | |||
2198 | // (note: handled in BuildTemplateIdExpr) | |||
2199 | // -- a conversion-function-id that specifies a dependent type, | |||
2200 | // -- a nested-name-specifier that contains a class-name that | |||
2201 | // names a dependent type. | |||
2202 | // Determine whether this is a member of an unknown specialization; | |||
2203 | // we need to handle these differently. | |||
2204 | bool DependentID = false; | |||
2205 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | |||
2206 | Name.getCXXNameType()->isDependentType()) { | |||
2207 | DependentID = true; | |||
2208 | } else if (SS.isSet()) { | |||
2209 | if (DeclContext *DC = computeDeclContext(SS, false)) { | |||
2210 | if (RequireCompleteDeclContext(SS, DC)) | |||
2211 | return ExprError(); | |||
2212 | } else { | |||
2213 | DependentID = true; | |||
2214 | } | |||
2215 | } | |||
2216 | ||||
2217 | if (DependentID) | |||
2218 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2219 | IsAddressOfOperand, TemplateArgs); | |||
2220 | ||||
2221 | // Perform the required lookup. | |||
2222 | LookupResult R(*this, NameInfo, | |||
2223 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | |||
2224 | ? LookupObjCImplicitSelfParam | |||
2225 | : LookupOrdinaryName); | |||
2226 | if (TemplateKWLoc.isValid() || TemplateArgs) { | |||
2227 | // Lookup the template name again to correctly establish the context in | |||
2228 | // which it was found. This is really unfortunate as we already did the | |||
2229 | // lookup to determine that it was a template name in the first place. If | |||
2230 | // this becomes a performance hit, we can work harder to preserve those | |||
2231 | // results until we get here but it's likely not worth it. | |||
2232 | bool MemberOfUnknownSpecialization; | |||
2233 | AssumedTemplateKind AssumedTemplate; | |||
2234 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | |||
2235 | MemberOfUnknownSpecialization, TemplateKWLoc, | |||
2236 | &AssumedTemplate)) | |||
2237 | return ExprError(); | |||
2238 | ||||
2239 | if (MemberOfUnknownSpecialization || | |||
2240 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | |||
2241 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2242 | IsAddressOfOperand, TemplateArgs); | |||
2243 | } else { | |||
2244 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | |||
2245 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | |||
2246 | ||||
2247 | // If the result might be in a dependent base class, this is a dependent | |||
2248 | // id-expression. | |||
2249 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2250 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | |||
2251 | IsAddressOfOperand, TemplateArgs); | |||
2252 | ||||
2253 | // If this reference is in an Objective-C method, then we need to do | |||
2254 | // some special Objective-C lookup, too. | |||
2255 | if (IvarLookupFollowUp) { | |||
2256 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | |||
2257 | if (E.isInvalid()) | |||
2258 | return ExprError(); | |||
2259 | ||||
2260 | if (Expr *Ex = E.getAs<Expr>()) | |||
2261 | return Ex; | |||
2262 | } | |||
2263 | } | |||
2264 | ||||
2265 | if (R.isAmbiguous()) | |||
2266 | return ExprError(); | |||
2267 | ||||
2268 | // This could be an implicitly declared function reference (legal in C90, | |||
2269 | // extension in C99, forbidden in C++). | |||
2270 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | |||
2271 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | |||
2272 | if (D) R.addDecl(D); | |||
2273 | } | |||
2274 | ||||
2275 | // Determine whether this name might be a candidate for | |||
2276 | // argument-dependent lookup. | |||
2277 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | |||
2278 | ||||
2279 | if (R.empty() && !ADL) { | |||
2280 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
2281 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | |||
2282 | TemplateKWLoc, TemplateArgs)) | |||
2283 | return E; | |||
2284 | } | |||
2285 | ||||
2286 | // Don't diagnose an empty lookup for inline assembly. | |||
2287 | if (IsInlineAsmIdentifier) | |||
2288 | return ExprError(); | |||
2289 | ||||
2290 | // If this name wasn't predeclared and if this is not a function | |||
2291 | // call, diagnose the problem. | |||
2292 | TypoExpr *TE = nullptr; | |||
2293 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | |||
2294 | : nullptr); | |||
2295 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | |||
2296 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2297, __PRETTY_FUNCTION__)) | |||
2297 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2297, __PRETTY_FUNCTION__)); | |||
2298 | if (CCC) { | |||
2299 | // Make sure the callback knows what the typo being diagnosed is. | |||
2300 | CCC->setTypoName(II); | |||
2301 | if (SS.isValid()) | |||
2302 | CCC->setTypoNNS(SS.getScopeRep()); | |||
2303 | } | |||
2304 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | |||
2305 | // a template name, but we happen to have always already looked up the name | |||
2306 | // before we get here if it must be a template name. | |||
2307 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | |||
2308 | None, &TE)) { | |||
2309 | if (TE && KeywordReplacement) { | |||
2310 | auto &State = getTypoExprState(TE); | |||
2311 | auto BestTC = State.Consumer->getNextCorrection(); | |||
2312 | if (BestTC.isKeyword()) { | |||
2313 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | |||
2314 | if (State.DiagHandler) | |||
2315 | State.DiagHandler(BestTC); | |||
2316 | KeywordReplacement->startToken(); | |||
2317 | KeywordReplacement->setKind(II->getTokenID()); | |||
2318 | KeywordReplacement->setIdentifierInfo(II); | |||
2319 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | |||
2320 | // Clean up the state associated with the TypoExpr, since it has | |||
2321 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | |||
2322 | clearDelayedTypo(TE); | |||
2323 | // Signal that a correction to a keyword was performed by returning a | |||
2324 | // valid-but-null ExprResult. | |||
2325 | return (Expr*)nullptr; | |||
2326 | } | |||
2327 | State.Consumer->resetCorrectionStream(); | |||
2328 | } | |||
2329 | return TE ? TE : ExprError(); | |||
2330 | } | |||
2331 | ||||
2332 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2333, __PRETTY_FUNCTION__)) | |||
2333 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2333, __PRETTY_FUNCTION__)); | |||
2334 | ||||
2335 | // If we found an Objective-C instance variable, let | |||
2336 | // LookupInObjCMethod build the appropriate expression to | |||
2337 | // reference the ivar. | |||
2338 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | |||
2339 | R.clear(); | |||
2340 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | |||
2341 | // In a hopelessly buggy code, Objective-C instance variable | |||
2342 | // lookup fails and no expression will be built to reference it. | |||
2343 | if (!E.isInvalid() && !E.get()) | |||
2344 | return ExprError(); | |||
2345 | return E; | |||
2346 | } | |||
2347 | } | |||
2348 | ||||
2349 | // This is guaranteed from this point on. | |||
2350 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2350, __PRETTY_FUNCTION__)); | |||
2351 | ||||
2352 | // Check whether this might be a C++ implicit instance member access. | |||
2353 | // C++ [class.mfct.non-static]p3: | |||
2354 | // When an id-expression that is not part of a class member access | |||
2355 | // syntax and not used to form a pointer to member is used in the | |||
2356 | // body of a non-static member function of class X, if name lookup | |||
2357 | // resolves the name in the id-expression to a non-static non-type | |||
2358 | // member of some class C, the id-expression is transformed into a | |||
2359 | // class member access expression using (*this) as the | |||
2360 | // postfix-expression to the left of the . operator. | |||
2361 | // | |||
2362 | // But we don't actually need to do this for '&' operands if R | |||
2363 | // resolved to a function or overloaded function set, because the | |||
2364 | // expression is ill-formed if it actually works out to be a | |||
2365 | // non-static member function: | |||
2366 | // | |||
2367 | // C++ [expr.ref]p4: | |||
2368 | // Otherwise, if E1.E2 refers to a non-static member function. . . | |||
2369 | // [t]he expression can be used only as the left-hand operand of a | |||
2370 | // member function call. | |||
2371 | // | |||
2372 | // There are other safeguards against such uses, but it's important | |||
2373 | // to get this right here so that we don't end up making a | |||
2374 | // spuriously dependent expression if we're inside a dependent | |||
2375 | // instance method. | |||
2376 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | |||
2377 | bool MightBeImplicitMember; | |||
2378 | if (!IsAddressOfOperand) | |||
2379 | MightBeImplicitMember = true; | |||
2380 | else if (!SS.isEmpty()) | |||
2381 | MightBeImplicitMember = false; | |||
2382 | else if (R.isOverloadedResult()) | |||
2383 | MightBeImplicitMember = false; | |||
2384 | else if (R.isUnresolvableResult()) | |||
2385 | MightBeImplicitMember = true; | |||
2386 | else | |||
2387 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | |||
2388 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | |||
2389 | isa<MSPropertyDecl>(R.getFoundDecl()); | |||
2390 | ||||
2391 | if (MightBeImplicitMember) | |||
2392 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | |||
2393 | R, TemplateArgs, S); | |||
2394 | } | |||
2395 | ||||
2396 | if (TemplateArgs || TemplateKWLoc.isValid()) { | |||
2397 | ||||
2398 | // In C++1y, if this is a variable template id, then check it | |||
2399 | // in BuildTemplateIdExpr(). | |||
2400 | // The single lookup result must be a variable template declaration. | |||
2401 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | |||
2402 | Id.TemplateId->Kind == TNK_Var_template) { | |||
2403 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2404, __PRETTY_FUNCTION__)) | |||
2404 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2404, __PRETTY_FUNCTION__)); | |||
2405 | } | |||
2406 | ||||
2407 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | |||
2408 | } | |||
2409 | ||||
2410 | return BuildDeclarationNameExpr(SS, R, ADL); | |||
2411 | } | |||
2412 | ||||
2413 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | |||
2414 | /// declaration name, generally during template instantiation. | |||
2415 | /// There's a large number of things which don't need to be done along | |||
2416 | /// this path. | |||
2417 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | |||
2418 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | |||
2419 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | |||
2420 | DeclContext *DC = computeDeclContext(SS, false); | |||
2421 | if (!DC) | |||
2422 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2423 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2424 | ||||
2425 | if (RequireCompleteDeclContext(SS, DC)) | |||
2426 | return ExprError(); | |||
2427 | ||||
2428 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
2429 | LookupQualifiedName(R, DC); | |||
2430 | ||||
2431 | if (R.isAmbiguous()) | |||
2432 | return ExprError(); | |||
2433 | ||||
2434 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | |||
2435 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
2436 | NameInfo, /*TemplateArgs=*/nullptr); | |||
2437 | ||||
2438 | if (R.empty()) { | |||
2439 | Diag(NameInfo.getLoc(), diag::err_no_member) | |||
2440 | << NameInfo.getName() << DC << SS.getRange(); | |||
2441 | return ExprError(); | |||
2442 | } | |||
2443 | ||||
2444 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | |||
2445 | // Diagnose a missing typename if this resolved unambiguously to a type in | |||
2446 | // a dependent context. If we can recover with a type, downgrade this to | |||
2447 | // a warning in Microsoft compatibility mode. | |||
2448 | unsigned DiagID = diag::err_typename_missing; | |||
2449 | if (RecoveryTSI && getLangOpts().MSVCCompat) | |||
2450 | DiagID = diag::ext_typename_missing; | |||
2451 | SourceLocation Loc = SS.getBeginLoc(); | |||
2452 | auto D = Diag(Loc, DiagID); | |||
2453 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | |||
2454 | << SourceRange(Loc, NameInfo.getEndLoc()); | |||
2455 | ||||
2456 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | |||
2457 | // context. | |||
2458 | if (!RecoveryTSI) | |||
2459 | return ExprError(); | |||
2460 | ||||
2461 | // Only issue the fixit if we're prepared to recover. | |||
2462 | D << FixItHint::CreateInsertion(Loc, "typename "); | |||
2463 | ||||
2464 | // Recover by pretending this was an elaborated type. | |||
2465 | QualType Ty = Context.getTypeDeclType(TD); | |||
2466 | TypeLocBuilder TLB; | |||
2467 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | |||
2468 | ||||
2469 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | |||
2470 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | |||
2471 | QTL.setElaboratedKeywordLoc(SourceLocation()); | |||
2472 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
2473 | ||||
2474 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | |||
2475 | ||||
2476 | return ExprEmpty(); | |||
2477 | } | |||
2478 | ||||
2479 | // Defend against this resolving to an implicit member access. We usually | |||
2480 | // won't get here if this might be a legitimate a class member (we end up in | |||
2481 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | |||
2482 | // a pointer-to-member or in an unevaluated context in C++11. | |||
2483 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | |||
2484 | return BuildPossibleImplicitMemberExpr(SS, | |||
2485 | /*TemplateKWLoc=*/SourceLocation(), | |||
2486 | R, /*TemplateArgs=*/nullptr, S); | |||
2487 | ||||
2488 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | |||
2489 | } | |||
2490 | ||||
2491 | /// The parser has read a name in, and Sema has detected that we're currently | |||
2492 | /// inside an ObjC method. Perform some additional checks and determine if we | |||
2493 | /// should form a reference to an ivar. | |||
2494 | /// | |||
2495 | /// Ideally, most of this would be done by lookup, but there's | |||
2496 | /// actually quite a lot of extra work involved. | |||
2497 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2498 | IdentifierInfo *II) { | |||
2499 | SourceLocation Loc = Lookup.getNameLoc(); | |||
2500 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2501 | ||||
2502 | // Check for error condition which is already reported. | |||
2503 | if (!CurMethod) | |||
2504 | return DeclResult(true); | |||
2505 | ||||
2506 | // There are two cases to handle here. 1) scoped lookup could have failed, | |||
2507 | // in which case we should look for an ivar. 2) scoped lookup could have | |||
2508 | // found a decl, but that decl is outside the current instance method (i.e. | |||
2509 | // a global variable). In these two cases, we do a lookup for an ivar with | |||
2510 | // this name, if the lookup sucedes, we replace it our current decl. | |||
2511 | ||||
2512 | // If we're in a class method, we don't normally want to look for | |||
2513 | // ivars. But if we don't find anything else, and there's an | |||
2514 | // ivar, that's an error. | |||
2515 | bool IsClassMethod = CurMethod->isClassMethod(); | |||
2516 | ||||
2517 | bool LookForIvars; | |||
2518 | if (Lookup.empty()) | |||
2519 | LookForIvars = true; | |||
2520 | else if (IsClassMethod) | |||
2521 | LookForIvars = false; | |||
2522 | else | |||
2523 | LookForIvars = (Lookup.isSingleResult() && | |||
2524 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | |||
2525 | ObjCInterfaceDecl *IFace = nullptr; | |||
2526 | if (LookForIvars) { | |||
2527 | IFace = CurMethod->getClassInterface(); | |||
2528 | ObjCInterfaceDecl *ClassDeclared; | |||
2529 | ObjCIvarDecl *IV = nullptr; | |||
2530 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | |||
2531 | // Diagnose using an ivar in a class method. | |||
2532 | if (IsClassMethod) { | |||
2533 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | |||
2534 | return DeclResult(true); | |||
2535 | } | |||
2536 | ||||
2537 | // Diagnose the use of an ivar outside of the declaring class. | |||
2538 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | |||
2539 | !declaresSameEntity(ClassDeclared, IFace) && | |||
2540 | !getLangOpts().DebuggerSupport) | |||
2541 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | |||
2542 | ||||
2543 | // Success. | |||
2544 | return IV; | |||
2545 | } | |||
2546 | } else if (CurMethod->isInstanceMethod()) { | |||
2547 | // We should warn if a local variable hides an ivar. | |||
2548 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | |||
2549 | ObjCInterfaceDecl *ClassDeclared; | |||
2550 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | |||
2551 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | |||
2552 | declaresSameEntity(IFace, ClassDeclared)) | |||
2553 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | |||
2554 | } | |||
2555 | } | |||
2556 | } else if (Lookup.isSingleResult() && | |||
2557 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | |||
2558 | // If accessing a stand-alone ivar in a class method, this is an error. | |||
2559 | if (const ObjCIvarDecl *IV = | |||
2560 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | |||
2561 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | |||
2562 | return DeclResult(true); | |||
2563 | } | |||
2564 | } | |||
2565 | ||||
2566 | // Didn't encounter an error, didn't find an ivar. | |||
2567 | return DeclResult(false); | |||
2568 | } | |||
2569 | ||||
2570 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | |||
2571 | ObjCIvarDecl *IV) { | |||
2572 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
2573 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2574, __PRETTY_FUNCTION__)) | |||
2574 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2574, __PRETTY_FUNCTION__)); | |||
2575 | ||||
2576 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | |||
2577 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2577, __PRETTY_FUNCTION__)); | |||
2578 | ||||
2579 | // If we're referencing an invalid decl, just return this as a silent | |||
2580 | // error node. The error diagnostic was already emitted on the decl. | |||
2581 | if (IV->isInvalidDecl()) | |||
2582 | return ExprError(); | |||
2583 | ||||
2584 | // Check if referencing a field with __attribute__((deprecated)). | |||
2585 | if (DiagnoseUseOfDecl(IV, Loc)) | |||
2586 | return ExprError(); | |||
2587 | ||||
2588 | // FIXME: This should use a new expr for a direct reference, don't | |||
2589 | // turn this into Self->ivar, just return a BareIVarExpr or something. | |||
2590 | IdentifierInfo &II = Context.Idents.get("self"); | |||
2591 | UnqualifiedId SelfName; | |||
2592 | SelfName.setIdentifier(&II, SourceLocation()); | |||
2593 | SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); | |||
2594 | CXXScopeSpec SelfScopeSpec; | |||
2595 | SourceLocation TemplateKWLoc; | |||
2596 | ExprResult SelfExpr = | |||
2597 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | |||
2598 | /*HasTrailingLParen=*/false, | |||
2599 | /*IsAddressOfOperand=*/false); | |||
2600 | if (SelfExpr.isInvalid()) | |||
2601 | return ExprError(); | |||
2602 | ||||
2603 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | |||
2604 | if (SelfExpr.isInvalid()) | |||
2605 | return ExprError(); | |||
2606 | ||||
2607 | MarkAnyDeclReferenced(Loc, IV, true); | |||
2608 | ||||
2609 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | |||
2610 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | |||
2611 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | |||
2612 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | |||
2613 | ||||
2614 | ObjCIvarRefExpr *Result = new (Context) | |||
2615 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | |||
2616 | IV->getLocation(), SelfExpr.get(), true, true); | |||
2617 | ||||
2618 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
2619 | if (!isUnevaluatedContext() && | |||
2620 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | |||
2621 | getCurFunction()->recordUseOfWeak(Result); | |||
2622 | } | |||
2623 | if (getLangOpts().ObjCAutoRefCount) | |||
2624 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | |||
2625 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | |||
2626 | ||||
2627 | return Result; | |||
2628 | } | |||
2629 | ||||
2630 | /// The parser has read a name in, and Sema has detected that we're currently | |||
2631 | /// inside an ObjC method. Perform some additional checks and determine if we | |||
2632 | /// should form a reference to an ivar. If so, build an expression referencing | |||
2633 | /// that ivar. | |||
2634 | ExprResult | |||
2635 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | |||
2636 | IdentifierInfo *II, bool AllowBuiltinCreation) { | |||
2637 | // FIXME: Integrate this lookup step into LookupParsedName. | |||
2638 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | |||
2639 | if (Ivar.isInvalid()) | |||
2640 | return ExprError(); | |||
2641 | if (Ivar.isUsable()) | |||
2642 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | |||
2643 | cast<ObjCIvarDecl>(Ivar.get())); | |||
2644 | ||||
2645 | if (Lookup.empty() && II && AllowBuiltinCreation) | |||
2646 | LookupBuiltin(Lookup); | |||
2647 | ||||
2648 | // Sentinel value saying that we didn't do anything special. | |||
2649 | return ExprResult(false); | |||
2650 | } | |||
2651 | ||||
2652 | /// Cast a base object to a member's actual type. | |||
2653 | /// | |||
2654 | /// Logically this happens in three phases: | |||
2655 | /// | |||
2656 | /// * First we cast from the base type to the naming class. | |||
2657 | /// The naming class is the class into which we were looking | |||
2658 | /// when we found the member; it's the qualifier type if a | |||
2659 | /// qualifier was provided, and otherwise it's the base type. | |||
2660 | /// | |||
2661 | /// * Next we cast from the naming class to the declaring class. | |||
2662 | /// If the member we found was brought into a class's scope by | |||
2663 | /// a using declaration, this is that class; otherwise it's | |||
2664 | /// the class declaring the member. | |||
2665 | /// | |||
2666 | /// * Finally we cast from the declaring class to the "true" | |||
2667 | /// declaring class of the member. This conversion does not | |||
2668 | /// obey access control. | |||
2669 | ExprResult | |||
2670 | Sema::PerformObjectMemberConversion(Expr *From, | |||
2671 | NestedNameSpecifier *Qualifier, | |||
2672 | NamedDecl *FoundDecl, | |||
2673 | NamedDecl *Member) { | |||
2674 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | |||
2675 | if (!RD) | |||
2676 | return From; | |||
2677 | ||||
2678 | QualType DestRecordType; | |||
2679 | QualType DestType; | |||
2680 | QualType FromRecordType; | |||
2681 | QualType FromType = From->getType(); | |||
2682 | bool PointerConversions = false; | |||
2683 | if (isa<FieldDecl>(Member)) { | |||
2684 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | |||
2685 | auto FromPtrType = FromType->getAs<PointerType>(); | |||
2686 | DestRecordType = Context.getAddrSpaceQualType( | |||
2687 | DestRecordType, FromPtrType | |||
2688 | ? FromType->getPointeeType().getAddressSpace() | |||
2689 | : FromType.getAddressSpace()); | |||
2690 | ||||
2691 | if (FromPtrType) { | |||
2692 | DestType = Context.getPointerType(DestRecordType); | |||
2693 | FromRecordType = FromPtrType->getPointeeType(); | |||
2694 | PointerConversions = true; | |||
2695 | } else { | |||
2696 | DestType = DestRecordType; | |||
2697 | FromRecordType = FromType; | |||
2698 | } | |||
2699 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | |||
2700 | if (Method->isStatic()) | |||
2701 | return From; | |||
2702 | ||||
2703 | DestType = Method->getThisType(); | |||
2704 | DestRecordType = DestType->getPointeeType(); | |||
2705 | ||||
2706 | if (FromType->getAs<PointerType>()) { | |||
2707 | FromRecordType = FromType->getPointeeType(); | |||
2708 | PointerConversions = true; | |||
2709 | } else { | |||
2710 | FromRecordType = FromType; | |||
2711 | DestType = DestRecordType; | |||
2712 | } | |||
2713 | } else { | |||
2714 | // No conversion necessary. | |||
2715 | return From; | |||
2716 | } | |||
2717 | ||||
2718 | if (DestType->isDependentType() || FromType->isDependentType()) | |||
2719 | return From; | |||
2720 | ||||
2721 | // If the unqualified types are the same, no conversion is necessary. | |||
2722 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2723 | return From; | |||
2724 | ||||
2725 | SourceRange FromRange = From->getSourceRange(); | |||
2726 | SourceLocation FromLoc = FromRange.getBegin(); | |||
2727 | ||||
2728 | ExprValueKind VK = From->getValueKind(); | |||
2729 | ||||
2730 | // C++ [class.member.lookup]p8: | |||
2731 | // [...] Ambiguities can often be resolved by qualifying a name with its | |||
2732 | // class name. | |||
2733 | // | |||
2734 | // If the member was a qualified name and the qualified referred to a | |||
2735 | // specific base subobject type, we'll cast to that intermediate type | |||
2736 | // first and then to the object in which the member is declared. That allows | |||
2737 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | |||
2738 | // | |||
2739 | // class Base { public: int x; }; | |||
2740 | // class Derived1 : public Base { }; | |||
2741 | // class Derived2 : public Base { }; | |||
2742 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | |||
2743 | // | |||
2744 | // void VeryDerived::f() { | |||
2745 | // x = 17; // error: ambiguous base subobjects | |||
2746 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | |||
2747 | // } | |||
2748 | if (Qualifier && Qualifier->getAsType()) { | |||
2749 | QualType QType = QualType(Qualifier->getAsType(), 0); | |||
2750 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2750, __PRETTY_FUNCTION__)); | |||
2751 | ||||
2752 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | |||
2753 | ||||
2754 | // In C++98, the qualifier type doesn't actually have to be a base | |||
2755 | // type of the object type, in which case we just ignore it. | |||
2756 | // Otherwise build the appropriate casts. | |||
2757 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | |||
2758 | CXXCastPath BasePath; | |||
2759 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | |||
2760 | FromLoc, FromRange, &BasePath)) | |||
2761 | return ExprError(); | |||
2762 | ||||
2763 | if (PointerConversions) | |||
2764 | QType = Context.getPointerType(QType); | |||
2765 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | |||
2766 | VK, &BasePath).get(); | |||
2767 | ||||
2768 | FromType = QType; | |||
2769 | FromRecordType = QRecordType; | |||
2770 | ||||
2771 | // If the qualifier type was the same as the destination type, | |||
2772 | // we're done. | |||
2773 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | |||
2774 | return From; | |||
2775 | } | |||
2776 | } | |||
2777 | ||||
2778 | bool IgnoreAccess = false; | |||
2779 | ||||
2780 | // If we actually found the member through a using declaration, cast | |||
2781 | // down to the using declaration's type. | |||
2782 | // | |||
2783 | // Pointer equality is fine here because only one declaration of a | |||
2784 | // class ever has member declarations. | |||
2785 | if (FoundDecl->getDeclContext() != Member->getDeclContext()) { | |||
2786 | assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void > (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2786, __PRETTY_FUNCTION__)); | |||
2787 | QualType URecordType = Context.getTypeDeclType( | |||
2788 | cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | |||
2789 | ||||
2790 | // We only need to do this if the naming-class to declaring-class | |||
2791 | // conversion is non-trivial. | |||
2792 | if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { | |||
2793 | assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast <void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2793, __PRETTY_FUNCTION__)); | |||
2794 | CXXCastPath BasePath; | |||
2795 | if (CheckDerivedToBaseConversion(FromRecordType, URecordType, | |||
2796 | FromLoc, FromRange, &BasePath)) | |||
2797 | return ExprError(); | |||
2798 | ||||
2799 | QualType UType = URecordType; | |||
2800 | if (PointerConversions) | |||
2801 | UType = Context.getPointerType(UType); | |||
2802 | From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, | |||
2803 | VK, &BasePath).get(); | |||
2804 | FromType = UType; | |||
2805 | FromRecordType = URecordType; | |||
2806 | } | |||
2807 | ||||
2808 | // We don't do access control for the conversion from the | |||
2809 | // declaring class to the true declaring class. | |||
2810 | IgnoreAccess = true; | |||
2811 | } | |||
2812 | ||||
2813 | CXXCastPath BasePath; | |||
2814 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | |||
2815 | FromLoc, FromRange, &BasePath, | |||
2816 | IgnoreAccess)) | |||
2817 | return ExprError(); | |||
2818 | ||||
2819 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | |||
2820 | VK, &BasePath); | |||
2821 | } | |||
2822 | ||||
2823 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | |||
2824 | const LookupResult &R, | |||
2825 | bool HasTrailingLParen) { | |||
2826 | // Only when used directly as the postfix-expression of a call. | |||
2827 | if (!HasTrailingLParen) | |||
2828 | return false; | |||
2829 | ||||
2830 | // Never if a scope specifier was provided. | |||
2831 | if (SS.isSet()) | |||
2832 | return false; | |||
2833 | ||||
2834 | // Only in C++ or ObjC++. | |||
2835 | if (!getLangOpts().CPlusPlus) | |||
2836 | return false; | |||
2837 | ||||
2838 | // Turn off ADL when we find certain kinds of declarations during | |||
2839 | // normal lookup: | |||
2840 | for (NamedDecl *D : R) { | |||
2841 | // C++0x [basic.lookup.argdep]p3: | |||
2842 | // -- a declaration of a class member | |||
2843 | // Since using decls preserve this property, we check this on the | |||
2844 | // original decl. | |||
2845 | if (D->isCXXClassMember()) | |||
2846 | return false; | |||
2847 | ||||
2848 | // C++0x [basic.lookup.argdep]p3: | |||
2849 | // -- a block-scope function declaration that is not a | |||
2850 | // using-declaration | |||
2851 | // NOTE: we also trigger this for function templates (in fact, we | |||
2852 | // don't check the decl type at all, since all other decl types | |||
2853 | // turn off ADL anyway). | |||
2854 | if (isa<UsingShadowDecl>(D)) | |||
2855 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
2856 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | |||
2857 | return false; | |||
2858 | ||||
2859 | // C++0x [basic.lookup.argdep]p3: | |||
2860 | // -- a declaration that is neither a function or a function | |||
2861 | // template | |||
2862 | // And also for builtin functions. | |||
2863 | if (isa<FunctionDecl>(D)) { | |||
2864 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | |||
2865 | ||||
2866 | // But also builtin functions. | |||
2867 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | |||
2868 | return false; | |||
2869 | } else if (!isa<FunctionTemplateDecl>(D)) | |||
2870 | return false; | |||
2871 | } | |||
2872 | ||||
2873 | return true; | |||
2874 | } | |||
2875 | ||||
2876 | ||||
2877 | /// Diagnoses obvious problems with the use of the given declaration | |||
2878 | /// as an expression. This is only actually called for lookups that | |||
2879 | /// were not overloaded, and it doesn't promise that the declaration | |||
2880 | /// will in fact be used. | |||
2881 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | |||
2882 | if (D->isInvalidDecl()) | |||
2883 | return true; | |||
2884 | ||||
2885 | if (isa<TypedefNameDecl>(D)) { | |||
2886 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | |||
2887 | return true; | |||
2888 | } | |||
2889 | ||||
2890 | if (isa<ObjCInterfaceDecl>(D)) { | |||
2891 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | |||
2892 | return true; | |||
2893 | } | |||
2894 | ||||
2895 | if (isa<NamespaceDecl>(D)) { | |||
2896 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | |||
2897 | return true; | |||
2898 | } | |||
2899 | ||||
2900 | return false; | |||
2901 | } | |||
2902 | ||||
2903 | // Certain multiversion types should be treated as overloaded even when there is | |||
2904 | // only one result. | |||
2905 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | |||
2906 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2906, __PRETTY_FUNCTION__)); | |||
2907 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | |||
2908 | return FD && | |||
2909 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | |||
2910 | } | |||
2911 | ||||
2912 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | |||
2913 | LookupResult &R, bool NeedsADL, | |||
2914 | bool AcceptInvalidDecl) { | |||
2915 | // If this is a single, fully-resolved result and we don't need ADL, | |||
2916 | // just build an ordinary singleton decl ref. | |||
2917 | if (!NeedsADL && R.isSingleResult() && | |||
2918 | !R.getAsSingle<FunctionTemplateDecl>() && | |||
2919 | !ShouldLookupResultBeMultiVersionOverload(R)) | |||
2920 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | |||
2921 | R.getRepresentativeDecl(), nullptr, | |||
2922 | AcceptInvalidDecl); | |||
2923 | ||||
2924 | // We only need to check the declaration if there's exactly one | |||
2925 | // result, because in the overloaded case the results can only be | |||
2926 | // functions and function templates. | |||
2927 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | |||
2928 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | |||
2929 | return ExprError(); | |||
2930 | ||||
2931 | // Otherwise, just build an unresolved lookup expression. Suppress | |||
2932 | // any lookup-related diagnostics; we'll hash these out later, when | |||
2933 | // we've picked a target. | |||
2934 | R.suppressDiagnostics(); | |||
2935 | ||||
2936 | UnresolvedLookupExpr *ULE | |||
2937 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | |||
2938 | SS.getWithLocInContext(Context), | |||
2939 | R.getLookupNameInfo(), | |||
2940 | NeedsADL, R.isOverloadedResult(), | |||
2941 | R.begin(), R.end()); | |||
2942 | ||||
2943 | return ULE; | |||
2944 | } | |||
2945 | ||||
2946 | static void | |||
2947 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | |||
2948 | ValueDecl *var, DeclContext *DC); | |||
2949 | ||||
2950 | /// Complete semantic analysis for a reference to the given declaration. | |||
2951 | ExprResult Sema::BuildDeclarationNameExpr( | |||
2952 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | |||
2953 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | |||
2954 | bool AcceptInvalidDecl) { | |||
2955 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2955, __PRETTY_FUNCTION__)); | |||
2956 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2957, __PRETTY_FUNCTION__)) | |||
2957 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 2957, __PRETTY_FUNCTION__)); | |||
2958 | ||||
2959 | SourceLocation Loc = NameInfo.getLoc(); | |||
2960 | if (CheckDeclInExpr(*this, Loc, D)) | |||
2961 | return ExprError(); | |||
2962 | ||||
2963 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | |||
2964 | // Specifically diagnose references to class templates that are missing | |||
2965 | // a template argument list. | |||
2966 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | |||
2967 | return ExprError(); | |||
2968 | } | |||
2969 | ||||
2970 | // Make sure that we're referring to a value. | |||
2971 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | |||
2972 | if (!VD) { | |||
2973 | Diag(Loc, diag::err_ref_non_value) | |||
2974 | << D << SS.getRange(); | |||
2975 | Diag(D->getLocation(), diag::note_declared_at); | |||
2976 | return ExprError(); | |||
2977 | } | |||
2978 | ||||
2979 | // Check whether this declaration can be used. Note that we suppress | |||
2980 | // this check when we're going to perform argument-dependent lookup | |||
2981 | // on this function name, because this might not be the function | |||
2982 | // that overload resolution actually selects. | |||
2983 | if (DiagnoseUseOfDecl(VD, Loc)) | |||
2984 | return ExprError(); | |||
2985 | ||||
2986 | // Only create DeclRefExpr's for valid Decl's. | |||
2987 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | |||
2988 | return ExprError(); | |||
2989 | ||||
2990 | // Handle members of anonymous structs and unions. If we got here, | |||
2991 | // and the reference is to a class member indirect field, then this | |||
2992 | // must be the subject of a pointer-to-member expression. | |||
2993 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | |||
2994 | if (!indirectField->isCXXClassMember()) | |||
2995 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | |||
2996 | indirectField); | |||
2997 | ||||
2998 | { | |||
2999 | QualType type = VD->getType(); | |||
3000 | if (type.isNull()) | |||
3001 | return ExprError(); | |||
3002 | if (auto *FPT = type->getAs<FunctionProtoType>()) { | |||
3003 | // C++ [except.spec]p17: | |||
3004 | // An exception-specification is considered to be needed when: | |||
3005 | // - in an expression, the function is the unique lookup result or | |||
3006 | // the selected member of a set of overloaded functions. | |||
3007 | ResolveExceptionSpec(Loc, FPT); | |||
3008 | type = VD->getType(); | |||
3009 | } | |||
3010 | ExprValueKind valueKind = VK_RValue; | |||
3011 | ||||
3012 | switch (D->getKind()) { | |||
3013 | // Ignore all the non-ValueDecl kinds. | |||
3014 | #define ABSTRACT_DECL(kind) | |||
3015 | #define VALUE(type, base) | |||
3016 | #define DECL(type, base) \ | |||
3017 | case Decl::type: | |||
3018 | #include "clang/AST/DeclNodes.inc" | |||
3019 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3019); | |||
3020 | ||||
3021 | // These shouldn't make it here. | |||
3022 | case Decl::ObjCAtDefsField: | |||
3023 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3023); | |||
3024 | ||||
3025 | // Enum constants are always r-values and never references. | |||
3026 | // Unresolved using declarations are dependent. | |||
3027 | case Decl::EnumConstant: | |||
3028 | case Decl::UnresolvedUsingValue: | |||
3029 | case Decl::OMPDeclareReduction: | |||
3030 | case Decl::OMPDeclareMapper: | |||
3031 | valueKind = VK_RValue; | |||
3032 | break; | |||
3033 | ||||
3034 | // Fields and indirect fields that got here must be for | |||
3035 | // pointer-to-member expressions; we just call them l-values for | |||
3036 | // internal consistency, because this subexpression doesn't really | |||
3037 | // exist in the high-level semantics. | |||
3038 | case Decl::Field: | |||
3039 | case Decl::IndirectField: | |||
3040 | case Decl::ObjCIvar: | |||
3041 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3042, __PRETTY_FUNCTION__)) | |||
3042 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3042, __PRETTY_FUNCTION__)); | |||
3043 | ||||
3044 | // These can't have reference type in well-formed programs, but | |||
3045 | // for internal consistency we do this anyway. | |||
3046 | type = type.getNonReferenceType(); | |||
3047 | valueKind = VK_LValue; | |||
3048 | break; | |||
3049 | ||||
3050 | // Non-type template parameters are either l-values or r-values | |||
3051 | // depending on the type. | |||
3052 | case Decl::NonTypeTemplateParm: { | |||
3053 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | |||
3054 | type = reftype->getPointeeType(); | |||
3055 | valueKind = VK_LValue; // even if the parameter is an r-value reference | |||
3056 | break; | |||
3057 | } | |||
3058 | ||||
3059 | // For non-references, we need to strip qualifiers just in case | |||
3060 | // the template parameter was declared as 'const int' or whatever. | |||
3061 | valueKind = VK_RValue; | |||
3062 | type = type.getUnqualifiedType(); | |||
3063 | break; | |||
3064 | } | |||
3065 | ||||
3066 | case Decl::Var: | |||
3067 | case Decl::VarTemplateSpecialization: | |||
3068 | case Decl::VarTemplatePartialSpecialization: | |||
3069 | case Decl::Decomposition: | |||
3070 | case Decl::OMPCapturedExpr: | |||
3071 | // In C, "extern void blah;" is valid and is an r-value. | |||
3072 | if (!getLangOpts().CPlusPlus && | |||
3073 | !type.hasQualifiers() && | |||
3074 | type->isVoidType()) { | |||
3075 | valueKind = VK_RValue; | |||
3076 | break; | |||
3077 | } | |||
3078 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3079 | ||||
3080 | case Decl::ImplicitParam: | |||
3081 | case Decl::ParmVar: { | |||
3082 | // These are always l-values. | |||
3083 | valueKind = VK_LValue; | |||
3084 | type = type.getNonReferenceType(); | |||
3085 | ||||
3086 | // FIXME: Does the addition of const really only apply in | |||
3087 | // potentially-evaluated contexts? Since the variable isn't actually | |||
3088 | // captured in an unevaluated context, it seems that the answer is no. | |||
3089 | if (!isUnevaluatedContext()) { | |||
3090 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | |||
3091 | if (!CapturedType.isNull()) | |||
3092 | type = CapturedType; | |||
3093 | } | |||
3094 | ||||
3095 | break; | |||
3096 | } | |||
3097 | ||||
3098 | case Decl::Binding: { | |||
3099 | // These are always lvalues. | |||
3100 | valueKind = VK_LValue; | |||
3101 | type = type.getNonReferenceType(); | |||
3102 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | |||
3103 | // decides how that's supposed to work. | |||
3104 | auto *BD = cast<BindingDecl>(VD); | |||
3105 | if (BD->getDeclContext() != CurContext) { | |||
3106 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | |||
3107 | if (DD && DD->hasLocalStorage()) | |||
3108 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | |||
3109 | } | |||
3110 | break; | |||
3111 | } | |||
3112 | ||||
3113 | case Decl::Function: { | |||
3114 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | |||
3115 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | |||
3116 | type = Context.BuiltinFnTy; | |||
3117 | valueKind = VK_RValue; | |||
3118 | break; | |||
3119 | } | |||
3120 | } | |||
3121 | ||||
3122 | const FunctionType *fty = type->castAs<FunctionType>(); | |||
3123 | ||||
3124 | // If we're referring to a function with an __unknown_anytype | |||
3125 | // result type, make the entire expression __unknown_anytype. | |||
3126 | if (fty->getReturnType() == Context.UnknownAnyTy) { | |||
3127 | type = Context.UnknownAnyTy; | |||
3128 | valueKind = VK_RValue; | |||
3129 | break; | |||
3130 | } | |||
3131 | ||||
3132 | // Functions are l-values in C++. | |||
3133 | if (getLangOpts().CPlusPlus) { | |||
3134 | valueKind = VK_LValue; | |||
3135 | break; | |||
3136 | } | |||
3137 | ||||
3138 | // C99 DR 316 says that, if a function type comes from a | |||
3139 | // function definition (without a prototype), that type is only | |||
3140 | // used for checking compatibility. Therefore, when referencing | |||
3141 | // the function, we pretend that we don't have the full function | |||
3142 | // type. | |||
3143 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | |||
3144 | isa<FunctionProtoType>(fty)) | |||
3145 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | |||
3146 | fty->getExtInfo()); | |||
3147 | ||||
3148 | // Functions are r-values in C. | |||
3149 | valueKind = VK_RValue; | |||
3150 | break; | |||
3151 | } | |||
3152 | ||||
3153 | case Decl::CXXDeductionGuide: | |||
3154 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3154); | |||
3155 | ||||
3156 | case Decl::MSProperty: | |||
3157 | valueKind = VK_LValue; | |||
3158 | break; | |||
3159 | ||||
3160 | case Decl::CXXMethod: | |||
3161 | // If we're referring to a method with an __unknown_anytype | |||
3162 | // result type, make the entire expression __unknown_anytype. | |||
3163 | // This should only be possible with a type written directly. | |||
3164 | if (const FunctionProtoType *proto | |||
3165 | = dyn_cast<FunctionProtoType>(VD->getType())) | |||
3166 | if (proto->getReturnType() == Context.UnknownAnyTy) { | |||
3167 | type = Context.UnknownAnyTy; | |||
3168 | valueKind = VK_RValue; | |||
3169 | break; | |||
3170 | } | |||
3171 | ||||
3172 | // C++ methods are l-values if static, r-values if non-static. | |||
3173 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | |||
3174 | valueKind = VK_LValue; | |||
3175 | break; | |||
3176 | } | |||
3177 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3178 | ||||
3179 | case Decl::CXXConversion: | |||
3180 | case Decl::CXXDestructor: | |||
3181 | case Decl::CXXConstructor: | |||
3182 | valueKind = VK_RValue; | |||
3183 | break; | |||
3184 | } | |||
3185 | ||||
3186 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | |||
3187 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | |||
3188 | TemplateArgs); | |||
3189 | } | |||
3190 | } | |||
3191 | ||||
3192 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | |||
3193 | SmallString<32> &Target) { | |||
3194 | Target.resize(CharByteWidth * (Source.size() + 1)); | |||
3195 | char *ResultPtr = &Target[0]; | |||
3196 | const llvm::UTF8 *ErrorPtr; | |||
3197 | bool success = | |||
3198 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | |||
3199 | (void)success; | |||
3200 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3200, __PRETTY_FUNCTION__)); | |||
3201 | Target.resize(ResultPtr - &Target[0]); | |||
3202 | } | |||
3203 | ||||
3204 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | |||
3205 | PredefinedExpr::IdentKind IK) { | |||
3206 | // Pick the current block, lambda, captured statement or function. | |||
3207 | Decl *currentDecl = nullptr; | |||
3208 | if (const BlockScopeInfo *BSI = getCurBlock()) | |||
3209 | currentDecl = BSI->TheDecl; | |||
3210 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | |||
3211 | currentDecl = LSI->CallOperator; | |||
3212 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | |||
3213 | currentDecl = CSI->TheCapturedDecl; | |||
3214 | else | |||
3215 | currentDecl = getCurFunctionOrMethodDecl(); | |||
3216 | ||||
3217 | if (!currentDecl) { | |||
3218 | Diag(Loc, diag::ext_predef_outside_function); | |||
3219 | currentDecl = Context.getTranslationUnitDecl(); | |||
3220 | } | |||
3221 | ||||
3222 | QualType ResTy; | |||
3223 | StringLiteral *SL = nullptr; | |||
3224 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | |||
3225 | ResTy = Context.DependentTy; | |||
3226 | else { | |||
3227 | // Pre-defined identifiers are of type char[x], where x is the length of | |||
3228 | // the string. | |||
3229 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | |||
3230 | unsigned Length = Str.length(); | |||
3231 | ||||
3232 | llvm::APInt LengthI(32, Length + 1); | |||
3233 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | |||
3234 | ResTy = | |||
3235 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | |||
3236 | SmallString<32> RawChars; | |||
3237 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | |||
3238 | Str, RawChars); | |||
3239 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | |||
3240 | ArrayType::Normal, | |||
3241 | /*IndexTypeQuals*/ 0); | |||
3242 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | |||
3243 | /*Pascal*/ false, ResTy, Loc); | |||
3244 | } else { | |||
3245 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | |||
3246 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | |||
3247 | ArrayType::Normal, | |||
3248 | /*IndexTypeQuals*/ 0); | |||
3249 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | |||
3250 | /*Pascal*/ false, ResTy, Loc); | |||
3251 | } | |||
3252 | } | |||
3253 | ||||
3254 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | |||
3255 | } | |||
3256 | ||||
3257 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | |||
3258 | PredefinedExpr::IdentKind IK; | |||
3259 | ||||
3260 | switch (Kind) { | |||
3261 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3261); | |||
3262 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | |||
3263 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | |||
3264 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | |||
3265 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | |||
3266 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | |||
3267 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | |||
3268 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | |||
3269 | } | |||
3270 | ||||
3271 | return BuildPredefinedExpr(Loc, IK); | |||
3272 | } | |||
3273 | ||||
3274 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | |||
3275 | SmallString<16> CharBuffer; | |||
3276 | bool Invalid = false; | |||
3277 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | |||
3278 | if (Invalid) | |||
3279 | return ExprError(); | |||
3280 | ||||
3281 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | |||
3282 | PP, Tok.getKind()); | |||
3283 | if (Literal.hadError()) | |||
3284 | return ExprError(); | |||
3285 | ||||
3286 | QualType Ty; | |||
3287 | if (Literal.isWide()) | |||
3288 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | |||
3289 | else if (Literal.isUTF8() && getLangOpts().Char8) | |||
3290 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | |||
3291 | else if (Literal.isUTF16()) | |||
3292 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | |||
3293 | else if (Literal.isUTF32()) | |||
3294 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | |||
3295 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | |||
3296 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | |||
3297 | else | |||
3298 | Ty = Context.CharTy; // 'x' -> char in C++ | |||
3299 | ||||
3300 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | |||
3301 | if (Literal.isWide()) | |||
3302 | Kind = CharacterLiteral::Wide; | |||
3303 | else if (Literal.isUTF16()) | |||
3304 | Kind = CharacterLiteral::UTF16; | |||
3305 | else if (Literal.isUTF32()) | |||
3306 | Kind = CharacterLiteral::UTF32; | |||
3307 | else if (Literal.isUTF8()) | |||
3308 | Kind = CharacterLiteral::UTF8; | |||
3309 | ||||
3310 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | |||
3311 | Tok.getLocation()); | |||
3312 | ||||
3313 | if (Literal.getUDSuffix().empty()) | |||
3314 | return Lit; | |||
3315 | ||||
3316 | // We're building a user-defined literal. | |||
3317 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3318 | SourceLocation UDSuffixLoc = | |||
3319 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3320 | ||||
3321 | // Make sure we're allowed user-defined literals here. | |||
3322 | if (!UDLScope) | |||
3323 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | |||
3324 | ||||
3325 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | |||
3326 | // operator "" X (ch) | |||
3327 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | |||
3328 | Lit, Tok.getLocation()); | |||
3329 | } | |||
3330 | ||||
3331 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | |||
3332 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3333 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | |||
3334 | Context.IntTy, Loc); | |||
3335 | } | |||
3336 | ||||
3337 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | |||
3338 | QualType Ty, SourceLocation Loc) { | |||
3339 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | |||
3340 | ||||
3341 | using llvm::APFloat; | |||
3342 | APFloat Val(Format); | |||
3343 | ||||
3344 | APFloat::opStatus result = Literal.GetFloatValue(Val); | |||
3345 | ||||
3346 | // Overflow is always an error, but underflow is only an error if | |||
3347 | // we underflowed to zero (APFloat reports denormals as underflow). | |||
3348 | if ((result & APFloat::opOverflow) || | |||
3349 | ((result & APFloat::opUnderflow) && Val.isZero())) { | |||
3350 | unsigned diagnostic; | |||
3351 | SmallString<20> buffer; | |||
3352 | if (result & APFloat::opOverflow) { | |||
3353 | diagnostic = diag::warn_float_overflow; | |||
3354 | APFloat::getLargest(Format).toString(buffer); | |||
3355 | } else { | |||
3356 | diagnostic = diag::warn_float_underflow; | |||
3357 | APFloat::getSmallest(Format).toString(buffer); | |||
3358 | } | |||
3359 | ||||
3360 | S.Diag(Loc, diagnostic) | |||
3361 | << Ty | |||
3362 | << StringRef(buffer.data(), buffer.size()); | |||
3363 | } | |||
3364 | ||||
3365 | bool isExact = (result == APFloat::opOK); | |||
3366 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | |||
3367 | } | |||
3368 | ||||
3369 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | |||
3370 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3370, __PRETTY_FUNCTION__)); | |||
3371 | ||||
3372 | if (E->isValueDependent()) | |||
3373 | return false; | |||
3374 | ||||
3375 | QualType QT = E->getType(); | |||
3376 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | |||
3377 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | |||
3378 | return true; | |||
3379 | } | |||
3380 | ||||
3381 | llvm::APSInt ValueAPS; | |||
3382 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | |||
3383 | ||||
3384 | if (R.isInvalid()) | |||
3385 | return true; | |||
3386 | ||||
3387 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | |||
3388 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | |||
3389 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | |||
3390 | << ValueAPS.toString(10) << ValueIsPositive; | |||
3391 | return true; | |||
3392 | } | |||
3393 | ||||
3394 | return false; | |||
3395 | } | |||
3396 | ||||
3397 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | |||
3398 | // Fast path for a single digit (which is quite common). A single digit | |||
3399 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | |||
3400 | if (Tok.getLength() == 1) { | |||
3401 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | |||
3402 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | |||
3403 | } | |||
3404 | ||||
3405 | SmallString<128> SpellingBuffer; | |||
3406 | // NumericLiteralParser wants to overread by one character. Add padding to | |||
3407 | // the buffer in case the token is copied to the buffer. If getSpelling() | |||
3408 | // returns a StringRef to the memory buffer, it should have a null char at | |||
3409 | // the EOF, so it is also safe. | |||
3410 | SpellingBuffer.resize(Tok.getLength() + 1); | |||
3411 | ||||
3412 | // Get the spelling of the token, which eliminates trigraphs, etc. | |||
3413 | bool Invalid = false; | |||
3414 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | |||
3415 | if (Invalid) | |||
3416 | return ExprError(); | |||
3417 | ||||
3418 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); | |||
3419 | if (Literal.hadError) | |||
3420 | return ExprError(); | |||
3421 | ||||
3422 | if (Literal.hasUDSuffix()) { | |||
3423 | // We're building a user-defined literal. | |||
3424 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | |||
3425 | SourceLocation UDSuffixLoc = | |||
3426 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | |||
3427 | ||||
3428 | // Make sure we're allowed user-defined literals here. | |||
3429 | if (!UDLScope) | |||
3430 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | |||
3431 | ||||
3432 | QualType CookedTy; | |||
3433 | if (Literal.isFloatingLiteral()) { | |||
3434 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | |||
3435 | // long double, the literal is treated as a call of the form | |||
3436 | // operator "" X (f L) | |||
3437 | CookedTy = Context.LongDoubleTy; | |||
3438 | } else { | |||
3439 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | |||
3440 | // unsigned long long, the literal is treated as a call of the form | |||
3441 | // operator "" X (n ULL) | |||
3442 | CookedTy = Context.UnsignedLongLongTy; | |||
3443 | } | |||
3444 | ||||
3445 | DeclarationName OpName = | |||
3446 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | |||
3447 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | |||
3448 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | |||
3449 | ||||
3450 | SourceLocation TokLoc = Tok.getLocation(); | |||
3451 | ||||
3452 | // Perform literal operator lookup to determine if we're building a raw | |||
3453 | // literal or a cooked one. | |||
3454 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | |||
3455 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | |||
3456 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | |||
3457 | /*AllowStringTemplate*/ false, | |||
3458 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | |||
3459 | case LOLR_ErrorNoDiagnostic: | |||
3460 | // Lookup failure for imaginary constants isn't fatal, there's still the | |||
3461 | // GNU extension producing _Complex types. | |||
3462 | break; | |||
3463 | case LOLR_Error: | |||
3464 | return ExprError(); | |||
3465 | case LOLR_Cooked: { | |||
3466 | Expr *Lit; | |||
3467 | if (Literal.isFloatingLiteral()) { | |||
3468 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | |||
3469 | } else { | |||
3470 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | |||
3471 | if (Literal.GetIntegerValue(ResultVal)) | |||
3472 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3473 | << /* Unsigned */ 1; | |||
3474 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | |||
3475 | Tok.getLocation()); | |||
3476 | } | |||
3477 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3478 | } | |||
3479 | ||||
3480 | case LOLR_Raw: { | |||
3481 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | |||
3482 | // literal is treated as a call of the form | |||
3483 | // operator "" X ("n") | |||
3484 | unsigned Length = Literal.getUDSuffixOffset(); | |||
3485 | QualType StrTy = Context.getConstantArrayType( | |||
3486 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | |||
3487 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | |||
3488 | Expr *Lit = StringLiteral::Create( | |||
3489 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | |||
3490 | /*Pascal*/false, StrTy, &TokLoc, 1); | |||
3491 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | |||
3492 | } | |||
3493 | ||||
3494 | case LOLR_Template: { | |||
3495 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | |||
3496 | // template), L is treated as a call fo the form | |||
3497 | // operator "" X <'c1', 'c2', ... 'ck'>() | |||
3498 | // where n is the source character sequence c1 c2 ... ck. | |||
3499 | TemplateArgumentListInfo ExplicitArgs; | |||
3500 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | |||
3501 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | |||
3502 | llvm::APSInt Value(CharBits, CharIsUnsigned); | |||
3503 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | |||
3504 | Value = TokSpelling[I]; | |||
3505 | TemplateArgument Arg(Context, Value, Context.CharTy); | |||
3506 | TemplateArgumentLocInfo ArgInfo; | |||
3507 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | |||
3508 | } | |||
3509 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | |||
3510 | &ExplicitArgs); | |||
3511 | } | |||
3512 | case LOLR_StringTemplate: | |||
3513 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3513); | |||
3514 | } | |||
3515 | } | |||
3516 | ||||
3517 | Expr *Res; | |||
3518 | ||||
3519 | if (Literal.isFixedPointLiteral()) { | |||
3520 | QualType Ty; | |||
3521 | ||||
3522 | if (Literal.isAccum) { | |||
3523 | if (Literal.isHalf) { | |||
3524 | Ty = Context.ShortAccumTy; | |||
3525 | } else if (Literal.isLong) { | |||
3526 | Ty = Context.LongAccumTy; | |||
3527 | } else { | |||
3528 | Ty = Context.AccumTy; | |||
3529 | } | |||
3530 | } else if (Literal.isFract) { | |||
3531 | if (Literal.isHalf) { | |||
3532 | Ty = Context.ShortFractTy; | |||
3533 | } else if (Literal.isLong) { | |||
3534 | Ty = Context.LongFractTy; | |||
3535 | } else { | |||
3536 | Ty = Context.FractTy; | |||
3537 | } | |||
3538 | } | |||
3539 | ||||
3540 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | |||
3541 | ||||
3542 | bool isSigned = !Literal.isUnsigned; | |||
3543 | unsigned scale = Context.getFixedPointScale(Ty); | |||
3544 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | |||
3545 | ||||
3546 | llvm::APInt Val(bit_width, 0, isSigned); | |||
3547 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | |||
3548 | bool ValIsZero = Val.isNullValue() && !Overflowed; | |||
3549 | ||||
3550 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | |||
3551 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | |||
3552 | // Clause 6.4.4 - The value of a constant shall be in the range of | |||
3553 | // representable values for its type, with exception for constants of a | |||
3554 | // fract type with a value of exactly 1; such a constant shall denote | |||
3555 | // the maximal value for the type. | |||
3556 | --Val; | |||
3557 | else if (Val.ugt(MaxVal) || Overflowed) | |||
3558 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | |||
3559 | ||||
3560 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | |||
3561 | Tok.getLocation(), scale); | |||
3562 | } else if (Literal.isFloatingLiteral()) { | |||
3563 | QualType Ty; | |||
3564 | if (Literal.isHalf){ | |||
3565 | if (getOpenCLOptions().isEnabled("cl_khr_fp16")) | |||
3566 | Ty = Context.HalfTy; | |||
3567 | else { | |||
3568 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | |||
3569 | return ExprError(); | |||
3570 | } | |||
3571 | } else if (Literal.isFloat) | |||
3572 | Ty = Context.FloatTy; | |||
3573 | else if (Literal.isLong) | |||
3574 | Ty = Context.LongDoubleTy; | |||
3575 | else if (Literal.isFloat16) | |||
3576 | Ty = Context.Float16Ty; | |||
3577 | else if (Literal.isFloat128) | |||
3578 | Ty = Context.Float128Ty; | |||
3579 | else | |||
3580 | Ty = Context.DoubleTy; | |||
3581 | ||||
3582 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | |||
3583 | ||||
3584 | if (Ty == Context.DoubleTy) { | |||
3585 | if (getLangOpts().SinglePrecisionConstants) { | |||
3586 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
3587 | if (BTy->getKind() != BuiltinType::Float) { | |||
3588 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3589 | } | |||
3590 | } else if (getLangOpts().OpenCL && | |||
3591 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | |||
3592 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | |||
3593 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | |||
3594 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | |||
3595 | } | |||
3596 | } | |||
3597 | } else if (!Literal.isIntegerLiteral()) { | |||
3598 | return ExprError(); | |||
3599 | } else { | |||
3600 | QualType Ty; | |||
3601 | ||||
3602 | // 'long long' is a C99 or C++11 feature. | |||
3603 | if (!getLangOpts().C99 && Literal.isLongLong) { | |||
3604 | if (getLangOpts().CPlusPlus) | |||
3605 | Diag(Tok.getLocation(), | |||
3606 | getLangOpts().CPlusPlus11 ? | |||
3607 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
3608 | else | |||
3609 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | |||
3610 | } | |||
3611 | ||||
3612 | // Get the value in the widest-possible width. | |||
3613 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | |||
3614 | llvm::APInt ResultVal(MaxWidth, 0); | |||
3615 | ||||
3616 | if (Literal.GetIntegerValue(ResultVal)) { | |||
3617 | // If this value didn't fit into uintmax_t, error and force to ull. | |||
3618 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | |||
3619 | << /* Unsigned */ 1; | |||
3620 | Ty = Context.UnsignedLongLongTy; | |||
3621 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3622, __PRETTY_FUNCTION__)) | |||
3622 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3622, __PRETTY_FUNCTION__)); | |||
3623 | } else { | |||
3624 | // If this value fits into a ULL, try to figure out what else it fits into | |||
3625 | // according to the rules of C99 6.4.4.1p5. | |||
3626 | ||||
3627 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | |||
3628 | // be an unsigned int. | |||
3629 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | |||
3630 | ||||
3631 | // Check from smallest to largest, picking the smallest type we can. | |||
3632 | unsigned Width = 0; | |||
3633 | ||||
3634 | // Microsoft specific integer suffixes are explicitly sized. | |||
3635 | if (Literal.MicrosoftInteger) { | |||
3636 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | |||
3637 | Width = 8; | |||
3638 | Ty = Context.CharTy; | |||
3639 | } else { | |||
3640 | Width = Literal.MicrosoftInteger; | |||
3641 | Ty = Context.getIntTypeForBitwidth(Width, | |||
3642 | /*Signed=*/!Literal.isUnsigned); | |||
3643 | } | |||
3644 | } | |||
3645 | ||||
3646 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { | |||
3647 | // Are int/unsigned possibilities? | |||
3648 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | |||
3649 | ||||
3650 | // Does it fit in a unsigned int? | |||
3651 | if (ResultVal.isIntN(IntSize)) { | |||
3652 | // Does it fit in a signed int? | |||
3653 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | |||
3654 | Ty = Context.IntTy; | |||
3655 | else if (AllowUnsigned) | |||
3656 | Ty = Context.UnsignedIntTy; | |||
3657 | Width = IntSize; | |||
3658 | } | |||
3659 | } | |||
3660 | ||||
3661 | // Are long/unsigned long possibilities? | |||
3662 | if (Ty.isNull() && !Literal.isLongLong) { | |||
3663 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | |||
3664 | ||||
3665 | // Does it fit in a unsigned long? | |||
3666 | if (ResultVal.isIntN(LongSize)) { | |||
3667 | // Does it fit in a signed long? | |||
3668 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | |||
3669 | Ty = Context.LongTy; | |||
3670 | else if (AllowUnsigned) | |||
3671 | Ty = Context.UnsignedLongTy; | |||
3672 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | |||
3673 | // is compatible. | |||
3674 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | |||
3675 | const unsigned LongLongSize = | |||
3676 | Context.getTargetInfo().getLongLongWidth(); | |||
3677 | Diag(Tok.getLocation(), | |||
3678 | getLangOpts().CPlusPlus | |||
3679 | ? Literal.isLong | |||
3680 | ? diag::warn_old_implicitly_unsigned_long_cxx | |||
3681 | : /*C++98 UB*/ diag:: | |||
3682 | ext_old_implicitly_unsigned_long_cxx | |||
3683 | : diag::warn_old_implicitly_unsigned_long) | |||
3684 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | |||
3685 | : /*will be ill-formed*/ 1); | |||
3686 | Ty = Context.UnsignedLongTy; | |||
3687 | } | |||
3688 | Width = LongSize; | |||
3689 | } | |||
3690 | } | |||
3691 | ||||
3692 | // Check long long if needed. | |||
3693 | if (Ty.isNull()) { | |||
3694 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | |||
3695 | ||||
3696 | // Does it fit in a unsigned long long? | |||
3697 | if (ResultVal.isIntN(LongLongSize)) { | |||
3698 | // Does it fit in a signed long long? | |||
3699 | // To be compatible with MSVC, hex integer literals ending with the | |||
3700 | // LL or i64 suffix are always signed in Microsoft mode. | |||
3701 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | |||
3702 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | |||
3703 | Ty = Context.LongLongTy; | |||
3704 | else if (AllowUnsigned) | |||
3705 | Ty = Context.UnsignedLongLongTy; | |||
3706 | Width = LongLongSize; | |||
3707 | } | |||
3708 | } | |||
3709 | ||||
3710 | // If we still couldn't decide a type, we probably have something that | |||
3711 | // does not fit in a signed long long, but has no U suffix. | |||
3712 | if (Ty.isNull()) { | |||
3713 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); | |||
3714 | Ty = Context.UnsignedLongLongTy; | |||
3715 | Width = Context.getTargetInfo().getLongLongWidth(); | |||
3716 | } | |||
3717 | ||||
3718 | if (ResultVal.getBitWidth() != Width) | |||
3719 | ResultVal = ResultVal.trunc(Width); | |||
3720 | } | |||
3721 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | |||
3722 | } | |||
3723 | ||||
3724 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | |||
3725 | if (Literal.isImaginary) { | |||
3726 | Res = new (Context) ImaginaryLiteral(Res, | |||
3727 | Context.getComplexType(Res->getType())); | |||
3728 | ||||
3729 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | |||
3730 | } | |||
3731 | return Res; | |||
3732 | } | |||
3733 | ||||
3734 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | |||
3735 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3735, __PRETTY_FUNCTION__)); | |||
3736 | return new (Context) ParenExpr(L, R, E); | |||
3737 | } | |||
3738 | ||||
3739 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | |||
3740 | SourceLocation Loc, | |||
3741 | SourceRange ArgRange) { | |||
3742 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | |||
3743 | // scalar or vector data type argument..." | |||
3744 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | |||
3745 | // type (C99 6.2.5p18) or void. | |||
3746 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | |||
3747 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | |||
3748 | << T << ArgRange; | |||
3749 | return true; | |||
3750 | } | |||
3751 | ||||
3752 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3753, __PRETTY_FUNCTION__)) | |||
3753 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3753, __PRETTY_FUNCTION__)); | |||
3754 | return false; | |||
3755 | } | |||
3756 | ||||
3757 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | |||
3758 | SourceLocation Loc, | |||
3759 | SourceRange ArgRange, | |||
3760 | UnaryExprOrTypeTrait TraitKind) { | |||
3761 | // Invalid types must be hard errors for SFINAE in C++. | |||
3762 | if (S.LangOpts.CPlusPlus) | |||
3763 | return true; | |||
3764 | ||||
3765 | // C99 6.5.3.4p1: | |||
3766 | if (T->isFunctionType() && | |||
3767 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | |||
3768 | TraitKind == UETT_PreferredAlignOf)) { | |||
3769 | // sizeof(function)/alignof(function) is allowed as an extension. | |||
3770 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | |||
3771 | << TraitKind << ArgRange; | |||
3772 | return false; | |||
3773 | } | |||
3774 | ||||
3775 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | |||
3776 | // this is an error (OpenCL v1.1 s6.3.k) | |||
3777 | if (T->isVoidType()) { | |||
3778 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | |||
3779 | : diag::ext_sizeof_alignof_void_type; | |||
3780 | S.Diag(Loc, DiagID) << TraitKind << ArgRange; | |||
3781 | return false; | |||
3782 | } | |||
3783 | ||||
3784 | return true; | |||
3785 | } | |||
3786 | ||||
3787 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | |||
3788 | SourceLocation Loc, | |||
3789 | SourceRange ArgRange, | |||
3790 | UnaryExprOrTypeTrait TraitKind) { | |||
3791 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | |||
3792 | // runtime doesn't allow it. | |||
3793 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | |||
3794 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | |||
3795 | << T << (TraitKind == UETT_SizeOf) | |||
3796 | << ArgRange; | |||
3797 | return true; | |||
3798 | } | |||
3799 | ||||
3800 | return false; | |||
3801 | } | |||
3802 | ||||
3803 | /// Check whether E is a pointer from a decayed array type (the decayed | |||
3804 | /// pointer type is equal to T) and emit a warning if it is. | |||
3805 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | |||
3806 | Expr *E) { | |||
3807 | // Don't warn if the operation changed the type. | |||
3808 | if (T != E->getType()) | |||
3809 | return; | |||
3810 | ||||
3811 | // Now look for array decays. | |||
3812 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | |||
3813 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | |||
3814 | return; | |||
3815 | ||||
3816 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | |||
3817 | << ICE->getType() | |||
3818 | << ICE->getSubExpr()->getType(); | |||
3819 | } | |||
3820 | ||||
3821 | /// Check the constraints on expression operands to unary type expression | |||
3822 | /// and type traits. | |||
3823 | /// | |||
3824 | /// Completes any types necessary and validates the constraints on the operand | |||
3825 | /// expression. The logic mostly mirrors the type-based overload, but may modify | |||
3826 | /// the expression as it completes the type for that expression through template | |||
3827 | /// instantiation, etc. | |||
3828 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | |||
3829 | UnaryExprOrTypeTrait ExprKind) { | |||
3830 | QualType ExprTy = E->getType(); | |||
3831 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3831, __PRETTY_FUNCTION__)); | |||
3832 | ||||
3833 | bool IsUnevaluatedOperand = | |||
3834 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | |||
3835 | ExprKind == UETT_PreferredAlignOf); | |||
3836 | if (IsUnevaluatedOperand) { | |||
3837 | ExprResult Result = CheckUnevaluatedOperand(E); | |||
3838 | if (Result.isInvalid()) | |||
3839 | return true; | |||
3840 | E = Result.get(); | |||
3841 | } | |||
3842 | ||||
3843 | if (ExprKind == UETT_VecStep) | |||
3844 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
3845 | E->getSourceRange()); | |||
3846 | ||||
3847 | // Whitelist some types as extensions | |||
3848 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | |||
3849 | E->getSourceRange(), ExprKind)) | |||
3850 | return false; | |||
3851 | ||||
3852 | // 'alignof' applied to an expression only requires the base element type of | |||
3853 | // the expression to be complete. 'sizeof' requires the expression's type to | |||
3854 | // be complete (and will attempt to complete it if it's an array of unknown | |||
3855 | // bound). | |||
3856 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | |||
3857 | if (RequireCompleteType(E->getExprLoc(), | |||
3858 | Context.getBaseElementType(E->getType()), | |||
3859 | diag::err_sizeof_alignof_incomplete_type, ExprKind, | |||
3860 | E->getSourceRange())) | |||
3861 | return true; | |||
3862 | } else { | |||
3863 | if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, | |||
3864 | ExprKind, E->getSourceRange())) | |||
3865 | return true; | |||
3866 | } | |||
3867 | ||||
3868 | // Completing the expression's type may have changed it. | |||
3869 | ExprTy = E->getType(); | |||
3870 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 3870, __PRETTY_FUNCTION__)); | |||
3871 | ||||
3872 | if (ExprTy->isFunctionType()) { | |||
3873 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | |||
3874 | << ExprKind << E->getSourceRange(); | |||
3875 | return true; | |||
3876 | } | |||
3877 | ||||
3878 | // The operand for sizeof and alignof is in an unevaluated expression context, | |||
3879 | // so side effects could result in unintended consequences. | |||
3880 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | |||
3881 | E->HasSideEffects(Context, false)) | |||
3882 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
3883 | ||||
3884 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | |||
3885 | E->getSourceRange(), ExprKind)) | |||
3886 | return true; | |||
3887 | ||||
3888 | if (ExprKind == UETT_SizeOf) { | |||
3889 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
3890 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | |||
3891 | QualType OType = PVD->getOriginalType(); | |||
3892 | QualType Type = PVD->getType(); | |||
3893 | if (Type->isPointerType() && OType->isArrayType()) { | |||
3894 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | |||
3895 | << Type << OType; | |||
3896 | Diag(PVD->getLocation(), diag::note_declared_at); | |||
3897 | } | |||
3898 | } | |||
3899 | } | |||
3900 | ||||
3901 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | |||
3902 | // decays into a pointer and returns an unintended result. This is most | |||
3903 | // likely a typo for "sizeof(array) op x". | |||
3904 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | |||
3905 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
3906 | BO->getLHS()); | |||
3907 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | |||
3908 | BO->getRHS()); | |||
3909 | } | |||
3910 | } | |||
3911 | ||||
3912 | return false; | |||
3913 | } | |||
3914 | ||||
3915 | /// Check the constraints on operands to unary expression and type | |||
3916 | /// traits. | |||
3917 | /// | |||
3918 | /// This will complete any types necessary, and validate the various constraints | |||
3919 | /// on those operands. | |||
3920 | /// | |||
3921 | /// The UsualUnaryConversions() function is *not* called by this routine. | |||
3922 | /// C99 6.3.2.1p[2-4] all state: | |||
3923 | /// Except when it is the operand of the sizeof operator ... | |||
3924 | /// | |||
3925 | /// C++ [expr.sizeof]p4 | |||
3926 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | |||
3927 | /// standard conversions are not applied to the operand of sizeof. | |||
3928 | /// | |||
3929 | /// This policy is followed for all of the unary trait expressions. | |||
3930 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | |||
3931 | SourceLocation OpLoc, | |||
3932 | SourceRange ExprRange, | |||
3933 | UnaryExprOrTypeTrait ExprKind) { | |||
3934 | if (ExprType->isDependentType()) | |||
3935 | return false; | |||
3936 | ||||
3937 | // C++ [expr.sizeof]p2: | |||
3938 | // When applied to a reference or a reference type, the result | |||
3939 | // is the size of the referenced type. | |||
3940 | // C++11 [expr.alignof]p3: | |||
3941 | // When alignof is applied to a reference type, the result | |||
3942 | // shall be the alignment of the referenced type. | |||
3943 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | |||
3944 | ExprType = Ref->getPointeeType(); | |||
3945 | ||||
3946 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | |||
3947 | // When alignof or _Alignof is applied to an array type, the result | |||
3948 | // is the alignment of the element type. | |||
3949 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | |||
3950 | ExprKind == UETT_OpenMPRequiredSimdAlign) | |||
3951 | ExprType = Context.getBaseElementType(ExprType); | |||
3952 | ||||
3953 | if (ExprKind == UETT_VecStep) | |||
3954 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | |||
3955 | ||||
3956 | // Whitelist some types as extensions | |||
3957 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | |||
3958 | ExprKind)) | |||
3959 | return false; | |||
3960 | ||||
3961 | if (RequireCompleteType(OpLoc, ExprType, | |||
3962 | diag::err_sizeof_alignof_incomplete_type, | |||
3963 | ExprKind, ExprRange)) | |||
3964 | return true; | |||
3965 | ||||
3966 | if (ExprType->isFunctionType()) { | |||
3967 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | |||
3968 | << ExprKind << ExprRange; | |||
3969 | return true; | |||
3970 | } | |||
3971 | ||||
3972 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | |||
3973 | ExprKind)) | |||
3974 | return true; | |||
3975 | ||||
3976 | return false; | |||
3977 | } | |||
3978 | ||||
3979 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | |||
3980 | // Cannot know anything else if the expression is dependent. | |||
3981 | if (E->isTypeDependent()) | |||
3982 | return false; | |||
3983 | ||||
3984 | if (E->getObjectKind() == OK_BitField) { | |||
3985 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | |||
3986 | << 1 << E->getSourceRange(); | |||
3987 | return true; | |||
3988 | } | |||
3989 | ||||
3990 | ValueDecl *D = nullptr; | |||
3991 | Expr *Inner = E->IgnoreParens(); | |||
3992 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | |||
3993 | D = DRE->getDecl(); | |||
3994 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | |||
3995 | D = ME->getMemberDecl(); | |||
3996 | } | |||
3997 | ||||
3998 | // If it's a field, require the containing struct to have a | |||
3999 | // complete definition so that we can compute the layout. | |||
4000 | // | |||
4001 | // This can happen in C++11 onwards, either by naming the member | |||
4002 | // in a way that is not transformed into a member access expression | |||
4003 | // (in an unevaluated operand, for instance), or by naming the member | |||
4004 | // in a trailing-return-type. | |||
4005 | // | |||
4006 | // For the record, since __alignof__ on expressions is a GCC | |||
4007 | // extension, GCC seems to permit this but always gives the | |||
4008 | // nonsensical answer 0. | |||
4009 | // | |||
4010 | // We don't really need the layout here --- we could instead just | |||
4011 | // directly check for all the appropriate alignment-lowing | |||
4012 | // attributes --- but that would require duplicating a lot of | |||
4013 | // logic that just isn't worth duplicating for such a marginal | |||
4014 | // use-case. | |||
4015 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | |||
4016 | // Fast path this check, since we at least know the record has a | |||
4017 | // definition if we can find a member of it. | |||
4018 | if (!FD->getParent()->isCompleteDefinition()) { | |||
4019 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | |||
4020 | << E->getSourceRange(); | |||
4021 | return true; | |||
4022 | } | |||
4023 | ||||
4024 | // Otherwise, if it's a field, and the field doesn't have | |||
4025 | // reference type, then it must have a complete type (or be a | |||
4026 | // flexible array member, which we explicitly want to | |||
4027 | // white-list anyway), which makes the following checks trivial. | |||
4028 | if (!FD->getType()->isReferenceType()) | |||
4029 | return false; | |||
4030 | } | |||
4031 | ||||
4032 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | |||
4033 | } | |||
4034 | ||||
4035 | bool Sema::CheckVecStepExpr(Expr *E) { | |||
4036 | E = E->IgnoreParens(); | |||
4037 | ||||
4038 | // Cannot know anything else if the expression is dependent. | |||
4039 | if (E->isTypeDependent()) | |||
4040 | return false; | |||
4041 | ||||
4042 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | |||
4043 | } | |||
4044 | ||||
4045 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | |||
4046 | CapturingScopeInfo *CSI) { | |||
4047 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4047, __PRETTY_FUNCTION__)); | |||
4048 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4048, __PRETTY_FUNCTION__)); | |||
4049 | ||||
4050 | // We're going to walk down into the type and look for VLA expressions. | |||
4051 | do { | |||
4052 | const Type *Ty = T.getTypePtr(); | |||
4053 | switch (Ty->getTypeClass()) { | |||
4054 | #define TYPE(Class, Base) | |||
4055 | #define ABSTRACT_TYPE(Class, Base) | |||
4056 | #define NON_CANONICAL_TYPE(Class, Base) | |||
4057 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | |||
4058 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | |||
4059 | #include "clang/AST/TypeNodes.inc" | |||
4060 | T = QualType(); | |||
4061 | break; | |||
4062 | // These types are never variably-modified. | |||
4063 | case Type::Builtin: | |||
4064 | case Type::Complex: | |||
4065 | case Type::Vector: | |||
4066 | case Type::ExtVector: | |||
4067 | case Type::Record: | |||
4068 | case Type::Enum: | |||
4069 | case Type::Elaborated: | |||
4070 | case Type::TemplateSpecialization: | |||
4071 | case Type::ObjCObject: | |||
4072 | case Type::ObjCInterface: | |||
4073 | case Type::ObjCObjectPointer: | |||
4074 | case Type::ObjCTypeParam: | |||
4075 | case Type::Pipe: | |||
4076 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4076); | |||
4077 | case Type::Adjusted: | |||
4078 | T = cast<AdjustedType>(Ty)->getOriginalType(); | |||
4079 | break; | |||
4080 | case Type::Decayed: | |||
4081 | T = cast<DecayedType>(Ty)->getPointeeType(); | |||
4082 | break; | |||
4083 | case Type::Pointer: | |||
4084 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
4085 | break; | |||
4086 | case Type::BlockPointer: | |||
4087 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
4088 | break; | |||
4089 | case Type::LValueReference: | |||
4090 | case Type::RValueReference: | |||
4091 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
4092 | break; | |||
4093 | case Type::MemberPointer: | |||
4094 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
4095 | break; | |||
4096 | case Type::ConstantArray: | |||
4097 | case Type::IncompleteArray: | |||
4098 | // Losing element qualification here is fine. | |||
4099 | T = cast<ArrayType>(Ty)->getElementType(); | |||
4100 | break; | |||
4101 | case Type::VariableArray: { | |||
4102 | // Losing element qualification here is fine. | |||
4103 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | |||
4104 | ||||
4105 | // Unknown size indication requires no size computation. | |||
4106 | // Otherwise, evaluate and record it. | |||
4107 | auto Size = VAT->getSizeExpr(); | |||
4108 | if (Size && !CSI->isVLATypeCaptured(VAT) && | |||
4109 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | |||
4110 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | |||
4111 | ||||
4112 | T = VAT->getElementType(); | |||
4113 | break; | |||
4114 | } | |||
4115 | case Type::FunctionProto: | |||
4116 | case Type::FunctionNoProto: | |||
4117 | T = cast<FunctionType>(Ty)->getReturnType(); | |||
4118 | break; | |||
4119 | case Type::Paren: | |||
4120 | case Type::TypeOf: | |||
4121 | case Type::UnaryTransform: | |||
4122 | case Type::Attributed: | |||
4123 | case Type::SubstTemplateTypeParm: | |||
4124 | case Type::PackExpansion: | |||
4125 | case Type::MacroQualified: | |||
4126 | // Keep walking after single level desugaring. | |||
4127 | T = T.getSingleStepDesugaredType(Context); | |||
4128 | break; | |||
4129 | case Type::Typedef: | |||
4130 | T = cast<TypedefType>(Ty)->desugar(); | |||
4131 | break; | |||
4132 | case Type::Decltype: | |||
4133 | T = cast<DecltypeType>(Ty)->desugar(); | |||
4134 | break; | |||
4135 | case Type::Auto: | |||
4136 | case Type::DeducedTemplateSpecialization: | |||
4137 | T = cast<DeducedType>(Ty)->getDeducedType(); | |||
4138 | break; | |||
4139 | case Type::TypeOfExpr: | |||
4140 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | |||
4141 | break; | |||
4142 | case Type::Atomic: | |||
4143 | T = cast<AtomicType>(Ty)->getValueType(); | |||
4144 | break; | |||
4145 | } | |||
4146 | } while (!T.isNull() && T->isVariablyModifiedType()); | |||
4147 | } | |||
4148 | ||||
4149 | /// Build a sizeof or alignof expression given a type operand. | |||
4150 | ExprResult | |||
4151 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | |||
4152 | SourceLocation OpLoc, | |||
4153 | UnaryExprOrTypeTrait ExprKind, | |||
4154 | SourceRange R) { | |||
4155 | if (!TInfo) | |||
4156 | return ExprError(); | |||
4157 | ||||
4158 | QualType T = TInfo->getType(); | |||
4159 | ||||
4160 | if (!T->isDependentType() && | |||
4161 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | |||
4162 | return ExprError(); | |||
4163 | ||||
4164 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | |||
4165 | if (auto *TT = T->getAs<TypedefType>()) { | |||
4166 | for (auto I = FunctionScopes.rbegin(), | |||
4167 | E = std::prev(FunctionScopes.rend()); | |||
4168 | I != E; ++I) { | |||
4169 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
4170 | if (CSI == nullptr) | |||
4171 | break; | |||
4172 | DeclContext *DC = nullptr; | |||
4173 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
4174 | DC = LSI->CallOperator; | |||
4175 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
4176 | DC = CRSI->TheCapturedDecl; | |||
4177 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
4178 | DC = BSI->TheDecl; | |||
4179 | if (DC) { | |||
4180 | if (DC->containsDecl(TT->getDecl())) | |||
4181 | break; | |||
4182 | captureVariablyModifiedType(Context, T, CSI); | |||
4183 | } | |||
4184 | } | |||
4185 | } | |||
4186 | } | |||
4187 | ||||
4188 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4189 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4190 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | |||
4191 | } | |||
4192 | ||||
4193 | /// Build a sizeof or alignof expression given an expression | |||
4194 | /// operand. | |||
4195 | ExprResult | |||
4196 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | |||
4197 | UnaryExprOrTypeTrait ExprKind) { | |||
4198 | ExprResult PE = CheckPlaceholderExpr(E); | |||
4199 | if (PE.isInvalid()) | |||
4200 | return ExprError(); | |||
4201 | ||||
4202 | E = PE.get(); | |||
4203 | ||||
4204 | // Verify that the operand is valid. | |||
4205 | bool isInvalid = false; | |||
4206 | if (E->isTypeDependent()) { | |||
4207 | // Delay type-checking for type-dependent expressions. | |||
4208 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | |||
4209 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | |||
4210 | } else if (ExprKind == UETT_VecStep) { | |||
4211 | isInvalid = CheckVecStepExpr(E); | |||
4212 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | |||
4213 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | |||
4214 | isInvalid = true; | |||
4215 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | |||
4216 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | |||
4217 | isInvalid = true; | |||
4218 | } else { | |||
4219 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | |||
4220 | } | |||
4221 | ||||
4222 | if (isInvalid) | |||
4223 | return ExprError(); | |||
4224 | ||||
4225 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | |||
4226 | PE = TransformToPotentiallyEvaluated(E); | |||
4227 | if (PE.isInvalid()) return ExprError(); | |||
4228 | E = PE.get(); | |||
4229 | } | |||
4230 | ||||
4231 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | |||
4232 | return new (Context) UnaryExprOrTypeTraitExpr( | |||
4233 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | |||
4234 | } | |||
4235 | ||||
4236 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | |||
4237 | /// expr and the same for @c alignof and @c __alignof | |||
4238 | /// Note that the ArgRange is invalid if isType is false. | |||
4239 | ExprResult | |||
4240 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | |||
4241 | UnaryExprOrTypeTrait ExprKind, bool IsType, | |||
4242 | void *TyOrEx, SourceRange ArgRange) { | |||
4243 | // If error parsing type, ignore. | |||
4244 | if (!TyOrEx) return ExprError(); | |||
4245 | ||||
4246 | if (IsType) { | |||
4247 | TypeSourceInfo *TInfo; | |||
4248 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | |||
4249 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | |||
4250 | } | |||
4251 | ||||
4252 | Expr *ArgEx = (Expr *)TyOrEx; | |||
4253 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | |||
4254 | return Result; | |||
4255 | } | |||
4256 | ||||
4257 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | |||
4258 | bool IsReal) { | |||
4259 | if (V.get()->isTypeDependent()) | |||
4260 | return S.Context.DependentTy; | |||
4261 | ||||
4262 | // _Real and _Imag are only l-values for normal l-values. | |||
4263 | if (V.get()->getObjectKind() != OK_Ordinary) { | |||
4264 | V = S.DefaultLvalueConversion(V.get()); | |||
4265 | if (V.isInvalid()) | |||
4266 | return QualType(); | |||
4267 | } | |||
4268 | ||||
4269 | // These operators return the element type of a complex type. | |||
4270 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | |||
4271 | return CT->getElementType(); | |||
4272 | ||||
4273 | // Otherwise they pass through real integer and floating point types here. | |||
4274 | if (V.get()->getType()->isArithmeticType()) | |||
4275 | return V.get()->getType(); | |||
4276 | ||||
4277 | // Test for placeholders. | |||
4278 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | |||
4279 | if (PR.isInvalid()) return QualType(); | |||
4280 | if (PR.get() != V.get()) { | |||
4281 | V = PR; | |||
4282 | return CheckRealImagOperand(S, V, Loc, IsReal); | |||
4283 | } | |||
4284 | ||||
4285 | // Reject anything else. | |||
4286 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | |||
4287 | << (IsReal ? "__real" : "__imag"); | |||
4288 | return QualType(); | |||
4289 | } | |||
4290 | ||||
4291 | ||||
4292 | ||||
4293 | ExprResult | |||
4294 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4295 | tok::TokenKind Kind, Expr *Input) { | |||
4296 | UnaryOperatorKind Opc; | |||
4297 | switch (Kind) { | |||
4298 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4298); | |||
4299 | case tok::plusplus: Opc = UO_PostInc; break; | |||
4300 | case tok::minusminus: Opc = UO_PostDec; break; | |||
4301 | } | |||
4302 | ||||
4303 | // Since this might is a postfix expression, get rid of ParenListExprs. | |||
4304 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | |||
4305 | if (Result.isInvalid()) return ExprError(); | |||
4306 | Input = Result.get(); | |||
4307 | ||||
4308 | return BuildUnaryOp(S, OpLoc, Opc, Input); | |||
4309 | } | |||
4310 | ||||
4311 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | |||
4312 | /// | |||
4313 | /// \return true on error | |||
4314 | static bool checkArithmeticOnObjCPointer(Sema &S, | |||
4315 | SourceLocation opLoc, | |||
4316 | Expr *op) { | |||
4317 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4317, __PRETTY_FUNCTION__)); | |||
4318 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | |||
4319 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | |||
4320 | return false; | |||
4321 | ||||
4322 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | |||
4323 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | |||
4324 | << op->getSourceRange(); | |||
4325 | return true; | |||
4326 | } | |||
4327 | ||||
4328 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | |||
4329 | auto *BaseNoParens = Base->IgnoreParens(); | |||
4330 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | |||
4331 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | |||
4332 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | |||
4333 | } | |||
4334 | ||||
4335 | ExprResult | |||
4336 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | |||
4337 | Expr *idx, SourceLocation rbLoc) { | |||
4338 | if (base && !base->getType().isNull() && | |||
4339 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | |||
4340 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | |||
4341 | /*Length=*/nullptr, rbLoc); | |||
4342 | ||||
4343 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
4344 | if (isa<ParenListExpr>(base)) { | |||
4345 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | |||
4346 | if (result.isInvalid()) return ExprError(); | |||
4347 | base = result.get(); | |||
4348 | } | |||
4349 | ||||
4350 | // A comma-expression as the index is deprecated in C++2a onwards. | |||
4351 | if (getLangOpts().CPlusPlus2a && | |||
4352 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | |||
4353 | (isa<CXXOperatorCallExpr>(idx) && | |||
4354 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | |||
4355 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | |||
4356 | << SourceRange(base->getBeginLoc(), rbLoc); | |||
4357 | } | |||
4358 | ||||
4359 | // Handle any non-overload placeholder types in the base and index | |||
4360 | // expressions. We can't handle overloads here because the other | |||
4361 | // operand might be an overloadable type, in which case the overload | |||
4362 | // resolution for the operator overload should get the first crack | |||
4363 | // at the overload. | |||
4364 | bool IsMSPropertySubscript = false; | |||
4365 | if (base->getType()->isNonOverloadPlaceholderType()) { | |||
4366 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | |||
4367 | if (!IsMSPropertySubscript) { | |||
4368 | ExprResult result = CheckPlaceholderExpr(base); | |||
4369 | if (result.isInvalid()) | |||
4370 | return ExprError(); | |||
4371 | base = result.get(); | |||
4372 | } | |||
4373 | } | |||
4374 | if (idx->getType()->isNonOverloadPlaceholderType()) { | |||
4375 | ExprResult result = CheckPlaceholderExpr(idx); | |||
4376 | if (result.isInvalid()) return ExprError(); | |||
4377 | idx = result.get(); | |||
4378 | } | |||
4379 | ||||
4380 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4381 | if (getLangOpts().CPlusPlus && | |||
4382 | (base->isTypeDependent() || idx->isTypeDependent())) { | |||
4383 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | |||
4384 | VK_LValue, OK_Ordinary, rbLoc); | |||
4385 | } | |||
4386 | ||||
4387 | // MSDN, property (C++) | |||
4388 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | |||
4389 | // This attribute can also be used in the declaration of an empty array in a | |||
4390 | // class or structure definition. For example: | |||
4391 | // __declspec(property(get=GetX, put=PutX)) int x[]; | |||
4392 | // The above statement indicates that x[] can be used with one or more array | |||
4393 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | |||
4394 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | |||
4395 | if (IsMSPropertySubscript) { | |||
4396 | // Build MS property subscript expression if base is MS property reference | |||
4397 | // or MS property subscript. | |||
4398 | return new (Context) MSPropertySubscriptExpr( | |||
4399 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | |||
4400 | } | |||
4401 | ||||
4402 | // Use C++ overloaded-operator rules if either operand has record | |||
4403 | // type. The spec says to do this if either type is *overloadable*, | |||
4404 | // but enum types can't declare subscript operators or conversion | |||
4405 | // operators, so there's nothing interesting for overload resolution | |||
4406 | // to do if there aren't any record types involved. | |||
4407 | // | |||
4408 | // ObjC pointers have their own subscripting logic that is not tied | |||
4409 | // to overload resolution and so should not take this path. | |||
4410 | if (getLangOpts().CPlusPlus && | |||
4411 | (base->getType()->isRecordType() || | |||
4412 | (!base->getType()->isObjCObjectPointerType() && | |||
4413 | idx->getType()->isRecordType()))) { | |||
4414 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | |||
4415 | } | |||
4416 | ||||
4417 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | |||
4418 | ||||
4419 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | |||
4420 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | |||
4421 | ||||
4422 | return Res; | |||
4423 | } | |||
4424 | ||||
4425 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | |||
4426 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | |||
4427 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | |||
4428 | ||||
4429 | // For expressions like `&(*s).b`, the base is recorded and what should be | |||
4430 | // checked. | |||
4431 | const MemberExpr *Member = nullptr; | |||
4432 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | |||
4433 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | |||
4434 | ||||
4435 | LastRecord.PossibleDerefs.erase(StrippedExpr); | |||
4436 | } | |||
4437 | ||||
4438 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | |||
4439 | QualType ResultTy = E->getType(); | |||
4440 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | |||
4441 | ||||
4442 | // Bail if the element is an array since it is not memory access. | |||
4443 | if (isa<ArrayType>(ResultTy)) | |||
4444 | return; | |||
4445 | ||||
4446 | if (ResultTy->hasAttr(attr::NoDeref)) { | |||
4447 | LastRecord.PossibleDerefs.insert(E); | |||
4448 | return; | |||
4449 | } | |||
4450 | ||||
4451 | // Check if the base type is a pointer to a member access of a struct | |||
4452 | // marked with noderef. | |||
4453 | const Expr *Base = E->getBase(); | |||
4454 | QualType BaseTy = Base->getType(); | |||
4455 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | |||
4456 | // Not a pointer access | |||
4457 | return; | |||
4458 | ||||
4459 | const MemberExpr *Member = nullptr; | |||
4460 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | |||
4461 | Member->isArrow()) | |||
4462 | Base = Member->getBase(); | |||
4463 | ||||
4464 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | |||
4465 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | |||
4466 | LastRecord.PossibleDerefs.insert(E); | |||
4467 | } | |||
4468 | } | |||
4469 | ||||
4470 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | |||
4471 | Expr *LowerBound, | |||
4472 | SourceLocation ColonLoc, Expr *Length, | |||
4473 | SourceLocation RBLoc) { | |||
4474 | if (Base->getType()->isPlaceholderType() && | |||
4475 | !Base->getType()->isSpecificPlaceholderType( | |||
4476 | BuiltinType::OMPArraySection)) { | |||
4477 | ExprResult Result = CheckPlaceholderExpr(Base); | |||
4478 | if (Result.isInvalid()) | |||
4479 | return ExprError(); | |||
4480 | Base = Result.get(); | |||
4481 | } | |||
4482 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | |||
4483 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | |||
4484 | if (Result.isInvalid()) | |||
4485 | return ExprError(); | |||
4486 | Result = DefaultLvalueConversion(Result.get()); | |||
4487 | if (Result.isInvalid()) | |||
4488 | return ExprError(); | |||
4489 | LowerBound = Result.get(); | |||
4490 | } | |||
4491 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | |||
4492 | ExprResult Result = CheckPlaceholderExpr(Length); | |||
4493 | if (Result.isInvalid()) | |||
4494 | return ExprError(); | |||
4495 | Result = DefaultLvalueConversion(Result.get()); | |||
4496 | if (Result.isInvalid()) | |||
4497 | return ExprError(); | |||
4498 | Length = Result.get(); | |||
4499 | } | |||
4500 | ||||
4501 | // Build an unanalyzed expression if either operand is type-dependent. | |||
4502 | if (Base->isTypeDependent() || | |||
4503 | (LowerBound && | |||
4504 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | |||
4505 | (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { | |||
4506 | return new (Context) | |||
4507 | OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, | |||
4508 | VK_LValue, OK_Ordinary, ColonLoc, RBLoc); | |||
4509 | } | |||
4510 | ||||
4511 | // Perform default conversions. | |||
4512 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | |||
4513 | QualType ResultTy; | |||
4514 | if (OriginalTy->isAnyPointerType()) { | |||
4515 | ResultTy = OriginalTy->getPointeeType(); | |||
4516 | } else if (OriginalTy->isArrayType()) { | |||
4517 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | |||
4518 | } else { | |||
4519 | return ExprError( | |||
4520 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | |||
4521 | << Base->getSourceRange()); | |||
4522 | } | |||
4523 | // C99 6.5.2.1p1 | |||
4524 | if (LowerBound) { | |||
4525 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | |||
4526 | LowerBound); | |||
4527 | if (Res.isInvalid()) | |||
4528 | return ExprError(Diag(LowerBound->getExprLoc(), | |||
4529 | diag::err_omp_typecheck_section_not_integer) | |||
4530 | << 0 << LowerBound->getSourceRange()); | |||
4531 | LowerBound = Res.get(); | |||
4532 | ||||
4533 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4534 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4535 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | |||
4536 | << 0 << LowerBound->getSourceRange(); | |||
4537 | } | |||
4538 | if (Length) { | |||
4539 | auto Res = | |||
4540 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | |||
4541 | if (Res.isInvalid()) | |||
4542 | return ExprError(Diag(Length->getExprLoc(), | |||
4543 | diag::err_omp_typecheck_section_not_integer) | |||
4544 | << 1 << Length->getSourceRange()); | |||
4545 | Length = Res.get(); | |||
4546 | ||||
4547 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4548 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4549 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | |||
4550 | << 1 << Length->getSourceRange(); | |||
4551 | } | |||
4552 | ||||
4553 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
4554 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
4555 | // type. Note that functions are not objects, and that (in C99 parlance) | |||
4556 | // incomplete types are not object types. | |||
4557 | if (ResultTy->isFunctionType()) { | |||
4558 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | |||
4559 | << ResultTy << Base->getSourceRange(); | |||
4560 | return ExprError(); | |||
4561 | } | |||
4562 | ||||
4563 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | |||
4564 | diag::err_omp_section_incomplete_type, Base)) | |||
4565 | return ExprError(); | |||
4566 | ||||
4567 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | |||
4568 | Expr::EvalResult Result; | |||
4569 | if (LowerBound->EvaluateAsInt(Result, Context)) { | |||
4570 | // OpenMP 4.5, [2.4 Array Sections] | |||
4571 | // The array section must be a subset of the original array. | |||
4572 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | |||
4573 | if (LowerBoundValue.isNegative()) { | |||
4574 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | |||
4575 | << LowerBound->getSourceRange(); | |||
4576 | return ExprError(); | |||
4577 | } | |||
4578 | } | |||
4579 | } | |||
4580 | ||||
4581 | if (Length) { | |||
4582 | Expr::EvalResult Result; | |||
4583 | if (Length->EvaluateAsInt(Result, Context)) { | |||
4584 | // OpenMP 4.5, [2.4 Array Sections] | |||
4585 | // The length must evaluate to non-negative integers. | |||
4586 | llvm::APSInt LengthValue = Result.Val.getInt(); | |||
4587 | if (LengthValue.isNegative()) { | |||
4588 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | |||
4589 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | |||
4590 | << Length->getSourceRange(); | |||
4591 | return ExprError(); | |||
4592 | } | |||
4593 | } | |||
4594 | } else if (ColonLoc.isValid() && | |||
4595 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | |||
4596 | !OriginalTy->isVariableArrayType()))) { | |||
4597 | // OpenMP 4.5, [2.4 Array Sections] | |||
4598 | // When the size of the array dimension is not known, the length must be | |||
4599 | // specified explicitly. | |||
4600 | Diag(ColonLoc, diag::err_omp_section_length_undefined) | |||
4601 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | |||
4602 | return ExprError(); | |||
4603 | } | |||
4604 | ||||
4605 | if (!Base->getType()->isSpecificPlaceholderType( | |||
4606 | BuiltinType::OMPArraySection)) { | |||
4607 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | |||
4608 | if (Result.isInvalid()) | |||
4609 | return ExprError(); | |||
4610 | Base = Result.get(); | |||
4611 | } | |||
4612 | return new (Context) | |||
4613 | OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, | |||
4614 | VK_LValue, OK_Ordinary, ColonLoc, RBLoc); | |||
4615 | } | |||
4616 | ||||
4617 | ExprResult | |||
4618 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | |||
4619 | Expr *Idx, SourceLocation RLoc) { | |||
4620 | Expr *LHSExp = Base; | |||
4621 | Expr *RHSExp = Idx; | |||
4622 | ||||
4623 | ExprValueKind VK = VK_LValue; | |||
4624 | ExprObjectKind OK = OK_Ordinary; | |||
4625 | ||||
4626 | // Per C++ core issue 1213, the result is an xvalue if either operand is | |||
4627 | // a non-lvalue array, and an lvalue otherwise. | |||
4628 | if (getLangOpts().CPlusPlus11) { | |||
4629 | for (auto *Op : {LHSExp, RHSExp}) { | |||
4630 | Op = Op->IgnoreImplicit(); | |||
4631 | if (Op->getType()->isArrayType() && !Op->isLValue()) | |||
4632 | VK = VK_XValue; | |||
4633 | } | |||
4634 | } | |||
4635 | ||||
4636 | // Perform default conversions. | |||
4637 | if (!LHSExp->getType()->getAs<VectorType>()) { | |||
4638 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | |||
4639 | if (Result.isInvalid()) | |||
4640 | return ExprError(); | |||
4641 | LHSExp = Result.get(); | |||
4642 | } | |||
4643 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | |||
4644 | if (Result.isInvalid()) | |||
4645 | return ExprError(); | |||
4646 | RHSExp = Result.get(); | |||
4647 | ||||
4648 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | |||
4649 | ||||
4650 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | |||
4651 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | |||
4652 | // in the subscript position. As a result, we need to derive the array base | |||
4653 | // and index from the expression types. | |||
4654 | Expr *BaseExpr, *IndexExpr; | |||
4655 | QualType ResultType; | |||
4656 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | |||
4657 | BaseExpr = LHSExp; | |||
4658 | IndexExpr = RHSExp; | |||
4659 | ResultType = Context.DependentTy; | |||
4660 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | |||
4661 | BaseExpr = LHSExp; | |||
4662 | IndexExpr = RHSExp; | |||
4663 | ResultType = PTy->getPointeeType(); | |||
4664 | } else if (const ObjCObjectPointerType *PTy = | |||
4665 | LHSTy->getAs<ObjCObjectPointerType>()) { | |||
4666 | BaseExpr = LHSExp; | |||
4667 | IndexExpr = RHSExp; | |||
4668 | ||||
4669 | // Use custom logic if this should be the pseudo-object subscript | |||
4670 | // expression. | |||
4671 | if (!LangOpts.isSubscriptPointerArithmetic()) | |||
4672 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | |||
4673 | nullptr); | |||
4674 | ||||
4675 | ResultType = PTy->getPointeeType(); | |||
4676 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | |||
4677 | // Handle the uncommon case of "123[Ptr]". | |||
4678 | BaseExpr = RHSExp; | |||
4679 | IndexExpr = LHSExp; | |||
4680 | ResultType = PTy->getPointeeType(); | |||
4681 | } else if (const ObjCObjectPointerType *PTy = | |||
4682 | RHSTy->getAs<ObjCObjectPointerType>()) { | |||
4683 | // Handle the uncommon case of "123[Ptr]". | |||
4684 | BaseExpr = RHSExp; | |||
4685 | IndexExpr = LHSExp; | |||
4686 | ResultType = PTy->getPointeeType(); | |||
4687 | if (!LangOpts.isSubscriptPointerArithmetic()) { | |||
4688 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | |||
4689 | << ResultType << BaseExpr->getSourceRange(); | |||
4690 | return ExprError(); | |||
4691 | } | |||
4692 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | |||
4693 | BaseExpr = LHSExp; // vectors: V[123] | |||
4694 | IndexExpr = RHSExp; | |||
4695 | // We apply C++ DR1213 to vector subscripting too. | |||
4696 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | |||
4697 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | |||
4698 | if (Materialized.isInvalid()) | |||
4699 | return ExprError(); | |||
4700 | LHSExp = Materialized.get(); | |||
4701 | } | |||
4702 | VK = LHSExp->getValueKind(); | |||
4703 | if (VK != VK_RValue) | |||
4704 | OK = OK_VectorComponent; | |||
4705 | ||||
4706 | ResultType = VTy->getElementType(); | |||
4707 | QualType BaseType = BaseExpr->getType(); | |||
4708 | Qualifiers BaseQuals = BaseType.getQualifiers(); | |||
4709 | Qualifiers MemberQuals = ResultType.getQualifiers(); | |||
4710 | Qualifiers Combined = BaseQuals + MemberQuals; | |||
4711 | if (Combined != MemberQuals) | |||
4712 | ResultType = Context.getQualifiedType(ResultType, Combined); | |||
4713 | } else if (LHSTy->isArrayType()) { | |||
4714 | // If we see an array that wasn't promoted by | |||
4715 | // DefaultFunctionArrayLvalueConversion, it must be an array that | |||
4716 | // wasn't promoted because of the C90 rule that doesn't | |||
4717 | // allow promoting non-lvalue arrays. Warn, then | |||
4718 | // force the promotion here. | |||
4719 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | |||
4720 | << LHSExp->getSourceRange(); | |||
4721 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | |||
4722 | CK_ArrayToPointerDecay).get(); | |||
4723 | LHSTy = LHSExp->getType(); | |||
4724 | ||||
4725 | BaseExpr = LHSExp; | |||
4726 | IndexExpr = RHSExp; | |||
4727 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | |||
4728 | } else if (RHSTy->isArrayType()) { | |||
4729 | // Same as previous, except for 123[f().a] case | |||
4730 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | |||
4731 | << RHSExp->getSourceRange(); | |||
4732 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | |||
4733 | CK_ArrayToPointerDecay).get(); | |||
4734 | RHSTy = RHSExp->getType(); | |||
4735 | ||||
4736 | BaseExpr = RHSExp; | |||
4737 | IndexExpr = LHSExp; | |||
4738 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | |||
4739 | } else { | |||
4740 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | |||
4741 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | |||
4742 | } | |||
4743 | // C99 6.5.2.1p1 | |||
4744 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | |||
4745 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | |||
4746 | << IndexExpr->getSourceRange()); | |||
4747 | ||||
4748 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | |||
4749 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | |||
4750 | && !IndexExpr->isTypeDependent()) | |||
4751 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | |||
4752 | ||||
4753 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | |||
4754 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | |||
4755 | // type. Note that Functions are not objects, and that (in C99 parlance) | |||
4756 | // incomplete types are not object types. | |||
4757 | if (ResultType->isFunctionType()) { | |||
4758 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | |||
4759 | << ResultType << BaseExpr->getSourceRange(); | |||
4760 | return ExprError(); | |||
4761 | } | |||
4762 | ||||
4763 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | |||
4764 | // GNU extension: subscripting on pointer to void | |||
4765 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | |||
4766 | << BaseExpr->getSourceRange(); | |||
4767 | ||||
4768 | // C forbids expressions of unqualified void type from being l-values. | |||
4769 | // See IsCForbiddenLValueType. | |||
4770 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | |||
4771 | } else if (!ResultType->isDependentType() && | |||
4772 | RequireCompleteType(LLoc, ResultType, | |||
4773 | diag::err_subscript_incomplete_type, BaseExpr)) | |||
4774 | return ExprError(); | |||
4775 | ||||
4776 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4777, __PRETTY_FUNCTION__)) | |||
4777 | !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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4777, __PRETTY_FUNCTION__)); | |||
4778 | ||||
4779 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | |||
4780 | FunctionScopes.size() > 1) { | |||
4781 | if (auto *TT = | |||
4782 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | |||
4783 | for (auto I = FunctionScopes.rbegin(), | |||
4784 | E = std::prev(FunctionScopes.rend()); | |||
4785 | I != E; ++I) { | |||
4786 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | |||
4787 | if (CSI == nullptr) | |||
4788 | break; | |||
4789 | DeclContext *DC = nullptr; | |||
4790 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | |||
4791 | DC = LSI->CallOperator; | |||
4792 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | |||
4793 | DC = CRSI->TheCapturedDecl; | |||
4794 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | |||
4795 | DC = BSI->TheDecl; | |||
4796 | if (DC) { | |||
4797 | if (DC->containsDecl(TT->getDecl())) | |||
4798 | break; | |||
4799 | captureVariablyModifiedType( | |||
4800 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | |||
4801 | } | |||
4802 | } | |||
4803 | } | |||
4804 | } | |||
4805 | ||||
4806 | return new (Context) | |||
4807 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | |||
4808 | } | |||
4809 | ||||
4810 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | |||
4811 | ParmVarDecl *Param) { | |||
4812 | if (Param->hasUnparsedDefaultArg()) { | |||
4813 | Diag(CallLoc, | |||
4814 | diag::err_use_of_default_argument_to_function_declared_later) << | |||
4815 | FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); | |||
4816 | Diag(UnparsedDefaultArgLocs[Param], | |||
4817 | diag::note_default_argument_declared_here); | |||
4818 | return true; | |||
4819 | } | |||
4820 | ||||
4821 | if (Param->hasUninstantiatedDefaultArg()) { | |||
4822 | Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); | |||
4823 | ||||
4824 | EnterExpressionEvaluationContext EvalContext( | |||
4825 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | |||
4826 | ||||
4827 | // Instantiate the expression. | |||
4828 | // | |||
4829 | // FIXME: Pass in a correct Pattern argument, otherwise | |||
4830 | // getTemplateInstantiationArgs uses the lexical context of FD, e.g. | |||
4831 | // | |||
4832 | // template<typename T> | |||
4833 | // struct A { | |||
4834 | // static int FooImpl(); | |||
4835 | // | |||
4836 | // template<typename Tp> | |||
4837 | // // bug: default argument A<T>::FooImpl() is evaluated with 2-level | |||
4838 | // // template argument list [[T], [Tp]], should be [[Tp]]. | |||
4839 | // friend A<Tp> Foo(int a); | |||
4840 | // }; | |||
4841 | // | |||
4842 | // template<typename T> | |||
4843 | // A<T> Foo(int a = A<T>::FooImpl()); | |||
4844 | MultiLevelTemplateArgumentList MutiLevelArgList | |||
4845 | = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); | |||
4846 | ||||
4847 | InstantiatingTemplate Inst(*this, CallLoc, Param, | |||
4848 | MutiLevelArgList.getInnermost()); | |||
4849 | if (Inst.isInvalid()) | |||
4850 | return true; | |||
4851 | if (Inst.isAlreadyInstantiating()) { | |||
4852 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | |||
4853 | Param->setInvalidDecl(); | |||
4854 | return true; | |||
4855 | } | |||
4856 | ||||
4857 | ExprResult Result; | |||
4858 | { | |||
4859 | // C++ [dcl.fct.default]p5: | |||
4860 | // The names in the [default argument] expression are bound, and | |||
4861 | // the semantic constraints are checked, at the point where the | |||
4862 | // default argument expression appears. | |||
4863 | ContextRAII SavedContext(*this, FD); | |||
4864 | LocalInstantiationScope Local(*this); | |||
4865 | runWithSufficientStackSpace(CallLoc, [&] { | |||
4866 | Result = SubstInitializer(UninstExpr, MutiLevelArgList, | |||
4867 | /*DirectInit*/false); | |||
4868 | }); | |||
4869 | } | |||
4870 | if (Result.isInvalid()) | |||
4871 | return true; | |||
4872 | ||||
4873 | // Check the expression as an initializer for the parameter. | |||
4874 | InitializedEntity Entity | |||
4875 | = InitializedEntity::InitializeParameter(Context, Param); | |||
4876 | InitializationKind Kind = InitializationKind::CreateCopy( | |||
4877 | Param->getLocation(), | |||
4878 | /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); | |||
4879 | Expr *ResultE = Result.getAs<Expr>(); | |||
4880 | ||||
4881 | InitializationSequence InitSeq(*this, Entity, Kind, ResultE); | |||
4882 | Result = InitSeq.Perform(*this, Entity, Kind, ResultE); | |||
4883 | if (Result.isInvalid()) | |||
4884 | return true; | |||
4885 | ||||
4886 | Result = | |||
4887 | ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), | |||
4888 | /*DiscardedValue*/ false); | |||
4889 | if (Result.isInvalid()) | |||
4890 | return true; | |||
4891 | ||||
4892 | // Remember the instantiated default argument. | |||
4893 | Param->setDefaultArg(Result.getAs<Expr>()); | |||
4894 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
4895 | L->DefaultArgumentInstantiated(Param); | |||
4896 | } | |||
4897 | } | |||
4898 | ||||
4899 | // If the default argument expression is not set yet, we are building it now. | |||
4900 | if (!Param->hasInit()) { | |||
4901 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | |||
4902 | Param->setInvalidDecl(); | |||
4903 | return true; | |||
4904 | } | |||
4905 | ||||
4906 | // If the default expression creates temporaries, we need to | |||
4907 | // push them to the current stack of expression temporaries so they'll | |||
4908 | // be properly destroyed. | |||
4909 | // FIXME: We should really be rebuilding the default argument with new | |||
4910 | // bound temporaries; see the comment in PR5810. | |||
4911 | // We don't need to do that with block decls, though, because | |||
4912 | // blocks in default argument expression can never capture anything. | |||
4913 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | |||
4914 | // Set the "needs cleanups" bit regardless of whether there are | |||
4915 | // any explicit objects. | |||
4916 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | |||
4917 | ||||
4918 | // Append all the objects to the cleanup list. Right now, this | |||
4919 | // should always be a no-op, because blocks in default argument | |||
4920 | // expressions should never be able to capture anything. | |||
4921 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4922, __PRETTY_FUNCTION__)) | |||
4922 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 4922, __PRETTY_FUNCTION__)); | |||
4923 | } | |||
4924 | ||||
4925 | // We already type-checked the argument, so we know it works. | |||
4926 | // Just mark all of the declarations in this potentially-evaluated expression | |||
4927 | // as being "referenced". | |||
4928 | EnterExpressionEvaluationContext EvalContext( | |||
4929 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | |||
4930 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | |||
4931 | /*SkipLocalVariables=*/true); | |||
4932 | return false; | |||
4933 | } | |||
4934 | ||||
4935 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | |||
4936 | FunctionDecl *FD, ParmVarDecl *Param) { | |||
4937 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | |||
4938 | return ExprError(); | |||
4939 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | |||
4940 | } | |||
4941 | ||||
4942 | Sema::VariadicCallType | |||
4943 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | |||
4944 | Expr *Fn) { | |||
4945 | if (Proto && Proto->isVariadic()) { | |||
4946 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | |||
4947 | return VariadicConstructor; | |||
4948 | else if (Fn && Fn->getType()->isBlockPointerType()) | |||
4949 | return VariadicBlock; | |||
4950 | else if (FDecl) { | |||
4951 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | |||
4952 | if (Method->isInstance()) | |||
4953 | return VariadicMethod; | |||
4954 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | |||
4955 | return VariadicMethod; | |||
4956 | return VariadicFunction; | |||
4957 | } | |||
4958 | return VariadicDoesNotApply; | |||
4959 | } | |||
4960 | ||||
4961 | namespace { | |||
4962 | class FunctionCallCCC final : public FunctionCallFilterCCC { | |||
4963 | public: | |||
4964 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | |||
4965 | unsigned NumArgs, MemberExpr *ME) | |||
4966 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | |||
4967 | FunctionName(FuncName) {} | |||
4968 | ||||
4969 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
4970 | if (!candidate.getCorrectionSpecifier() || | |||
4971 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | |||
4972 | return false; | |||
4973 | } | |||
4974 | ||||
4975 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | |||
4976 | } | |||
4977 | ||||
4978 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
4979 | return std::make_unique<FunctionCallCCC>(*this); | |||
4980 | } | |||
4981 | ||||
4982 | private: | |||
4983 | const IdentifierInfo *const FunctionName; | |||
4984 | }; | |||
4985 | } | |||
4986 | ||||
4987 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | |||
4988 | FunctionDecl *FDecl, | |||
4989 | ArrayRef<Expr *> Args) { | |||
4990 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | |||
4991 | DeclarationName FuncName = FDecl->getDeclName(); | |||
4992 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | |||
4993 | ||||
4994 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | |||
4995 | if (TypoCorrection Corrected = S.CorrectTypo( | |||
4996 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | |||
4997 | S.getScopeForContext(S.CurContext), nullptr, CCC, | |||
4998 | Sema::CTK_ErrorRecovery)) { | |||
4999 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | |||
5000 | if (Corrected.isOverloaded()) { | |||
5001 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | |||
5002 | OverloadCandidateSet::iterator Best; | |||
5003 | for (NamedDecl *CD : Corrected) { | |||
5004 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | |||
5005 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | |||
5006 | OCS); | |||
5007 | } | |||
5008 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | |||
5009 | case OR_Success: | |||
5010 | ND = Best->FoundDecl; | |||
5011 | Corrected.setCorrectionDecl(ND); | |||
5012 | break; | |||
5013 | default: | |||
5014 | break; | |||
5015 | } | |||
5016 | } | |||
5017 | ND = ND->getUnderlyingDecl(); | |||
5018 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | |||
5019 | return Corrected; | |||
5020 | } | |||
5021 | } | |||
5022 | return TypoCorrection(); | |||
5023 | } | |||
5024 | ||||
5025 | /// ConvertArgumentsForCall - Converts the arguments specified in | |||
5026 | /// Args/NumArgs to the parameter types of the function FDecl with | |||
5027 | /// function prototype Proto. Call is the call expression itself, and | |||
5028 | /// Fn is the function expression. For a C++ member function, this | |||
5029 | /// routine does not attempt to convert the object argument. Returns | |||
5030 | /// true if the call is ill-formed. | |||
5031 | bool | |||
5032 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | |||
5033 | FunctionDecl *FDecl, | |||
5034 | const FunctionProtoType *Proto, | |||
5035 | ArrayRef<Expr *> Args, | |||
5036 | SourceLocation RParenLoc, | |||
5037 | bool IsExecConfig) { | |||
5038 | // Bail out early if calling a builtin with custom typechecking. | |||
5039 | if (FDecl) | |||
5040 | if (unsigned ID = FDecl->getBuiltinID()) | |||
5041 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | |||
5042 | return false; | |||
5043 | ||||
5044 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | |||
5045 | // assignment, to the types of the corresponding parameter, ... | |||
5046 | unsigned NumParams = Proto->getNumParams(); | |||
5047 | bool Invalid = false; | |||
5048 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | |||
5049 | unsigned FnKind = Fn->getType()->isBlockPointerType() | |||
5050 | ? 1 /* block */ | |||
5051 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | |||
5052 | : 0 /* function */); | |||
5053 | ||||
5054 | // If too few arguments are available (and we don't have default | |||
5055 | // arguments for the remaining parameters), don't make the call. | |||
5056 | if (Args.size() < NumParams) { | |||
5057 | if (Args.size() < MinArgs) { | |||
5058 | TypoCorrection TC; | |||
5059 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
5060 | unsigned diag_id = | |||
5061 | MinArgs == NumParams && !Proto->isVariadic() | |||
5062 | ? diag::err_typecheck_call_too_few_args_suggest | |||
5063 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | |||
5064 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | |||
5065 | << static_cast<unsigned>(Args.size()) | |||
5066 | << TC.getCorrectionRange()); | |||
5067 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | |||
5068 | Diag(RParenLoc, | |||
5069 | MinArgs == NumParams && !Proto->isVariadic() | |||
5070 | ? diag::err_typecheck_call_too_few_args_one | |||
5071 | : diag::err_typecheck_call_too_few_args_at_least_one) | |||
5072 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | |||
5073 | else | |||
5074 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | |||
5075 | ? diag::err_typecheck_call_too_few_args | |||
5076 | : diag::err_typecheck_call_too_few_args_at_least) | |||
5077 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | |||
5078 | << Fn->getSourceRange(); | |||
5079 | ||||
5080 | // Emit the location of the prototype. | |||
5081 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
5082 | Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; | |||
5083 | ||||
5084 | return true; | |||
5085 | } | |||
5086 | // We reserve space for the default arguments when we create | |||
5087 | // the call expression, before calling ConvertArgumentsForCall. | |||
5088 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5089, __PRETTY_FUNCTION__)) | |||
5089 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5089, __PRETTY_FUNCTION__)); | |||
5090 | } | |||
5091 | ||||
5092 | // If too many are passed and not variadic, error on the extras and drop | |||
5093 | // them. | |||
5094 | if (Args.size() > NumParams) { | |||
5095 | if (!Proto->isVariadic()) { | |||
5096 | TypoCorrection TC; | |||
5097 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | |||
5098 | unsigned diag_id = | |||
5099 | MinArgs == NumParams && !Proto->isVariadic() | |||
5100 | ? diag::err_typecheck_call_too_many_args_suggest | |||
5101 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | |||
5102 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | |||
5103 | << static_cast<unsigned>(Args.size()) | |||
5104 | << TC.getCorrectionRange()); | |||
5105 | } else if (NumParams == 1 && FDecl && | |||
5106 | FDecl->getParamDecl(0)->getDeclName()) | |||
5107 | Diag(Args[NumParams]->getBeginLoc(), | |||
5108 | MinArgs == NumParams | |||
5109 | ? diag::err_typecheck_call_too_many_args_one | |||
5110 | : diag::err_typecheck_call_too_many_args_at_most_one) | |||
5111 | << FnKind << FDecl->getParamDecl(0) | |||
5112 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | |||
5113 | << SourceRange(Args[NumParams]->getBeginLoc(), | |||
5114 | Args.back()->getEndLoc()); | |||
5115 | else | |||
5116 | Diag(Args[NumParams]->getBeginLoc(), | |||
5117 | MinArgs == NumParams | |||
5118 | ? diag::err_typecheck_call_too_many_args | |||
5119 | : diag::err_typecheck_call_too_many_args_at_most) | |||
5120 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | |||
5121 | << Fn->getSourceRange() | |||
5122 | << SourceRange(Args[NumParams]->getBeginLoc(), | |||
5123 | Args.back()->getEndLoc()); | |||
5124 | ||||
5125 | // Emit the location of the prototype. | |||
5126 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | |||
5127 | Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; | |||
5128 | ||||
5129 | // This deletes the extra arguments. | |||
5130 | Call->shrinkNumArgs(NumParams); | |||
5131 | return true; | |||
5132 | } | |||
5133 | } | |||
5134 | SmallVector<Expr *, 8> AllArgs; | |||
5135 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | |||
5136 | ||||
5137 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | |||
5138 | AllArgs, CallType); | |||
5139 | if (Invalid) | |||
5140 | return true; | |||
5141 | unsigned TotalNumArgs = AllArgs.size(); | |||
5142 | for (unsigned i = 0; i < TotalNumArgs; ++i) | |||
5143 | Call->setArg(i, AllArgs[i]); | |||
5144 | ||||
5145 | return false; | |||
5146 | } | |||
5147 | ||||
5148 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | |||
5149 | const FunctionProtoType *Proto, | |||
5150 | unsigned FirstParam, ArrayRef<Expr *> Args, | |||
5151 | SmallVectorImpl<Expr *> &AllArgs, | |||
5152 | VariadicCallType CallType, bool AllowExplicit, | |||
5153 | bool IsListInitialization) { | |||
5154 | unsigned NumParams = Proto->getNumParams(); | |||
5155 | bool Invalid = false; | |||
5156 | size_t ArgIx = 0; | |||
5157 | // Continue to check argument types (even if we have too few/many args). | |||
5158 | for (unsigned i = FirstParam; i < NumParams; i++) { | |||
5159 | QualType ProtoArgType = Proto->getParamType(i); | |||
5160 | ||||
5161 | Expr *Arg; | |||
5162 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | |||
5163 | if (ArgIx < Args.size()) { | |||
5164 | Arg = Args[ArgIx++]; | |||
5165 | ||||
5166 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | |||
5167 | diag::err_call_incomplete_argument, Arg)) | |||
5168 | return true; | |||
5169 | ||||
5170 | // Strip the unbridged-cast placeholder expression off, if applicable. | |||
5171 | bool CFAudited = false; | |||
5172 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | |||
5173 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
5174 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
5175 | Arg = stripARCUnbridgedCast(Arg); | |||
5176 | else if (getLangOpts().ObjCAutoRefCount && | |||
5177 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | |||
5178 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | |||
5179 | CFAudited = true; | |||
5180 | ||||
5181 | if (Proto->getExtParameterInfo(i).isNoEscape()) | |||
5182 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | |||
5183 | BE->getBlockDecl()->setDoesNotEscape(); | |||
5184 | ||||
5185 | InitializedEntity Entity = | |||
5186 | Param ? InitializedEntity::InitializeParameter(Context, Param, | |||
5187 | ProtoArgType) | |||
5188 | : InitializedEntity::InitializeParameter( | |||
5189 | Context, ProtoArgType, Proto->isParamConsumed(i)); | |||
5190 | ||||
5191 | // Remember that parameter belongs to a CF audited API. | |||
5192 | if (CFAudited) | |||
5193 | Entity.setParameterCFAudited(); | |||
5194 | ||||
5195 | ExprResult ArgE = PerformCopyInitialization( | |||
5196 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | |||
5197 | if (ArgE.isInvalid()) | |||
5198 | return true; | |||
5199 | ||||
5200 | Arg = ArgE.getAs<Expr>(); | |||
5201 | } else { | |||
5202 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5202, __PRETTY_FUNCTION__)); | |||
5203 | ||||
5204 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | |||
5205 | if (ArgExpr.isInvalid()) | |||
5206 | return true; | |||
5207 | ||||
5208 | Arg = ArgExpr.getAs<Expr>(); | |||
5209 | } | |||
5210 | ||||
5211 | // Check for array bounds violations for each argument to the call. This | |||
5212 | // check only triggers warnings when the argument isn't a more complex Expr | |||
5213 | // with its own checking, such as a BinaryOperator. | |||
5214 | CheckArrayAccess(Arg); | |||
5215 | ||||
5216 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | |||
5217 | CheckStaticArrayArgument(CallLoc, Param, Arg); | |||
5218 | ||||
5219 | AllArgs.push_back(Arg); | |||
5220 | } | |||
5221 | ||||
5222 | // If this is a variadic call, handle args passed through "...". | |||
5223 | if (CallType != VariadicDoesNotApply) { | |||
5224 | // Assume that extern "C" functions with variadic arguments that | |||
5225 | // return __unknown_anytype aren't *really* variadic. | |||
5226 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | |||
5227 | FDecl->isExternC()) { | |||
5228 | for (Expr *A : Args.slice(ArgIx)) { | |||
5229 | QualType paramType; // ignored | |||
5230 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | |||
5231 | Invalid |= arg.isInvalid(); | |||
5232 | AllArgs.push_back(arg.get()); | |||
5233 | } | |||
5234 | ||||
5235 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | |||
5236 | } else { | |||
5237 | for (Expr *A : Args.slice(ArgIx)) { | |||
5238 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | |||
5239 | Invalid |= Arg.isInvalid(); | |||
5240 | AllArgs.push_back(Arg.get()); | |||
5241 | } | |||
5242 | } | |||
5243 | ||||
5244 | // Check for array bounds violations. | |||
5245 | for (Expr *A : Args.slice(ArgIx)) | |||
5246 | CheckArrayAccess(A); | |||
5247 | } | |||
5248 | return Invalid; | |||
5249 | } | |||
5250 | ||||
5251 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | |||
5252 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | |||
5253 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | |||
5254 | TL = DTL.getOriginalLoc(); | |||
5255 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | |||
5256 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | |||
5257 | << ATL.getLocalSourceRange(); | |||
5258 | } | |||
5259 | ||||
5260 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | |||
5261 | /// array parameter, check that it is non-null, and that if it is formed by | |||
5262 | /// array-to-pointer decay, the underlying array is sufficiently large. | |||
5263 | /// | |||
5264 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | |||
5265 | /// array type derivation, then for each call to the function, the value of the | |||
5266 | /// corresponding actual argument shall provide access to the first element of | |||
5267 | /// an array with at least as many elements as specified by the size expression. | |||
5268 | void | |||
5269 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | |||
5270 | ParmVarDecl *Param, | |||
5271 | const Expr *ArgExpr) { | |||
5272 | // Static array parameters are not supported in C++. | |||
5273 | if (!Param || getLangOpts().CPlusPlus) | |||
5274 | return; | |||
5275 | ||||
5276 | QualType OrigTy = Param->getOriginalType(); | |||
5277 | ||||
5278 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | |||
5279 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | |||
5280 | return; | |||
5281 | ||||
5282 | if (ArgExpr->isNullPointerConstant(Context, | |||
5283 | Expr::NPC_NeverValueDependent)) { | |||
5284 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | |||
5285 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
5286 | return; | |||
5287 | } | |||
5288 | ||||
5289 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | |||
5290 | if (!CAT) | |||
5291 | return; | |||
5292 | ||||
5293 | const ConstantArrayType *ArgCAT = | |||
5294 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | |||
5295 | if (!ArgCAT) | |||
5296 | return; | |||
5297 | ||||
5298 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | |||
5299 | ArgCAT->getElementType())) { | |||
5300 | if (ArgCAT->getSize().ult(CAT->getSize())) { | |||
5301 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
5302 | << ArgExpr->getSourceRange() | |||
5303 | << (unsigned)ArgCAT->getSize().getZExtValue() | |||
5304 | << (unsigned)CAT->getSize().getZExtValue() << 0; | |||
5305 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
5306 | } | |||
5307 | return; | |||
5308 | } | |||
5309 | ||||
5310 | Optional<CharUnits> ArgSize = | |||
5311 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | |||
5312 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | |||
5313 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | |||
5314 | Diag(CallLoc, diag::warn_static_array_too_small) | |||
5315 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | |||
5316 | << (unsigned)ParmSize->getQuantity() << 1; | |||
5317 | DiagnoseCalleeStaticArrayParam(*this, Param); | |||
5318 | } | |||
5319 | } | |||
5320 | ||||
5321 | /// Given a function expression of unknown-any type, try to rebuild it | |||
5322 | /// to have a function type. | |||
5323 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | |||
5324 | ||||
5325 | /// Is the given type a placeholder that we need to lower out | |||
5326 | /// immediately during argument processing? | |||
5327 | static bool isPlaceholderToRemoveAsArg(QualType type) { | |||
5328 | // Placeholders are never sugared. | |||
5329 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | |||
5330 | if (!placeholder) return false; | |||
5331 | ||||
5332 | switch (placeholder->getKind()) { | |||
5333 | // Ignore all the non-placeholder types. | |||
5334 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
5335 | case BuiltinType::Id: | |||
5336 | #include "clang/Basic/OpenCLImageTypes.def" | |||
5337 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
5338 | case BuiltinType::Id: | |||
5339 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
5340 | // In practice we'll never use this, since all SVE types are sugared | |||
5341 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | |||
5342 | #define SVE_TYPE(Name, Id, SingletonId) \ | |||
5343 | case BuiltinType::Id: | |||
5344 | #include "clang/Basic/AArch64SVEACLETypes.def" | |||
5345 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | |||
5346 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | |||
5347 | #include "clang/AST/BuiltinTypes.def" | |||
5348 | return false; | |||
5349 | ||||
5350 | // We cannot lower out overload sets; they might validly be resolved | |||
5351 | // by the call machinery. | |||
5352 | case BuiltinType::Overload: | |||
5353 | return false; | |||
5354 | ||||
5355 | // Unbridged casts in ARC can be handled in some call positions and | |||
5356 | // should be left in place. | |||
5357 | case BuiltinType::ARCUnbridgedCast: | |||
5358 | return false; | |||
5359 | ||||
5360 | // Pseudo-objects should be converted as soon as possible. | |||
5361 | case BuiltinType::PseudoObject: | |||
5362 | return true; | |||
5363 | ||||
5364 | // The debugger mode could theoretically but currently does not try | |||
5365 | // to resolve unknown-typed arguments based on known parameter types. | |||
5366 | case BuiltinType::UnknownAny: | |||
5367 | return true; | |||
5368 | ||||
5369 | // These are always invalid as call arguments and should be reported. | |||
5370 | case BuiltinType::BoundMember: | |||
5371 | case BuiltinType::BuiltinFn: | |||
5372 | case BuiltinType::OMPArraySection: | |||
5373 | return true; | |||
5374 | ||||
5375 | } | |||
5376 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5376); | |||
5377 | } | |||
5378 | ||||
5379 | /// Check an argument list for placeholders that we won't try to | |||
5380 | /// handle later. | |||
5381 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | |||
5382 | // Apply this processing to all the arguments at once instead of | |||
5383 | // dying at the first failure. | |||
5384 | bool hasInvalid = false; | |||
5385 | for (size_t i = 0, e = args.size(); i != e; i++) { | |||
5386 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | |||
5387 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | |||
5388 | if (result.isInvalid()) hasInvalid = true; | |||
5389 | else args[i] = result.get(); | |||
5390 | } else if (hasInvalid) { | |||
5391 | (void)S.CorrectDelayedTyposInExpr(args[i]); | |||
5392 | } | |||
5393 | } | |||
5394 | return hasInvalid; | |||
5395 | } | |||
5396 | ||||
5397 | /// If a builtin function has a pointer argument with no explicit address | |||
5398 | /// space, then it should be able to accept a pointer to any address | |||
5399 | /// space as input. In order to do this, we need to replace the | |||
5400 | /// standard builtin declaration with one that uses the same address space | |||
5401 | /// as the call. | |||
5402 | /// | |||
5403 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | |||
5404 | /// it does not contain any pointer arguments without | |||
5405 | /// an address space qualifer. Otherwise the rewritten | |||
5406 | /// FunctionDecl is returned. | |||
5407 | /// TODO: Handle pointer return types. | |||
5408 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | |||
5409 | FunctionDecl *FDecl, | |||
5410 | MultiExprArg ArgExprs) { | |||
5411 | ||||
5412 | QualType DeclType = FDecl->getType(); | |||
5413 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | |||
5414 | ||||
5415 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | |||
5416 | ArgExprs.size() < FT->getNumParams()) | |||
5417 | return nullptr; | |||
5418 | ||||
5419 | bool NeedsNewDecl = false; | |||
5420 | unsigned i = 0; | |||
5421 | SmallVector<QualType, 8> OverloadParams; | |||
5422 | ||||
5423 | for (QualType ParamType : FT->param_types()) { | |||
5424 | ||||
5425 | // Convert array arguments to pointer to simplify type lookup. | |||
5426 | ExprResult ArgRes = | |||
5427 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | |||
5428 | if (ArgRes.isInvalid()) | |||
5429 | return nullptr; | |||
5430 | Expr *Arg = ArgRes.get(); | |||
5431 | QualType ArgType = Arg->getType(); | |||
5432 | if (!ParamType->isPointerType() || | |||
5433 | ParamType.getQualifiers().hasAddressSpace() || | |||
5434 | !ArgType->isPointerType() || | |||
5435 | !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { | |||
5436 | OverloadParams.push_back(ParamType); | |||
5437 | continue; | |||
5438 | } | |||
5439 | ||||
5440 | QualType PointeeType = ParamType->getPointeeType(); | |||
5441 | if (PointeeType.getQualifiers().hasAddressSpace()) | |||
5442 | continue; | |||
5443 | ||||
5444 | NeedsNewDecl = true; | |||
5445 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | |||
5446 | ||||
5447 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | |||
5448 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | |||
5449 | } | |||
5450 | ||||
5451 | if (!NeedsNewDecl) | |||
5452 | return nullptr; | |||
5453 | ||||
5454 | FunctionProtoType::ExtProtoInfo EPI; | |||
5455 | EPI.Variadic = FT->isVariadic(); | |||
5456 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | |||
5457 | OverloadParams, EPI); | |||
5458 | DeclContext *Parent = FDecl->getParent(); | |||
5459 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, | |||
5460 | FDecl->getLocation(), | |||
5461 | FDecl->getLocation(), | |||
5462 | FDecl->getIdentifier(), | |||
5463 | OverloadTy, | |||
5464 | /*TInfo=*/nullptr, | |||
5465 | SC_Extern, false, | |||
5466 | /*hasPrototype=*/true); | |||
5467 | SmallVector<ParmVarDecl*, 16> Params; | |||
5468 | FT = cast<FunctionProtoType>(OverloadTy); | |||
5469 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
5470 | QualType ParamType = FT->getParamType(i); | |||
5471 | ParmVarDecl *Parm = | |||
5472 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | |||
5473 | SourceLocation(), nullptr, ParamType, | |||
5474 | /*TInfo=*/nullptr, SC_None, nullptr); | |||
5475 | Parm->setScopeInfo(0, i); | |||
5476 | Params.push_back(Parm); | |||
5477 | } | |||
5478 | OverloadDecl->setParams(Params); | |||
5479 | return OverloadDecl; | |||
5480 | } | |||
5481 | ||||
5482 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | |||
5483 | FunctionDecl *Callee, | |||
5484 | MultiExprArg ArgExprs) { | |||
5485 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | |||
5486 | // similar attributes) really don't like it when functions are called with an | |||
5487 | // invalid number of args. | |||
5488 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | |||
5489 | /*PartialOverloading=*/false) && | |||
5490 | !Callee->isVariadic()) | |||
5491 | return; | |||
5492 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | |||
5493 | return; | |||
5494 | ||||
5495 | if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { | |||
5496 | S.Diag(Fn->getBeginLoc(), | |||
5497 | isa<CXXMethodDecl>(Callee) | |||
5498 | ? diag::err_ovl_no_viable_member_function_in_call | |||
5499 | : diag::err_ovl_no_viable_function_in_call) | |||
5500 | << Callee << Callee->getSourceRange(); | |||
5501 | S.Diag(Callee->getLocation(), | |||
5502 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
5503 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
5504 | return; | |||
5505 | } | |||
5506 | } | |||
5507 | ||||
5508 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | |||
5509 | const UnresolvedMemberExpr *const UME, Sema &S) { | |||
5510 | ||||
5511 | const auto GetFunctionLevelDCIfCXXClass = | |||
5512 | [](Sema &S) -> const CXXRecordDecl * { | |||
5513 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | |||
5514 | if (!DC || !DC->getParent()) | |||
5515 | return nullptr; | |||
5516 | ||||
5517 | // If the call to some member function was made from within a member | |||
5518 | // function body 'M' return return 'M's parent. | |||
5519 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
5520 | return MD->getParent()->getCanonicalDecl(); | |||
5521 | // else the call was made from within a default member initializer of a | |||
5522 | // class, so return the class. | |||
5523 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
5524 | return RD->getCanonicalDecl(); | |||
5525 | return nullptr; | |||
5526 | }; | |||
5527 | // If our DeclContext is neither a member function nor a class (in the | |||
5528 | // case of a lambda in a default member initializer), we can't have an | |||
5529 | // enclosing 'this'. | |||
5530 | ||||
5531 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | |||
5532 | if (!CurParentClass) | |||
5533 | return false; | |||
5534 | ||||
5535 | // The naming class for implicit member functions call is the class in which | |||
5536 | // name lookup starts. | |||
5537 | const CXXRecordDecl *const NamingClass = | |||
5538 | UME->getNamingClass()->getCanonicalDecl(); | |||
5539 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5539, __PRETTY_FUNCTION__)); | |||
5540 | ||||
5541 | // If the unresolved member functions were found in a 'naming class' that is | |||
5542 | // related (either the same or derived from) to the class that contains the | |||
5543 | // member function that itself contained the implicit member access. | |||
5544 | ||||
5545 | return CurParentClass == NamingClass || | |||
5546 | CurParentClass->isDerivedFrom(NamingClass); | |||
5547 | } | |||
5548 | ||||
5549 | static void | |||
5550 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
5551 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | |||
5552 | ||||
5553 | if (!UME) | |||
5554 | return; | |||
5555 | ||||
5556 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | |||
5557 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | |||
5558 | // already been captured, or if this is an implicit member function call (if | |||
5559 | // it isn't, an attempt to capture 'this' should already have been made). | |||
5560 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | |||
5561 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | |||
5562 | return; | |||
5563 | ||||
5564 | // Check if the naming class in which the unresolved members were found is | |||
5565 | // related (same as or is a base of) to the enclosing class. | |||
5566 | ||||
5567 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | |||
5568 | return; | |||
5569 | ||||
5570 | ||||
5571 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | |||
5572 | // If the enclosing function is not dependent, then this lambda is | |||
5573 | // capture ready, so if we can capture this, do so. | |||
5574 | if (!EnclosingFunctionCtx->isDependentContext()) { | |||
5575 | // If the current lambda and all enclosing lambdas can capture 'this' - | |||
5576 | // then go ahead and capture 'this' (since our unresolved overload set | |||
5577 | // contains at least one non-static member function). | |||
5578 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | |||
5579 | S.CheckCXXThisCapture(CallLoc); | |||
5580 | } else if (S.CurContext->isDependentContext()) { | |||
5581 | // ... since this is an implicit member reference, that might potentially | |||
5582 | // involve a 'this' capture, mark 'this' for potential capture in | |||
5583 | // enclosing lambdas. | |||
5584 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | |||
5585 | CurLSI->addPotentialThisCapture(CallLoc); | |||
5586 | } | |||
5587 | } | |||
5588 | ||||
5589 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
5590 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
5591 | Expr *ExecConfig) { | |||
5592 | ExprResult Call = | |||
5593 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); | |||
5594 | if (Call.isInvalid()) | |||
5595 | return Call; | |||
5596 | ||||
5597 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | |||
5598 | // language modes. | |||
5599 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | |||
5600 | if (ULE->hasExplicitTemplateArgs() && | |||
5601 | ULE->decls_begin() == ULE->decls_end()) { | |||
5602 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a | |||
5603 | ? diag::warn_cxx17_compat_adl_only_template_id | |||
5604 | : diag::ext_adl_only_template_id) | |||
5605 | << ULE->getName(); | |||
5606 | } | |||
5607 | } | |||
5608 | ||||
5609 | return Call; | |||
5610 | } | |||
5611 | ||||
5612 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | |||
5613 | /// This provides the location of the left/right parens and a list of comma | |||
5614 | /// locations. | |||
5615 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | |||
5616 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
5617 | Expr *ExecConfig, bool IsExecConfig) { | |||
5618 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
5619 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | |||
5620 | if (Result.isInvalid()) return ExprError(); | |||
5621 | Fn = Result.get(); | |||
5622 | ||||
5623 | if (checkArgsForPlaceholders(*this, ArgExprs)) | |||
5624 | return ExprError(); | |||
5625 | ||||
5626 | if (getLangOpts().CPlusPlus) { | |||
5627 | // If this is a pseudo-destructor expression, build the call immediately. | |||
5628 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | |||
5629 | if (!ArgExprs.empty()) { | |||
5630 | // Pseudo-destructor calls should not have any arguments. | |||
5631 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | |||
5632 | << FixItHint::CreateRemoval( | |||
5633 | SourceRange(ArgExprs.front()->getBeginLoc(), | |||
5634 | ArgExprs.back()->getEndLoc())); | |||
5635 | } | |||
5636 | ||||
5637 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | |||
5638 | VK_RValue, RParenLoc); | |||
5639 | } | |||
5640 | if (Fn->getType() == Context.PseudoObjectTy) { | |||
5641 | ExprResult result = CheckPlaceholderExpr(Fn); | |||
5642 | if (result.isInvalid()) return ExprError(); | |||
5643 | Fn = result.get(); | |||
5644 | } | |||
5645 | ||||
5646 | // Determine whether this is a dependent call inside a C++ template, | |||
5647 | // in which case we won't do any semantic analysis now. | |||
5648 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | |||
5649 | if (ExecConfig) { | |||
5650 | return CUDAKernelCallExpr::Create( | |||
5651 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, | |||
5652 | Context.DependentTy, VK_RValue, RParenLoc); | |||
5653 | } else { | |||
5654 | ||||
5655 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | |||
5656 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | |||
5657 | Fn->getBeginLoc()); | |||
5658 | ||||
5659 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | |||
5660 | VK_RValue, RParenLoc); | |||
5661 | } | |||
5662 | } | |||
5663 | ||||
5664 | // Determine whether this is a call to an object (C++ [over.call.object]). | |||
5665 | if (Fn->getType()->isRecordType()) | |||
5666 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | |||
5667 | RParenLoc); | |||
5668 | ||||
5669 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
5670 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
5671 | if (result.isInvalid()) return ExprError(); | |||
5672 | Fn = result.get(); | |||
5673 | } | |||
5674 | ||||
5675 | if (Fn->getType() == Context.BoundMemberTy) { | |||
5676 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
5677 | RParenLoc); | |||
5678 | } | |||
5679 | } | |||
5680 | ||||
5681 | // Check for overloaded calls. This can happen even in C due to extensions. | |||
5682 | if (Fn->getType() == Context.OverloadTy) { | |||
5683 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | |||
5684 | ||||
5685 | // We aren't supposed to apply this logic if there's an '&' involved. | |||
5686 | if (!find.HasFormOfMemberPointer) { | |||
5687 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | |||
5688 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | |||
5689 | VK_RValue, RParenLoc); | |||
5690 | OverloadExpr *ovl = find.Expression; | |||
5691 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | |||
5692 | return BuildOverloadedCallExpr( | |||
5693 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | |||
5694 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | |||
5695 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | |||
5696 | RParenLoc); | |||
5697 | } | |||
5698 | } | |||
5699 | ||||
5700 | // If we're directly calling a function, get the appropriate declaration. | |||
5701 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
5702 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | |||
5703 | if (result.isInvalid()) return ExprError(); | |||
5704 | Fn = result.get(); | |||
5705 | } | |||
5706 | ||||
5707 | Expr *NakedFn = Fn->IgnoreParens(); | |||
5708 | ||||
5709 | bool CallingNDeclIndirectly = false; | |||
5710 | NamedDecl *NDecl = nullptr; | |||
5711 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | |||
5712 | if (UnOp->getOpcode() == UO_AddrOf) { | |||
5713 | CallingNDeclIndirectly = true; | |||
5714 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | |||
5715 | } | |||
5716 | } | |||
5717 | ||||
5718 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | |||
5719 | NDecl = DRE->getDecl(); | |||
5720 | ||||
5721 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | |||
5722 | if (FDecl && FDecl->getBuiltinID()) { | |||
5723 | // Rewrite the function decl for this builtin by replacing parameters | |||
5724 | // with no explicit address space with the address space of the arguments | |||
5725 | // in ArgExprs. | |||
5726 | if ((FDecl = | |||
5727 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | |||
5728 | NDecl = FDecl; | |||
5729 | Fn = DeclRefExpr::Create( | |||
5730 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | |||
5731 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | |||
5732 | nullptr, DRE->isNonOdrUse()); | |||
5733 | } | |||
5734 | } | |||
5735 | } else if (isa<MemberExpr>(NakedFn)) | |||
5736 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | |||
5737 | ||||
5738 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | |||
5739 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | |||
5740 | FD, /*Complain=*/true, Fn->getBeginLoc())) | |||
5741 | return ExprError(); | |||
5742 | ||||
5743 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) | |||
5744 | return ExprError(); | |||
5745 | ||||
5746 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | |||
5747 | } | |||
5748 | ||||
5749 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | |||
5750 | ExecConfig, IsExecConfig); | |||
5751 | } | |||
5752 | ||||
5753 | /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. | |||
5754 | /// | |||
5755 | /// __builtin_astype( value, dst type ) | |||
5756 | /// | |||
5757 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | |||
5758 | SourceLocation BuiltinLoc, | |||
5759 | SourceLocation RParenLoc) { | |||
5760 | ExprValueKind VK = VK_RValue; | |||
5761 | ExprObjectKind OK = OK_Ordinary; | |||
5762 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | |||
5763 | QualType SrcTy = E->getType(); | |||
5764 | if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) | |||
5765 | return ExprError(Diag(BuiltinLoc, | |||
5766 | diag::err_invalid_astype_of_different_size) | |||
5767 | << DstTy | |||
5768 | << SrcTy | |||
5769 | << E->getSourceRange()); | |||
5770 | return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); | |||
5771 | } | |||
5772 | ||||
5773 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | |||
5774 | /// provided arguments. | |||
5775 | /// | |||
5776 | /// __builtin_convertvector( value, dst type ) | |||
5777 | /// | |||
5778 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | |||
5779 | SourceLocation BuiltinLoc, | |||
5780 | SourceLocation RParenLoc) { | |||
5781 | TypeSourceInfo *TInfo; | |||
5782 | GetTypeFromParser(ParsedDestTy, &TInfo); | |||
5783 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | |||
5784 | } | |||
5785 | ||||
5786 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | |||
5787 | /// i.e. an expression not of \p OverloadTy. The expression should | |||
5788 | /// unary-convert to an expression of function-pointer or | |||
5789 | /// block-pointer type. | |||
5790 | /// | |||
5791 | /// \param NDecl the declaration being called, if available | |||
5792 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | |||
5793 | SourceLocation LParenLoc, | |||
5794 | ArrayRef<Expr *> Args, | |||
5795 | SourceLocation RParenLoc, Expr *Config, | |||
5796 | bool IsExecConfig, ADLCallKind UsesADL) { | |||
5797 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | |||
| ||||
5798 | unsigned BuiltinID = (FDecl
| |||
5799 | ||||
5800 | // Functions with 'interrupt' attribute cannot be called directly. | |||
5801 | if (FDecl
| |||
5802 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | |||
5803 | return ExprError(); | |||
5804 | } | |||
5805 | ||||
5806 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | |||
5807 | // so there's some risk when calling out to non-interrupt handler functions | |||
5808 | // that the callee might not preserve them. This is easy to diagnose here, | |||
5809 | // but can be very challenging to debug. | |||
5810 | if (auto *Caller = getCurFunctionDecl()) | |||
5811 | if (Caller->hasAttr<ARMInterruptAttr>()) { | |||
5812 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | |||
5813 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) | |||
5814 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | |||
5815 | } | |||
5816 | ||||
5817 | // Promote the function operand. | |||
5818 | // We special-case function promotion here because we only allow promoting | |||
5819 | // builtin functions to function pointers in the callee of a call. | |||
5820 | ExprResult Result; | |||
5821 | QualType ResultTy; | |||
5822 | if (BuiltinID
| |||
5823 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | |||
5824 | // Extract the return type from the (builtin) function pointer type. | |||
5825 | // FIXME Several builtins still have setType in | |||
5826 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | |||
5827 | // Builtins.def to ensure they are correct before removing setType calls. | |||
5828 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | |||
5829 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | |||
5830 | ResultTy = FDecl->getCallResultType(); | |||
5831 | } else { | |||
5832 | Result = CallExprUnaryConversions(Fn); | |||
5833 | ResultTy = Context.BoolTy; | |||
5834 | } | |||
5835 | if (Result.isInvalid()) | |||
5836 | return ExprError(); | |||
5837 | Fn = Result.get(); | |||
5838 | ||||
5839 | // Check for a valid function type, but only if it is not a builtin which | |||
5840 | // requires custom type checking. These will be handled by | |||
5841 | // CheckBuiltinFunctionCall below just after creation of the call expression. | |||
5842 | const FunctionType *FuncT = nullptr; | |||
5843 | if (!BuiltinID
| |||
5844 | retry: | |||
5845 | if (const PointerType *PT
| |||
5846 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | |||
5847 | // have type pointer to function". | |||
5848 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | |||
5849 | if (!FuncT) | |||
5850 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
5851 | << Fn->getType() << Fn->getSourceRange()); | |||
5852 | } else if (const BlockPointerType *BPT = | |||
5853 | Fn->getType()->getAs<BlockPointerType>()) { | |||
5854 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | |||
5855 | } else { | |||
5856 | // Handle calls to expressions of unknown-any type. | |||
5857 | if (Fn->getType() == Context.UnknownAnyTy) { | |||
5858 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | |||
5859 | if (rewrite.isInvalid()) | |||
5860 | return ExprError(); | |||
5861 | Fn = rewrite.get(); | |||
5862 | goto retry; | |||
5863 | } | |||
5864 | ||||
5865 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | |||
5866 | << Fn->getType() << Fn->getSourceRange()); | |||
5867 | } | |||
5868 | } | |||
5869 | ||||
5870 | // Get the number of parameters in the function prototype, if any. | |||
5871 | // We will allocate space for max(Args.size(), NumParams) arguments | |||
5872 | // in the call expression. | |||
5873 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | |||
5874 | unsigned NumParams = Proto
| |||
5875 | ||||
5876 | CallExpr *TheCall; | |||
5877 | if (Config) { | |||
5878 | 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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5879, __PRETTY_FUNCTION__)) | |||
5879 | "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-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExpr.cpp" , 5879, __PRETTY_FUNCTION__)); | |||
5880 | TheCall = | |||
5881 | CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, | |||
5882 | ResultTy, VK_RValue, RParenLoc, NumParams); | |||
5883 | } else { | |||
5884 | TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, | |||
5885 | RParenLoc, NumParams, UsesADL); | |||
5886 | } | |||
5887 | ||||
5888 | if (!getLangOpts().CPlusPlus) { | |||
5889 | // Forget about the nulled arguments since typo correction | |||
5890 | // do not handle them well. | |||
5891 | TheCall->shrinkNumArgs(Args.size()); | |||
5892 | // C cannot always handle TypoExpr nodes in builtin calls and direct | |||
5893 | // function calls as their argument checking don't necessarily handle | |||
5894 | // dependent types properly, so make sure any TypoExprs have been | |||
5895 | // dealt with. | |||
5896 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | |||
5897 | if (!Result.isUsable()) return ExprError(); | |||
5898 | CallExpr *TheOldCall = TheCall; | |||
5899 | TheCall = dyn_cast<CallExpr>(Result.get()); | |||
5900 | bool CorrectedTypos = TheCall != TheOldCall; | |||
5901 | if (!TheCall) return Result; | |||
5902 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | |||
5903 | ||||
5904 | // A new call expression node was created if some typos were corrected. | |||
5905 | // However it may not have been constructed with enough storage. In this | |||
5906 | // case, rebuild the node with enough storage. The waste of space is | |||
5907 | // immaterial since this only happens when some typos were corrected. | |||
5908 | if (CorrectedTypos && Args.size() < NumParams) { | |||
5909 | if (Config) | |||
5910 | TheCall = CUDAKernelCallExpr::Create( | |||
5911 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, | |||
5912 | RParenLoc, NumParams); | |||
5913 | else | |||
5914 | TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, | |||
5915 | RParenLoc, NumParams, UsesADL); | |||
5916 | } | |||
5917 | // We can now handle the nulled arguments for the default arguments. | |||
5918 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | |||
5919 | } | |||
5920 | ||||
5921 | // Bail out early if calling a builtin with custom type checking. | |||
5922 | if (BuiltinID
| |||
5923 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | |||
5924 | ||||
5925 | if (getLangOpts().CUDA) { | |||
5926 | if (Config) { | |||
5927 | // CUDA: Kernel calls must be to global functions | |||
5928 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) | |||
5929 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | |||
5930 | << FDecl << Fn->getSourceRange()); | |||
5931 | ||||
5932 | // CUDA: Kernel function must have 'void' return type | |||
5933 | if (!FuncT->getReturnType()->isVoidType() && | |||
5934 | !FuncT->getReturnType()->getAs<AutoType>() && | |||
5935 | !FuncT->getReturnType()->isInstantiationD |