1 | //===--- Expr.cpp - Expression AST Node Implementation --------------------===// |
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 the Expr class and subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "clang/AST/Expr.h" |
14 | #include "clang/AST/APValue.h" |
15 | #include "clang/AST/ASTContext.h" |
16 | #include "clang/AST/Attr.h" |
17 | #include "clang/AST/ComputeDependence.h" |
18 | #include "clang/AST/DeclCXX.h" |
19 | #include "clang/AST/DeclObjC.h" |
20 | #include "clang/AST/DeclTemplate.h" |
21 | #include "clang/AST/DependenceFlags.h" |
22 | #include "clang/AST/EvaluatedExprVisitor.h" |
23 | #include "clang/AST/ExprCXX.h" |
24 | #include "clang/AST/IgnoreExpr.h" |
25 | #include "clang/AST/Mangle.h" |
26 | #include "clang/AST/RecordLayout.h" |
27 | #include "clang/AST/StmtVisitor.h" |
28 | #include "clang/Basic/Builtins.h" |
29 | #include "clang/Basic/CharInfo.h" |
30 | #include "clang/Basic/SourceManager.h" |
31 | #include "clang/Basic/TargetInfo.h" |
32 | #include "clang/Lex/Lexer.h" |
33 | #include "clang/Lex/LiteralSupport.h" |
34 | #include "clang/Lex/Preprocessor.h" |
35 | #include "llvm/Support/ErrorHandling.h" |
36 | #include "llvm/Support/Format.h" |
37 | #include "llvm/Support/raw_ostream.h" |
38 | #include <algorithm> |
39 | #include <cstring> |
40 | #include <optional> |
41 | using namespace clang; |
42 | |
43 | const Expr *Expr::getBestDynamicClassTypeExpr() const { |
44 | const Expr *E = this; |
45 | while (true) { |
46 | E = E->IgnoreParenBaseCasts(); |
47 | |
48 | // Follow the RHS of a comma operator. |
49 | if (auto *BO = dyn_cast<BinaryOperator>(Val: E)) { |
50 | if (BO->getOpcode() == BO_Comma) { |
51 | E = BO->getRHS(); |
52 | continue; |
53 | } |
54 | } |
55 | |
56 | // Step into initializer for materialized temporaries. |
57 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) { |
58 | E = MTE->getSubExpr(); |
59 | continue; |
60 | } |
61 | |
62 | break; |
63 | } |
64 | |
65 | return E; |
66 | } |
67 | |
68 | const CXXRecordDecl *Expr::getBestDynamicClassType() const { |
69 | const Expr *E = getBestDynamicClassTypeExpr(); |
70 | QualType DerivedType = E->getType(); |
71 | if (const PointerType *PTy = DerivedType->getAs<PointerType>()) |
72 | DerivedType = PTy->getPointeeType(); |
73 | |
74 | if (DerivedType->isDependentType()) |
75 | return nullptr; |
76 | |
77 | const RecordType *Ty = DerivedType->castAs<RecordType>(); |
78 | Decl *D = Ty->getDecl(); |
79 | return cast<CXXRecordDecl>(Val: D); |
80 | } |
81 | |
82 | const Expr *Expr::skipRValueSubobjectAdjustments( |
83 | SmallVectorImpl<const Expr *> &CommaLHSs, |
84 | SmallVectorImpl<SubobjectAdjustment> &Adjustments) const { |
85 | const Expr *E = this; |
86 | while (true) { |
87 | E = E->IgnoreParens(); |
88 | |
89 | if (const auto *CE = dyn_cast<CastExpr>(Val: E)) { |
90 | if ((CE->getCastKind() == CK_DerivedToBase || |
91 | CE->getCastKind() == CK_UncheckedDerivedToBase) && |
92 | E->getType()->isRecordType()) { |
93 | E = CE->getSubExpr(); |
94 | const auto *Derived = |
95 | cast<CXXRecordDecl>(Val: E->getType()->castAs<RecordType>()->getDecl()); |
96 | Adjustments.push_back(Elt: SubobjectAdjustment(CE, Derived)); |
97 | continue; |
98 | } |
99 | |
100 | if (CE->getCastKind() == CK_NoOp) { |
101 | E = CE->getSubExpr(); |
102 | continue; |
103 | } |
104 | } else if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) { |
105 | if (!ME->isArrow()) { |
106 | assert(ME->getBase()->getType()->isRecordType()); |
107 | if (const auto *Field = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) { |
108 | if (!Field->isBitField() && !Field->getType()->isReferenceType()) { |
109 | E = ME->getBase(); |
110 | Adjustments.push_back(Elt: SubobjectAdjustment(Field)); |
111 | continue; |
112 | } |
113 | } |
114 | } |
115 | } else if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) { |
116 | if (BO->getOpcode() == BO_PtrMemD) { |
117 | assert(BO->getRHS()->isPRValue()); |
118 | E = BO->getLHS(); |
119 | const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>(); |
120 | Adjustments.push_back(Elt: SubobjectAdjustment(MPT, BO->getRHS())); |
121 | continue; |
122 | } |
123 | if (BO->getOpcode() == BO_Comma) { |
124 | CommaLHSs.push_back(Elt: BO->getLHS()); |
125 | E = BO->getRHS(); |
126 | continue; |
127 | } |
128 | } |
129 | |
130 | // Nothing changed. |
131 | break; |
132 | } |
133 | return E; |
134 | } |
135 | |
136 | bool Expr::isKnownToHaveBooleanValue(bool Semantic) const { |
137 | const Expr *E = IgnoreParens(); |
138 | |
139 | // If this value has _Bool type, it is obvious 0/1. |
140 | if (E->getType()->isBooleanType()) return true; |
141 | // If this is a non-scalar-integer type, we don't care enough to try. |
142 | if (!E->getType()->isIntegralOrEnumerationType()) return false; |
143 | |
144 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) { |
145 | switch (UO->getOpcode()) { |
146 | case UO_Plus: |
147 | return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic); |
148 | case UO_LNot: |
149 | return true; |
150 | default: |
151 | return false; |
152 | } |
153 | } |
154 | |
155 | // Only look through implicit casts. If the user writes |
156 | // '(int) (a && b)' treat it as an arbitrary int. |
157 | // FIXME: Should we look through any cast expression in !Semantic mode? |
158 | if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Val: E)) |
159 | return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic); |
160 | |
161 | if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
162 | switch (BO->getOpcode()) { |
163 | default: return false; |
164 | case BO_LT: // Relational operators. |
165 | case BO_GT: |
166 | case BO_LE: |
167 | case BO_GE: |
168 | case BO_EQ: // Equality operators. |
169 | case BO_NE: |
170 | case BO_LAnd: // AND operator. |
171 | case BO_LOr: // Logical OR operator. |
172 | return true; |
173 | |
174 | case BO_And: // Bitwise AND operator. |
175 | case BO_Xor: // Bitwise XOR operator. |
176 | case BO_Or: // Bitwise OR operator. |
177 | // Handle things like (x==2)|(y==12). |
178 | return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) && |
179 | BO->getRHS()->isKnownToHaveBooleanValue(Semantic); |
180 | |
181 | case BO_Comma: |
182 | case BO_Assign: |
183 | return BO->getRHS()->isKnownToHaveBooleanValue(Semantic); |
184 | } |
185 | } |
186 | |
187 | if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) |
188 | return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) && |
189 | CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic); |
190 | |
191 | if (isa<ObjCBoolLiteralExpr>(Val: E)) |
192 | return true; |
193 | |
194 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) |
195 | return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic); |
196 | |
197 | if (const FieldDecl *FD = E->getSourceBitField()) |
198 | if (!Semantic && FD->getType()->isUnsignedIntegerType() && |
199 | !FD->getBitWidth()->isValueDependent() && |
200 | FD->getBitWidthValue(Ctx: FD->getASTContext()) == 1) |
201 | return true; |
202 | |
203 | return false; |
204 | } |
205 | |
206 | bool Expr::isFlexibleArrayMemberLike( |
207 | ASTContext &Ctx, |
208 | LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, |
209 | bool IgnoreTemplateOrMacroSubstitution) const { |
210 | const Expr *E = IgnoreParens(); |
211 | const Decl *D = nullptr; |
212 | |
213 | if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) |
214 | D = ME->getMemberDecl(); |
215 | else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
216 | D = DRE->getDecl(); |
217 | else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(Val: E)) |
218 | D = IRE->getDecl(); |
219 | |
220 | return Decl::isFlexibleArrayMemberLike(Context&: Ctx, D, Ty: E->getType(), |
221 | StrictFlexArraysLevel, |
222 | IgnoreTemplateOrMacroSubstitution); |
223 | } |
224 | |
225 | const ValueDecl * |
226 | Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const { |
227 | Expr::EvalResult Eval; |
228 | |
229 | if (EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) { |
230 | APValue &Value = Eval.Val; |
231 | |
232 | if (Value.isMemberPointer()) |
233 | return Value.getMemberPointerDecl(); |
234 | |
235 | if (Value.isLValue() && Value.getLValueOffset().isZero()) |
236 | return Value.getLValueBase().dyn_cast<const ValueDecl *>(); |
237 | } |
238 | |
239 | return nullptr; |
240 | } |
241 | |
242 | // Amusing macro metaprogramming hack: check whether a class provides |
243 | // a more specific implementation of getExprLoc(). |
244 | // |
245 | // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}. |
246 | namespace { |
247 | /// This implementation is used when a class provides a custom |
248 | /// implementation of getExprLoc. |
249 | template <class E, class T> |
250 | SourceLocation getExprLocImpl(const Expr *expr, |
251 | SourceLocation (T::*v)() const) { |
252 | return static_cast<const E*>(expr)->getExprLoc(); |
253 | } |
254 | |
255 | /// This implementation is used when a class doesn't provide |
256 | /// a custom implementation of getExprLoc. Overload resolution |
257 | /// should pick it over the implementation above because it's |
258 | /// more specialized according to function template partial ordering. |
259 | template <class E> |
260 | SourceLocation getExprLocImpl(const Expr *expr, |
261 | SourceLocation (Expr::*v)() const) { |
262 | return static_cast<const E *>(expr)->getBeginLoc(); |
263 | } |
264 | } |
265 | |
266 | QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const { |
267 | if (isa<EnumType>(Val: getType())) |
268 | return getType(); |
269 | if (const auto *ECD = getEnumConstantDecl()) { |
270 | const auto *ED = cast<EnumDecl>(ECD->getDeclContext()); |
271 | if (ED->isCompleteDefinition()) |
272 | return Ctx.getTypeDeclType(Decl: ED); |
273 | } |
274 | return getType(); |
275 | } |
276 | |
277 | SourceLocation Expr::getExprLoc() const { |
278 | switch (getStmtClass()) { |
279 | case Stmt::NoStmtClass: llvm_unreachable("statement without class" ); |
280 | #define ABSTRACT_STMT(type) |
281 | #define STMT(type, base) \ |
282 | case Stmt::type##Class: break; |
283 | #define EXPR(type, base) \ |
284 | case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc); |
285 | #include "clang/AST/StmtNodes.inc" |
286 | } |
287 | llvm_unreachable("unknown expression kind" ); |
288 | } |
289 | |
290 | //===----------------------------------------------------------------------===// |
291 | // Primary Expressions. |
292 | //===----------------------------------------------------------------------===// |
293 | |
294 | static void AssertResultStorageKind(ConstantResultStorageKind Kind) { |
295 | assert((Kind == ConstantResultStorageKind::APValue || |
296 | Kind == ConstantResultStorageKind::Int64 || |
297 | Kind == ConstantResultStorageKind::None) && |
298 | "Invalid StorageKind Value" ); |
299 | (void)Kind; |
300 | } |
301 | |
302 | ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) { |
303 | switch (Value.getKind()) { |
304 | case APValue::None: |
305 | case APValue::Indeterminate: |
306 | return ConstantResultStorageKind::None; |
307 | case APValue::Int: |
308 | if (!Value.getInt().needsCleanup()) |
309 | return ConstantResultStorageKind::Int64; |
310 | [[fallthrough]]; |
311 | default: |
312 | return ConstantResultStorageKind::APValue; |
313 | } |
314 | } |
315 | |
316 | ConstantResultStorageKind |
317 | ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) { |
318 | if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64) |
319 | return ConstantResultStorageKind::Int64; |
320 | return ConstantResultStorageKind::APValue; |
321 | } |
322 | |
323 | ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind, |
324 | bool IsImmediateInvocation) |
325 | : FullExpr(ConstantExprClass, SubExpr) { |
326 | ConstantExprBits.ResultKind = llvm::to_underlying(E: StorageKind); |
327 | ConstantExprBits.APValueKind = APValue::None; |
328 | ConstantExprBits.IsUnsigned = false; |
329 | ConstantExprBits.BitWidth = 0; |
330 | ConstantExprBits.HasCleanup = false; |
331 | ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation; |
332 | |
333 | if (StorageKind == ConstantResultStorageKind::APValue) |
334 | ::new (getTrailingObjects<APValue>()) APValue(); |
335 | } |
336 | |
337 | ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E, |
338 | ConstantResultStorageKind StorageKind, |
339 | bool IsImmediateInvocation) { |
340 | assert(!isa<ConstantExpr>(E)); |
341 | AssertResultStorageKind(Kind: StorageKind); |
342 | |
343 | unsigned Size = totalSizeToAlloc<APValue, uint64_t>( |
344 | Counts: StorageKind == ConstantResultStorageKind::APValue, |
345 | Counts: StorageKind == ConstantResultStorageKind::Int64); |
346 | void *Mem = Context.Allocate(Size, Align: alignof(ConstantExpr)); |
347 | return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation); |
348 | } |
349 | |
350 | ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E, |
351 | const APValue &Result) { |
352 | ConstantResultStorageKind StorageKind = getStorageKind(Value: Result); |
353 | ConstantExpr *Self = Create(Context, E, StorageKind); |
354 | Self->SetResult(Value: Result, Context); |
355 | return Self; |
356 | } |
357 | |
358 | ConstantExpr::ConstantExpr(EmptyShell Empty, |
359 | ConstantResultStorageKind StorageKind) |
360 | : FullExpr(ConstantExprClass, Empty) { |
361 | ConstantExprBits.ResultKind = llvm::to_underlying(E: StorageKind); |
362 | |
363 | if (StorageKind == ConstantResultStorageKind::APValue) |
364 | ::new (getTrailingObjects<APValue>()) APValue(); |
365 | } |
366 | |
367 | ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context, |
368 | ConstantResultStorageKind StorageKind) { |
369 | AssertResultStorageKind(Kind: StorageKind); |
370 | |
371 | unsigned Size = totalSizeToAlloc<APValue, uint64_t>( |
372 | Counts: StorageKind == ConstantResultStorageKind::APValue, |
373 | Counts: StorageKind == ConstantResultStorageKind::Int64); |
374 | void *Mem = Context.Allocate(Size, Align: alignof(ConstantExpr)); |
375 | return new (Mem) ConstantExpr(EmptyShell(), StorageKind); |
376 | } |
377 | |
378 | void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) { |
379 | assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind && |
380 | "Invalid storage for this value kind" ); |
381 | ConstantExprBits.APValueKind = Value.getKind(); |
382 | switch (getResultStorageKind()) { |
383 | case ConstantResultStorageKind::None: |
384 | return; |
385 | case ConstantResultStorageKind::Int64: |
386 | Int64Result() = *Value.getInt().getRawData(); |
387 | ConstantExprBits.BitWidth = Value.getInt().getBitWidth(); |
388 | ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned(); |
389 | return; |
390 | case ConstantResultStorageKind::APValue: |
391 | if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) { |
392 | ConstantExprBits.HasCleanup = true; |
393 | Context.addDestruction(Ptr: &APValueResult()); |
394 | } |
395 | APValueResult() = std::move(Value); |
396 | return; |
397 | } |
398 | llvm_unreachable("Invalid ResultKind Bits" ); |
399 | } |
400 | |
401 | llvm::APSInt ConstantExpr::getResultAsAPSInt() const { |
402 | switch (getResultStorageKind()) { |
403 | case ConstantResultStorageKind::APValue: |
404 | return APValueResult().getInt(); |
405 | case ConstantResultStorageKind::Int64: |
406 | return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()), |
407 | ConstantExprBits.IsUnsigned); |
408 | default: |
409 | llvm_unreachable("invalid Accessor" ); |
410 | } |
411 | } |
412 | |
413 | APValue ConstantExpr::getAPValueResult() const { |
414 | |
415 | switch (getResultStorageKind()) { |
416 | case ConstantResultStorageKind::APValue: |
417 | return APValueResult(); |
418 | case ConstantResultStorageKind::Int64: |
419 | return APValue( |
420 | llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()), |
421 | ConstantExprBits.IsUnsigned)); |
422 | case ConstantResultStorageKind::None: |
423 | if (ConstantExprBits.APValueKind == APValue::Indeterminate) |
424 | return APValue::IndeterminateValue(); |
425 | return APValue(); |
426 | } |
427 | llvm_unreachable("invalid ResultKind" ); |
428 | } |
429 | |
430 | DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, |
431 | bool RefersToEnclosingVariableOrCapture, QualType T, |
432 | ExprValueKind VK, SourceLocation L, |
433 | const DeclarationNameLoc &LocInfo, |
434 | NonOdrUseReason NOUR) |
435 | : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) { |
436 | DeclRefExprBits.HasQualifier = false; |
437 | DeclRefExprBits.HasTemplateKWAndArgsInfo = false; |
438 | DeclRefExprBits.HasFoundDecl = false; |
439 | DeclRefExprBits.HadMultipleCandidates = false; |
440 | DeclRefExprBits.RefersToEnclosingVariableOrCapture = |
441 | RefersToEnclosingVariableOrCapture; |
442 | DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false; |
443 | DeclRefExprBits.NonOdrUseReason = NOUR; |
444 | DeclRefExprBits.IsImmediateEscalating = false; |
445 | DeclRefExprBits.Loc = L; |
446 | setDependence(computeDependence(E: this, Ctx)); |
447 | } |
448 | |
449 | DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, |
450 | NestedNameSpecifierLoc QualifierLoc, |
451 | SourceLocation TemplateKWLoc, ValueDecl *D, |
452 | bool RefersToEnclosingVariableOrCapture, |
453 | const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, |
454 | const TemplateArgumentListInfo *TemplateArgs, |
455 | QualType T, ExprValueKind VK, NonOdrUseReason NOUR) |
456 | : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), |
457 | DNLoc(NameInfo.getInfo()) { |
458 | DeclRefExprBits.Loc = NameInfo.getLoc(); |
459 | DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0; |
460 | if (QualifierLoc) |
461 | new (getTrailingObjects<NestedNameSpecifierLoc>()) |
462 | NestedNameSpecifierLoc(QualifierLoc); |
463 | DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0; |
464 | if (FoundD) |
465 | *getTrailingObjects<NamedDecl *>() = FoundD; |
466 | DeclRefExprBits.HasTemplateKWAndArgsInfo |
467 | = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0; |
468 | DeclRefExprBits.RefersToEnclosingVariableOrCapture = |
469 | RefersToEnclosingVariableOrCapture; |
470 | DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false; |
471 | DeclRefExprBits.NonOdrUseReason = NOUR; |
472 | if (TemplateArgs) { |
473 | auto Deps = TemplateArgumentDependence::None; |
474 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom( |
475 | TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(), |
476 | Deps); |
477 | assert(!(Deps & TemplateArgumentDependence::Dependent) && |
478 | "built a DeclRefExpr with dependent template args" ); |
479 | } else if (TemplateKWLoc.isValid()) { |
480 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom( |
481 | TemplateKWLoc); |
482 | } |
483 | DeclRefExprBits.IsImmediateEscalating = false; |
484 | DeclRefExprBits.HadMultipleCandidates = 0; |
485 | setDependence(computeDependence(E: this, Ctx)); |
486 | } |
487 | |
488 | DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context, |
489 | NestedNameSpecifierLoc QualifierLoc, |
490 | SourceLocation TemplateKWLoc, ValueDecl *D, |
491 | bool RefersToEnclosingVariableOrCapture, |
492 | SourceLocation NameLoc, QualType T, |
493 | ExprValueKind VK, NamedDecl *FoundD, |
494 | const TemplateArgumentListInfo *TemplateArgs, |
495 | NonOdrUseReason NOUR) { |
496 | return Create(Context, QualifierLoc, TemplateKWLoc, D, |
497 | RefersToEnclosingVariableOrCapture, |
498 | NameInfo: DeclarationNameInfo(D->getDeclName(), NameLoc), |
499 | T, VK, FoundD, TemplateArgs, NOUR); |
500 | } |
501 | |
502 | DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context, |
503 | NestedNameSpecifierLoc QualifierLoc, |
504 | SourceLocation TemplateKWLoc, ValueDecl *D, |
505 | bool RefersToEnclosingVariableOrCapture, |
506 | const DeclarationNameInfo &NameInfo, |
507 | QualType T, ExprValueKind VK, |
508 | NamedDecl *FoundD, |
509 | const TemplateArgumentListInfo *TemplateArgs, |
510 | NonOdrUseReason NOUR) { |
511 | // Filter out cases where the found Decl is the same as the value refenenced. |
512 | if (D == FoundD) |
513 | FoundD = nullptr; |
514 | |
515 | bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid(); |
516 | std::size_t Size = |
517 | totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *, |
518 | ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>( |
519 | Counts: QualifierLoc ? 1 : 0, Counts: FoundD ? 1 : 0, |
520 | Counts: HasTemplateKWAndArgsInfo ? 1 : 0, |
521 | Counts: TemplateArgs ? TemplateArgs->size() : 0); |
522 | |
523 | void *Mem = Context.Allocate(Size, Align: alignof(DeclRefExpr)); |
524 | return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D, |
525 | RefersToEnclosingVariableOrCapture, NameInfo, |
526 | FoundD, TemplateArgs, T, VK, NOUR); |
527 | } |
528 | |
529 | DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context, |
530 | bool HasQualifier, |
531 | bool HasFoundDecl, |
532 | bool HasTemplateKWAndArgsInfo, |
533 | unsigned NumTemplateArgs) { |
534 | assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo); |
535 | std::size_t Size = |
536 | totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *, |
537 | ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>( |
538 | Counts: HasQualifier ? 1 : 0, Counts: HasFoundDecl ? 1 : 0, Counts: HasTemplateKWAndArgsInfo, |
539 | Counts: NumTemplateArgs); |
540 | void *Mem = Context.Allocate(Size, Align: alignof(DeclRefExpr)); |
541 | return new (Mem) DeclRefExpr(EmptyShell()); |
542 | } |
543 | |
544 | void DeclRefExpr::setDecl(ValueDecl *NewD) { |
545 | D = NewD; |
546 | if (getType()->isUndeducedType()) |
547 | setType(NewD->getType()); |
548 | setDependence(computeDependence(this, NewD->getASTContext())); |
549 | } |
550 | |
551 | SourceLocation DeclRefExpr::getBeginLoc() const { |
552 | if (hasQualifier()) |
553 | return getQualifierLoc().getBeginLoc(); |
554 | return getNameInfo().getBeginLoc(); |
555 | } |
556 | SourceLocation DeclRefExpr::getEndLoc() const { |
557 | if (hasExplicitTemplateArgs()) |
558 | return getRAngleLoc(); |
559 | return getNameInfo().getEndLoc(); |
560 | } |
561 | |
562 | SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc, |
563 | SourceLocation LParen, |
564 | SourceLocation RParen, |
565 | QualType ResultTy, |
566 | TypeSourceInfo *TSI) |
567 | : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary), |
568 | OpLoc(OpLoc), LParen(LParen), RParen(RParen) { |
569 | setTypeSourceInfo(TSI); |
570 | setDependence(computeDependence(E: this)); |
571 | } |
572 | |
573 | SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty, |
574 | QualType ResultTy) |
575 | : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {} |
576 | |
577 | SYCLUniqueStableNameExpr * |
578 | SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc, |
579 | SourceLocation LParen, SourceLocation RParen, |
580 | TypeSourceInfo *TSI) { |
581 | QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst()); |
582 | return new (Ctx) |
583 | SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI); |
584 | } |
585 | |
586 | SYCLUniqueStableNameExpr * |
587 | SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) { |
588 | QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst()); |
589 | return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy); |
590 | } |
591 | |
592 | std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const { |
593 | return SYCLUniqueStableNameExpr::ComputeName(Context, |
594 | Ty: getTypeSourceInfo()->getType()); |
595 | } |
596 | |
597 | std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context, |
598 | QualType Ty) { |
599 | auto MangleCallback = [](ASTContext &Ctx, |
600 | const NamedDecl *ND) -> std::optional<unsigned> { |
601 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND)) |
602 | return RD->getDeviceLambdaManglingNumber(); |
603 | return std::nullopt; |
604 | }; |
605 | |
606 | std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create( |
607 | Context, Diags&: Context.getDiagnostics(), Discriminator: MangleCallback)}; |
608 | |
609 | std::string Buffer; |
610 | Buffer.reserve(res: 128); |
611 | llvm::raw_string_ostream Out(Buffer); |
612 | Ctx->mangleCanonicalTypeName(T: Ty, Out); |
613 | |
614 | return Out.str(); |
615 | } |
616 | |
617 | PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, |
618 | PredefinedIdentKind IK, bool IsTransparent, |
619 | StringLiteral *SL) |
620 | : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) { |
621 | PredefinedExprBits.Kind = llvm::to_underlying(E: IK); |
622 | assert((getIdentKind() == IK) && |
623 | "IdentKind do not fit in PredefinedExprBitfields!" ); |
624 | bool HasFunctionName = SL != nullptr; |
625 | PredefinedExprBits.HasFunctionName = HasFunctionName; |
626 | PredefinedExprBits.IsTransparent = IsTransparent; |
627 | PredefinedExprBits.Loc = L; |
628 | if (HasFunctionName) |
629 | setFunctionName(SL); |
630 | setDependence(computeDependence(E: this)); |
631 | } |
632 | |
633 | PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName) |
634 | : Expr(PredefinedExprClass, Empty) { |
635 | PredefinedExprBits.HasFunctionName = HasFunctionName; |
636 | } |
637 | |
638 | PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L, |
639 | QualType FNTy, PredefinedIdentKind IK, |
640 | bool IsTransparent, StringLiteral *SL) { |
641 | bool HasFunctionName = SL != nullptr; |
642 | void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: HasFunctionName), |
643 | Align: alignof(PredefinedExpr)); |
644 | return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL); |
645 | } |
646 | |
647 | PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx, |
648 | bool HasFunctionName) { |
649 | void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: HasFunctionName), |
650 | Align: alignof(PredefinedExpr)); |
651 | return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName); |
652 | } |
653 | |
654 | StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) { |
655 | switch (IK) { |
656 | case PredefinedIdentKind::Func: |
657 | return "__func__" ; |
658 | case PredefinedIdentKind::Function: |
659 | return "__FUNCTION__" ; |
660 | case PredefinedIdentKind::FuncDName: |
661 | return "__FUNCDNAME__" ; |
662 | case PredefinedIdentKind::LFunction: |
663 | return "L__FUNCTION__" ; |
664 | case PredefinedIdentKind::PrettyFunction: |
665 | return "__PRETTY_FUNCTION__" ; |
666 | case PredefinedIdentKind::FuncSig: |
667 | return "__FUNCSIG__" ; |
668 | case PredefinedIdentKind::LFuncSig: |
669 | return "L__FUNCSIG__" ; |
670 | case PredefinedIdentKind::PrettyFunctionNoVirtual: |
671 | break; |
672 | } |
673 | llvm_unreachable("Unknown ident kind for PredefinedExpr" ); |
674 | } |
675 | |
676 | // FIXME: Maybe this should use DeclPrinter with a special "print predefined |
677 | // expr" policy instead. |
678 | std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK, |
679 | const Decl *CurrentDecl, |
680 | bool ForceElaboratedPrinting) { |
681 | ASTContext &Context = CurrentDecl->getASTContext(); |
682 | |
683 | if (IK == PredefinedIdentKind::FuncDName) { |
684 | if (const NamedDecl *ND = dyn_cast<NamedDecl>(Val: CurrentDecl)) { |
685 | std::unique_ptr<MangleContext> MC; |
686 | MC.reset(p: Context.createMangleContext()); |
687 | |
688 | if (MC->shouldMangleDeclName(D: ND)) { |
689 | SmallString<256> Buffer; |
690 | llvm::raw_svector_ostream Out(Buffer); |
691 | GlobalDecl GD; |
692 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: ND)) |
693 | GD = GlobalDecl(CD, Ctor_Base); |
694 | else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Val: ND)) |
695 | GD = GlobalDecl(DD, Dtor_Base); |
696 | else if (ND->hasAttr<CUDAGlobalAttr>()) |
697 | GD = GlobalDecl(cast<FunctionDecl>(Val: ND)); |
698 | else |
699 | GD = GlobalDecl(ND); |
700 | MC->mangleName(GD, Out); |
701 | |
702 | if (!Buffer.empty() && Buffer.front() == '\01') |
703 | return std::string(Buffer.substr(Start: 1)); |
704 | return std::string(Buffer); |
705 | } |
706 | return std::string(ND->getIdentifier()->getName()); |
707 | } |
708 | return "" ; |
709 | } |
710 | if (isa<BlockDecl>(Val: CurrentDecl)) { |
711 | // For blocks we only emit something if it is enclosed in a function |
712 | // For top-level block we'd like to include the name of variable, but we |
713 | // don't have it at this point. |
714 | auto DC = CurrentDecl->getDeclContext(); |
715 | if (DC->isFileContext()) |
716 | return "" ; |
717 | |
718 | SmallString<256> Buffer; |
719 | llvm::raw_svector_ostream Out(Buffer); |
720 | if (auto *DCBlock = dyn_cast<BlockDecl>(Val: DC)) |
721 | // For nested blocks, propagate up to the parent. |
722 | Out << ComputeName(IK, DCBlock); |
723 | else if (auto *DCDecl = dyn_cast<Decl>(Val: DC)) |
724 | Out << ComputeName(IK, CurrentDecl: DCDecl) << "_block_invoke" ; |
725 | return std::string(Out.str()); |
726 | } |
727 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CurrentDecl)) { |
728 | const auto &LO = Context.getLangOpts(); |
729 | bool IsFuncOrFunctionInNonMSVCCompatEnv = |
730 | ((IK == PredefinedIdentKind::Func || |
731 | IK == PredefinedIdentKind ::Function) && |
732 | !LO.MSVCCompat); |
733 | bool IsLFunctionInMSVCCommpatEnv = |
734 | IK == PredefinedIdentKind::LFunction && LO.MSVCCompat; |
735 | bool IsFuncOrFunctionOrLFunctionOrFuncDName = |
736 | IK != PredefinedIdentKind::PrettyFunction && |
737 | IK != PredefinedIdentKind::PrettyFunctionNoVirtual && |
738 | IK != PredefinedIdentKind::FuncSig && |
739 | IK != PredefinedIdentKind::LFuncSig; |
740 | if ((ForceElaboratedPrinting && |
741 | (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) || |
742 | (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName)) |
743 | return FD->getNameAsString(); |
744 | |
745 | SmallString<256> Name; |
746 | llvm::raw_svector_ostream Out(Name); |
747 | |
748 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
749 | if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual) |
750 | Out << "virtual " ; |
751 | if (MD->isStatic()) |
752 | Out << "static " ; |
753 | } |
754 | |
755 | class PrettyCallbacks final : public PrintingCallbacks { |
756 | public: |
757 | PrettyCallbacks(const LangOptions &LO) : LO(LO) {} |
758 | std::string remapPath(StringRef Path) const override { |
759 | SmallString<128> p(Path); |
760 | LO.remapPathPrefix(Path&: p); |
761 | return std::string(p); |
762 | } |
763 | |
764 | private: |
765 | const LangOptions &LO; |
766 | }; |
767 | PrintingPolicy Policy(Context.getLangOpts()); |
768 | PrettyCallbacks PrettyCB(Context.getLangOpts()); |
769 | Policy.Callbacks = &PrettyCB; |
770 | if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting) |
771 | Policy.SuppressTagKeyword = !LO.MSVCCompat; |
772 | std::string Proto; |
773 | llvm::raw_string_ostream POut(Proto); |
774 | |
775 | const FunctionDecl *Decl = FD; |
776 | if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern()) |
777 | Decl = Pattern; |
778 | const FunctionType *AFT = Decl->getType()->getAs<FunctionType>(); |
779 | const FunctionProtoType *FT = nullptr; |
780 | if (FD->hasWrittenPrototype()) |
781 | FT = dyn_cast<FunctionProtoType>(Val: AFT); |
782 | |
783 | if (IK == PredefinedIdentKind::FuncSig || |
784 | IK == PredefinedIdentKind::LFuncSig) { |
785 | switch (AFT->getCallConv()) { |
786 | case CC_C: POut << "__cdecl " ; break; |
787 | case CC_X86StdCall: POut << "__stdcall " ; break; |
788 | case CC_X86FastCall: POut << "__fastcall " ; break; |
789 | case CC_X86ThisCall: POut << "__thiscall " ; break; |
790 | case CC_X86VectorCall: POut << "__vectorcall " ; break; |
791 | case CC_X86RegCall: POut << "__regcall " ; break; |
792 | // Only bother printing the conventions that MSVC knows about. |
793 | default: break; |
794 | } |
795 | } |
796 | |
797 | FD->printQualifiedName(POut, Policy); |
798 | |
799 | if (IK == PredefinedIdentKind::Function) { |
800 | POut.flush(); |
801 | Out << Proto; |
802 | return std::string(Name); |
803 | } |
804 | |
805 | POut << "(" ; |
806 | if (FT) { |
807 | for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) { |
808 | if (i) POut << ", " ; |
809 | POut << Decl->getParamDecl(i)->getType().stream(Policy); |
810 | } |
811 | |
812 | if (FT->isVariadic()) { |
813 | if (FD->getNumParams()) POut << ", " ; |
814 | POut << "..." ; |
815 | } else if ((IK == PredefinedIdentKind::FuncSig || |
816 | IK == PredefinedIdentKind::LFuncSig || |
817 | !Context.getLangOpts().CPlusPlus) && |
818 | !Decl->getNumParams()) { |
819 | POut << "void" ; |
820 | } |
821 | } |
822 | POut << ")" ; |
823 | |
824 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
825 | assert(FT && "We must have a written prototype in this case." ); |
826 | if (FT->isConst()) |
827 | POut << " const" ; |
828 | if (FT->isVolatile()) |
829 | POut << " volatile" ; |
830 | RefQualifierKind Ref = MD->getRefQualifier(); |
831 | if (Ref == RQ_LValue) |
832 | POut << " &" ; |
833 | else if (Ref == RQ_RValue) |
834 | POut << " &&" ; |
835 | } |
836 | |
837 | typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy; |
838 | SpecsTy Specs; |
839 | const DeclContext *Ctx = FD->getDeclContext(); |
840 | while (Ctx && isa<NamedDecl>(Val: Ctx)) { |
841 | const ClassTemplateSpecializationDecl *Spec |
842 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Ctx); |
843 | if (Spec && !Spec->isExplicitSpecialization()) |
844 | Specs.push_back(Elt: Spec); |
845 | Ctx = Ctx->getParent(); |
846 | } |
847 | |
848 | std::string TemplateParams; |
849 | llvm::raw_string_ostream TOut(TemplateParams); |
850 | for (const ClassTemplateSpecializationDecl *D : llvm::reverse(C&: Specs)) { |
851 | const TemplateParameterList *Params = |
852 | D->getSpecializedTemplate()->getTemplateParameters(); |
853 | const TemplateArgumentList &Args = D->getTemplateArgs(); |
854 | assert(Params->size() == Args.size()); |
855 | for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) { |
856 | StringRef Param = Params->getParam(Idx: i)->getName(); |
857 | if (Param.empty()) continue; |
858 | TOut << Param << " = " ; |
859 | Args.get(Idx: i).print(Policy, Out&: TOut, |
860 | IncludeType: TemplateParameterList::shouldIncludeTypeForArgument( |
861 | Policy, TPL: Params, Idx: i)); |
862 | TOut << ", " ; |
863 | } |
864 | } |
865 | |
866 | FunctionTemplateSpecializationInfo *FSI |
867 | = FD->getTemplateSpecializationInfo(); |
868 | if (FSI && !FSI->isExplicitSpecialization()) { |
869 | const TemplateParameterList* Params |
870 | = FSI->getTemplate()->getTemplateParameters(); |
871 | const TemplateArgumentList* Args = FSI->TemplateArguments; |
872 | assert(Params->size() == Args->size()); |
873 | for (unsigned i = 0, e = Params->size(); i != e; ++i) { |
874 | StringRef Param = Params->getParam(Idx: i)->getName(); |
875 | if (Param.empty()) continue; |
876 | TOut << Param << " = " ; |
877 | Args->get(Idx: i).print(Policy, Out&: TOut, /*IncludeType*/ true); |
878 | TOut << ", " ; |
879 | } |
880 | } |
881 | |
882 | TOut.flush(); |
883 | if (!TemplateParams.empty()) { |
884 | // remove the trailing comma and space |
885 | TemplateParams.resize(n: TemplateParams.size() - 2); |
886 | POut << " [" << TemplateParams << "]" ; |
887 | } |
888 | |
889 | POut.flush(); |
890 | |
891 | // Print "auto" for all deduced return types. This includes C++1y return |
892 | // type deduction and lambdas. For trailing return types resolve the |
893 | // decltype expression. Otherwise print the real type when this is |
894 | // not a constructor or destructor. |
895 | if (isa<CXXMethodDecl>(Val: FD) && |
896 | cast<CXXMethodDecl>(Val: FD)->getParent()->isLambda()) |
897 | Proto = "auto " + Proto; |
898 | else if (FT && FT->getReturnType()->getAs<DecltypeType>()) |
899 | FT->getReturnType() |
900 | ->getAs<DecltypeType>() |
901 | ->getUnderlyingType() |
902 | .getAsStringInternal(Proto, Policy); |
903 | else if (!isa<CXXConstructorDecl>(Val: FD) && !isa<CXXDestructorDecl>(Val: FD)) |
904 | AFT->getReturnType().getAsStringInternal(Str&: Proto, Policy); |
905 | |
906 | Out << Proto; |
907 | |
908 | return std::string(Name); |
909 | } |
910 | if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(Val: CurrentDecl)) { |
911 | for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent()) |
912 | // Skip to its enclosing function or method, but not its enclosing |
913 | // CapturedDecl. |
914 | if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) { |
915 | const Decl *D = Decl::castFromDeclContext(DC); |
916 | return ComputeName(IK, CurrentDecl: D); |
917 | } |
918 | llvm_unreachable("CapturedDecl not inside a function or method" ); |
919 | } |
920 | if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: CurrentDecl)) { |
921 | SmallString<256> Name; |
922 | llvm::raw_svector_ostream Out(Name); |
923 | Out << (MD->isInstanceMethod() ? '-' : '+'); |
924 | Out << '['; |
925 | |
926 | // For incorrect code, there might not be an ObjCInterfaceDecl. Do |
927 | // a null check to avoid a crash. |
928 | if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) |
929 | Out << *ID; |
930 | |
931 | if (const ObjCCategoryImplDecl *CID = |
932 | dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext())) |
933 | Out << '(' << *CID << ')'; |
934 | |
935 | Out << ' '; |
936 | MD->getSelector().print(OS&: Out); |
937 | Out << ']'; |
938 | |
939 | return std::string(Name); |
940 | } |
941 | if (isa<TranslationUnitDecl>(Val: CurrentDecl) && |
942 | IK == PredefinedIdentKind::PrettyFunction) { |
943 | // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. |
944 | return "top level" ; |
945 | } |
946 | return "" ; |
947 | } |
948 | |
949 | void APNumericStorage::setIntValue(const ASTContext &C, |
950 | const llvm::APInt &Val) { |
951 | if (hasAllocation()) |
952 | C.Deallocate(Ptr: pVal); |
953 | |
954 | BitWidth = Val.getBitWidth(); |
955 | unsigned NumWords = Val.getNumWords(); |
956 | const uint64_t* Words = Val.getRawData(); |
957 | if (NumWords > 1) { |
958 | pVal = new (C) uint64_t[NumWords]; |
959 | std::copy(first: Words, last: Words + NumWords, result: pVal); |
960 | } else if (NumWords == 1) |
961 | VAL = Words[0]; |
962 | else |
963 | VAL = 0; |
964 | } |
965 | |
966 | IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V, |
967 | QualType type, SourceLocation l) |
968 | : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) { |
969 | assert(type->isIntegerType() && "Illegal type in IntegerLiteral" ); |
970 | assert(V.getBitWidth() == C.getIntWidth(type) && |
971 | "Integer type is not the correct size for constant." ); |
972 | setValue(C, V); |
973 | setDependence(ExprDependence::None); |
974 | } |
975 | |
976 | IntegerLiteral * |
977 | IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V, |
978 | QualType type, SourceLocation l) { |
979 | return new (C) IntegerLiteral(C, V, type, l); |
980 | } |
981 | |
982 | IntegerLiteral * |
983 | IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) { |
984 | return new (C) IntegerLiteral(Empty); |
985 | } |
986 | |
987 | FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, |
988 | QualType type, SourceLocation l, |
989 | unsigned Scale) |
990 | : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l), |
991 | Scale(Scale) { |
992 | assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral" ); |
993 | assert(V.getBitWidth() == C.getTypeInfo(type).Width && |
994 | "Fixed point type is not the correct size for constant." ); |
995 | setValue(C, V); |
996 | setDependence(ExprDependence::None); |
997 | } |
998 | |
999 | FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C, |
1000 | const llvm::APInt &V, |
1001 | QualType type, |
1002 | SourceLocation l, |
1003 | unsigned Scale) { |
1004 | return new (C) FixedPointLiteral(C, V, type, l, Scale); |
1005 | } |
1006 | |
1007 | FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C, |
1008 | EmptyShell Empty) { |
1009 | return new (C) FixedPointLiteral(Empty); |
1010 | } |
1011 | |
1012 | std::string FixedPointLiteral::getValueAsString(unsigned Radix) const { |
1013 | // Currently the longest decimal number that can be printed is the max for an |
1014 | // unsigned long _Accum: 4294967295.99999999976716935634613037109375 |
1015 | // which is 43 characters. |
1016 | SmallString<64> S; |
1017 | FixedPointValueToString( |
1018 | S, llvm::APSInt::getUnsigned(X: getValue().getZExtValue()), Scale); |
1019 | return std::string(S); |
1020 | } |
1021 | |
1022 | void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind, |
1023 | raw_ostream &OS) { |
1024 | switch (Kind) { |
1025 | case CharacterLiteralKind::Ascii: |
1026 | break; // no prefix. |
1027 | case CharacterLiteralKind::Wide: |
1028 | OS << 'L'; |
1029 | break; |
1030 | case CharacterLiteralKind::UTF8: |
1031 | OS << "u8" ; |
1032 | break; |
1033 | case CharacterLiteralKind::UTF16: |
1034 | OS << 'u'; |
1035 | break; |
1036 | case CharacterLiteralKind::UTF32: |
1037 | OS << 'U'; |
1038 | break; |
1039 | } |
1040 | |
1041 | StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Val); |
1042 | if (!Escaped.empty()) { |
1043 | OS << "'" << Escaped << "'" ; |
1044 | } else { |
1045 | // A character literal might be sign-extended, which |
1046 | // would result in an invalid \U escape sequence. |
1047 | // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF' |
1048 | // are not correctly handled. |
1049 | if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii) |
1050 | Val &= 0xFFu; |
1051 | if (Val < 256 && isPrintable(c: (unsigned char)Val)) |
1052 | OS << "'" << (char)Val << "'" ; |
1053 | else if (Val < 256) |
1054 | OS << "'\\x" << llvm::format(Fmt: "%02x" , Vals: Val) << "'" ; |
1055 | else if (Val <= 0xFFFF) |
1056 | OS << "'\\u" << llvm::format(Fmt: "%04x" , Vals: Val) << "'" ; |
1057 | else |
1058 | OS << "'\\U" << llvm::format(Fmt: "%08x" , Vals: Val) << "'" ; |
1059 | } |
1060 | } |
1061 | |
1062 | FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, |
1063 | bool isexact, QualType Type, SourceLocation L) |
1064 | : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) { |
1065 | setSemantics(V.getSemantics()); |
1066 | FloatingLiteralBits.IsExact = isexact; |
1067 | setValue(C, Val: V); |
1068 | setDependence(ExprDependence::None); |
1069 | } |
1070 | |
1071 | FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty) |
1072 | : Expr(FloatingLiteralClass, Empty) { |
1073 | setRawSemantics(llvm::APFloatBase::S_IEEEhalf); |
1074 | FloatingLiteralBits.IsExact = false; |
1075 | } |
1076 | |
1077 | FloatingLiteral * |
1078 | FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V, |
1079 | bool isexact, QualType Type, SourceLocation L) { |
1080 | return new (C) FloatingLiteral(C, V, isexact, Type, L); |
1081 | } |
1082 | |
1083 | FloatingLiteral * |
1084 | FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) { |
1085 | return new (C) FloatingLiteral(C, Empty); |
1086 | } |
1087 | |
1088 | /// getValueAsApproximateDouble - This returns the value as an inaccurate |
1089 | /// double. Note that this may cause loss of precision, but is useful for |
1090 | /// debugging dumps, etc. |
1091 | double FloatingLiteral::getValueAsApproximateDouble() const { |
1092 | llvm::APFloat V = getValue(); |
1093 | bool ignored; |
1094 | V.convert(ToSemantics: llvm::APFloat::IEEEdouble(), RM: llvm::APFloat::rmNearestTiesToEven, |
1095 | losesInfo: &ignored); |
1096 | return V.convertToDouble(); |
1097 | } |
1098 | |
1099 | unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target, |
1100 | StringLiteralKind SK) { |
1101 | unsigned CharByteWidth = 0; |
1102 | switch (SK) { |
1103 | case StringLiteralKind::Ordinary: |
1104 | case StringLiteralKind::UTF8: |
1105 | CharByteWidth = Target.getCharWidth(); |
1106 | break; |
1107 | case StringLiteralKind::Wide: |
1108 | CharByteWidth = Target.getWCharWidth(); |
1109 | break; |
1110 | case StringLiteralKind::UTF16: |
1111 | CharByteWidth = Target.getChar16Width(); |
1112 | break; |
1113 | case StringLiteralKind::UTF32: |
1114 | CharByteWidth = Target.getChar32Width(); |
1115 | break; |
1116 | case StringLiteralKind::Unevaluated: |
1117 | return sizeof(char); // Host; |
1118 | } |
1119 | assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple" ); |
1120 | CharByteWidth /= 8; |
1121 | assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && |
1122 | "The only supported character byte widths are 1,2 and 4!" ); |
1123 | return CharByteWidth; |
1124 | } |
1125 | |
1126 | StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str, |
1127 | StringLiteralKind Kind, bool Pascal, QualType Ty, |
1128 | const SourceLocation *Loc, |
1129 | unsigned NumConcatenated) |
1130 | : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) { |
1131 | |
1132 | unsigned Length = Str.size(); |
1133 | |
1134 | StringLiteralBits.Kind = llvm::to_underlying(E: Kind); |
1135 | StringLiteralBits.NumConcatenated = NumConcatenated; |
1136 | |
1137 | if (Kind != StringLiteralKind::Unevaluated) { |
1138 | assert(Ctx.getAsConstantArrayType(Ty) && |
1139 | "StringLiteral must be of constant array type!" ); |
1140 | unsigned CharByteWidth = mapCharByteWidth(Target: Ctx.getTargetInfo(), SK: Kind); |
1141 | unsigned ByteLength = Str.size(); |
1142 | assert((ByteLength % CharByteWidth == 0) && |
1143 | "The size of the data must be a multiple of CharByteWidth!" ); |
1144 | |
1145 | // Avoid the expensive division. The compiler should be able to figure it |
1146 | // out by itself. However as of clang 7, even with the appropriate |
1147 | // llvm_unreachable added just here, it is not able to do so. |
1148 | switch (CharByteWidth) { |
1149 | case 1: |
1150 | Length = ByteLength; |
1151 | break; |
1152 | case 2: |
1153 | Length = ByteLength / 2; |
1154 | break; |
1155 | case 4: |
1156 | Length = ByteLength / 4; |
1157 | break; |
1158 | default: |
1159 | llvm_unreachable("Unsupported character width!" ); |
1160 | } |
1161 | |
1162 | StringLiteralBits.CharByteWidth = CharByteWidth; |
1163 | StringLiteralBits.IsPascal = Pascal; |
1164 | } else { |
1165 | assert(!Pascal && "Can't make an unevaluated Pascal string" ); |
1166 | StringLiteralBits.CharByteWidth = 1; |
1167 | StringLiteralBits.IsPascal = false; |
1168 | } |
1169 | |
1170 | *getTrailingObjects<unsigned>() = Length; |
1171 | |
1172 | // Initialize the trailing array of SourceLocation. |
1173 | // This is safe since SourceLocation is POD-like. |
1174 | std::memcpy(dest: getTrailingObjects<SourceLocation>(), src: Loc, |
1175 | n: NumConcatenated * sizeof(SourceLocation)); |
1176 | |
1177 | // Initialize the trailing array of char holding the string data. |
1178 | std::memcpy(dest: getTrailingObjects<char>(), src: Str.data(), n: Str.size()); |
1179 | |
1180 | setDependence(ExprDependence::None); |
1181 | } |
1182 | |
1183 | StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated, |
1184 | unsigned Length, unsigned CharByteWidth) |
1185 | : Expr(StringLiteralClass, Empty) { |
1186 | StringLiteralBits.CharByteWidth = CharByteWidth; |
1187 | StringLiteralBits.NumConcatenated = NumConcatenated; |
1188 | *getTrailingObjects<unsigned>() = Length; |
1189 | } |
1190 | |
1191 | StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str, |
1192 | StringLiteralKind Kind, bool Pascal, |
1193 | QualType Ty, const SourceLocation *Loc, |
1194 | unsigned NumConcatenated) { |
1195 | void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<unsigned, SourceLocation, char>( |
1196 | Counts: 1, Counts: NumConcatenated, Counts: Str.size()), |
1197 | Align: alignof(StringLiteral)); |
1198 | return new (Mem) |
1199 | StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated); |
1200 | } |
1201 | |
1202 | StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx, |
1203 | unsigned NumConcatenated, |
1204 | unsigned Length, |
1205 | unsigned CharByteWidth) { |
1206 | void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<unsigned, SourceLocation, char>( |
1207 | Counts: 1, Counts: NumConcatenated, Counts: Length * CharByteWidth), |
1208 | Align: alignof(StringLiteral)); |
1209 | return new (Mem) |
1210 | StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth); |
1211 | } |
1212 | |
1213 | void StringLiteral::outputString(raw_ostream &OS) const { |
1214 | switch (getKind()) { |
1215 | case StringLiteralKind::Unevaluated: |
1216 | case StringLiteralKind::Ordinary: |
1217 | break; // no prefix. |
1218 | case StringLiteralKind::Wide: |
1219 | OS << 'L'; |
1220 | break; |
1221 | case StringLiteralKind::UTF8: |
1222 | OS << "u8" ; |
1223 | break; |
1224 | case StringLiteralKind::UTF16: |
1225 | OS << 'u'; |
1226 | break; |
1227 | case StringLiteralKind::UTF32: |
1228 | OS << 'U'; |
1229 | break; |
1230 | } |
1231 | OS << '"'; |
1232 | static const char Hex[] = "0123456789ABCDEF" ; |
1233 | |
1234 | unsigned LastSlashX = getLength(); |
1235 | for (unsigned I = 0, N = getLength(); I != N; ++I) { |
1236 | uint32_t Char = getCodeUnit(i: I); |
1237 | StringRef Escaped = escapeCStyle<EscapeChar::Double>(Ch: Char); |
1238 | if (Escaped.empty()) { |
1239 | // FIXME: Convert UTF-8 back to codepoints before rendering. |
1240 | |
1241 | // Convert UTF-16 surrogate pairs back to codepoints before rendering. |
1242 | // Leave invalid surrogates alone; we'll use \x for those. |
1243 | if (getKind() == StringLiteralKind::UTF16 && I != N - 1 && |
1244 | Char >= 0xd800 && Char <= 0xdbff) { |
1245 | uint32_t Trail = getCodeUnit(i: I + 1); |
1246 | if (Trail >= 0xdc00 && Trail <= 0xdfff) { |
1247 | Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00); |
1248 | ++I; |
1249 | } |
1250 | } |
1251 | |
1252 | if (Char > 0xff) { |
1253 | // If this is a wide string, output characters over 0xff using \x |
1254 | // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a |
1255 | // codepoint: use \x escapes for invalid codepoints. |
1256 | if (getKind() == StringLiteralKind::Wide || |
1257 | (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) { |
1258 | // FIXME: Is this the best way to print wchar_t? |
1259 | OS << "\\x" ; |
1260 | int Shift = 28; |
1261 | while ((Char >> Shift) == 0) |
1262 | Shift -= 4; |
1263 | for (/**/; Shift >= 0; Shift -= 4) |
1264 | OS << Hex[(Char >> Shift) & 15]; |
1265 | LastSlashX = I; |
1266 | continue; |
1267 | } |
1268 | |
1269 | if (Char > 0xffff) |
1270 | OS << "\\U00" |
1271 | << Hex[(Char >> 20) & 15] |
1272 | << Hex[(Char >> 16) & 15]; |
1273 | else |
1274 | OS << "\\u" ; |
1275 | OS << Hex[(Char >> 12) & 15] |
1276 | << Hex[(Char >> 8) & 15] |
1277 | << Hex[(Char >> 4) & 15] |
1278 | << Hex[(Char >> 0) & 15]; |
1279 | continue; |
1280 | } |
1281 | |
1282 | // If we used \x... for the previous character, and this character is a |
1283 | // hexadecimal digit, prevent it being slurped as part of the \x. |
1284 | if (LastSlashX + 1 == I) { |
1285 | switch (Char) { |
1286 | case '0': case '1': case '2': case '3': case '4': |
1287 | case '5': case '6': case '7': case '8': case '9': |
1288 | case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': |
1289 | case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': |
1290 | OS << "\"\"" ; |
1291 | } |
1292 | } |
1293 | |
1294 | assert(Char <= 0xff && |
1295 | "Characters above 0xff should already have been handled." ); |
1296 | |
1297 | if (isPrintable(c: Char)) |
1298 | OS << (char)Char; |
1299 | else // Output anything hard as an octal escape. |
1300 | OS << '\\' |
1301 | << (char)('0' + ((Char >> 6) & 7)) |
1302 | << (char)('0' + ((Char >> 3) & 7)) |
1303 | << (char)('0' + ((Char >> 0) & 7)); |
1304 | } else { |
1305 | // Handle some common non-printable cases to make dumps prettier. |
1306 | OS << Escaped; |
1307 | } |
1308 | } |
1309 | OS << '"'; |
1310 | } |
1311 | |
1312 | /// getLocationOfByte - Return a source location that points to the specified |
1313 | /// byte of this string literal. |
1314 | /// |
1315 | /// Strings are amazingly complex. They can be formed from multiple tokens and |
1316 | /// can have escape sequences in them in addition to the usual trigraph and |
1317 | /// escaped newline business. This routine handles this complexity. |
1318 | /// |
1319 | /// The *StartToken sets the first token to be searched in this function and |
1320 | /// the *StartTokenByteOffset is the byte offset of the first token. Before |
1321 | /// returning, it updates the *StartToken to the TokNo of the token being found |
1322 | /// and sets *StartTokenByteOffset to the byte offset of the token in the |
1323 | /// string. |
1324 | /// Using these two parameters can reduce the time complexity from O(n^2) to |
1325 | /// O(n) if one wants to get the location of byte for all the tokens in a |
1326 | /// string. |
1327 | /// |
1328 | SourceLocation |
1329 | StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, |
1330 | const LangOptions &Features, |
1331 | const TargetInfo &Target, unsigned *StartToken, |
1332 | unsigned *StartTokenByteOffset) const { |
1333 | assert((getKind() == StringLiteralKind::Ordinary || |
1334 | getKind() == StringLiteralKind::UTF8 || |
1335 | getKind() == StringLiteralKind::Unevaluated) && |
1336 | "Only narrow string literals are currently supported" ); |
1337 | |
1338 | // Loop over all of the tokens in this string until we find the one that |
1339 | // contains the byte we're looking for. |
1340 | unsigned TokNo = 0; |
1341 | unsigned StringOffset = 0; |
1342 | if (StartToken) |
1343 | TokNo = *StartToken; |
1344 | if (StartTokenByteOffset) { |
1345 | StringOffset = *StartTokenByteOffset; |
1346 | ByteNo -= StringOffset; |
1347 | } |
1348 | while (true) { |
1349 | assert(TokNo < getNumConcatenated() && "Invalid byte number!" ); |
1350 | SourceLocation StrTokLoc = getStrTokenLoc(TokNum: TokNo); |
1351 | |
1352 | // Get the spelling of the string so that we can get the data that makes up |
1353 | // the string literal, not the identifier for the macro it is potentially |
1354 | // expanded through. |
1355 | SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(Loc: StrTokLoc); |
1356 | |
1357 | // Re-lex the token to get its length and original spelling. |
1358 | std::pair<FileID, unsigned> LocInfo = |
1359 | SM.getDecomposedLoc(Loc: StrTokSpellingLoc); |
1360 | bool Invalid = false; |
1361 | StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid); |
1362 | if (Invalid) { |
1363 | if (StartTokenByteOffset != nullptr) |
1364 | *StartTokenByteOffset = StringOffset; |
1365 | if (StartToken != nullptr) |
1366 | *StartToken = TokNo; |
1367 | return StrTokSpellingLoc; |
1368 | } |
1369 | |
1370 | const char *StrData = Buffer.data()+LocInfo.second; |
1371 | |
1372 | // Create a lexer starting at the beginning of this token. |
1373 | Lexer TheLexer(SM.getLocForStartOfFile(FID: LocInfo.first), Features, |
1374 | Buffer.begin(), StrData, Buffer.end()); |
1375 | Token TheTok; |
1376 | TheLexer.LexFromRawLexer(Result&: TheTok); |
1377 | |
1378 | // Use the StringLiteralParser to compute the length of the string in bytes. |
1379 | StringLiteralParser SLP(TheTok, SM, Features, Target); |
1380 | unsigned TokNumBytes = SLP.GetStringLength(); |
1381 | |
1382 | // If the byte is in this token, return the location of the byte. |
1383 | if (ByteNo < TokNumBytes || |
1384 | (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) { |
1385 | unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo); |
1386 | |
1387 | // Now that we know the offset of the token in the spelling, use the |
1388 | // preprocessor to get the offset in the original source. |
1389 | if (StartTokenByteOffset != nullptr) |
1390 | *StartTokenByteOffset = StringOffset; |
1391 | if (StartToken != nullptr) |
1392 | *StartToken = TokNo; |
1393 | return Lexer::AdvanceToTokenCharacter(TokStart: StrTokLoc, Characters: Offset, SM, LangOpts: Features); |
1394 | } |
1395 | |
1396 | // Move to the next string token. |
1397 | StringOffset += TokNumBytes; |
1398 | ++TokNo; |
1399 | ByteNo -= TokNumBytes; |
1400 | } |
1401 | } |
1402 | |
1403 | /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it |
1404 | /// corresponds to, e.g. "sizeof" or "[pre]++". |
1405 | StringRef UnaryOperator::getOpcodeStr(Opcode Op) { |
1406 | switch (Op) { |
1407 | #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling; |
1408 | #include "clang/AST/OperationKinds.def" |
1409 | } |
1410 | llvm_unreachable("Unknown unary operator" ); |
1411 | } |
1412 | |
1413 | UnaryOperatorKind |
1414 | UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { |
1415 | switch (OO) { |
1416 | default: llvm_unreachable("No unary operator for overloaded function" ); |
1417 | case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc; |
1418 | case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec; |
1419 | case OO_Amp: return UO_AddrOf; |
1420 | case OO_Star: return UO_Deref; |
1421 | case OO_Plus: return UO_Plus; |
1422 | case OO_Minus: return UO_Minus; |
1423 | case OO_Tilde: return UO_Not; |
1424 | case OO_Exclaim: return UO_LNot; |
1425 | case OO_Coawait: return UO_Coawait; |
1426 | } |
1427 | } |
1428 | |
1429 | OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { |
1430 | switch (Opc) { |
1431 | case UO_PostInc: case UO_PreInc: return OO_PlusPlus; |
1432 | case UO_PostDec: case UO_PreDec: return OO_MinusMinus; |
1433 | case UO_AddrOf: return OO_Amp; |
1434 | case UO_Deref: return OO_Star; |
1435 | case UO_Plus: return OO_Plus; |
1436 | case UO_Minus: return OO_Minus; |
1437 | case UO_Not: return OO_Tilde; |
1438 | case UO_LNot: return OO_Exclaim; |
1439 | case UO_Coawait: return OO_Coawait; |
1440 | default: return OO_None; |
1441 | } |
1442 | } |
1443 | |
1444 | |
1445 | //===----------------------------------------------------------------------===// |
1446 | // Postfix Operators. |
1447 | //===----------------------------------------------------------------------===// |
1448 | |
1449 | CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs, |
1450 | ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, |
1451 | SourceLocation RParenLoc, FPOptionsOverride FPFeatures, |
1452 | unsigned MinNumArgs, ADLCallKind UsesADL) |
1453 | : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) { |
1454 | NumArgs = std::max<unsigned>(a: Args.size(), b: MinNumArgs); |
1455 | unsigned NumPreArgs = PreArgs.size(); |
1456 | CallExprBits.NumPreArgs = NumPreArgs; |
1457 | assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!" ); |
1458 | |
1459 | unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC); |
1460 | CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects; |
1461 | assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && |
1462 | "OffsetToTrailingObjects overflow!" ); |
1463 | |
1464 | CallExprBits.UsesADL = static_cast<bool>(UsesADL); |
1465 | |
1466 | setCallee(Fn); |
1467 | for (unsigned I = 0; I != NumPreArgs; ++I) |
1468 | setPreArg(I, PreArgs[I]); |
1469 | for (unsigned I = 0; I != Args.size(); ++I) |
1470 | setArg(Arg: I, ArgExpr: Args[I]); |
1471 | for (unsigned I = Args.size(); I != NumArgs; ++I) |
1472 | setArg(Arg: I, ArgExpr: nullptr); |
1473 | |
1474 | this->computeDependence(); |
1475 | |
1476 | CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
1477 | if (hasStoredFPFeatures()) |
1478 | setStoredFPFeatures(FPFeatures); |
1479 | } |
1480 | |
1481 | CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs, |
1482 | bool HasFPFeatures, EmptyShell Empty) |
1483 | : Expr(SC, Empty), NumArgs(NumArgs) { |
1484 | CallExprBits.NumPreArgs = NumPreArgs; |
1485 | assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!" ); |
1486 | |
1487 | unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC); |
1488 | CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects; |
1489 | assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && |
1490 | "OffsetToTrailingObjects overflow!" ); |
1491 | CallExprBits.HasFPFeatures = HasFPFeatures; |
1492 | } |
1493 | |
1494 | CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn, |
1495 | ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, |
1496 | SourceLocation RParenLoc, |
1497 | FPOptionsOverride FPFeatures, unsigned MinNumArgs, |
1498 | ADLCallKind UsesADL) { |
1499 | unsigned NumArgs = std::max<unsigned>(a: Args.size(), b: MinNumArgs); |
1500 | unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects( |
1501 | /*NumPreArgs=*/0, NumArgs, HasFPFeatures: FPFeatures.requiresTrailingStorage()); |
1502 | void *Mem = |
1503 | Ctx.Allocate(Size: sizeof(CallExpr) + SizeOfTrailingObjects, Align: alignof(CallExpr)); |
1504 | return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK, |
1505 | RParenLoc, FPFeatures, MinNumArgs, UsesADL); |
1506 | } |
1507 | |
1508 | CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty, |
1509 | ExprValueKind VK, SourceLocation RParenLoc, |
1510 | ADLCallKind UsesADL) { |
1511 | assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) && |
1512 | "Misaligned memory in CallExpr::CreateTemporary!" ); |
1513 | return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty, |
1514 | VK, RParenLoc, FPOptionsOverride(), |
1515 | /*MinNumArgs=*/0, UsesADL); |
1516 | } |
1517 | |
1518 | CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, |
1519 | bool HasFPFeatures, EmptyShell Empty) { |
1520 | unsigned SizeOfTrailingObjects = |
1521 | CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures); |
1522 | void *Mem = |
1523 | Ctx.Allocate(Size: sizeof(CallExpr) + SizeOfTrailingObjects, Align: alignof(CallExpr)); |
1524 | return new (Mem) |
1525 | CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty); |
1526 | } |
1527 | |
1528 | unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) { |
1529 | switch (SC) { |
1530 | case CallExprClass: |
1531 | return sizeof(CallExpr); |
1532 | case CXXOperatorCallExprClass: |
1533 | return sizeof(CXXOperatorCallExpr); |
1534 | case CXXMemberCallExprClass: |
1535 | return sizeof(CXXMemberCallExpr); |
1536 | case UserDefinedLiteralClass: |
1537 | return sizeof(UserDefinedLiteral); |
1538 | case CUDAKernelCallExprClass: |
1539 | return sizeof(CUDAKernelCallExpr); |
1540 | default: |
1541 | llvm_unreachable("unexpected class deriving from CallExpr!" ); |
1542 | } |
1543 | } |
1544 | |
1545 | Decl *Expr::getReferencedDeclOfCallee() { |
1546 | Expr *CEE = IgnoreParenImpCasts(); |
1547 | |
1548 | while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: CEE)) |
1549 | CEE = NTTP->getReplacement()->IgnoreParenImpCasts(); |
1550 | |
1551 | // If we're calling a dereference, look at the pointer instead. |
1552 | while (true) { |
1553 | if (auto *BO = dyn_cast<BinaryOperator>(Val: CEE)) { |
1554 | if (BO->isPtrMemOp()) { |
1555 | CEE = BO->getRHS()->IgnoreParenImpCasts(); |
1556 | continue; |
1557 | } |
1558 | } else if (auto *UO = dyn_cast<UnaryOperator>(Val: CEE)) { |
1559 | if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf || |
1560 | UO->getOpcode() == UO_Plus) { |
1561 | CEE = UO->getSubExpr()->IgnoreParenImpCasts(); |
1562 | continue; |
1563 | } |
1564 | } |
1565 | break; |
1566 | } |
1567 | |
1568 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CEE)) |
1569 | return DRE->getDecl(); |
1570 | if (auto *ME = dyn_cast<MemberExpr>(Val: CEE)) |
1571 | return ME->getMemberDecl(); |
1572 | if (auto *BE = dyn_cast<BlockExpr>(Val: CEE)) |
1573 | return BE->getBlockDecl(); |
1574 | |
1575 | return nullptr; |
1576 | } |
1577 | |
1578 | /// If this is a call to a builtin, return the builtin ID. If not, return 0. |
1579 | unsigned CallExpr::getBuiltinCallee() const { |
1580 | const auto *FDecl = getDirectCallee(); |
1581 | return FDecl ? FDecl->getBuiltinID() : 0; |
1582 | } |
1583 | |
1584 | bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const { |
1585 | if (unsigned BI = getBuiltinCallee()) |
1586 | return Ctx.BuiltinInfo.isUnevaluated(ID: BI); |
1587 | return false; |
1588 | } |
1589 | |
1590 | QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const { |
1591 | const Expr *Callee = getCallee(); |
1592 | QualType CalleeType = Callee->getType(); |
1593 | if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) { |
1594 | CalleeType = FnTypePtr->getPointeeType(); |
1595 | } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) { |
1596 | CalleeType = BPT->getPointeeType(); |
1597 | } else if (CalleeType->isSpecificPlaceholderType(K: BuiltinType::BoundMember)) { |
1598 | if (isa<CXXPseudoDestructorExpr>(Val: Callee->IgnoreParens())) |
1599 | return Ctx.VoidTy; |
1600 | |
1601 | if (isa<UnresolvedMemberExpr>(Val: Callee->IgnoreParens())) |
1602 | return Ctx.DependentTy; |
1603 | |
1604 | // This should never be overloaded and so should never return null. |
1605 | CalleeType = Expr::findBoundMemberType(expr: Callee); |
1606 | assert(!CalleeType.isNull()); |
1607 | } else if (CalleeType->isRecordType()) { |
1608 | // If the Callee is a record type, then it is a not-yet-resolved |
1609 | // dependent call to the call operator of that type. |
1610 | return Ctx.DependentTy; |
1611 | } else if (CalleeType->isDependentType() || |
1612 | CalleeType->isSpecificPlaceholderType(K: BuiltinType::Overload)) { |
1613 | return Ctx.DependentTy; |
1614 | } |
1615 | |
1616 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); |
1617 | return FnType->getReturnType(); |
1618 | } |
1619 | |
1620 | const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const { |
1621 | // If the return type is a struct, union, or enum that is marked nodiscard, |
1622 | // then return the return type attribute. |
1623 | if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl()) |
1624 | if (const auto *A = TD->getAttr<WarnUnusedResultAttr>()) |
1625 | return A; |
1626 | |
1627 | for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD; |
1628 | TD = TD->desugar()->getAs<TypedefType>()) |
1629 | if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>()) |
1630 | return A; |
1631 | |
1632 | // Otherwise, see if the callee is marked nodiscard and return that attribute |
1633 | // instead. |
1634 | const Decl *D = getCalleeDecl(); |
1635 | return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr; |
1636 | } |
1637 | |
1638 | SourceLocation CallExpr::getBeginLoc() const { |
1639 | if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: this)) |
1640 | return OCE->getBeginLoc(); |
1641 | |
1642 | SourceLocation begin = getCallee()->getBeginLoc(); |
1643 | if (begin.isInvalid() && getNumArgs() > 0 && getArg(Arg: 0)) |
1644 | begin = getArg(Arg: 0)->getBeginLoc(); |
1645 | return begin; |
1646 | } |
1647 | SourceLocation CallExpr::getEndLoc() const { |
1648 | if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: this)) |
1649 | return OCE->getEndLoc(); |
1650 | |
1651 | SourceLocation end = getRParenLoc(); |
1652 | if (end.isInvalid() && getNumArgs() > 0 && getArg(Arg: getNumArgs() - 1)) |
1653 | end = getArg(Arg: getNumArgs() - 1)->getEndLoc(); |
1654 | return end; |
1655 | } |
1656 | |
1657 | OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type, |
1658 | SourceLocation OperatorLoc, |
1659 | TypeSourceInfo *tsi, |
1660 | ArrayRef<OffsetOfNode> comps, |
1661 | ArrayRef<Expr*> exprs, |
1662 | SourceLocation RParenLoc) { |
1663 | void *Mem = C.Allocate( |
1664 | Size: totalSizeToAlloc<OffsetOfNode, Expr *>(Counts: comps.size(), Counts: exprs.size())); |
1665 | |
1666 | return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs, |
1667 | RParenLoc); |
1668 | } |
1669 | |
1670 | OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C, |
1671 | unsigned numComps, unsigned numExprs) { |
1672 | void *Mem = |
1673 | C.Allocate(Size: totalSizeToAlloc<OffsetOfNode, Expr *>(Counts: numComps, Counts: numExprs)); |
1674 | return new (Mem) OffsetOfExpr(numComps, numExprs); |
1675 | } |
1676 | |
1677 | OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type, |
1678 | SourceLocation OperatorLoc, TypeSourceInfo *tsi, |
1679 | ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs, |
1680 | SourceLocation RParenLoc) |
1681 | : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary), |
1682 | OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), |
1683 | NumComps(comps.size()), NumExprs(exprs.size()) { |
1684 | for (unsigned i = 0; i != comps.size(); ++i) |
1685 | setComponent(Idx: i, ON: comps[i]); |
1686 | for (unsigned i = 0; i != exprs.size(); ++i) |
1687 | setIndexExpr(Idx: i, E: exprs[i]); |
1688 | |
1689 | setDependence(computeDependence(E: this)); |
1690 | } |
1691 | |
1692 | IdentifierInfo *OffsetOfNode::getFieldName() const { |
1693 | assert(getKind() == Field || getKind() == Identifier); |
1694 | if (getKind() == Field) |
1695 | return getField()->getIdentifier(); |
1696 | |
1697 | return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); |
1698 | } |
1699 | |
1700 | UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr( |
1701 | UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType, |
1702 | SourceLocation op, SourceLocation rp) |
1703 | : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary), |
1704 | OpLoc(op), RParenLoc(rp) { |
1705 | assert(ExprKind <= UETT_Last && "invalid enum value!" ); |
1706 | UnaryExprOrTypeTraitExprBits.Kind = ExprKind; |
1707 | assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind && |
1708 | "UnaryExprOrTypeTraitExprBits.Kind overflow!" ); |
1709 | UnaryExprOrTypeTraitExprBits.IsType = false; |
1710 | Argument.Ex = E; |
1711 | setDependence(computeDependence(E: this)); |
1712 | } |
1713 | |
1714 | MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, |
1715 | NestedNameSpecifierLoc QualifierLoc, |
1716 | SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, |
1717 | DeclAccessPair FoundDecl, |
1718 | const DeclarationNameInfo &NameInfo, |
1719 | const TemplateArgumentListInfo *TemplateArgs, QualType T, |
1720 | ExprValueKind VK, ExprObjectKind OK, |
1721 | NonOdrUseReason NOUR) |
1722 | : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl), |
1723 | MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) { |
1724 | assert(!NameInfo.getName() || |
1725 | MemberDecl->getDeclName() == NameInfo.getName()); |
1726 | MemberExprBits.IsArrow = IsArrow; |
1727 | MemberExprBits.HasQualifier = QualifierLoc.hasQualifier(); |
1728 | MemberExprBits.HasFoundDecl = |
1729 | FoundDecl.getDecl() != MemberDecl || |
1730 | FoundDecl.getAccess() != MemberDecl->getAccess(); |
1731 | MemberExprBits.HasTemplateKWAndArgsInfo = |
1732 | TemplateArgs || TemplateKWLoc.isValid(); |
1733 | MemberExprBits.HadMultipleCandidates = false; |
1734 | MemberExprBits.NonOdrUseReason = NOUR; |
1735 | MemberExprBits.OperatorLoc = OperatorLoc; |
1736 | |
1737 | if (hasQualifier()) |
1738 | new (getTrailingObjects<NestedNameSpecifierLoc>()) |
1739 | NestedNameSpecifierLoc(QualifierLoc); |
1740 | if (hasFoundDecl()) |
1741 | *getTrailingObjects<DeclAccessPair>() = FoundDecl; |
1742 | if (TemplateArgs) { |
1743 | auto Deps = TemplateArgumentDependence::None; |
1744 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom( |
1745 | TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(), |
1746 | Deps); |
1747 | } else if (TemplateKWLoc.isValid()) { |
1748 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom( |
1749 | TemplateKWLoc); |
1750 | } |
1751 | setDependence(computeDependence(E: this)); |
1752 | } |
1753 | |
1754 | MemberExpr *MemberExpr::Create( |
1755 | const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, |
1756 | NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, |
1757 | ValueDecl *MemberDecl, DeclAccessPair FoundDecl, |
1758 | DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs, |
1759 | QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) { |
1760 | bool HasQualifier = QualifierLoc.hasQualifier(); |
1761 | bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl || |
1762 | FoundDecl.getAccess() != MemberDecl->getAccess(); |
1763 | bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid(); |
1764 | std::size_t Size = |
1765 | totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair, |
1766 | ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>( |
1767 | Counts: HasQualifier, Counts: HasFoundDecl, Counts: HasTemplateKWAndArgsInfo, |
1768 | Counts: TemplateArgs ? TemplateArgs->size() : 0); |
1769 | |
1770 | void *Mem = C.Allocate(Size, Align: alignof(MemberExpr)); |
1771 | return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc, |
1772 | TemplateKWLoc, MemberDecl, FoundDecl, NameInfo, |
1773 | TemplateArgs, T, VK, OK, NOUR); |
1774 | } |
1775 | |
1776 | MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context, |
1777 | bool HasQualifier, bool HasFoundDecl, |
1778 | bool HasTemplateKWAndArgsInfo, |
1779 | unsigned NumTemplateArgs) { |
1780 | assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) && |
1781 | "template args but no template arg info?" ); |
1782 | std::size_t Size = |
1783 | totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair, |
1784 | ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>( |
1785 | Counts: HasQualifier, Counts: HasFoundDecl, Counts: HasTemplateKWAndArgsInfo, |
1786 | Counts: NumTemplateArgs); |
1787 | void *Mem = Context.Allocate(Size, Align: alignof(MemberExpr)); |
1788 | return new (Mem) MemberExpr(EmptyShell()); |
1789 | } |
1790 | |
1791 | void MemberExpr::setMemberDecl(ValueDecl *NewD) { |
1792 | MemberDecl = NewD; |
1793 | if (getType()->isUndeducedType()) |
1794 | setType(NewD->getType()); |
1795 | setDependence(computeDependence(E: this)); |
1796 | } |
1797 | |
1798 | SourceLocation MemberExpr::getBeginLoc() const { |
1799 | if (isImplicitAccess()) { |
1800 | if (hasQualifier()) |
1801 | return getQualifierLoc().getBeginLoc(); |
1802 | return MemberLoc; |
1803 | } |
1804 | |
1805 | // FIXME: We don't want this to happen. Rather, we should be able to |
1806 | // detect all kinds of implicit accesses more cleanly. |
1807 | SourceLocation BaseStartLoc = getBase()->getBeginLoc(); |
1808 | if (BaseStartLoc.isValid()) |
1809 | return BaseStartLoc; |
1810 | return MemberLoc; |
1811 | } |
1812 | SourceLocation MemberExpr::getEndLoc() const { |
1813 | SourceLocation EndLoc = getMemberNameInfo().getEndLoc(); |
1814 | if (hasExplicitTemplateArgs()) |
1815 | EndLoc = getRAngleLoc(); |
1816 | else if (EndLoc.isInvalid()) |
1817 | EndLoc = getBase()->getEndLoc(); |
1818 | return EndLoc; |
1819 | } |
1820 | |
1821 | bool CastExpr::CastConsistency() const { |
1822 | switch (getCastKind()) { |
1823 | case CK_DerivedToBase: |
1824 | case CK_UncheckedDerivedToBase: |
1825 | case CK_DerivedToBaseMemberPointer: |
1826 | case CK_BaseToDerived: |
1827 | case CK_BaseToDerivedMemberPointer: |
1828 | assert(!path_empty() && "Cast kind should have a base path!" ); |
1829 | break; |
1830 | |
1831 | case CK_CPointerToObjCPointerCast: |
1832 | assert(getType()->isObjCObjectPointerType()); |
1833 | assert(getSubExpr()->getType()->isPointerType()); |
1834 | goto CheckNoBasePath; |
1835 | |
1836 | case CK_BlockPointerToObjCPointerCast: |
1837 | assert(getType()->isObjCObjectPointerType()); |
1838 | assert(getSubExpr()->getType()->isBlockPointerType()); |
1839 | goto CheckNoBasePath; |
1840 | |
1841 | case CK_ReinterpretMemberPointer: |
1842 | assert(getType()->isMemberPointerType()); |
1843 | assert(getSubExpr()->getType()->isMemberPointerType()); |
1844 | goto CheckNoBasePath; |
1845 | |
1846 | case CK_BitCast: |
1847 | // Arbitrary casts to C pointer types count as bitcasts. |
1848 | // Otherwise, we should only have block and ObjC pointer casts |
1849 | // here if they stay within the type kind. |
1850 | if (!getType()->isPointerType()) { |
1851 | assert(getType()->isObjCObjectPointerType() == |
1852 | getSubExpr()->getType()->isObjCObjectPointerType()); |
1853 | assert(getType()->isBlockPointerType() == |
1854 | getSubExpr()->getType()->isBlockPointerType()); |
1855 | } |
1856 | goto CheckNoBasePath; |
1857 | |
1858 | case CK_AnyPointerToBlockPointerCast: |
1859 | assert(getType()->isBlockPointerType()); |
1860 | assert(getSubExpr()->getType()->isAnyPointerType() && |
1861 | !getSubExpr()->getType()->isBlockPointerType()); |
1862 | goto CheckNoBasePath; |
1863 | |
1864 | case CK_CopyAndAutoreleaseBlockObject: |
1865 | assert(getType()->isBlockPointerType()); |
1866 | assert(getSubExpr()->getType()->isBlockPointerType()); |
1867 | goto CheckNoBasePath; |
1868 | |
1869 | case CK_FunctionToPointerDecay: |
1870 | assert(getType()->isPointerType()); |
1871 | assert(getSubExpr()->getType()->isFunctionType()); |
1872 | goto CheckNoBasePath; |
1873 | |
1874 | case CK_AddressSpaceConversion: { |
1875 | auto Ty = getType(); |
1876 | auto SETy = getSubExpr()->getType(); |
1877 | assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy)); |
1878 | if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) { |
1879 | Ty = Ty->getPointeeType(); |
1880 | SETy = SETy->getPointeeType(); |
1881 | } |
1882 | assert((Ty->isDependentType() || SETy->isDependentType()) || |
1883 | (!Ty.isNull() && !SETy.isNull() && |
1884 | Ty.getAddressSpace() != SETy.getAddressSpace())); |
1885 | goto CheckNoBasePath; |
1886 | } |
1887 | // These should not have an inheritance path. |
1888 | case CK_Dynamic: |
1889 | case CK_ToUnion: |
1890 | case CK_ArrayToPointerDecay: |
1891 | case CK_NullToMemberPointer: |
1892 | case CK_NullToPointer: |
1893 | case CK_ConstructorConversion: |
1894 | case CK_IntegralToPointer: |
1895 | case CK_PointerToIntegral: |
1896 | case CK_ToVoid: |
1897 | case CK_VectorSplat: |
1898 | case CK_IntegralCast: |
1899 | case CK_BooleanToSignedIntegral: |
1900 | case CK_IntegralToFloating: |
1901 | case CK_FloatingToIntegral: |
1902 | case CK_FloatingCast: |
1903 | case CK_ObjCObjectLValueCast: |
1904 | case CK_FloatingRealToComplex: |
1905 | case CK_FloatingComplexToReal: |
1906 | case CK_FloatingComplexCast: |
1907 | case CK_FloatingComplexToIntegralComplex: |
1908 | case CK_IntegralRealToComplex: |
1909 | case CK_IntegralComplexToReal: |
1910 | case CK_IntegralComplexCast: |
1911 | case CK_IntegralComplexToFloatingComplex: |
1912 | case CK_ARCProduceObject: |
1913 | case CK_ARCConsumeObject: |
1914 | case CK_ARCReclaimReturnedObject: |
1915 | case CK_ARCExtendBlockObject: |
1916 | case CK_ZeroToOCLOpaqueType: |
1917 | case CK_IntToOCLSampler: |
1918 | case CK_FloatingToFixedPoint: |
1919 | case CK_FixedPointToFloating: |
1920 | case CK_FixedPointCast: |
1921 | case CK_FixedPointToIntegral: |
1922 | case CK_IntegralToFixedPoint: |
1923 | case CK_MatrixCast: |
1924 | case CK_HLSLVectorTruncation: |
1925 | assert(!getType()->isBooleanType() && "unheralded conversion to bool" ); |
1926 | goto CheckNoBasePath; |
1927 | |
1928 | case CK_Dependent: |
1929 | case CK_LValueToRValue: |
1930 | case CK_NoOp: |
1931 | case CK_AtomicToNonAtomic: |
1932 | case CK_NonAtomicToAtomic: |
1933 | case CK_PointerToBoolean: |
1934 | case CK_IntegralToBoolean: |
1935 | case CK_FloatingToBoolean: |
1936 | case CK_MemberPointerToBoolean: |
1937 | case CK_FloatingComplexToBoolean: |
1938 | case CK_IntegralComplexToBoolean: |
1939 | case CK_LValueBitCast: // -> bool& |
1940 | case CK_LValueToRValueBitCast: |
1941 | case CK_UserDefinedConversion: // operator bool() |
1942 | case CK_BuiltinFnToFnPtr: |
1943 | case CK_FixedPointToBoolean: |
1944 | case CK_HLSLArrayRValue: |
1945 | CheckNoBasePath: |
1946 | assert(path_empty() && "Cast kind should not have a base path!" ); |
1947 | break; |
1948 | } |
1949 | return true; |
1950 | } |
1951 | |
1952 | const char *CastExpr::getCastKindName(CastKind CK) { |
1953 | switch (CK) { |
1954 | #define CAST_OPERATION(Name) case CK_##Name: return #Name; |
1955 | #include "clang/AST/OperationKinds.def" |
1956 | } |
1957 | llvm_unreachable("Unhandled cast kind!" ); |
1958 | } |
1959 | |
1960 | namespace { |
1961 | // Skip over implicit nodes produced as part of semantic analysis. |
1962 | // Designed for use with IgnoreExprNodes. |
1963 | static Expr *ignoreImplicitSemaNodes(Expr *E) { |
1964 | if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(Val: E)) |
1965 | return Materialize->getSubExpr(); |
1966 | |
1967 | if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(Val: E)) |
1968 | return Binder->getSubExpr(); |
1969 | |
1970 | if (auto *Full = dyn_cast<FullExpr>(Val: E)) |
1971 | return Full->getSubExpr(); |
1972 | |
1973 | if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(Val: E); |
1974 | CPLIE && CPLIE->getInitExprs().size() == 1) |
1975 | return CPLIE->getInitExprs()[0]; |
1976 | |
1977 | return E; |
1978 | } |
1979 | } // namespace |
1980 | |
1981 | Expr *CastExpr::getSubExprAsWritten() { |
1982 | const Expr *SubExpr = nullptr; |
1983 | |
1984 | for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(Val: SubExpr)) { |
1985 | SubExpr = IgnoreExprNodes(E: E->getSubExpr(), Fns&: ignoreImplicitSemaNodes); |
1986 | |
1987 | // Conversions by constructor and conversion functions have a |
1988 | // subexpression describing the call; strip it off. |
1989 | if (E->getCastKind() == CK_ConstructorConversion) { |
1990 | SubExpr = IgnoreExprNodes(E: cast<CXXConstructExpr>(Val: SubExpr)->getArg(Arg: 0), |
1991 | Fns&: ignoreImplicitSemaNodes); |
1992 | } else if (E->getCastKind() == CK_UserDefinedConversion) { |
1993 | assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && |
1994 | "Unexpected SubExpr for CK_UserDefinedConversion." ); |
1995 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: SubExpr)) |
1996 | SubExpr = MCE->getImplicitObjectArgument(); |
1997 | } |
1998 | } |
1999 | |
2000 | return const_cast<Expr *>(SubExpr); |
2001 | } |
2002 | |
2003 | NamedDecl *CastExpr::getConversionFunction() const { |
2004 | const Expr *SubExpr = nullptr; |
2005 | |
2006 | for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(Val: SubExpr)) { |
2007 | SubExpr = IgnoreExprNodes(E: E->getSubExpr(), Fns&: ignoreImplicitSemaNodes); |
2008 | |
2009 | if (E->getCastKind() == CK_ConstructorConversion) |
2010 | return cast<CXXConstructExpr>(Val: SubExpr)->getConstructor(); |
2011 | |
2012 | if (E->getCastKind() == CK_UserDefinedConversion) { |
2013 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: SubExpr)) |
2014 | return MCE->getMethodDecl(); |
2015 | } |
2016 | } |
2017 | |
2018 | return nullptr; |
2019 | } |
2020 | |
2021 | CXXBaseSpecifier **CastExpr::path_buffer() { |
2022 | switch (getStmtClass()) { |
2023 | #define ABSTRACT_STMT(x) |
2024 | #define CASTEXPR(Type, Base) \ |
2025 | case Stmt::Type##Class: \ |
2026 | return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>(); |
2027 | #define STMT(Type, Base) |
2028 | #include "clang/AST/StmtNodes.inc" |
2029 | default: |
2030 | llvm_unreachable("non-cast expressions not possible here" ); |
2031 | } |
2032 | } |
2033 | |
2034 | const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType, |
2035 | QualType opType) { |
2036 | auto RD = unionType->castAs<RecordType>()->getDecl(); |
2037 | return getTargetFieldForToUnionCast(RD, opType); |
2038 | } |
2039 | |
2040 | const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD, |
2041 | QualType OpType) { |
2042 | auto &Ctx = RD->getASTContext(); |
2043 | RecordDecl::field_iterator Field, FieldEnd; |
2044 | for (Field = RD->field_begin(), FieldEnd = RD->field_end(); |
2045 | Field != FieldEnd; ++Field) { |
2046 | if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) && |
2047 | !Field->isUnnamedBitField()) { |
2048 | return *Field; |
2049 | } |
2050 | } |
2051 | return nullptr; |
2052 | } |
2053 | |
2054 | FPOptionsOverride *CastExpr::getTrailingFPFeatures() { |
2055 | assert(hasStoredFPFeatures()); |
2056 | switch (getStmtClass()) { |
2057 | case ImplicitCastExprClass: |
2058 | return static_cast<ImplicitCastExpr *>(this) |
2059 | ->getTrailingObjects<FPOptionsOverride>(); |
2060 | case CStyleCastExprClass: |
2061 | return static_cast<CStyleCastExpr *>(this) |
2062 | ->getTrailingObjects<FPOptionsOverride>(); |
2063 | case CXXFunctionalCastExprClass: |
2064 | return static_cast<CXXFunctionalCastExpr *>(this) |
2065 | ->getTrailingObjects<FPOptionsOverride>(); |
2066 | case CXXStaticCastExprClass: |
2067 | return static_cast<CXXStaticCastExpr *>(this) |
2068 | ->getTrailingObjects<FPOptionsOverride>(); |
2069 | default: |
2070 | llvm_unreachable("Cast does not have FPFeatures" ); |
2071 | } |
2072 | } |
2073 | |
2074 | ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, |
2075 | CastKind Kind, Expr *Operand, |
2076 | const CXXCastPath *BasePath, |
2077 | ExprValueKind VK, |
2078 | FPOptionsOverride FPO) { |
2079 | unsigned PathSize = (BasePath ? BasePath->size() : 0); |
2080 | void *Buffer = |
2081 | C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( |
2082 | Counts: PathSize, Counts: FPO.requiresTrailingStorage())); |
2083 | // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and |
2084 | // std::nullptr_t have special semantics not captured by CK_LValueToRValue. |
2085 | assert((Kind != CK_LValueToRValue || |
2086 | !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && |
2087 | "invalid type for lvalue-to-rvalue conversion" ); |
2088 | ImplicitCastExpr *E = |
2089 | new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK); |
2090 | if (PathSize) |
2091 | std::uninitialized_copy_n(BasePath->data(), BasePath->size(), |
2092 | E->getTrailingObjects<CXXBaseSpecifier *>()); |
2093 | return E; |
2094 | } |
2095 | |
2096 | ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C, |
2097 | unsigned PathSize, |
2098 | bool HasFPFeatures) { |
2099 | void *Buffer = |
2100 | C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( |
2101 | Counts: PathSize, Counts: HasFPFeatures)); |
2102 | return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures); |
2103 | } |
2104 | |
2105 | CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, |
2106 | ExprValueKind VK, CastKind K, Expr *Op, |
2107 | const CXXCastPath *BasePath, |
2108 | FPOptionsOverride FPO, |
2109 | TypeSourceInfo *WrittenTy, |
2110 | SourceLocation L, SourceLocation R) { |
2111 | unsigned PathSize = (BasePath ? BasePath->size() : 0); |
2112 | void *Buffer = |
2113 | C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( |
2114 | Counts: PathSize, Counts: FPO.requiresTrailingStorage())); |
2115 | CStyleCastExpr *E = |
2116 | new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R); |
2117 | if (PathSize) |
2118 | std::uninitialized_copy_n(BasePath->data(), BasePath->size(), |
2119 | E->getTrailingObjects<CXXBaseSpecifier *>()); |
2120 | return E; |
2121 | } |
2122 | |
2123 | CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C, |
2124 | unsigned PathSize, |
2125 | bool HasFPFeatures) { |
2126 | void *Buffer = |
2127 | C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>( |
2128 | Counts: PathSize, Counts: HasFPFeatures)); |
2129 | return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures); |
2130 | } |
2131 | |
2132 | /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it |
2133 | /// corresponds to, e.g. "<<=". |
2134 | StringRef BinaryOperator::getOpcodeStr(Opcode Op) { |
2135 | switch (Op) { |
2136 | #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling; |
2137 | #include "clang/AST/OperationKinds.def" |
2138 | } |
2139 | llvm_unreachable("Invalid OpCode!" ); |
2140 | } |
2141 | |
2142 | BinaryOperatorKind |
2143 | BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { |
2144 | switch (OO) { |
2145 | default: llvm_unreachable("Not an overloadable binary operator" ); |
2146 | case OO_Plus: return BO_Add; |
2147 | case OO_Minus: return BO_Sub; |
2148 | case OO_Star: return BO_Mul; |
2149 | case OO_Slash: return BO_Div; |
2150 | case OO_Percent: return BO_Rem; |
2151 | case OO_Caret: return BO_Xor; |
2152 | case OO_Amp: return BO_And; |
2153 | case OO_Pipe: return BO_Or; |
2154 | case OO_Equal: return BO_Assign; |
2155 | case OO_Spaceship: return BO_Cmp; |
2156 | case OO_Less: return BO_LT; |
2157 | case OO_Greater: return BO_GT; |
2158 | case OO_PlusEqual: return BO_AddAssign; |
2159 | case OO_MinusEqual: return BO_SubAssign; |
2160 | case OO_StarEqual: return BO_MulAssign; |
2161 | case OO_SlashEqual: return BO_DivAssign; |
2162 | case OO_PercentEqual: return BO_RemAssign; |
2163 | case OO_CaretEqual: return BO_XorAssign; |
2164 | case OO_AmpEqual: return BO_AndAssign; |
2165 | case OO_PipeEqual: return BO_OrAssign; |
2166 | case OO_LessLess: return BO_Shl; |
2167 | case OO_GreaterGreater: return BO_Shr; |
2168 | case OO_LessLessEqual: return BO_ShlAssign; |
2169 | case OO_GreaterGreaterEqual: return BO_ShrAssign; |
2170 | case OO_EqualEqual: return BO_EQ; |
2171 | case OO_ExclaimEqual: return BO_NE; |
2172 | case OO_LessEqual: return BO_LE; |
2173 | case OO_GreaterEqual: return BO_GE; |
2174 | case OO_AmpAmp: return BO_LAnd; |
2175 | case OO_PipePipe: return BO_LOr; |
2176 | case OO_Comma: return BO_Comma; |
2177 | case OO_ArrowStar: return BO_PtrMemI; |
2178 | } |
2179 | } |
2180 | |
2181 | OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { |
2182 | static const OverloadedOperatorKind OverOps[] = { |
2183 | /* .* Cannot be overloaded */OO_None, OO_ArrowStar, |
2184 | OO_Star, OO_Slash, OO_Percent, |
2185 | OO_Plus, OO_Minus, |
2186 | OO_LessLess, OO_GreaterGreater, |
2187 | OO_Spaceship, |
2188 | OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, |
2189 | OO_EqualEqual, OO_ExclaimEqual, |
2190 | OO_Amp, |
2191 | OO_Caret, |
2192 | OO_Pipe, |
2193 | OO_AmpAmp, |
2194 | OO_PipePipe, |
2195 | OO_Equal, OO_StarEqual, |
2196 | OO_SlashEqual, OO_PercentEqual, |
2197 | OO_PlusEqual, OO_MinusEqual, |
2198 | OO_LessLessEqual, OO_GreaterGreaterEqual, |
2199 | OO_AmpEqual, OO_CaretEqual, |
2200 | OO_PipeEqual, |
2201 | OO_Comma |
2202 | }; |
2203 | return OverOps[Opc]; |
2204 | } |
2205 | |
2206 | bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx, |
2207 | Opcode Opc, |
2208 | const Expr *LHS, |
2209 | const Expr *RHS) { |
2210 | if (Opc != BO_Add) |
2211 | return false; |
2212 | |
2213 | // Check that we have one pointer and one integer operand. |
2214 | const Expr *PExp; |
2215 | if (LHS->getType()->isPointerType()) { |
2216 | if (!RHS->getType()->isIntegerType()) |
2217 | return false; |
2218 | PExp = LHS; |
2219 | } else if (RHS->getType()->isPointerType()) { |
2220 | if (!LHS->getType()->isIntegerType()) |
2221 | return false; |
2222 | PExp = RHS; |
2223 | } else { |
2224 | return false; |
2225 | } |
2226 | |
2227 | // Check that the pointer is a nullptr. |
2228 | if (!PExp->IgnoreParenCasts() |
2229 | ->isNullPointerConstant(Ctx, NPC: Expr::NPC_ValueDependentIsNotNull)) |
2230 | return false; |
2231 | |
2232 | // Check that the pointee type is char-sized. |
2233 | const PointerType *PTy = PExp->getType()->getAs<PointerType>(); |
2234 | if (!PTy || !PTy->getPointeeType()->isCharType()) |
2235 | return false; |
2236 | |
2237 | return true; |
2238 | } |
2239 | |
2240 | SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind, |
2241 | QualType ResultTy, SourceLocation BLoc, |
2242 | SourceLocation RParenLoc, |
2243 | DeclContext *ParentContext) |
2244 | : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary), |
2245 | BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) { |
2246 | SourceLocExprBits.Kind = llvm::to_underlying(E: Kind); |
2247 | // In dependent contexts, function names may change. |
2248 | setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext() |
2249 | ? ExprDependence::Value |
2250 | : ExprDependence::None); |
2251 | } |
2252 | |
2253 | StringRef SourceLocExpr::getBuiltinStr() const { |
2254 | switch (getIdentKind()) { |
2255 | case SourceLocIdentKind::File: |
2256 | return "__builtin_FILE" ; |
2257 | case SourceLocIdentKind::FileName: |
2258 | return "__builtin_FILE_NAME" ; |
2259 | case SourceLocIdentKind::Function: |
2260 | return "__builtin_FUNCTION" ; |
2261 | case SourceLocIdentKind::FuncSig: |
2262 | return "__builtin_FUNCSIG" ; |
2263 | case SourceLocIdentKind::Line: |
2264 | return "__builtin_LINE" ; |
2265 | case SourceLocIdentKind::Column: |
2266 | return "__builtin_COLUMN" ; |
2267 | case SourceLocIdentKind::SourceLocStruct: |
2268 | return "__builtin_source_location" ; |
2269 | } |
2270 | llvm_unreachable("unexpected IdentKind!" ); |
2271 | } |
2272 | |
2273 | APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx, |
2274 | const Expr *DefaultExpr) const { |
2275 | SourceLocation Loc; |
2276 | const DeclContext *Context; |
2277 | |
2278 | if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(Val: DefaultExpr)) { |
2279 | Loc = DIE->getUsedLocation(); |
2280 | Context = DIE->getUsedContext(); |
2281 | } else if (const auto *DAE = |
2282 | dyn_cast_if_present<CXXDefaultArgExpr>(Val: DefaultExpr)) { |
2283 | Loc = DAE->getUsedLocation(); |
2284 | Context = DAE->getUsedContext(); |
2285 | } else { |
2286 | Loc = getLocation(); |
2287 | Context = getParentContext(); |
2288 | } |
2289 | |
2290 | PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc( |
2291 | Loc: Ctx.getSourceManager().getExpansionRange(Loc).getEnd()); |
2292 | |
2293 | auto MakeStringLiteral = [&](StringRef Tmp) { |
2294 | using LValuePathEntry = APValue::LValuePathEntry; |
2295 | StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Key: Tmp); |
2296 | // Decay the string to a pointer to the first character. |
2297 | LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(Index: 0)}; |
2298 | return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false); |
2299 | }; |
2300 | |
2301 | switch (getIdentKind()) { |
2302 | case SourceLocIdentKind::FileName: { |
2303 | // __builtin_FILE_NAME() is a Clang-specific extension that expands to the |
2304 | // the last part of __builtin_FILE(). |
2305 | SmallString<256> FileName; |
2306 | clang::Preprocessor::processPathToFileName( |
2307 | FileName, PLoc, LangOpts: Ctx.getLangOpts(), TI: Ctx.getTargetInfo()); |
2308 | return MakeStringLiteral(FileName); |
2309 | } |
2310 | case SourceLocIdentKind::File: { |
2311 | SmallString<256> Path(PLoc.getFilename()); |
2312 | clang::Preprocessor::processPathForFileMacro(Path, LangOpts: Ctx.getLangOpts(), |
2313 | TI: Ctx.getTargetInfo()); |
2314 | return MakeStringLiteral(Path); |
2315 | } |
2316 | case SourceLocIdentKind::Function: |
2317 | case SourceLocIdentKind::FuncSig: { |
2318 | const auto *CurDecl = dyn_cast<Decl>(Val: Context); |
2319 | const auto Kind = getIdentKind() == SourceLocIdentKind::Function |
2320 | ? PredefinedIdentKind::Function |
2321 | : PredefinedIdentKind::FuncSig; |
2322 | return MakeStringLiteral( |
2323 | CurDecl ? PredefinedExpr::ComputeName(IK: Kind, CurrentDecl: CurDecl) : std::string("" )); |
2324 | } |
2325 | case SourceLocIdentKind::Line: |
2326 | return APValue(Ctx.MakeIntValue(Value: PLoc.getLine(), Type: Ctx.UnsignedIntTy)); |
2327 | case SourceLocIdentKind::Column: |
2328 | return APValue(Ctx.MakeIntValue(Value: PLoc.getColumn(), Type: Ctx.UnsignedIntTy)); |
2329 | case SourceLocIdentKind::SourceLocStruct: { |
2330 | // Fill in a std::source_location::__impl structure, by creating an |
2331 | // artificial file-scoped CompoundLiteralExpr, and returning a pointer to |
2332 | // that. |
2333 | const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl(); |
2334 | assert(ImplDecl); |
2335 | |
2336 | // Construct an APValue for the __impl struct, and get or create a Decl |
2337 | // corresponding to that. Note that we've already verified that the shape of |
2338 | // the ImplDecl type is as expected. |
2339 | |
2340 | APValue Value(APValue::UninitStruct(), 0, 4); |
2341 | for (const FieldDecl *F : ImplDecl->fields()) { |
2342 | StringRef Name = F->getName(); |
2343 | if (Name == "_M_file_name" ) { |
2344 | SmallString<256> Path(PLoc.getFilename()); |
2345 | clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(), |
2346 | Ctx.getTargetInfo()); |
2347 | Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path); |
2348 | } else if (Name == "_M_function_name" ) { |
2349 | // Note: this emits the PrettyFunction name -- different than what |
2350 | // __builtin_FUNCTION() above returns! |
2351 | const auto *CurDecl = dyn_cast<Decl>(Context); |
2352 | Value.getStructField(F->getFieldIndex()) = MakeStringLiteral( |
2353 | CurDecl && !isa<TranslationUnitDecl>(CurDecl) |
2354 | ? StringRef(PredefinedExpr::ComputeName( |
2355 | PredefinedIdentKind::PrettyFunction, CurDecl)) |
2356 | : "" ); |
2357 | } else if (Name == "_M_line" ) { |
2358 | llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType()); |
2359 | Value.getStructField(F->getFieldIndex()) = APValue(IntVal); |
2360 | } else if (Name == "_M_column" ) { |
2361 | llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType()); |
2362 | Value.getStructField(F->getFieldIndex()) = APValue(IntVal); |
2363 | } |
2364 | } |
2365 | |
2366 | UnnamedGlobalConstantDecl *GV = |
2367 | Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value); |
2368 | |
2369 | return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{}, |
2370 | false); |
2371 | } |
2372 | } |
2373 | llvm_unreachable("unhandled case" ); |
2374 | } |
2375 | |
2376 | InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc, |
2377 | ArrayRef<Expr *> initExprs, SourceLocation rbraceloc) |
2378 | : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary), |
2379 | InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc), |
2380 | RBraceLoc(rbraceloc), AltForm(nullptr, true) { |
2381 | sawArrayRangeDesignator(ARD: false); |
2382 | InitExprs.insert(C, I: InitExprs.end(), From: initExprs.begin(), To: initExprs.end()); |
2383 | |
2384 | setDependence(computeDependence(E: this)); |
2385 | } |
2386 | |
2387 | void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) { |
2388 | if (NumInits > InitExprs.size()) |
2389 | InitExprs.reserve(C, N: NumInits); |
2390 | } |
2391 | |
2392 | void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) { |
2393 | InitExprs.resize(C, N: NumInits, NV: nullptr); |
2394 | } |
2395 | |
2396 | Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) { |
2397 | if (Init >= InitExprs.size()) { |
2398 | InitExprs.insert(C, I: InitExprs.end(), NumToInsert: Init - InitExprs.size() + 1, Elt: nullptr); |
2399 | setInit(Init, expr); |
2400 | return nullptr; |
2401 | } |
2402 | |
2403 | Expr *Result = cast_or_null<Expr>(Val: InitExprs[Init]); |
2404 | setInit(Init, expr); |
2405 | return Result; |
2406 | } |
2407 | |
2408 | void InitListExpr::setArrayFiller(Expr *filler) { |
2409 | assert(!hasArrayFiller() && "Filler already set!" ); |
2410 | ArrayFillerOrUnionFieldInit = filler; |
2411 | // Fill out any "holes" in the array due to designated initializers. |
2412 | Expr **inits = getInits(); |
2413 | for (unsigned i = 0, e = getNumInits(); i != e; ++i) |
2414 | if (inits[i] == nullptr) |
2415 | inits[i] = filler; |
2416 | } |
2417 | |
2418 | bool InitListExpr::isStringLiteralInit() const { |
2419 | if (getNumInits() != 1) |
2420 | return false; |
2421 | const ArrayType *AT = getType()->getAsArrayTypeUnsafe(); |
2422 | if (!AT || !AT->getElementType()->isIntegerType()) |
2423 | return false; |
2424 | // It is possible for getInit() to return null. |
2425 | const Expr *Init = getInit(Init: 0); |
2426 | if (!Init) |
2427 | return false; |
2428 | Init = Init->IgnoreParenImpCasts(); |
2429 | return isa<StringLiteral>(Val: Init) || isa<ObjCEncodeExpr>(Val: Init); |
2430 | } |
2431 | |
2432 | bool InitListExpr::isTransparent() const { |
2433 | assert(isSemanticForm() && "syntactic form never semantically transparent" ); |
2434 | |
2435 | // A glvalue InitListExpr is always just sugar. |
2436 | if (isGLValue()) { |
2437 | assert(getNumInits() == 1 && "multiple inits in glvalue init list" ); |
2438 | return true; |
2439 | } |
2440 | |
2441 | // Otherwise, we're sugar if and only if we have exactly one initializer that |
2442 | // is of the same type. |
2443 | if (getNumInits() != 1 || !getInit(Init: 0)) |
2444 | return false; |
2445 | |
2446 | // Don't confuse aggregate initialization of a struct X { X &x; }; with a |
2447 | // transparent struct copy. |
2448 | if (!getInit(Init: 0)->isPRValue() && getType()->isRecordType()) |
2449 | return false; |
2450 | |
2451 | return getType().getCanonicalType() == |
2452 | getInit(Init: 0)->getType().getCanonicalType(); |
2453 | } |
2454 | |
2455 | bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const { |
2456 | assert(isSyntacticForm() && "only test syntactic form as zero initializer" ); |
2457 | |
2458 | if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(Init: 0)) { |
2459 | return false; |
2460 | } |
2461 | |
2462 | const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(Val: getInit(Init: 0)->IgnoreImplicit()); |
2463 | return Lit && Lit->getValue() == 0; |
2464 | } |
2465 | |
2466 | SourceLocation InitListExpr::getBeginLoc() const { |
2467 | if (InitListExpr *SyntacticForm = getSyntacticForm()) |
2468 | return SyntacticForm->getBeginLoc(); |
2469 | SourceLocation Beg = LBraceLoc; |
2470 | if (Beg.isInvalid()) { |
2471 | // Find the first non-null initializer. |
2472 | for (InitExprsTy::const_iterator I = InitExprs.begin(), |
2473 | E = InitExprs.end(); |
2474 | I != E; ++I) { |
2475 | if (Stmt *S = *I) { |
2476 | Beg = S->getBeginLoc(); |
2477 | break; |
2478 | } |
2479 | } |
2480 | } |
2481 | return Beg; |
2482 | } |
2483 | |
2484 | SourceLocation InitListExpr::getEndLoc() const { |
2485 | if (InitListExpr *SyntacticForm = getSyntacticForm()) |
2486 | return SyntacticForm->getEndLoc(); |
2487 | SourceLocation End = RBraceLoc; |
2488 | if (End.isInvalid()) { |
2489 | // Find the first non-null initializer from the end. |
2490 | for (Stmt *S : llvm::reverse(C: InitExprs)) { |
2491 | if (S) { |
2492 | End = S->getEndLoc(); |
2493 | break; |
2494 | } |
2495 | } |
2496 | } |
2497 | return End; |
2498 | } |
2499 | |
2500 | /// getFunctionType - Return the underlying function type for this block. |
2501 | /// |
2502 | const FunctionProtoType *BlockExpr::getFunctionType() const { |
2503 | // The block pointer is never sugared, but the function type might be. |
2504 | return cast<BlockPointerType>(getType()) |
2505 | ->getPointeeType()->castAs<FunctionProtoType>(); |
2506 | } |
2507 | |
2508 | SourceLocation BlockExpr::getCaretLocation() const { |
2509 | return TheBlock->getCaretLocation(); |
2510 | } |
2511 | const Stmt *BlockExpr::getBody() const { |
2512 | return TheBlock->getBody(); |
2513 | } |
2514 | Stmt *BlockExpr::getBody() { |
2515 | return TheBlock->getBody(); |
2516 | } |
2517 | |
2518 | |
2519 | //===----------------------------------------------------------------------===// |
2520 | // Generic Expression Routines |
2521 | //===----------------------------------------------------------------------===// |
2522 | |
2523 | bool Expr::isReadIfDiscardedInCPlusPlus11() const { |
2524 | // In C++11, discarded-value expressions of a certain form are special, |
2525 | // according to [expr]p10: |
2526 | // The lvalue-to-rvalue conversion (4.1) is applied only if the |
2527 | // expression is a glvalue of volatile-qualified type and it has |
2528 | // one of the following forms: |
2529 | if (!isGLValue() || !getType().isVolatileQualified()) |
2530 | return false; |
2531 | |
2532 | const Expr *E = IgnoreParens(); |
2533 | |
2534 | // - id-expression (5.1.1), |
2535 | if (isa<DeclRefExpr>(Val: E)) |
2536 | return true; |
2537 | |
2538 | // - subscripting (5.2.1), |
2539 | if (isa<ArraySubscriptExpr>(Val: E)) |
2540 | return true; |
2541 | |
2542 | // - class member access (5.2.5), |
2543 | if (isa<MemberExpr>(Val: E)) |
2544 | return true; |
2545 | |
2546 | // - indirection (5.3.1), |
2547 | if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) |
2548 | if (UO->getOpcode() == UO_Deref) |
2549 | return true; |
2550 | |
2551 | if (auto *BO = dyn_cast<BinaryOperator>(Val: E)) { |
2552 | // - pointer-to-member operation (5.5), |
2553 | if (BO->isPtrMemOp()) |
2554 | return true; |
2555 | |
2556 | // - comma expression (5.18) where the right operand is one of the above. |
2557 | if (BO->getOpcode() == BO_Comma) |
2558 | return BO->getRHS()->isReadIfDiscardedInCPlusPlus11(); |
2559 | } |
2560 | |
2561 | // - conditional expression (5.16) where both the second and the third |
2562 | // operands are one of the above, or |
2563 | if (auto *CO = dyn_cast<ConditionalOperator>(Val: E)) |
2564 | return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() && |
2565 | CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11(); |
2566 | // The related edge case of "*x ?: *x". |
2567 | if (auto *BCO = |
2568 | dyn_cast<BinaryConditionalOperator>(Val: E)) { |
2569 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: BCO->getTrueExpr())) |
2570 | return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() && |
2571 | BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11(); |
2572 | } |
2573 | |
2574 | // Objective-C++ extensions to the rule. |
2575 | if (isa<ObjCIvarRefExpr>(Val: E)) |
2576 | return true; |
2577 | if (const auto *POE = dyn_cast<PseudoObjectExpr>(Val: E)) { |
2578 | if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(Val: POE->getSyntacticForm())) |
2579 | return true; |
2580 | } |
2581 | |
2582 | return false; |
2583 | } |
2584 | |
2585 | /// isUnusedResultAWarning - Return true if this immediate expression should |
2586 | /// be warned about if the result is unused. If so, fill in Loc and Ranges |
2587 | /// with location to warn on and the source range[s] to report with the |
2588 | /// warning. |
2589 | bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, |
2590 | SourceRange &R1, SourceRange &R2, |
2591 | ASTContext &Ctx) const { |
2592 | // Don't warn if the expr is type dependent. The type could end up |
2593 | // instantiating to void. |
2594 | if (isTypeDependent()) |
2595 | return false; |
2596 | |
2597 | switch (getStmtClass()) { |
2598 | default: |
2599 | if (getType()->isVoidType()) |
2600 | return false; |
2601 | WarnE = this; |
2602 | Loc = getExprLoc(); |
2603 | R1 = getSourceRange(); |
2604 | return true; |
2605 | case ParenExprClass: |
2606 | return cast<ParenExpr>(Val: this)->getSubExpr()-> |
2607 | isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2608 | case GenericSelectionExprClass: |
2609 | return cast<GenericSelectionExpr>(Val: this)->getResultExpr()-> |
2610 | isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2611 | case CoawaitExprClass: |
2612 | case CoyieldExprClass: |
2613 | return cast<CoroutineSuspendExpr>(Val: this)->getResumeExpr()-> |
2614 | isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2615 | case ChooseExprClass: |
2616 | return cast<ChooseExpr>(Val: this)->getChosenSubExpr()-> |
2617 | isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2618 | case UnaryOperatorClass: { |
2619 | const UnaryOperator *UO = cast<UnaryOperator>(Val: this); |
2620 | |
2621 | switch (UO->getOpcode()) { |
2622 | case UO_Plus: |
2623 | case UO_Minus: |
2624 | case UO_AddrOf: |
2625 | case UO_Not: |
2626 | case UO_LNot: |
2627 | case UO_Deref: |
2628 | break; |
2629 | case UO_Coawait: |
2630 | // This is just the 'operator co_await' call inside the guts of a |
2631 | // dependent co_await call. |
2632 | case UO_PostInc: |
2633 | case UO_PostDec: |
2634 | case UO_PreInc: |
2635 | case UO_PreDec: // ++/-- |
2636 | return false; // Not a warning. |
2637 | case UO_Real: |
2638 | case UO_Imag: |
2639 | // accessing a piece of a volatile complex is a side-effect. |
2640 | if (Ctx.getCanonicalType(T: UO->getSubExpr()->getType()) |
2641 | .isVolatileQualified()) |
2642 | return false; |
2643 | break; |
2644 | case UO_Extension: |
2645 | return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2646 | } |
2647 | WarnE = this; |
2648 | Loc = UO->getOperatorLoc(); |
2649 | R1 = UO->getSubExpr()->getSourceRange(); |
2650 | return true; |
2651 | } |
2652 | case BinaryOperatorClass: { |
2653 | const BinaryOperator *BO = cast<BinaryOperator>(Val: this); |
2654 | switch (BO->getOpcode()) { |
2655 | default: |
2656 | break; |
2657 | // Consider the RHS of comma for side effects. LHS was checked by |
2658 | // Sema::CheckCommaOperands. |
2659 | case BO_Comma: |
2660 | // ((foo = <blah>), 0) is an idiom for hiding the result (and |
2661 | // lvalue-ness) of an assignment written in a macro. |
2662 | if (IntegerLiteral *IE = |
2663 | dyn_cast<IntegerLiteral>(Val: BO->getRHS()->IgnoreParens())) |
2664 | if (IE->getValue() == 0) |
2665 | return false; |
2666 | return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2667 | // Consider '||', '&&' to have side effects if the LHS or RHS does. |
2668 | case BO_LAnd: |
2669 | case BO_LOr: |
2670 | if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) || |
2671 | !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) |
2672 | return false; |
2673 | break; |
2674 | } |
2675 | if (BO->isAssignmentOp()) |
2676 | return false; |
2677 | WarnE = this; |
2678 | Loc = BO->getOperatorLoc(); |
2679 | R1 = BO->getLHS()->getSourceRange(); |
2680 | R2 = BO->getRHS()->getSourceRange(); |
2681 | return true; |
2682 | } |
2683 | case CompoundAssignOperatorClass: |
2684 | case VAArgExprClass: |
2685 | case AtomicExprClass: |
2686 | return false; |
2687 | |
2688 | case ConditionalOperatorClass: { |
2689 | // If only one of the LHS or RHS is a warning, the operator might |
2690 | // be being used for control flow. Only warn if both the LHS and |
2691 | // RHS are warnings. |
2692 | const auto *Exp = cast<ConditionalOperator>(Val: this); |
2693 | return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) && |
2694 | Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2695 | } |
2696 | case BinaryConditionalOperatorClass: { |
2697 | const auto *Exp = cast<BinaryConditionalOperator>(Val: this); |
2698 | return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2699 | } |
2700 | |
2701 | case MemberExprClass: |
2702 | WarnE = this; |
2703 | Loc = cast<MemberExpr>(Val: this)->getMemberLoc(); |
2704 | R1 = SourceRange(Loc, Loc); |
2705 | R2 = cast<MemberExpr>(Val: this)->getBase()->getSourceRange(); |
2706 | return true; |
2707 | |
2708 | case ArraySubscriptExprClass: |
2709 | WarnE = this; |
2710 | Loc = cast<ArraySubscriptExpr>(Val: this)->getRBracketLoc(); |
2711 | R1 = cast<ArraySubscriptExpr>(Val: this)->getLHS()->getSourceRange(); |
2712 | R2 = cast<ArraySubscriptExpr>(Val: this)->getRHS()->getSourceRange(); |
2713 | return true; |
2714 | |
2715 | case CXXOperatorCallExprClass: { |
2716 | // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator |
2717 | // overloads as there is no reasonable way to define these such that they |
2718 | // have non-trivial, desirable side-effects. See the -Wunused-comparison |
2719 | // warning: operators == and != are commonly typo'ed, and so warning on them |
2720 | // provides additional value as well. If this list is updated, |
2721 | // DiagnoseUnusedComparison should be as well. |
2722 | const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(Val: this); |
2723 | switch (Op->getOperator()) { |
2724 | default: |
2725 | break; |
2726 | case OO_EqualEqual: |
2727 | case OO_ExclaimEqual: |
2728 | case OO_Less: |
2729 | case OO_Greater: |
2730 | case OO_GreaterEqual: |
2731 | case OO_LessEqual: |
2732 | if (Op->getCallReturnType(Ctx)->isReferenceType() || |
2733 | Op->getCallReturnType(Ctx)->isVoidType()) |
2734 | break; |
2735 | WarnE = this; |
2736 | Loc = Op->getOperatorLoc(); |
2737 | R1 = Op->getSourceRange(); |
2738 | return true; |
2739 | } |
2740 | |
2741 | // Fallthrough for generic call handling. |
2742 | [[fallthrough]]; |
2743 | } |
2744 | case CallExprClass: |
2745 | case CXXMemberCallExprClass: |
2746 | case UserDefinedLiteralClass: { |
2747 | // If this is a direct call, get the callee. |
2748 | const CallExpr *CE = cast<CallExpr>(Val: this); |
2749 | if (const Decl *FD = CE->getCalleeDecl()) { |
2750 | // If the callee has attribute pure, const, or warn_unused_result, warn |
2751 | // about it. void foo() { strlen("bar"); } should warn. |
2752 | // |
2753 | // Note: If new cases are added here, DiagnoseUnusedExprResult should be |
2754 | // updated to match for QoI. |
2755 | if (CE->hasUnusedResultAttr(Ctx) || |
2756 | FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) { |
2757 | WarnE = this; |
2758 | Loc = CE->getCallee()->getBeginLoc(); |
2759 | R1 = CE->getCallee()->getSourceRange(); |
2760 | |
2761 | if (unsigned NumArgs = CE->getNumArgs()) |
2762 | R2 = SourceRange(CE->getArg(Arg: 0)->getBeginLoc(), |
2763 | CE->getArg(Arg: NumArgs - 1)->getEndLoc()); |
2764 | return true; |
2765 | } |
2766 | } |
2767 | return false; |
2768 | } |
2769 | |
2770 | // If we don't know precisely what we're looking at, let's not warn. |
2771 | case UnresolvedLookupExprClass: |
2772 | case CXXUnresolvedConstructExprClass: |
2773 | case RecoveryExprClass: |
2774 | return false; |
2775 | |
2776 | case CXXTemporaryObjectExprClass: |
2777 | case CXXConstructExprClass: { |
2778 | if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) { |
2779 | const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>(); |
2780 | if (Type->hasAttr<WarnUnusedAttr>() || |
2781 | (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) { |
2782 | WarnE = this; |
2783 | Loc = getBeginLoc(); |
2784 | R1 = getSourceRange(); |
2785 | return true; |
2786 | } |
2787 | } |
2788 | |
2789 | const auto *CE = cast<CXXConstructExpr>(Val: this); |
2790 | if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { |
2791 | const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>(); |
2792 | if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) { |
2793 | WarnE = this; |
2794 | Loc = getBeginLoc(); |
2795 | R1 = getSourceRange(); |
2796 | |
2797 | if (unsigned NumArgs = CE->getNumArgs()) |
2798 | R2 = SourceRange(CE->getArg(Arg: 0)->getBeginLoc(), |
2799 | CE->getArg(Arg: NumArgs - 1)->getEndLoc()); |
2800 | return true; |
2801 | } |
2802 | } |
2803 | |
2804 | return false; |
2805 | } |
2806 | |
2807 | case ObjCMessageExprClass: { |
2808 | const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(Val: this); |
2809 | if (Ctx.getLangOpts().ObjCAutoRefCount && |
2810 | ME->isInstanceMessage() && |
2811 | !ME->getType()->isVoidType() && |
2812 | ME->getMethodFamily() == OMF_init) { |
2813 | WarnE = this; |
2814 | Loc = getExprLoc(); |
2815 | R1 = ME->getSourceRange(); |
2816 | return true; |
2817 | } |
2818 | |
2819 | if (const ObjCMethodDecl *MD = ME->getMethodDecl()) |
2820 | if (MD->hasAttr<WarnUnusedResultAttr>()) { |
2821 | WarnE = this; |
2822 | Loc = getExprLoc(); |
2823 | return true; |
2824 | } |
2825 | |
2826 | return false; |
2827 | } |
2828 | |
2829 | case ObjCPropertyRefExprClass: |
2830 | case ObjCSubscriptRefExprClass: |
2831 | WarnE = this; |
2832 | Loc = getExprLoc(); |
2833 | R1 = getSourceRange(); |
2834 | return true; |
2835 | |
2836 | case PseudoObjectExprClass: { |
2837 | const auto *POE = cast<PseudoObjectExpr>(Val: this); |
2838 | |
2839 | // For some syntactic forms, we should always warn. |
2840 | if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>( |
2841 | Val: POE->getSyntacticForm())) { |
2842 | WarnE = this; |
2843 | Loc = getExprLoc(); |
2844 | R1 = getSourceRange(); |
2845 | return true; |
2846 | } |
2847 | |
2848 | // For others, we should never warn. |
2849 | if (auto *BO = dyn_cast<BinaryOperator>(Val: POE->getSyntacticForm())) |
2850 | if (BO->isAssignmentOp()) |
2851 | return false; |
2852 | if (auto *UO = dyn_cast<UnaryOperator>(Val: POE->getSyntacticForm())) |
2853 | if (UO->isIncrementDecrementOp()) |
2854 | return false; |
2855 | |
2856 | // Otherwise, warn if the result expression would warn. |
2857 | const Expr *Result = POE->getResultExpr(); |
2858 | return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2859 | } |
2860 | |
2861 | case StmtExprClass: { |
2862 | // Statement exprs don't logically have side effects themselves, but are |
2863 | // sometimes used in macros in ways that give them a type that is unused. |
2864 | // For example ({ blah; foo(); }) will end up with a type if foo has a type. |
2865 | // however, if the result of the stmt expr is dead, we don't want to emit a |
2866 | // warning. |
2867 | const CompoundStmt *CS = cast<StmtExpr>(Val: this)->getSubStmt(); |
2868 | if (!CS->body_empty()) { |
2869 | if (const Expr *E = dyn_cast<Expr>(Val: CS->body_back())) |
2870 | return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2871 | if (const LabelStmt *Label = dyn_cast<LabelStmt>(Val: CS->body_back())) |
2872 | if (const Expr *E = dyn_cast<Expr>(Val: Label->getSubStmt())) |
2873 | return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2874 | } |
2875 | |
2876 | if (getType()->isVoidType()) |
2877 | return false; |
2878 | WarnE = this; |
2879 | Loc = cast<StmtExpr>(Val: this)->getLParenLoc(); |
2880 | R1 = getSourceRange(); |
2881 | return true; |
2882 | } |
2883 | case CXXFunctionalCastExprClass: |
2884 | case CStyleCastExprClass: { |
2885 | // Ignore an explicit cast to void, except in C++98 if the operand is a |
2886 | // volatile glvalue for which we would trigger an implicit read in any |
2887 | // other language mode. (Such an implicit read always happens as part of |
2888 | // the lvalue conversion in C, and happens in C++ for expressions of all |
2889 | // forms where it seems likely the user intended to trigger a volatile |
2890 | // load.) |
2891 | const CastExpr *CE = cast<CastExpr>(Val: this); |
2892 | const Expr *SubE = CE->getSubExpr()->IgnoreParens(); |
2893 | if (CE->getCastKind() == CK_ToVoid) { |
2894 | if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 && |
2895 | SubE->isReadIfDiscardedInCPlusPlus11()) { |
2896 | // Suppress the "unused value" warning for idiomatic usage of |
2897 | // '(void)var;' used to suppress "unused variable" warnings. |
2898 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: SubE)) |
2899 | if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) |
2900 | if (!VD->isExternallyVisible()) |
2901 | return false; |
2902 | |
2903 | // The lvalue-to-rvalue conversion would have no effect for an array. |
2904 | // It's implausible that the programmer expected this to result in a |
2905 | // volatile array load, so don't warn. |
2906 | if (SubE->getType()->isArrayType()) |
2907 | return false; |
2908 | |
2909 | return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2910 | } |
2911 | return false; |
2912 | } |
2913 | |
2914 | // If this is a cast to a constructor conversion, check the operand. |
2915 | // Otherwise, the result of the cast is unused. |
2916 | if (CE->getCastKind() == CK_ConstructorConversion) |
2917 | return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2918 | if (CE->getCastKind() == CK_Dependent) |
2919 | return false; |
2920 | |
2921 | WarnE = this; |
2922 | if (const CXXFunctionalCastExpr *CXXCE = |
2923 | dyn_cast<CXXFunctionalCastExpr>(Val: this)) { |
2924 | Loc = CXXCE->getBeginLoc(); |
2925 | R1 = CXXCE->getSubExpr()->getSourceRange(); |
2926 | } else { |
2927 | const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(Val: this); |
2928 | Loc = CStyleCE->getLParenLoc(); |
2929 | R1 = CStyleCE->getSubExpr()->getSourceRange(); |
2930 | } |
2931 | return true; |
2932 | } |
2933 | case ImplicitCastExprClass: { |
2934 | const CastExpr *ICE = cast<ImplicitCastExpr>(Val: this); |
2935 | |
2936 | // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect. |
2937 | if (ICE->getCastKind() == CK_LValueToRValue && |
2938 | ICE->getSubExpr()->getType().isVolatileQualified()) |
2939 | return false; |
2940 | |
2941 | return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2942 | } |
2943 | case CXXDefaultArgExprClass: |
2944 | return (cast<CXXDefaultArgExpr>(Val: this) |
2945 | ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); |
2946 | case CXXDefaultInitExprClass: |
2947 | return (cast<CXXDefaultInitExpr>(Val: this) |
2948 | ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); |
2949 | |
2950 | case CXXNewExprClass: |
2951 | // FIXME: In theory, there might be new expressions that don't have side |
2952 | // effects (e.g. a placement new with an uninitialized POD). |
2953 | case CXXDeleteExprClass: |
2954 | return false; |
2955 | case MaterializeTemporaryExprClass: |
2956 | return cast<MaterializeTemporaryExpr>(Val: this) |
2957 | ->getSubExpr() |
2958 | ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2959 | case CXXBindTemporaryExprClass: |
2960 | return cast<CXXBindTemporaryExpr>(Val: this)->getSubExpr() |
2961 | ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2962 | case ExprWithCleanupsClass: |
2963 | return cast<ExprWithCleanups>(Val: this)->getSubExpr() |
2964 | ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); |
2965 | } |
2966 | } |
2967 | |
2968 | /// isOBJCGCCandidate - Check if an expression is objc gc'able. |
2969 | /// returns true, if it is; false otherwise. |
2970 | bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { |
2971 | const Expr *E = IgnoreParens(); |
2972 | switch (E->getStmtClass()) { |
2973 | default: |
2974 | return false; |
2975 | case ObjCIvarRefExprClass: |
2976 | return true; |
2977 | case Expr::UnaryOperatorClass: |
2978 | return cast<UnaryOperator>(Val: E)->getSubExpr()->isOBJCGCCandidate(Ctx); |
2979 | case ImplicitCastExprClass: |
2980 | return cast<ImplicitCastExpr>(Val: E)->getSubExpr()->isOBJCGCCandidate(Ctx); |
2981 | case MaterializeTemporaryExprClass: |
2982 | return cast<MaterializeTemporaryExpr>(Val: E)->getSubExpr()->isOBJCGCCandidate( |
2983 | Ctx); |
2984 | case CStyleCastExprClass: |
2985 | return cast<CStyleCastExpr>(Val: E)->getSubExpr()->isOBJCGCCandidate(Ctx); |
2986 | case DeclRefExprClass: { |
2987 | const Decl *D = cast<DeclRefExpr>(Val: E)->getDecl(); |
2988 | |
2989 | if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
2990 | if (VD->hasGlobalStorage()) |
2991 | return true; |
2992 | QualType T = VD->getType(); |
2993 | // dereferencing to a pointer is always a gc'able candidate, |
2994 | // unless it is __weak. |
2995 | return T->isPointerType() && |
2996 | (Ctx.getObjCGCAttrKind(Ty: T) != Qualifiers::Weak); |
2997 | } |
2998 | return false; |
2999 | } |
3000 | case MemberExprClass: { |
3001 | const MemberExpr *M = cast<MemberExpr>(Val: E); |
3002 | return M->getBase()->isOBJCGCCandidate(Ctx); |
3003 | } |
3004 | case ArraySubscriptExprClass: |
3005 | return cast<ArraySubscriptExpr>(Val: E)->getBase()->isOBJCGCCandidate(Ctx); |
3006 | } |
3007 | } |
3008 | |
3009 | bool Expr::isBoundMemberFunction(ASTContext &Ctx) const { |
3010 | if (isTypeDependent()) |
3011 | return false; |
3012 | return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; |
3013 | } |
3014 | |
3015 | QualType Expr::findBoundMemberType(const Expr *expr) { |
3016 | assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); |
3017 | |
3018 | // Bound member expressions are always one of these possibilities: |
3019 | // x->m x.m x->*y x.*y |
3020 | // (possibly parenthesized) |
3021 | |
3022 | expr = expr->IgnoreParens(); |
3023 | if (const MemberExpr *mem = dyn_cast<MemberExpr>(Val: expr)) { |
3024 | assert(isa<CXXMethodDecl>(mem->getMemberDecl())); |
3025 | return mem->getMemberDecl()->getType(); |
3026 | } |
3027 | |
3028 | if (const BinaryOperator *op = dyn_cast<BinaryOperator>(Val: expr)) { |
3029 | QualType type = op->getRHS()->getType()->castAs<MemberPointerType>() |
3030 | ->getPointeeType(); |
3031 | assert(type->isFunctionType()); |
3032 | return type; |
3033 | } |
3034 | |
3035 | assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr)); |
3036 | return QualType(); |
3037 | } |
3038 | |
3039 | Expr *Expr::IgnoreImpCasts() { |
3040 | return IgnoreExprNodes(E: this, Fns&: IgnoreImplicitCastsSingleStep); |
3041 | } |
3042 | |
3043 | Expr *Expr::IgnoreCasts() { |
3044 | return IgnoreExprNodes(E: this, Fns&: IgnoreCastsSingleStep); |
3045 | } |
3046 | |
3047 | Expr *Expr::IgnoreImplicit() { |
3048 | return IgnoreExprNodes(E: this, Fns&: IgnoreImplicitSingleStep); |
3049 | } |
3050 | |
3051 | Expr *Expr::IgnoreImplicitAsWritten() { |
3052 | return IgnoreExprNodes(E: this, Fns&: IgnoreImplicitAsWrittenSingleStep); |
3053 | } |
3054 | |
3055 | Expr *Expr::IgnoreParens() { |
3056 | return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep); |
3057 | } |
3058 | |
3059 | Expr *Expr::IgnoreParenImpCasts() { |
3060 | return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep, |
3061 | Fns&: IgnoreImplicitCastsExtraSingleStep); |
3062 | } |
3063 | |
3064 | Expr *Expr::IgnoreParenCasts() { |
3065 | return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep, Fns&: IgnoreCastsSingleStep); |
3066 | } |
3067 | |
3068 | Expr *Expr::IgnoreConversionOperatorSingleStep() { |
3069 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: this)) { |
3070 | if (MCE->getMethodDecl() && isa<CXXConversionDecl>(Val: MCE->getMethodDecl())) |
3071 | return MCE->getImplicitObjectArgument(); |
3072 | } |
3073 | return this; |
3074 | } |
3075 | |
3076 | Expr *Expr::IgnoreParenLValueCasts() { |
3077 | return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep, |
3078 | Fns&: IgnoreLValueCastsSingleStep); |
3079 | } |
3080 | |
3081 | Expr *Expr::IgnoreParenBaseCasts() { |
3082 | return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep, |
3083 | Fns&: IgnoreBaseCastsSingleStep); |
3084 | } |
3085 | |
3086 | Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) { |
3087 | auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) { |
3088 | if (auto *CE = dyn_cast<CastExpr>(Val: E)) { |
3089 | // We ignore integer <-> casts that are of the same width, ptr<->ptr and |
3090 | // ptr<->int casts of the same width. We also ignore all identity casts. |
3091 | Expr *SubExpr = CE->getSubExpr(); |
3092 | bool IsIdentityCast = |
3093 | Ctx.hasSameUnqualifiedType(T1: E->getType(), T2: SubExpr->getType()); |
3094 | bool IsSameWidthCast = (E->getType()->isPointerType() || |
3095 | E->getType()->isIntegralType(Ctx)) && |
3096 | (SubExpr->getType()->isPointerType() || |
3097 | SubExpr->getType()->isIntegralType(Ctx)) && |
3098 | (Ctx.getTypeSize(T: E->getType()) == |
3099 | Ctx.getTypeSize(T: SubExpr->getType())); |
3100 | |
3101 | if (IsIdentityCast || IsSameWidthCast) |
3102 | return SubExpr; |
3103 | } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: E)) |
3104 | return NTTP->getReplacement(); |
3105 | |
3106 | return E; |
3107 | }; |
3108 | return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep, |
3109 | Fns&: IgnoreNoopCastsSingleStep); |
3110 | } |
3111 | |
3112 | Expr *Expr::IgnoreUnlessSpelledInSource() { |
3113 | auto IgnoreImplicitConstructorSingleStep = [](Expr *E) { |
3114 | if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(Val: E)) { |
3115 | auto *SE = Cast->getSubExpr(); |
3116 | if (SE->getSourceRange() == E->getSourceRange()) |
3117 | return SE; |
3118 | } |
3119 | |
3120 | if (auto *C = dyn_cast<CXXConstructExpr>(Val: E)) { |
3121 | auto NumArgs = C->getNumArgs(); |
3122 | if (NumArgs == 1 || |
3123 | (NumArgs > 1 && isa<CXXDefaultArgExpr>(Val: C->getArg(Arg: 1)))) { |
3124 | Expr *A = C->getArg(Arg: 0); |
3125 | if (A->getSourceRange() == E->getSourceRange() || C->isElidable()) |
3126 | return A; |
3127 | } |
3128 | } |
3129 | return E; |
3130 | }; |
3131 | auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) { |
3132 | if (auto *C = dyn_cast<CXXMemberCallExpr>(Val: E)) { |
3133 | Expr *ExprNode = C->getImplicitObjectArgument(); |
3134 | if (ExprNode->getSourceRange() == E->getSourceRange()) { |
3135 | return ExprNode; |
3136 | } |
3137 | if (auto *PE = dyn_cast<ParenExpr>(Val: ExprNode)) { |
3138 | if (PE->getSourceRange() == C->getSourceRange()) { |
3139 | return cast<Expr>(Val: PE); |
3140 | } |
3141 | } |
3142 | ExprNode = ExprNode->IgnoreParenImpCasts(); |
3143 | if (ExprNode->getSourceRange() == E->getSourceRange()) |
3144 | return ExprNode; |
3145 | } |
3146 | return E; |
3147 | }; |
3148 | return IgnoreExprNodes( |
3149 | E: this, Fns&: IgnoreImplicitSingleStep, Fns&: IgnoreImplicitCastsExtraSingleStep, |
3150 | Fns&: IgnoreParensOnlySingleStep, Fns&: IgnoreImplicitConstructorSingleStep, |
3151 | Fns&: IgnoreImplicitMemberCallSingleStep); |
3152 | } |
3153 | |
3154 | bool Expr::isDefaultArgument() const { |
3155 | const Expr *E = this; |
3156 | if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(Val: E)) |
3157 | E = M->getSubExpr(); |
3158 | |
3159 | while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
3160 | E = ICE->getSubExprAsWritten(); |
3161 | |
3162 | return isa<CXXDefaultArgExpr>(Val: E); |
3163 | } |
3164 | |
3165 | /// Skip over any no-op casts and any temporary-binding |
3166 | /// expressions. |
3167 | static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { |
3168 | if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(Val: E)) |
3169 | E = M->getSubExpr(); |
3170 | |
3171 | while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
3172 | if (ICE->getCastKind() == CK_NoOp) |
3173 | E = ICE->getSubExpr(); |
3174 | else |
3175 | break; |
3176 | } |
3177 | |
3178 | while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(Val: E)) |
3179 | E = BE->getSubExpr(); |
3180 | |
3181 | while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
3182 | if (ICE->getCastKind() == CK_NoOp) |
3183 | E = ICE->getSubExpr(); |
3184 | else |
3185 | break; |
3186 | } |
3187 | |
3188 | return E->IgnoreParens(); |
3189 | } |
3190 | |
3191 | /// isTemporaryObject - Determines if this expression produces a |
3192 | /// temporary of the given class type. |
3193 | bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { |
3194 | if (!C.hasSameUnqualifiedType(T1: getType(), T2: C.getTypeDeclType(TempTy))) |
3195 | return false; |
3196 | |
3197 | const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(E: this); |
3198 | |
3199 | // Temporaries are by definition pr-values of class type. |
3200 | if (!E->Classify(Ctx&: C).isPRValue()) { |
3201 | // In this context, property reference is a message call and is pr-value. |
3202 | if (!isa<ObjCPropertyRefExpr>(Val: E)) |
3203 | return false; |
3204 | } |
3205 | |
3206 | // Black-list a few cases which yield pr-values of class type that don't |
3207 | // refer to temporaries of that type: |
3208 | |
3209 | // - implicit derived-to-base conversions |
3210 | if (isa<ImplicitCastExpr>(Val: E)) { |
3211 | switch (cast<ImplicitCastExpr>(Val: E)->getCastKind()) { |
3212 | case CK_DerivedToBase: |
3213 | case CK_UncheckedDerivedToBase: |
3214 | return false; |
3215 | default: |
3216 | break; |
3217 | } |
3218 | } |
3219 | |
3220 | // - member expressions (all) |
3221 | if (isa<MemberExpr>(Val: E)) |
3222 | return false; |
3223 | |
3224 | if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) |
3225 | if (BO->isPtrMemOp()) |
3226 | return false; |
3227 | |
3228 | // - opaque values (all) |
3229 | if (isa<OpaqueValueExpr>(Val: E)) |
3230 | return false; |
3231 | |
3232 | return true; |
3233 | } |
3234 | |
3235 | bool Expr::isImplicitCXXThis() const { |
3236 | const Expr *E = this; |
3237 | |
3238 | // Strip away parentheses and casts we don't care about. |
3239 | while (true) { |
3240 | if (const ParenExpr *Paren = dyn_cast<ParenExpr>(Val: E)) { |
3241 | E = Paren->getSubExpr(); |
3242 | continue; |
3243 | } |
3244 | |
3245 | if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
3246 | if (ICE->getCastKind() == CK_NoOp || |
3247 | ICE->getCastKind() == CK_LValueToRValue || |
3248 | ICE->getCastKind() == CK_DerivedToBase || |
3249 | ICE->getCastKind() == CK_UncheckedDerivedToBase) { |
3250 | E = ICE->getSubExpr(); |
3251 | continue; |
3252 | } |
3253 | } |
3254 | |
3255 | if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(Val: E)) { |
3256 | if (UnOp->getOpcode() == UO_Extension) { |
3257 | E = UnOp->getSubExpr(); |
3258 | continue; |
3259 | } |
3260 | } |
3261 | |
3262 | if (const MaterializeTemporaryExpr *M |
3263 | = dyn_cast<MaterializeTemporaryExpr>(Val: E)) { |
3264 | E = M->getSubExpr(); |
3265 | continue; |
3266 | } |
3267 | |
3268 | break; |
3269 | } |
3270 | |
3271 | if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(Val: E)) |
3272 | return This->isImplicit(); |
3273 | |
3274 | return false; |
3275 | } |
3276 | |
3277 | /// hasAnyTypeDependentArguments - Determines if any of the expressions |
3278 | /// in Exprs is type-dependent. |
3279 | bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) { |
3280 | for (unsigned I = 0; I < Exprs.size(); ++I) |
3281 | if (Exprs[I]->isTypeDependent()) |
3282 | return true; |
3283 | |
3284 | return false; |
3285 | } |
3286 | |
3287 | bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef, |
3288 | const Expr **Culprit) const { |
3289 | assert(!isValueDependent() && |
3290 | "Expression evaluator can't be called on a dependent expression." ); |
3291 | |
3292 | // This function is attempting whether an expression is an initializer |
3293 | // which can be evaluated at compile-time. It very closely parallels |
3294 | // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it |
3295 | // will lead to unexpected results. Like ConstExprEmitter, it falls back |
3296 | // to isEvaluatable most of the time. |
3297 | // |
3298 | // If we ever capture reference-binding directly in the AST, we can |
3299 | // kill the second parameter. |
3300 | |
3301 | if (IsForRef) { |
3302 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: this)) |
3303 | return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit); |
3304 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: this)) |
3305 | return MTE->getSubExpr()->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3306 | EvalResult Result; |
3307 | if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects) |
3308 | return true; |
3309 | if (Culprit) |
3310 | *Culprit = this; |
3311 | return false; |
3312 | } |
3313 | |
3314 | switch (getStmtClass()) { |
3315 | default: break; |
3316 | case Stmt::ExprWithCleanupsClass: |
3317 | return cast<ExprWithCleanups>(Val: this)->getSubExpr()->isConstantInitializer( |
3318 | Ctx, IsForRef, Culprit); |
3319 | case StringLiteralClass: |
3320 | case ObjCEncodeExprClass: |
3321 | return true; |
3322 | case CXXTemporaryObjectExprClass: |
3323 | case CXXConstructExprClass: { |
3324 | const CXXConstructExpr *CE = cast<CXXConstructExpr>(Val: this); |
3325 | |
3326 | if (CE->getConstructor()->isTrivial() && |
3327 | CE->getConstructor()->getParent()->hasTrivialDestructor()) { |
3328 | // Trivial default constructor |
3329 | if (!CE->getNumArgs()) return true; |
3330 | |
3331 | // Trivial copy constructor |
3332 | assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument" ); |
3333 | return CE->getArg(Arg: 0)->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3334 | } |
3335 | |
3336 | break; |
3337 | } |
3338 | case ConstantExprClass: { |
3339 | // FIXME: We should be able to return "true" here, but it can lead to extra |
3340 | // error messages. E.g. in Sema/array-init.c. |
3341 | const Expr *Exp = cast<ConstantExpr>(Val: this)->getSubExpr(); |
3342 | return Exp->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3343 | } |
3344 | case CompoundLiteralExprClass: { |
3345 | // This handles gcc's extension that allows global initializers like |
3346 | // "struct x {int x;} x = (struct x) {};". |
3347 | // FIXME: This accepts other cases it shouldn't! |
3348 | const Expr *Exp = cast<CompoundLiteralExpr>(Val: this)->getInitializer(); |
3349 | return Exp->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3350 | } |
3351 | case DesignatedInitUpdateExprClass: { |
3352 | const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(Val: this); |
3353 | return DIUE->getBase()->isConstantInitializer(Ctx, IsForRef: false, Culprit) && |
3354 | DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit); |
3355 | } |
3356 | case InitListExprClass: { |
3357 | // C++ [dcl.init.aggr]p2: |
3358 | // The elements of an aggregate are: |
3359 | // - for an array, the array elements in increasing subscript order, or |
3360 | // - for a class, the direct base classes in declaration order, followed |
3361 | // by the direct non-static data members (11.4) that are not members of |
3362 | // an anonymous union, in declaration order. |
3363 | const InitListExpr *ILE = cast<InitListExpr>(Val: this); |
3364 | assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form" ); |
3365 | if (ILE->getType()->isArrayType()) { |
3366 | unsigned numInits = ILE->getNumInits(); |
3367 | for (unsigned i = 0; i < numInits; i++) { |
3368 | if (!ILE->getInit(Init: i)->isConstantInitializer(Ctx, IsForRef: false, Culprit)) |
3369 | return false; |
3370 | } |
3371 | return true; |
3372 | } |
3373 | |
3374 | if (ILE->getType()->isRecordType()) { |
3375 | unsigned ElementNo = 0; |
3376 | RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl(); |
3377 | |
3378 | // In C++17, bases were added to the list of members used by aggregate |
3379 | // initialization. |
3380 | if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
3381 | for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) { |
3382 | if (ElementNo < ILE->getNumInits()) { |
3383 | const Expr *Elt = ILE->getInit(Init: ElementNo++); |
3384 | if (!Elt->isConstantInitializer(Ctx, IsForRef: false, Culprit)) |
3385 | return false; |
3386 | } |
3387 | } |
3388 | } |
3389 | |
3390 | for (const auto *Field : RD->fields()) { |
3391 | // If this is a union, skip all the fields that aren't being initialized. |
3392 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field) |
3393 | continue; |
3394 | |
3395 | // Don't emit anonymous bitfields, they just affect layout. |
3396 | if (Field->isUnnamedBitField()) |
3397 | continue; |
3398 | |
3399 | if (ElementNo < ILE->getNumInits()) { |
3400 | const Expr *Elt = ILE->getInit(ElementNo++); |
3401 | if (Field->isBitField()) { |
3402 | // Bitfields have to evaluate to an integer. |
3403 | EvalResult Result; |
3404 | if (!Elt->EvaluateAsInt(Result, Ctx)) { |
3405 | if (Culprit) |
3406 | *Culprit = Elt; |
3407 | return false; |
3408 | } |
3409 | } else { |
3410 | bool RefType = Field->getType()->isReferenceType(); |
3411 | if (!Elt->isConstantInitializer(Ctx, RefType, Culprit)) |
3412 | return false; |
3413 | } |
3414 | } |
3415 | } |
3416 | return true; |
3417 | } |
3418 | |
3419 | break; |
3420 | } |
3421 | case ImplicitValueInitExprClass: |
3422 | case NoInitExprClass: |
3423 | return true; |
3424 | case ParenExprClass: |
3425 | return cast<ParenExpr>(Val: this)->getSubExpr() |
3426 | ->isConstantInitializer(Ctx, IsForRef, Culprit); |
3427 | case GenericSelectionExprClass: |
3428 | return cast<GenericSelectionExpr>(Val: this)->getResultExpr() |
3429 | ->isConstantInitializer(Ctx, IsForRef, Culprit); |
3430 | case ChooseExprClass: |
3431 | if (cast<ChooseExpr>(Val: this)->isConditionDependent()) { |
3432 | if (Culprit) |
3433 | *Culprit = this; |
3434 | return false; |
3435 | } |
3436 | return cast<ChooseExpr>(Val: this)->getChosenSubExpr() |
3437 | ->isConstantInitializer(Ctx, IsForRef, Culprit); |
3438 | case UnaryOperatorClass: { |
3439 | const UnaryOperator* Exp = cast<UnaryOperator>(Val: this); |
3440 | if (Exp->getOpcode() == UO_Extension) |
3441 | return Exp->getSubExpr()->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3442 | break; |
3443 | } |
3444 | case PackIndexingExprClass: { |
3445 | return cast<PackIndexingExpr>(Val: this) |
3446 | ->getSelectedExpr() |
3447 | ->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3448 | } |
3449 | case CXXFunctionalCastExprClass: |
3450 | case CXXStaticCastExprClass: |
3451 | case ImplicitCastExprClass: |
3452 | case CStyleCastExprClass: |
3453 | case ObjCBridgedCastExprClass: |
3454 | case CXXDynamicCastExprClass: |
3455 | case CXXReinterpretCastExprClass: |
3456 | case CXXAddrspaceCastExprClass: |
3457 | case CXXConstCastExprClass: { |
3458 | const CastExpr *CE = cast<CastExpr>(Val: this); |
3459 | |
3460 | // Handle misc casts we want to ignore. |
3461 | if (CE->getCastKind() == CK_NoOp || |
3462 | CE->getCastKind() == CK_LValueToRValue || |
3463 | CE->getCastKind() == CK_ToUnion || |
3464 | CE->getCastKind() == CK_ConstructorConversion || |
3465 | CE->getCastKind() == CK_NonAtomicToAtomic || |
3466 | CE->getCastKind() == CK_AtomicToNonAtomic || |
3467 | CE->getCastKind() == CK_NullToPointer || |
3468 | CE->getCastKind() == CK_IntToOCLSampler) |
3469 | return CE->getSubExpr()->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3470 | |
3471 | break; |
3472 | } |
3473 | case MaterializeTemporaryExprClass: |
3474 | return cast<MaterializeTemporaryExpr>(Val: this) |
3475 | ->getSubExpr() |
3476 | ->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3477 | |
3478 | case SubstNonTypeTemplateParmExprClass: |
3479 | return cast<SubstNonTypeTemplateParmExpr>(Val: this)->getReplacement() |
3480 | ->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3481 | case CXXDefaultArgExprClass: |
3482 | return cast<CXXDefaultArgExpr>(Val: this)->getExpr() |
3483 | ->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3484 | case CXXDefaultInitExprClass: |
3485 | return cast<CXXDefaultInitExpr>(Val: this)->getExpr() |
3486 | ->isConstantInitializer(Ctx, IsForRef: false, Culprit); |
3487 | } |
3488 | // Allow certain forms of UB in constant initializers: signed integer |
3489 | // overflow and floating-point division by zero. We'll give a warning on |
3490 | // these, but they're common enough that we have to accept them. |
3491 | if (isEvaluatable(Ctx, AllowSideEffects: SE_AllowUndefinedBehavior)) |
3492 | return true; |
3493 | if (Culprit) |
3494 | *Culprit = this; |
3495 | return false; |
3496 | } |
3497 | |
3498 | bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const { |
3499 | unsigned BuiltinID = getBuiltinCallee(); |
3500 | if (BuiltinID != Builtin::BI__assume && |
3501 | BuiltinID != Builtin::BI__builtin_assume) |
3502 | return false; |
3503 | |
3504 | const Expr* Arg = getArg(Arg: 0); |
3505 | bool ArgVal; |
3506 | return !Arg->isValueDependent() && |
3507 | Arg->EvaluateAsBooleanCondition(Result&: ArgVal, Ctx) && !ArgVal; |
3508 | } |
3509 | |
3510 | bool CallExpr::isCallToStdMove() const { |
3511 | return getBuiltinCallee() == Builtin::BImove; |
3512 | } |
3513 | |
3514 | namespace { |
3515 | /// Look for any side effects within a Stmt. |
3516 | class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> { |
3517 | typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited; |
3518 | const bool IncludePossibleEffects; |
3519 | bool HasSideEffects; |
3520 | |
3521 | public: |
3522 | explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible) |
3523 | : Inherited(Context), |
3524 | IncludePossibleEffects(IncludePossible), HasSideEffects(false) { } |
3525 | |
3526 | bool hasSideEffects() const { return HasSideEffects; } |
3527 | |
3528 | void VisitDecl(const Decl *D) { |
3529 | if (!D) |
3530 | return; |
3531 | |
3532 | // We assume the caller checks subexpressions (eg, the initializer, VLA |
3533 | // bounds) for side-effects on our behalf. |
3534 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) { |
3535 | // Registering a destructor is a side-effect. |
3536 | if (IncludePossibleEffects && VD->isThisDeclarationADefinition() && |
3537 | VD->needsDestruction(Ctx: Context)) |
3538 | HasSideEffects = true; |
3539 | } |
3540 | } |
3541 | |
3542 | void VisitDeclStmt(const DeclStmt *DS) { |
3543 | for (auto *D : DS->decls()) |
3544 | VisitDecl(D); |
3545 | Inherited::VisitDeclStmt(DS); |
3546 | } |
3547 | |
3548 | void VisitExpr(const Expr *E) { |
3549 | if (!HasSideEffects && |
3550 | E->HasSideEffects(Ctx: Context, IncludePossibleEffects)) |
3551 | HasSideEffects = true; |
3552 | } |
3553 | }; |
3554 | } |
3555 | |
3556 | bool Expr::HasSideEffects(const ASTContext &Ctx, |
3557 | bool IncludePossibleEffects) const { |
3558 | // In circumstances where we care about definite side effects instead of |
3559 | // potential side effects, we want to ignore expressions that are part of a |
3560 | // macro expansion as a potential side effect. |
3561 | if (!IncludePossibleEffects && getExprLoc().isMacroID()) |
3562 | return false; |
3563 | |
3564 | switch (getStmtClass()) { |
3565 | case NoStmtClass: |
3566 | #define ABSTRACT_STMT(Type) |
3567 | #define STMT(Type, Base) case Type##Class: |
3568 | #define EXPR(Type, Base) |
3569 | #include "clang/AST/StmtNodes.inc" |
3570 | llvm_unreachable("unexpected Expr kind" ); |
3571 | |
3572 | case DependentScopeDeclRefExprClass: |
3573 | case CXXUnresolvedConstructExprClass: |
3574 | case CXXDependentScopeMemberExprClass: |
3575 | case UnresolvedLookupExprClass: |
3576 | case UnresolvedMemberExprClass: |
3577 | case PackExpansionExprClass: |
3578 | case SubstNonTypeTemplateParmPackExprClass: |
3579 | case FunctionParmPackExprClass: |
3580 | case TypoExprClass: |
3581 | case RecoveryExprClass: |
3582 | case CXXFoldExprClass: |
3583 | // Make a conservative assumption for dependent nodes. |
3584 | return IncludePossibleEffects; |
3585 | |
3586 | case DeclRefExprClass: |
3587 | case ObjCIvarRefExprClass: |
3588 | case PredefinedExprClass: |
3589 | case IntegerLiteralClass: |
3590 | case FixedPointLiteralClass: |
3591 | case FloatingLiteralClass: |
3592 | case ImaginaryLiteralClass: |
3593 | case StringLiteralClass: |
3594 | case CharacterLiteralClass: |
3595 | case OffsetOfExprClass: |
3596 | case ImplicitValueInitExprClass: |
3597 | case UnaryExprOrTypeTraitExprClass: |
3598 | case AddrLabelExprClass: |
3599 | case GNUNullExprClass: |
3600 | case ArrayInitIndexExprClass: |
3601 | case NoInitExprClass: |
3602 | case CXXBoolLiteralExprClass: |
3603 | case CXXNullPtrLiteralExprClass: |
3604 | case CXXThisExprClass: |
3605 | case CXXScalarValueInitExprClass: |
3606 | case TypeTraitExprClass: |
3607 | case ArrayTypeTraitExprClass: |
3608 | case ExpressionTraitExprClass: |
3609 | case CXXNoexceptExprClass: |
3610 | case SizeOfPackExprClass: |
3611 | case ObjCStringLiteralClass: |
3612 | case ObjCEncodeExprClass: |
3613 | case ObjCBoolLiteralExprClass: |
3614 | case ObjCAvailabilityCheckExprClass: |
3615 | case CXXUuidofExprClass: |
3616 | case OpaqueValueExprClass: |
3617 | case SourceLocExprClass: |
3618 | case ConceptSpecializationExprClass: |
3619 | case RequiresExprClass: |
3620 | case SYCLUniqueStableNameExprClass: |
3621 | // These never have a side-effect. |
3622 | return false; |
3623 | |
3624 | case PackIndexingExprClass: |
3625 | return cast<PackIndexingExpr>(this)->getSelectedExpr()->HasSideEffects( |
3626 | Ctx, IncludePossibleEffects); |
3627 | case ConstantExprClass: |
3628 | // FIXME: Move this into the "return false;" block above. |
3629 | return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects( |
3630 | Ctx, IncludePossibleEffects); |
3631 | |
3632 | case CallExprClass: |
3633 | case CXXOperatorCallExprClass: |
3634 | case CXXMemberCallExprClass: |
3635 | case CUDAKernelCallExprClass: |
3636 | case UserDefinedLiteralClass: { |
3637 | // We don't know a call definitely has side effects, except for calls |
3638 | // to pure/const functions that definitely don't. |
3639 | // If the call itself is considered side-effect free, check the operands. |
3640 | const Decl *FD = cast<CallExpr>(this)->getCalleeDecl(); |
3641 | bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>()); |
3642 | if (IsPure || !IncludePossibleEffects) |
3643 | break; |
3644 | return true; |
3645 | } |
3646 | |
3647 | case BlockExprClass: |
3648 | case CXXBindTemporaryExprClass: |
3649 | if (!IncludePossibleEffects) |
3650 | break; |
3651 | return true; |
3652 | |
3653 | case MSPropertyRefExprClass: |
3654 | case MSPropertySubscriptExprClass: |
3655 | case CompoundAssignOperatorClass: |
3656 | case VAArgExprClass: |
3657 | case AtomicExprClass: |
3658 | case CXXThrowExprClass: |
3659 | case CXXNewExprClass: |
3660 | case CXXDeleteExprClass: |
3661 | case CoawaitExprClass: |
3662 | case DependentCoawaitExprClass: |
3663 | case CoyieldExprClass: |
3664 | // These always have a side-effect. |
3665 | return true; |
3666 | |
3667 | case StmtExprClass: { |
3668 | // StmtExprs have a side-effect if any substatement does. |
3669 | SideEffectFinder Finder(Ctx, IncludePossibleEffects); |
3670 | Finder.Visit(S: cast<StmtExpr>(this)->getSubStmt()); |
3671 | return Finder.hasSideEffects(); |
3672 | } |
3673 | |
3674 | case ExprWithCleanupsClass: |
3675 | if (IncludePossibleEffects) |
3676 | if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects()) |
3677 | return true; |
3678 | break; |
3679 | |
3680 | case ParenExprClass: |
3681 | case ArraySubscriptExprClass: |
3682 | case MatrixSubscriptExprClass: |
3683 | case OMPArraySectionExprClass: |
3684 | case OMPArrayShapingExprClass: |
3685 | case OMPIteratorExprClass: |
3686 | case MemberExprClass: |
3687 | case ConditionalOperatorClass: |
3688 | case BinaryConditionalOperatorClass: |
3689 | case CompoundLiteralExprClass: |
3690 | case ExtVectorElementExprClass: |
3691 | case DesignatedInitExprClass: |
3692 | case DesignatedInitUpdateExprClass: |
3693 | case ArrayInitLoopExprClass: |
3694 | case ParenListExprClass: |
3695 | case CXXPseudoDestructorExprClass: |
3696 | case CXXRewrittenBinaryOperatorClass: |
3697 | case CXXStdInitializerListExprClass: |
3698 | case SubstNonTypeTemplateParmExprClass: |
3699 | case MaterializeTemporaryExprClass: |
3700 | case ShuffleVectorExprClass: |
3701 | case ConvertVectorExprClass: |
3702 | case AsTypeExprClass: |
3703 | case CXXParenListInitExprClass: |
3704 | // These have a side-effect if any subexpression does. |
3705 | break; |
3706 | |
3707 | case UnaryOperatorClass: |
3708 | if (cast<UnaryOperator>(this)->isIncrementDecrementOp()) |
3709 | return true; |
3710 | break; |
3711 | |
3712 | case BinaryOperatorClass: |
3713 | if (cast<BinaryOperator>(this)->isAssignmentOp()) |
3714 | return true; |
3715 | break; |
3716 | |
3717 | case InitListExprClass: |
3718 | // FIXME: The children for an InitListExpr doesn't include the array filler. |
3719 | if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller()) |
3720 | if (E->HasSideEffects(Ctx, IncludePossibleEffects)) |
3721 | return true; |
3722 | break; |
3723 | |
3724 | case GenericSelectionExprClass: |
3725 | return cast<GenericSelectionExpr>(this)->getResultExpr()-> |
3726 | HasSideEffects(Ctx, IncludePossibleEffects); |
3727 | |
3728 | case ChooseExprClass: |
3729 | return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects( |
3730 | Ctx, IncludePossibleEffects); |
3731 | |
3732 | case CXXDefaultArgExprClass: |
3733 | return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects( |
3734 | Ctx, IncludePossibleEffects); |
3735 | |
3736 | case CXXDefaultInitExprClass: { |
3737 | const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField(); |
3738 | if (const Expr *E = FD->getInClassInitializer()) |
3739 | return E->HasSideEffects(Ctx, IncludePossibleEffects); |
3740 | // If we've not yet parsed the initializer, assume it has side-effects. |
3741 | return true; |
3742 | } |
3743 | |
3744 | case CXXDynamicCastExprClass: { |
3745 | // A dynamic_cast expression has side-effects if it can throw. |
3746 | const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this); |
3747 | if (DCE->getTypeAsWritten()->isReferenceType() && |
3748 | DCE->getCastKind() == CK_Dynamic) |
3749 | return true; |
3750 | } |
3751 | [[fallthrough]]; |
3752 | case ImplicitCastExprClass: |
3753 | case CStyleCastExprClass: |
3754 | case CXXStaticCastExprClass: |
3755 | case CXXReinterpretCastExprClass: |
3756 | case CXXConstCastExprClass: |
3757 | case CXXAddrspaceCastExprClass: |
3758 | case CXXFunctionalCastExprClass: |
3759 | case BuiltinBitCastExprClass: { |
3760 | // While volatile reads are side-effecting in both C and C++, we treat them |
3761 | // as having possible (not definite) side-effects. This allows idiomatic |
3762 | // code to behave without warning, such as sizeof(*v) for a volatile- |
3763 | // qualified pointer. |
3764 | if (!IncludePossibleEffects) |
3765 | break; |
3766 | |
3767 | const CastExpr *CE = cast<CastExpr>(this); |
3768 | if (CE->getCastKind() == CK_LValueToRValue && |
3769 | CE->getSubExpr()->getType().isVolatileQualified()) |
3770 | return true; |
3771 | break; |
3772 | } |
3773 | |
3774 | case CXXTypeidExprClass: |
3775 | // typeid might throw if its subexpression is potentially-evaluated, so has |
3776 | // side-effects in that case whether or not its subexpression does. |
3777 | return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated(); |
3778 | |
3779 | case CXXConstructExprClass: |
3780 | case CXXTemporaryObjectExprClass: { |
3781 | const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); |
3782 | if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects) |
3783 | return true; |
3784 | // A trivial constructor does not add any side-effects of its own. Just look |
3785 | // at its arguments. |
3786 | break; |
3787 | } |
3788 | |
3789 | case CXXInheritedCtorInitExprClass: { |
3790 | const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this); |
3791 | if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects) |
3792 | return true; |
3793 | break; |
3794 | } |
3795 | |
3796 | case LambdaExprClass: { |
3797 | const LambdaExpr *LE = cast<LambdaExpr>(this); |
3798 | for (Expr *E : LE->capture_inits()) |
3799 | if (E && E->HasSideEffects(Ctx, IncludePossibleEffects)) |
3800 | return true; |
3801 | return false; |
3802 | } |
3803 | |
3804 | case PseudoObjectExprClass: { |
3805 | // Only look for side-effects in the semantic form, and look past |
3806 | // OpaqueValueExpr bindings in that form. |
3807 | const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); |
3808 | for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(), |
3809 | E = PO->semantics_end(); |
3810 | I != E; ++I) { |
3811 | const Expr *Subexpr = *I; |
3812 | if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr)) |
3813 | Subexpr = OVE->getSourceExpr(); |
3814 | if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects)) |
3815 | return true; |
3816 | } |
3817 | return false; |
3818 | } |
3819 | |
3820 | case ObjCBoxedExprClass: |
3821 | case ObjCArrayLiteralClass: |
3822 | case ObjCDictionaryLiteralClass: |
3823 | case ObjCSelectorExprClass: |
3824 | case ObjCProtocolExprClass: |
3825 | case ObjCIsaExprClass: |
3826 | case ObjCIndirectCopyRestoreExprClass: |
3827 | case ObjCSubscriptRefExprClass: |
3828 | case ObjCBridgedCastExprClass: |
3829 | case ObjCMessageExprClass: |
3830 | case ObjCPropertyRefExprClass: |
3831 | // FIXME: Classify these cases better. |
3832 | if (IncludePossibleEffects) |
3833 | return true; |
3834 | break; |
3835 | } |
3836 | |
3837 | // Recurse to children. |
3838 | for (const Stmt *SubStmt : children()) |
3839 | if (SubStmt && |
3840 | cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects)) |
3841 | return true; |
3842 | |
3843 | return false; |
3844 | } |
3845 | |
3846 | FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const { |
3847 | if (auto Call = dyn_cast<CallExpr>(Val: this)) |
3848 | return Call->getFPFeaturesInEffect(LO); |
3849 | if (auto UO = dyn_cast<UnaryOperator>(Val: this)) |
3850 | return UO->getFPFeaturesInEffect(LO); |
3851 | if (auto BO = dyn_cast<BinaryOperator>(Val: this)) |
3852 | return BO->getFPFeaturesInEffect(LO); |
3853 | if (auto Cast = dyn_cast<CastExpr>(Val: this)) |
3854 | return Cast->getFPFeaturesInEffect(LO); |
3855 | return FPOptions::defaultWithoutTrailingStorage(LO); |
3856 | } |
3857 | |
3858 | namespace { |
3859 | /// Look for a call to a non-trivial function within an expression. |
3860 | class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder> |
3861 | { |
3862 | typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited; |
3863 | |
3864 | bool NonTrivial; |
3865 | |
3866 | public: |
3867 | explicit NonTrivialCallFinder(const ASTContext &Context) |
3868 | : Inherited(Context), NonTrivial(false) { } |
3869 | |
3870 | bool hasNonTrivialCall() const { return NonTrivial; } |
3871 | |
3872 | void VisitCallExpr(const CallExpr *E) { |
3873 | if (const CXXMethodDecl *Method |
3874 | = dyn_cast_or_null<const CXXMethodDecl>(Val: E->getCalleeDecl())) { |
3875 | if (Method->isTrivial()) { |
3876 | // Recurse to children of the call. |
3877 | Inherited::VisitStmt(E); |
3878 | return; |
3879 | } |
3880 | } |
3881 | |
3882 | NonTrivial = true; |
3883 | } |
3884 | |
3885 | void VisitCXXConstructExpr(const CXXConstructExpr *E) { |
3886 | if (E->getConstructor()->isTrivial()) { |
3887 | // Recurse to children of the call. |
3888 | Inherited::VisitStmt(E); |
3889 | return; |
3890 | } |
3891 | |
3892 | NonTrivial = true; |
3893 | } |
3894 | |
3895 | void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { |
3896 | if (E->getTemporary()->getDestructor()->isTrivial()) { |
3897 | Inherited::VisitStmt(E); |
3898 | return; |
3899 | } |
3900 | |
3901 | NonTrivial = true; |
3902 | } |
3903 | }; |
3904 | } |
3905 | |
3906 | bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const { |
3907 | NonTrivialCallFinder Finder(Ctx); |
3908 | Finder.Visit(this); |
3909 | return Finder.hasNonTrivialCall(); |
3910 | } |
3911 | |
3912 | /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null |
3913 | /// pointer constant or not, as well as the specific kind of constant detected. |
3914 | /// Null pointer constants can be integer constant expressions with the |
3915 | /// value zero, casts of zero to void*, nullptr (C++0X), or __null |
3916 | /// (a GNU extension). |
3917 | Expr::NullPointerConstantKind |
3918 | Expr::isNullPointerConstant(ASTContext &Ctx, |
3919 | NullPointerConstantValueDependence NPC) const { |
3920 | if (isValueDependent() && |
3921 | (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) { |
3922 | // Error-dependent expr should never be a null pointer. |
3923 | if (containsErrors()) |
3924 | return NPCK_NotNull; |
3925 | switch (NPC) { |
3926 | case NPC_NeverValueDependent: |
3927 | llvm_unreachable("Unexpected value dependent expression!" ); |
3928 | case NPC_ValueDependentIsNull: |
3929 | if (isTypeDependent() || getType()->isIntegralType(Ctx)) |
3930 | return NPCK_ZeroExpression; |
3931 | else |
3932 | return NPCK_NotNull; |
3933 | |
3934 | case NPC_ValueDependentIsNotNull: |
3935 | return NPCK_NotNull; |
3936 | } |
3937 | } |
3938 | |
3939 | // Strip off a cast to void*, if it exists. Except in C++. |
3940 | if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(Val: this)) { |
3941 | if (!Ctx.getLangOpts().CPlusPlus) { |
3942 | // Check that it is a cast to void*. |
3943 | if (const PointerType *PT = CE->getType()->getAs<PointerType>()) { |
3944 | QualType Pointee = PT->getPointeeType(); |
3945 | Qualifiers Qs = Pointee.getQualifiers(); |
3946 | // Only (void*)0 or equivalent are treated as nullptr. If pointee type |
3947 | // has non-default address space it is not treated as nullptr. |
3948 | // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr |
3949 | // since it cannot be assigned to a pointer to constant address space. |
3950 | if (Ctx.getLangOpts().OpenCL && |
3951 | Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace()) |
3952 | Qs.removeAddressSpace(); |
3953 | |
3954 | if (Pointee->isVoidType() && Qs.empty() && // to void* |
3955 | CE->getSubExpr()->getType()->isIntegerType()) // from int |
3956 | return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); |
3957 | } |
3958 | } |
3959 | } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: this)) { |
3960 | // Ignore the ImplicitCastExpr type entirely. |
3961 | return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); |
3962 | } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: this)) { |
3963 | // Accept ((void*)0) as a null pointer constant, as many other |
3964 | // implementations do. |
3965 | return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); |
3966 | } else if (const GenericSelectionExpr *GE = |
3967 | dyn_cast<GenericSelectionExpr>(Val: this)) { |
3968 | if (GE->isResultDependent()) |
3969 | return NPCK_NotNull; |
3970 | return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); |
3971 | } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Val: this)) { |
3972 | if (CE->isConditionDependent()) |
3973 | return NPCK_NotNull; |
3974 | return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC); |
3975 | } else if (const CXXDefaultArgExpr *DefaultArg |
3976 | = dyn_cast<CXXDefaultArgExpr>(Val: this)) { |
3977 | // See through default argument expressions. |
3978 | return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); |
3979 | } else if (const CXXDefaultInitExpr *DefaultInit |
3980 | = dyn_cast<CXXDefaultInitExpr>(Val: this)) { |
3981 | // See through default initializer expressions. |
3982 | return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC); |
3983 | } else if (isa<GNUNullExpr>(Val: this)) { |
3984 | // The GNU __null extension is always a null pointer constant. |
3985 | return NPCK_GNUNull; |
3986 | } else if (const MaterializeTemporaryExpr *M |
3987 | = dyn_cast<MaterializeTemporaryExpr>(Val: this)) { |
3988 | return M->getSubExpr()->isNullPointerConstant(Ctx, NPC); |
3989 | } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: this)) { |
3990 | if (const Expr *Source = OVE->getSourceExpr()) |
3991 | return Source->isNullPointerConstant(Ctx, NPC); |
3992 | } |
3993 | |
3994 | // If the expression has no type information, it cannot be a null pointer |
3995 | // constant. |
3996 | if (getType().isNull()) |
3997 | return NPCK_NotNull; |
3998 | |
3999 | // C++11/C23 nullptr_t is always a null pointer constant. |
4000 | if (getType()->isNullPtrType()) |
4001 | return NPCK_CXX11_nullptr; |
4002 | |
4003 | if (const RecordType *UT = getType()->getAsUnionType()) |
4004 | if (!Ctx.getLangOpts().CPlusPlus11 && |
4005 | UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
4006 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Val: this)){ |
4007 | const Expr *InitExpr = CLE->getInitializer(); |
4008 | if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Val: InitExpr)) |
4009 | return ILE->getInit(Init: 0)->isNullPointerConstant(Ctx, NPC); |
4010 | } |
4011 | // This expression must be an integer type. |
4012 | if (!getType()->isIntegerType() || |
4013 | (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType())) |
4014 | return NPCK_NotNull; |
4015 | |
4016 | if (Ctx.getLangOpts().CPlusPlus11) { |
4017 | // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with |
4018 | // value zero or a prvalue of type std::nullptr_t. |
4019 | // Microsoft mode permits C++98 rules reflecting MSVC behavior. |
4020 | const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(Val: this); |
4021 | if (Lit && !Lit->getValue()) |
4022 | return NPCK_ZeroLiteral; |
4023 | if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx)) |
4024 | return NPCK_NotNull; |
4025 | } else { |
4026 | // If we have an integer constant expression, we need to *evaluate* it and |
4027 | // test for the value 0. |
4028 | if (!isIntegerConstantExpr(Ctx)) |
4029 | return NPCK_NotNull; |
4030 | } |
4031 | |
4032 | if (EvaluateKnownConstInt(Ctx) != 0) |
4033 | return NPCK_NotNull; |
4034 | |
4035 | if (isa<IntegerLiteral>(Val: this)) |
4036 | return NPCK_ZeroLiteral; |
4037 | return NPCK_ZeroExpression; |
4038 | } |
4039 | |
4040 | /// If this expression is an l-value for an Objective C |
4041 | /// property, find the underlying property reference expression. |
4042 | const ObjCPropertyRefExpr *Expr::getObjCProperty() const { |
4043 | const Expr *E = this; |
4044 | while (true) { |
4045 | assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) && |
4046 | "expression is not a property reference" ); |
4047 | E = E->IgnoreParenCasts(); |
4048 | if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
4049 | if (BO->getOpcode() == BO_Comma) { |
4050 | E = BO->getRHS(); |
4051 | continue; |
4052 | } |
4053 | } |
4054 | |
4055 | break; |
4056 | } |
4057 | |
4058 | return cast<ObjCPropertyRefExpr>(Val: E); |
4059 | } |
4060 | |
4061 | bool Expr::isObjCSelfExpr() const { |
4062 | const Expr *E = IgnoreParenImpCasts(); |
4063 | |
4064 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
4065 | if (!DRE) |
4066 | return false; |
4067 | |
4068 | const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(Val: DRE->getDecl()); |
4069 | if (!Param) |
4070 | return false; |
4071 | |
4072 | const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext()); |
4073 | if (!M) |
4074 | return false; |
4075 | |
4076 | return M->getSelfDecl() == Param; |
4077 | } |
4078 | |
4079 | FieldDecl *Expr::getSourceBitField() { |
4080 | Expr *E = this->IgnoreParens(); |
4081 | |
4082 | while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
4083 | if (ICE->getCastKind() == CK_LValueToRValue || |
4084 | (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)) |
4085 | E = ICE->getSubExpr()->IgnoreParens(); |
4086 | else |
4087 | break; |
4088 | } |
4089 | |
4090 | if (MemberExpr *MemRef = dyn_cast<MemberExpr>(Val: E)) |
4091 | if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: MemRef->getMemberDecl())) |
4092 | if (Field->isBitField()) |
4093 | return Field; |
4094 | |
4095 | if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(Val: E)) { |
4096 | FieldDecl *Ivar = IvarRef->getDecl(); |
4097 | if (Ivar->isBitField()) |
4098 | return Ivar; |
4099 | } |
4100 | |
4101 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Val: E)) { |
4102 | if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: DeclRef->getDecl())) |
4103 | if (Field->isBitField()) |
4104 | return Field; |
4105 | |
4106 | if (BindingDecl *BD = dyn_cast<BindingDecl>(Val: DeclRef->getDecl())) |
4107 | if (Expr *E = BD->getBinding()) |
4108 | return E->getSourceBitField(); |
4109 | } |
4110 | |
4111 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: E)) { |
4112 | if (BinOp->isAssignmentOp() && BinOp->getLHS()) |
4113 | return BinOp->getLHS()->getSourceBitField(); |
4114 | |
4115 | if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS()) |
4116 | return BinOp->getRHS()->getSourceBitField(); |
4117 | } |
4118 | |
4119 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) |
4120 | if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp()) |
4121 | return UnOp->getSubExpr()->getSourceBitField(); |
4122 | |
4123 | return nullptr; |
4124 | } |
4125 | |
4126 | EnumConstantDecl *Expr::getEnumConstantDecl() { |
4127 | Expr *E = this->IgnoreParenImpCasts(); |
4128 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
4129 | return dyn_cast<EnumConstantDecl>(Val: DRE->getDecl()); |
4130 | return nullptr; |
4131 | } |
4132 | |
4133 | bool Expr::refersToVectorElement() const { |
4134 | // FIXME: Why do we not just look at the ObjectKind here? |
4135 | const Expr *E = this->IgnoreParens(); |
4136 | |
4137 | while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) { |
4138 | if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp) |
4139 | E = ICE->getSubExpr()->IgnoreParens(); |
4140 | else |
4141 | break; |
4142 | } |
4143 | |
4144 | if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Val: E)) |
4145 | return ASE->getBase()->getType()->isVectorType(); |
4146 | |
4147 | if (isa<ExtVectorElementExpr>(Val: E)) |
4148 | return true; |
4149 | |
4150 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
4151 | if (auto *BD = dyn_cast<BindingDecl>(Val: DRE->getDecl())) |
4152 | if (auto *E = BD->getBinding()) |
4153 | return E->refersToVectorElement(); |
4154 | |
4155 | return false; |
4156 | } |
4157 | |
4158 | bool Expr::refersToGlobalRegisterVar() const { |
4159 | const Expr *E = this->IgnoreParenImpCasts(); |
4160 | |
4161 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
4162 | if (const auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) |
4163 | if (VD->getStorageClass() == SC_Register && |
4164 | VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) |
4165 | return true; |
4166 | |
4167 | return false; |
4168 | } |
4169 | |
4170 | bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) { |
4171 | E1 = E1->IgnoreParens(); |
4172 | E2 = E2->IgnoreParens(); |
4173 | |
4174 | if (E1->getStmtClass() != E2->getStmtClass()) |
4175 | return false; |
4176 | |
4177 | switch (E1->getStmtClass()) { |
4178 | default: |
4179 | return false; |
4180 | case CXXThisExprClass: |
4181 | return true; |
4182 | case DeclRefExprClass: { |
4183 | // DeclRefExpr without an ImplicitCastExpr can happen for integral |
4184 | // template parameters. |
4185 | const auto *DRE1 = cast<DeclRefExpr>(Val: E1); |
4186 | const auto *DRE2 = cast<DeclRefExpr>(Val: E2); |
4187 | return DRE1->isPRValue() && DRE2->isPRValue() && |
4188 | DRE1->getDecl() == DRE2->getDecl(); |
4189 | } |
4190 | case ImplicitCastExprClass: { |
4191 | // Peel off implicit casts. |
4192 | while (true) { |
4193 | const auto *ICE1 = dyn_cast<ImplicitCastExpr>(Val: E1); |
4194 | const auto *ICE2 = dyn_cast<ImplicitCastExpr>(Val: E2); |
4195 | if (!ICE1 || !ICE2) |
4196 | return false; |
4197 | if (ICE1->getCastKind() != ICE2->getCastKind()) |
4198 | return false; |
4199 | E1 = ICE1->getSubExpr()->IgnoreParens(); |
4200 | E2 = ICE2->getSubExpr()->IgnoreParens(); |
4201 | // The final cast must be one of these types. |
4202 | if (ICE1->getCastKind() == CK_LValueToRValue || |
4203 | ICE1->getCastKind() == CK_ArrayToPointerDecay || |
4204 | ICE1->getCastKind() == CK_FunctionToPointerDecay) { |
4205 | break; |
4206 | } |
4207 | } |
4208 | |
4209 | const auto *DRE1 = dyn_cast<DeclRefExpr>(Val: E1); |
4210 | const auto *DRE2 = dyn_cast<DeclRefExpr>(Val: E2); |
4211 | if (DRE1 && DRE2) |
4212 | return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl()); |
4213 | |
4214 | const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(Val: E1); |
4215 | const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(Val: E2); |
4216 | if (Ivar1 && Ivar2) { |
4217 | return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() && |
4218 | declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl()); |
4219 | } |
4220 | |
4221 | const auto *Array1 = dyn_cast<ArraySubscriptExpr>(Val: E1); |
4222 | const auto *Array2 = dyn_cast<ArraySubscriptExpr>(Val: E2); |
4223 | if (Array1 && Array2) { |
4224 | if (!isSameComparisonOperand(E1: Array1->getBase(), E2: Array2->getBase())) |
4225 | return false; |
4226 | |
4227 | auto Idx1 = Array1->getIdx(); |
4228 | auto Idx2 = Array2->getIdx(); |
4229 | const auto Integer1 = dyn_cast<IntegerLiteral>(Val: Idx1); |
4230 | const auto Integer2 = dyn_cast<IntegerLiteral>(Val: Idx2); |
4231 | if (Integer1 && Integer2) { |
4232 | if (!llvm::APInt::isSameValue(I1: Integer1->getValue(), |
4233 | I2: Integer2->getValue())) |
4234 | return false; |
4235 | } else { |
4236 | if (!isSameComparisonOperand(E1: Idx1, E2: Idx2)) |
4237 | return false; |
4238 | } |
4239 | |
4240 | return true; |
4241 | } |
4242 | |
4243 | // Walk the MemberExpr chain. |
4244 | while (isa<MemberExpr>(Val: E1) && isa<MemberExpr>(Val: E2)) { |
4245 | const auto *ME1 = cast<MemberExpr>(Val: E1); |
4246 | const auto *ME2 = cast<MemberExpr>(Val: E2); |
4247 | if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl())) |
4248 | return false; |
4249 | if (const auto *D = dyn_cast<VarDecl>(Val: ME1->getMemberDecl())) |
4250 | if (D->isStaticDataMember()) |
4251 | return true; |
4252 | E1 = ME1->getBase()->IgnoreParenImpCasts(); |
4253 | E2 = ME2->getBase()->IgnoreParenImpCasts(); |
4254 | } |
4255 | |
4256 | if (isa<CXXThisExpr>(Val: E1) && isa<CXXThisExpr>(Val: E2)) |
4257 | return true; |
4258 | |
4259 | // A static member variable can end the MemberExpr chain with either |
4260 | // a MemberExpr or a DeclRefExpr. |
4261 | auto getAnyDecl = [](const Expr *E) -> const ValueDecl * { |
4262 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
4263 | return DRE->getDecl(); |
4264 | if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) |
4265 | return ME->getMemberDecl(); |
4266 | return nullptr; |
4267 | }; |
4268 | |
4269 | const ValueDecl *VD1 = getAnyDecl(E1); |
4270 | const ValueDecl *VD2 = getAnyDecl(E2); |
4271 | return declaresSameEntity(VD1, VD2); |
4272 | } |
4273 | } |
4274 | } |
4275 | |
4276 | /// isArrow - Return true if the base expression is a pointer to vector, |
4277 | /// return false if the base expression is a vector. |
4278 | bool ExtVectorElementExpr::isArrow() const { |
4279 | return getBase()->getType()->isPointerType(); |
4280 | } |
4281 | |
4282 | unsigned ExtVectorElementExpr::getNumElements() const { |
4283 | if (const VectorType *VT = getType()->getAs<VectorType>()) |
4284 | return VT->getNumElements(); |
4285 | return 1; |
4286 | } |
4287 | |
4288 | /// containsDuplicateElements - Return true if any element access is repeated. |
4289 | bool ExtVectorElementExpr::containsDuplicateElements() const { |
4290 | // FIXME: Refactor this code to an accessor on the AST node which returns the |
4291 | // "type" of component access, and share with code below and in Sema. |
4292 | StringRef Comp = Accessor->getName(); |
4293 | |
4294 | // Halving swizzles do not contain duplicate elements. |
4295 | if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd" ) |
4296 | return false; |
4297 | |
4298 | // Advance past s-char prefix on hex swizzles. |
4299 | if (Comp[0] == 's' || Comp[0] == 'S') |
4300 | Comp = Comp.substr(Start: 1); |
4301 | |
4302 | for (unsigned i = 0, e = Comp.size(); i != e; ++i) |
4303 | if (Comp.substr(Start: i + 1).contains(C: Comp[i])) |
4304 | return true; |
4305 | |
4306 | return false; |
4307 | } |
4308 | |
4309 | /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. |
4310 | void ExtVectorElementExpr::getEncodedElementAccess( |
4311 | SmallVectorImpl<uint32_t> &Elts) const { |
4312 | StringRef Comp = Accessor->getName(); |
4313 | bool isNumericAccessor = false; |
4314 | if (Comp[0] == 's' || Comp[0] == 'S') { |
4315 | Comp = Comp.substr(Start: 1); |
4316 | isNumericAccessor = true; |
4317 | } |
4318 | |
4319 | bool isHi = Comp == "hi" ; |
4320 | bool isLo = Comp == "lo" ; |
4321 | bool isEven = Comp == "even" ; |
4322 | bool isOdd = Comp == "odd" ; |
4323 | |
4324 | for (unsigned i = 0, e = getNumElements(); i != e; ++i) { |
4325 | uint64_t Index; |
4326 | |
4327 | if (isHi) |
4328 | Index = e + i; |
4329 | else if (isLo) |
4330 | Index = i; |
4331 | else if (isEven) |
4332 | Index = 2 * i; |
4333 | else if (isOdd) |
4334 | Index = 2 * i + 1; |
4335 | else |
4336 | Index = ExtVectorType::getAccessorIdx(c: Comp[i], isNumericAccessor); |
4337 | |
4338 | Elts.push_back(Elt: Index); |
4339 | } |
4340 | } |
4341 | |
4342 | ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args, |
4343 | QualType Type, SourceLocation BLoc, |
4344 | SourceLocation RP) |
4345 | : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary), |
4346 | BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) { |
4347 | SubExprs = new (C) Stmt*[args.size()]; |
4348 | for (unsigned i = 0; i != args.size(); i++) |
4349 | SubExprs[i] = args[i]; |
4350 | |
4351 | setDependence(computeDependence(E: this)); |
4352 | } |
4353 | |
4354 | void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) { |
4355 | if (SubExprs) C.Deallocate(Ptr: SubExprs); |
4356 | |
4357 | this->NumExprs = Exprs.size(); |
4358 | SubExprs = new (C) Stmt*[NumExprs]; |
4359 | memcpy(dest: SubExprs, src: Exprs.data(), n: sizeof(Expr *) * Exprs.size()); |
4360 | } |
4361 | |
4362 | GenericSelectionExpr::GenericSelectionExpr( |
4363 | const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr, |
4364 | ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, |
4365 | SourceLocation DefaultLoc, SourceLocation RParenLoc, |
4366 | bool ContainsUnexpandedParameterPack, unsigned ResultIndex) |
4367 | : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(), |
4368 | AssocExprs[ResultIndex]->getValueKind(), |
4369 | AssocExprs[ResultIndex]->getObjectKind()), |
4370 | NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex), |
4371 | IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { |
4372 | assert(AssocTypes.size() == AssocExprs.size() && |
4373 | "Must have the same number of association expressions" |
4374 | " and TypeSourceInfo!" ); |
4375 | assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!" ); |
4376 | |
4377 | GenericSelectionExprBits.GenericLoc = GenericLoc; |
4378 | getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] = |
4379 | ControllingExpr; |
4380 | std::copy(AssocExprs.begin(), AssocExprs.end(), |
4381 | getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs()); |
4382 | std::copy(AssocTypes.begin(), AssocTypes.end(), |
4383 | getTrailingObjects<TypeSourceInfo *>() + |
4384 | getIndexOfStartOfAssociatedTypes()); |
4385 | |
4386 | setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack)); |
4387 | } |
4388 | |
4389 | GenericSelectionExpr::GenericSelectionExpr( |
4390 | const ASTContext &, SourceLocation GenericLoc, |
4391 | TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes, |
4392 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
4393 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, |
4394 | unsigned ResultIndex) |
4395 | : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(), |
4396 | AssocExprs[ResultIndex]->getValueKind(), |
4397 | AssocExprs[ResultIndex]->getObjectKind()), |
4398 | NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex), |
4399 | IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { |
4400 | assert(AssocTypes.size() == AssocExprs.size() && |
4401 | "Must have the same number of association expressions" |
4402 | " and TypeSourceInfo!" ); |
4403 | assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!" ); |
4404 | |
4405 | GenericSelectionExprBits.GenericLoc = GenericLoc; |
4406 | getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] = |
4407 | ControllingType; |
4408 | std::copy(AssocExprs.begin(), AssocExprs.end(), |
4409 | getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs()); |
4410 | std::copy(AssocTypes.begin(), AssocTypes.end(), |
4411 | getTrailingObjects<TypeSourceInfo *>() + |
4412 | getIndexOfStartOfAssociatedTypes()); |
4413 | |
4414 | setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack)); |
4415 | } |
4416 | |
4417 | GenericSelectionExpr::GenericSelectionExpr( |
4418 | const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, |
4419 | ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, |
4420 | SourceLocation DefaultLoc, SourceLocation RParenLoc, |
4421 | bool ContainsUnexpandedParameterPack) |
4422 | : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue, |
4423 | OK_Ordinary), |
4424 | NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex), |
4425 | IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { |
4426 | assert(AssocTypes.size() == AssocExprs.size() && |
4427 | "Must have the same number of association expressions" |
4428 | " and TypeSourceInfo!" ); |
4429 | |
4430 | GenericSelectionExprBits.GenericLoc = GenericLoc; |
4431 | getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] = |
4432 | ControllingExpr; |
4433 | std::copy(AssocExprs.begin(), AssocExprs.end(), |
4434 | getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs()); |
4435 | std::copy(AssocTypes.begin(), AssocTypes.end(), |
4436 | getTrailingObjects<TypeSourceInfo *>() + |
4437 | getIndexOfStartOfAssociatedTypes()); |
4438 | |
4439 | setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack)); |
4440 | } |
4441 | |
4442 | GenericSelectionExpr::GenericSelectionExpr( |
4443 | const ASTContext &Context, SourceLocation GenericLoc, |
4444 | TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes, |
4445 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
4446 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) |
4447 | : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue, |
4448 | OK_Ordinary), |
4449 | NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex), |
4450 | IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { |
4451 | assert(AssocTypes.size() == AssocExprs.size() && |
4452 | "Must have the same number of association expressions" |
4453 | " and TypeSourceInfo!" ); |
4454 | |
4455 | GenericSelectionExprBits.GenericLoc = GenericLoc; |
4456 | getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] = |
4457 | ControllingType; |
4458 | std::copy(AssocExprs.begin(), AssocExprs.end(), |
4459 | getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs()); |
4460 | std::copy(AssocTypes.begin(), AssocTypes.end(), |
4461 | getTrailingObjects<TypeSourceInfo *>() + |
4462 | getIndexOfStartOfAssociatedTypes()); |
4463 | |
4464 | setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack)); |
4465 | } |
4466 | |
4467 | GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs) |
4468 | : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {} |
4469 | |
4470 | GenericSelectionExpr *GenericSelectionExpr::Create( |
4471 | const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, |
4472 | ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, |
4473 | SourceLocation DefaultLoc, SourceLocation RParenLoc, |
4474 | bool ContainsUnexpandedParameterPack, unsigned ResultIndex) { |
4475 | unsigned NumAssocs = AssocExprs.size(); |
4476 | void *Mem = Context.Allocate( |
4477 | Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs), |
4478 | Align: alignof(GenericSelectionExpr)); |
4479 | return new (Mem) GenericSelectionExpr( |
4480 | Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc, |
4481 | RParenLoc, ContainsUnexpandedParameterPack, ResultIndex); |
4482 | } |
4483 | |
4484 | GenericSelectionExpr *GenericSelectionExpr::Create( |
4485 | const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, |
4486 | ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs, |
4487 | SourceLocation DefaultLoc, SourceLocation RParenLoc, |
4488 | bool ContainsUnexpandedParameterPack) { |
4489 | unsigned NumAssocs = AssocExprs.size(); |
4490 | void *Mem = Context.Allocate( |
4491 | Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs), |
4492 | Align: alignof(GenericSelectionExpr)); |
4493 | return new (Mem) GenericSelectionExpr( |
4494 | Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc, |
4495 | RParenLoc, ContainsUnexpandedParameterPack); |
4496 | } |
4497 | |
4498 | GenericSelectionExpr *GenericSelectionExpr::Create( |
4499 | const ASTContext &Context, SourceLocation GenericLoc, |
4500 | TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes, |
4501 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
4502 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, |
4503 | unsigned ResultIndex) { |
4504 | unsigned NumAssocs = AssocExprs.size(); |
4505 | void *Mem = Context.Allocate( |
4506 | Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs), |
4507 | Align: alignof(GenericSelectionExpr)); |
4508 | return new (Mem) GenericSelectionExpr( |
4509 | Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc, |
4510 | RParenLoc, ContainsUnexpandedParameterPack, ResultIndex); |
4511 | } |
4512 | |
4513 | GenericSelectionExpr *GenericSelectionExpr::Create( |
4514 | const ASTContext &Context, SourceLocation GenericLoc, |
4515 | TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes, |
4516 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
4517 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) { |
4518 | unsigned NumAssocs = AssocExprs.size(); |
4519 | void *Mem = Context.Allocate( |
4520 | Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs), |
4521 | Align: alignof(GenericSelectionExpr)); |
4522 | return new (Mem) GenericSelectionExpr( |
4523 | Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc, |
4524 | RParenLoc, ContainsUnexpandedParameterPack); |
4525 | } |
4526 | |
4527 | GenericSelectionExpr * |
4528 | GenericSelectionExpr::CreateEmpty(const ASTContext &Context, |
4529 | unsigned NumAssocs) { |
4530 | void *Mem = Context.Allocate( |
4531 | Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs), |
4532 | Align: alignof(GenericSelectionExpr)); |
4533 | return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs); |
4534 | } |
4535 | |
4536 | //===----------------------------------------------------------------------===// |
4537 | // DesignatedInitExpr |
4538 | //===----------------------------------------------------------------------===// |
4539 | |
4540 | const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const { |
4541 | assert(isFieldDesignator() && "Only valid on a field designator" ); |
4542 | if (FieldInfo.NameOrField & 0x01) |
4543 | return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01); |
4544 | return getFieldDecl()->getIdentifier(); |
4545 | } |
4546 | |
4547 | DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty, |
4548 | llvm::ArrayRef<Designator> Designators, |
4549 | SourceLocation EqualOrColonLoc, |
4550 | bool GNUSyntax, |
4551 | ArrayRef<Expr *> IndexExprs, Expr *Init) |
4552 | : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(), |
4553 | Init->getObjectKind()), |
4554 | EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), |
4555 | NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) { |
4556 | this->Designators = new (C) Designator[NumDesignators]; |
4557 | |
4558 | // Record the initializer itself. |
4559 | child_iterator Child = child_begin(); |
4560 | *Child++ = Init; |
4561 | |
4562 | // Copy the designators and their subexpressions, computing |
4563 | // value-dependence along the way. |
4564 | unsigned IndexIdx = 0; |
4565 | for (unsigned I = 0; I != NumDesignators; ++I) { |
4566 | this->Designators[I] = Designators[I]; |
4567 | if (this->Designators[I].isArrayDesignator()) { |
4568 | // Copy the index expressions into permanent storage. |
4569 | *Child++ = IndexExprs[IndexIdx++]; |
4570 | } else if (this->Designators[I].isArrayRangeDesignator()) { |
4571 | // Copy the start/end expressions into permanent storage. |
4572 | *Child++ = IndexExprs[IndexIdx++]; |
4573 | *Child++ = IndexExprs[IndexIdx++]; |
4574 | } |
4575 | } |
4576 | |
4577 | assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions" ); |
4578 | setDependence(computeDependence(E: this)); |
4579 | } |
4580 | |
4581 | DesignatedInitExpr * |
4582 | DesignatedInitExpr::Create(const ASTContext &C, |
4583 | llvm::ArrayRef<Designator> Designators, |
4584 | ArrayRef<Expr*> IndexExprs, |
4585 | SourceLocation ColonOrEqualLoc, |
4586 | bool UsesColonSyntax, Expr *Init) { |
4587 | void *Mem = C.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: IndexExprs.size() + 1), |
4588 | Align: alignof(DesignatedInitExpr)); |
4589 | return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators, |
4590 | ColonOrEqualLoc, UsesColonSyntax, |
4591 | IndexExprs, Init); |
4592 | } |
4593 | |
4594 | DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C, |
4595 | unsigned NumIndexExprs) { |
4596 | void *Mem = C.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: NumIndexExprs + 1), |
4597 | Align: alignof(DesignatedInitExpr)); |
4598 | return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); |
4599 | } |
4600 | |
4601 | void DesignatedInitExpr::setDesignators(const ASTContext &C, |
4602 | const Designator *Desigs, |
4603 | unsigned NumDesigs) { |
4604 | Designators = new (C) Designator[NumDesigs]; |
4605 | NumDesignators = NumDesigs; |
4606 | for (unsigned I = 0; I != NumDesigs; ++I) |
4607 | Designators[I] = Desigs[I]; |
4608 | } |
4609 | |
4610 | SourceRange DesignatedInitExpr::() const { |
4611 | DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this); |
4612 | if (size() == 1) |
4613 | return DIE->getDesignator(Idx: 0)->getSourceRange(); |
4614 | return SourceRange(DIE->getDesignator(Idx: 0)->getBeginLoc(), |
4615 | DIE->getDesignator(Idx: size() - 1)->getEndLoc()); |
4616 | } |
4617 | |
4618 | SourceLocation DesignatedInitExpr::getBeginLoc() const { |
4619 | auto *DIE = const_cast<DesignatedInitExpr *>(this); |
4620 | Designator &First = *DIE->getDesignator(Idx: 0); |
4621 | if (First.isFieldDesignator()) { |
4622 | // Skip past implicit designators for anonymous structs/unions, since |
4623 | // these do not have valid source locations. |
4624 | for (unsigned int i = 0; i < DIE->size(); i++) { |
4625 | Designator &Des = *DIE->getDesignator(Idx: i); |
4626 | SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc(); |
4627 | if (!retval.isValid()) |
4628 | continue; |
4629 | return retval; |
4630 | } |
4631 | } |
4632 | return First.getLBracketLoc(); |
4633 | } |
4634 | |
4635 | SourceLocation DesignatedInitExpr::getEndLoc() const { |
4636 | return getInit()->getEndLoc(); |
4637 | } |
4638 | |
4639 | Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const { |
4640 | assert(D.isArrayDesignator() && "Requires array designator" ); |
4641 | return getSubExpr(Idx: D.getArrayIndex() + 1); |
4642 | } |
4643 | |
4644 | Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const { |
4645 | assert(D.isArrayRangeDesignator() && "Requires array range designator" ); |
4646 | return getSubExpr(Idx: D.getArrayIndex() + 1); |
4647 | } |
4648 | |
4649 | Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const { |
4650 | assert(D.isArrayRangeDesignator() && "Requires array range designator" ); |
4651 | return getSubExpr(Idx: D.getArrayIndex() + 2); |
4652 | } |
4653 | |
4654 | /// Replaces the designator at index @p Idx with the series |
4655 | /// of designators in [First, Last). |
4656 | void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx, |
4657 | const Designator *First, |
4658 | const Designator *Last) { |
4659 | unsigned NumNewDesignators = Last - First; |
4660 | if (NumNewDesignators == 0) { |
4661 | std::copy_backward(first: Designators + Idx + 1, |
4662 | last: Designators + NumDesignators, |
4663 | result: Designators + Idx); |
4664 | --NumNewDesignators; |
4665 | return; |
4666 | } |
4667 | if (NumNewDesignators == 1) { |
4668 | Designators[Idx] = *First; |
4669 | return; |
4670 | } |
4671 | |
4672 | Designator *NewDesignators |
4673 | = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; |
4674 | std::copy(first: Designators, last: Designators + Idx, result: NewDesignators); |
4675 | std::copy(first: First, last: Last, result: NewDesignators + Idx); |
4676 | std::copy(first: Designators + Idx + 1, last: Designators + NumDesignators, |
4677 | result: NewDesignators + Idx + NumNewDesignators); |
4678 | Designators = NewDesignators; |
4679 | NumDesignators = NumDesignators - 1 + NumNewDesignators; |
4680 | } |
4681 | |
4682 | DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C, |
4683 | SourceLocation lBraceLoc, |
4684 | Expr *baseExpr, |
4685 | SourceLocation rBraceLoc) |
4686 | : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue, |
4687 | OK_Ordinary) { |
4688 | BaseAndUpdaterExprs[0] = baseExpr; |
4689 | |
4690 | InitListExpr *ILE = |
4691 | new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc); |
4692 | ILE->setType(baseExpr->getType()); |
4693 | BaseAndUpdaterExprs[1] = ILE; |
4694 | |
4695 | // FIXME: this is wrong, set it correctly. |
4696 | setDependence(ExprDependence::None); |
4697 | } |
4698 | |
4699 | SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const { |
4700 | return getBase()->getBeginLoc(); |
4701 | } |
4702 | |
4703 | SourceLocation DesignatedInitUpdateExpr::getEndLoc() const { |
4704 | return getBase()->getEndLoc(); |
4705 | } |
4706 | |
4707 | ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, |
4708 | SourceLocation RParenLoc) |
4709 | : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary), |
4710 | LParenLoc(LParenLoc), RParenLoc(RParenLoc) { |
4711 | ParenListExprBits.NumExprs = Exprs.size(); |
4712 | |
4713 | for (unsigned I = 0, N = Exprs.size(); I != N; ++I) |
4714 | getTrailingObjects<Stmt *>()[I] = Exprs[I]; |
4715 | setDependence(computeDependence(E: this)); |
4716 | } |
4717 | |
4718 | ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs) |
4719 | : Expr(ParenListExprClass, Empty) { |
4720 | ParenListExprBits.NumExprs = NumExprs; |
4721 | } |
4722 | |
4723 | ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx, |
4724 | SourceLocation LParenLoc, |
4725 | ArrayRef<Expr *> Exprs, |
4726 | SourceLocation RParenLoc) { |
4727 | void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: Exprs.size()), |
4728 | Align: alignof(ParenListExpr)); |
4729 | return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc); |
4730 | } |
4731 | |
4732 | ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx, |
4733 | unsigned NumExprs) { |
4734 | void *Mem = |
4735 | Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: NumExprs), Align: alignof(ParenListExpr)); |
4736 | return new (Mem) ParenListExpr(EmptyShell(), NumExprs); |
4737 | } |
4738 | |
4739 | BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, |
4740 | Opcode opc, QualType ResTy, ExprValueKind VK, |
4741 | ExprObjectKind OK, SourceLocation opLoc, |
4742 | FPOptionsOverride FPFeatures) |
4743 | : Expr(BinaryOperatorClass, ResTy, VK, OK) { |
4744 | BinaryOperatorBits.Opc = opc; |
4745 | assert(!isCompoundAssignmentOp() && |
4746 | "Use CompoundAssignOperator for compound assignments" ); |
4747 | BinaryOperatorBits.OpLoc = opLoc; |
4748 | SubExprs[LHS] = lhs; |
4749 | SubExprs[RHS] = rhs; |
4750 | BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
4751 | if (hasStoredFPFeatures()) |
4752 | setStoredFPFeatures(FPFeatures); |
4753 | setDependence(computeDependence(E: this)); |
4754 | } |
4755 | |
4756 | BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, |
4757 | Opcode opc, QualType ResTy, ExprValueKind VK, |
4758 | ExprObjectKind OK, SourceLocation opLoc, |
4759 | FPOptionsOverride FPFeatures, bool dead2) |
4760 | : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) { |
4761 | BinaryOperatorBits.Opc = opc; |
4762 | assert(isCompoundAssignmentOp() && |
4763 | "Use CompoundAssignOperator for compound assignments" ); |
4764 | BinaryOperatorBits.OpLoc = opLoc; |
4765 | SubExprs[LHS] = lhs; |
4766 | SubExprs[RHS] = rhs; |
4767 | BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
4768 | if (hasStoredFPFeatures()) |
4769 | setStoredFPFeatures(FPFeatures); |
4770 | setDependence(computeDependence(E: this)); |
4771 | } |
4772 | |
4773 | BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C, |
4774 | bool HasFPFeatures) { |
4775 | unsigned = sizeOfTrailingObjects(HasFPFeatures); |
4776 | void *Mem = |
4777 | C.Allocate(Size: sizeof(BinaryOperator) + Extra, Align: alignof(BinaryOperator)); |
4778 | return new (Mem) BinaryOperator(EmptyShell()); |
4779 | } |
4780 | |
4781 | BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs, |
4782 | Expr *rhs, Opcode opc, QualType ResTy, |
4783 | ExprValueKind VK, ExprObjectKind OK, |
4784 | SourceLocation opLoc, |
4785 | FPOptionsOverride FPFeatures) { |
4786 | bool HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
4787 | unsigned = sizeOfTrailingObjects(HasFPFeatures); |
4788 | void *Mem = |
4789 | C.Allocate(Size: sizeof(BinaryOperator) + Extra, Align: alignof(BinaryOperator)); |
4790 | return new (Mem) |
4791 | BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures); |
4792 | } |
4793 | |
4794 | CompoundAssignOperator * |
4795 | CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) { |
4796 | unsigned = sizeOfTrailingObjects(HasFPFeatures); |
4797 | void *Mem = C.Allocate(Size: sizeof(CompoundAssignOperator) + Extra, |
4798 | Align: alignof(CompoundAssignOperator)); |
4799 | return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures); |
4800 | } |
4801 | |
4802 | CompoundAssignOperator * |
4803 | CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs, |
4804 | Opcode opc, QualType ResTy, ExprValueKind VK, |
4805 | ExprObjectKind OK, SourceLocation opLoc, |
4806 | FPOptionsOverride FPFeatures, |
4807 | QualType CompLHSType, QualType CompResultType) { |
4808 | bool HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
4809 | unsigned = sizeOfTrailingObjects(HasFPFeatures); |
4810 | void *Mem = C.Allocate(Size: sizeof(CompoundAssignOperator) + Extra, |
4811 | Align: alignof(CompoundAssignOperator)); |
4812 | return new (Mem) |
4813 | CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures, |
4814 | CompLHSType, CompResultType); |
4815 | } |
4816 | |
4817 | UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C, |
4818 | bool hasFPFeatures) { |
4819 | void *Mem = C.Allocate(Size: totalSizeToAlloc<FPOptionsOverride>(Counts: hasFPFeatures), |
4820 | Align: alignof(UnaryOperator)); |
4821 | return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell()); |
4822 | } |
4823 | |
4824 | UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, |
4825 | QualType type, ExprValueKind VK, ExprObjectKind OK, |
4826 | SourceLocation l, bool CanOverflow, |
4827 | FPOptionsOverride FPFeatures) |
4828 | : Expr(UnaryOperatorClass, type, VK, OK), Val(input) { |
4829 | UnaryOperatorBits.Opc = opc; |
4830 | UnaryOperatorBits.CanOverflow = CanOverflow; |
4831 | UnaryOperatorBits.Loc = l; |
4832 | UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
4833 | if (hasStoredFPFeatures()) |
4834 | setStoredFPFeatures(FPFeatures); |
4835 | setDependence(computeDependence(E: this, Ctx)); |
4836 | } |
4837 | |
4838 | UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input, |
4839 | Opcode opc, QualType type, |
4840 | ExprValueKind VK, ExprObjectKind OK, |
4841 | SourceLocation l, bool CanOverflow, |
4842 | FPOptionsOverride FPFeatures) { |
4843 | bool HasFPFeatures = FPFeatures.requiresTrailingStorage(); |
4844 | unsigned Size = totalSizeToAlloc<FPOptionsOverride>(Counts: HasFPFeatures); |
4845 | void *Mem = C.Allocate(Size, Align: alignof(UnaryOperator)); |
4846 | return new (Mem) |
4847 | UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures); |
4848 | } |
4849 | |
4850 | const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { |
4851 | if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(Val: e)) |
4852 | e = ewc->getSubExpr(); |
4853 | if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(Val: e)) |
4854 | e = m->getSubExpr(); |
4855 | e = cast<CXXConstructExpr>(Val: e)->getArg(Arg: 0); |
4856 | while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(Val: e)) |
4857 | e = ice->getSubExpr(); |
4858 | return cast<OpaqueValueExpr>(Val: e); |
4859 | } |
4860 | |
4861 | PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context, |
4862 | EmptyShell sh, |
4863 | unsigned numSemanticExprs) { |
4864 | void *buffer = |
4865 | Context.Allocate(Size: totalSizeToAlloc<Expr *>(Counts: 1 + numSemanticExprs), |
4866 | Align: alignof(PseudoObjectExpr)); |
4867 | return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); |
4868 | } |
4869 | |
4870 | PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) |
4871 | : Expr(PseudoObjectExprClass, shell) { |
4872 | PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; |
4873 | } |
4874 | |
4875 | PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax, |
4876 | ArrayRef<Expr*> semantics, |
4877 | unsigned resultIndex) { |
4878 | assert(syntax && "no syntactic expression!" ); |
4879 | assert(semantics.size() && "no semantic expressions!" ); |
4880 | |
4881 | QualType type; |
4882 | ExprValueKind VK; |
4883 | if (resultIndex == NoResult) { |
4884 | type = C.VoidTy; |
4885 | VK = VK_PRValue; |
4886 | } else { |
4887 | assert(resultIndex < semantics.size()); |
4888 | type = semantics[resultIndex]->getType(); |
4889 | VK = semantics[resultIndex]->getValueKind(); |
4890 | assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary); |
4891 | } |
4892 | |
4893 | void *buffer = C.Allocate(Size: totalSizeToAlloc<Expr *>(Counts: semantics.size() + 1), |
4894 | Align: alignof(PseudoObjectExpr)); |
4895 | return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, |
4896 | resultIndex); |
4897 | } |
4898 | |
4899 | PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, |
4900 | Expr *syntax, ArrayRef<Expr *> semantics, |
4901 | unsigned resultIndex) |
4902 | : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) { |
4903 | PseudoObjectExprBits.NumSubExprs = semantics.size() + 1; |
4904 | PseudoObjectExprBits.ResultIndex = resultIndex + 1; |
4905 | |
4906 | for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { |
4907 | Expr *E = (i == 0 ? syntax : semantics[i-1]); |
4908 | getSubExprsBuffer()[i] = E; |
4909 | |
4910 | if (isa<OpaqueValueExpr>(Val: E)) |
4911 | assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && |
4912 | "opaque-value semantic expressions for pseudo-object " |
4913 | "operations must have sources" ); |
4914 | } |
4915 | |
4916 | setDependence(computeDependence(E: this)); |
4917 | } |
4918 | |
4919 | //===----------------------------------------------------------------------===// |
4920 | // Child Iterators for iterating over subexpressions/substatements |
4921 | //===----------------------------------------------------------------------===// |
4922 | |
4923 | // UnaryExprOrTypeTraitExpr |
4924 | Stmt::child_range UnaryExprOrTypeTraitExpr::children() { |
4925 | const_child_range CCR = |
4926 | const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children(); |
4927 | return child_range(cast_away_const(RHS: CCR.begin()), cast_away_const(RHS: CCR.end())); |
4928 | } |
4929 | |
4930 | Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const { |
4931 | // If this is of a type and the type is a VLA type (and not a typedef), the |
4932 | // size expression of the VLA needs to be treated as an executable expression. |
4933 | // Why isn't this weirdness documented better in StmtIterator? |
4934 | if (isArgumentType()) { |
4935 | if (const VariableArrayType *T = |
4936 | dyn_cast<VariableArrayType>(Val: getArgumentType().getTypePtr())) |
4937 | return const_child_range(const_child_iterator(T), const_child_iterator()); |
4938 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4939 | } |
4940 | return const_child_range(&Argument.Ex, &Argument.Ex + 1); |
4941 | } |
4942 | |
4943 | AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t, |
4944 | AtomicOp op, SourceLocation RP) |
4945 | : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary), |
4946 | NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) { |
4947 | assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions" ); |
4948 | for (unsigned i = 0; i != args.size(); i++) |
4949 | SubExprs[i] = args[i]; |
4950 | setDependence(computeDependence(E: this)); |
4951 | } |
4952 | |
4953 | unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) { |
4954 | switch (Op) { |
4955 | case AO__c11_atomic_init: |
4956 | case AO__opencl_atomic_init: |
4957 | case AO__c11_atomic_load: |
4958 | case AO__atomic_load_n: |
4959 | return 2; |
4960 | |
4961 | case AO__scoped_atomic_load_n: |
4962 | case AO__opencl_atomic_load: |
4963 | case AO__hip_atomic_load: |
4964 | case AO__c11_atomic_store: |
4965 | case AO__c11_atomic_exchange: |
4966 | case AO__atomic_load: |
4967 | case AO__atomic_store: |
4968 | case AO__atomic_store_n: |
4969 | case AO__atomic_exchange_n: |
4970 | case AO__c11_atomic_fetch_add: |
4971 | case AO__c11_atomic_fetch_sub: |
4972 | case AO__c11_atomic_fetch_and: |
4973 | case AO__c11_atomic_fetch_or: |
4974 | case AO__c11_atomic_fetch_xor: |
4975 | case AO__c11_atomic_fetch_nand: |
4976 | case AO__c11_atomic_fetch_max: |
4977 | case AO__c11_atomic_fetch_min: |
4978 | case AO__atomic_fetch_add: |
4979 | case AO__atomic_fetch_sub: |
4980 | case AO__atomic_fetch_and: |
4981 | case AO__atomic_fetch_or: |
4982 | case AO__atomic_fetch_xor: |
4983 | case AO__atomic_fetch_nand: |
4984 | case AO__atomic_add_fetch: |
4985 | case AO__atomic_sub_fetch: |
4986 | case AO__atomic_and_fetch: |
4987 | case AO__atomic_or_fetch: |
4988 | case AO__atomic_xor_fetch: |
4989 | case AO__atomic_nand_fetch: |
4990 | case AO__atomic_min_fetch: |
4991 | case AO__atomic_max_fetch: |
4992 | case AO__atomic_fetch_min: |
4993 | case AO__atomic_fetch_max: |
4994 | return 3; |
4995 | |
4996 | case AO__scoped_atomic_load: |
4997 | case AO__scoped_atomic_store: |
4998 | case AO__scoped_atomic_store_n: |
4999 | case AO__scoped_atomic_fetch_add: |
5000 | case AO__scoped_atomic_fetch_sub: |
5001 | case AO__scoped_atomic_fetch_and: |
5002 | case AO__scoped_atomic_fetch_or: |
5003 | case AO__scoped_atomic_fetch_xor: |
5004 | case AO__scoped_atomic_fetch_nand: |
5005 | case AO__scoped_atomic_add_fetch: |
5006 | case AO__scoped_atomic_sub_fetch: |
5007 | case AO__scoped_atomic_and_fetch: |
5008 | case AO__scoped_atomic_or_fetch: |
5009 | case AO__scoped_atomic_xor_fetch: |
5010 | case AO__scoped_atomic_nand_fetch: |
5011 | case AO__scoped_atomic_min_fetch: |
5012 | case AO__scoped_atomic_max_fetch: |
5013 | case AO__scoped_atomic_fetch_min: |
5014 | case AO__scoped_atomic_fetch_max: |
5015 | case AO__scoped_atomic_exchange_n: |
5016 | case AO__hip_atomic_exchange: |
5017 | case AO__hip_atomic_fetch_add: |
5018 | case AO__hip_atomic_fetch_sub: |
5019 | case AO__hip_atomic_fetch_and: |
5020 | case AO__hip_atomic_fetch_or: |
5021 | case AO__hip_atomic_fetch_xor: |
5022 | case AO__hip_atomic_fetch_min: |
5023 | case AO__hip_atomic_fetch_max: |
5024 | case AO__opencl_atomic_store: |
5025 | case AO__hip_atomic_store: |
5026 | case AO__opencl_atomic_exchange: |
5027 | case AO__opencl_atomic_fetch_add: |
5028 | case AO__opencl_atomic_fetch_sub: |
5029 | case AO__opencl_atomic_fetch_and: |
5030 | case AO__opencl_atomic_fetch_or: |
5031 | case AO__opencl_atomic_fetch_xor: |
5032 | case AO__opencl_atomic_fetch_min: |
5033 | case AO__opencl_atomic_fetch_max: |
5034 | case AO__atomic_exchange: |
5035 | return 4; |
5036 | |
5037 | case AO__scoped_atomic_exchange: |
5038 | case AO__c11_atomic_compare_exchange_strong: |
5039 | case AO__c11_atomic_compare_exchange_weak: |
5040 | return 5; |
5041 | case AO__hip_atomic_compare_exchange_strong: |
5042 | case AO__opencl_atomic_compare_exchange_strong: |
5043 | case AO__opencl_atomic_compare_exchange_weak: |
5044 | case AO__hip_atomic_compare_exchange_weak: |
5045 | case AO__atomic_compare_exchange: |
5046 | case AO__atomic_compare_exchange_n: |
5047 | return 6; |
5048 | |
5049 | case AO__scoped_atomic_compare_exchange: |
5050 | case AO__scoped_atomic_compare_exchange_n: |
5051 | return 7; |
5052 | } |
5053 | llvm_unreachable("unknown atomic op" ); |
5054 | } |
5055 | |
5056 | QualType AtomicExpr::getValueType() const { |
5057 | auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType(); |
5058 | if (auto AT = T->getAs<AtomicType>()) |
5059 | return AT->getValueType(); |
5060 | return T; |
5061 | } |
5062 | |
5063 | QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) { |
5064 | unsigned ArraySectionCount = 0; |
5065 | while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Val: Base->IgnoreParens())) { |
5066 | Base = OASE->getBase(); |
5067 | ++ArraySectionCount; |
5068 | } |
5069 | while (auto *ASE = |
5070 | dyn_cast<ArraySubscriptExpr>(Val: Base->IgnoreParenImpCasts())) { |
5071 | Base = ASE->getBase(); |
5072 | ++ArraySectionCount; |
5073 | } |
5074 | Base = Base->IgnoreParenImpCasts(); |
5075 | auto OriginalTy = Base->getType(); |
5076 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Base)) |
5077 | if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) |
5078 | OriginalTy = PVD->getOriginalType().getNonReferenceType(); |
5079 | |
5080 | for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) { |
5081 | if (OriginalTy->isAnyPointerType()) |
5082 | OriginalTy = OriginalTy->getPointeeType(); |
5083 | else if (OriginalTy->isArrayType()) |
5084 | OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType(); |
5085 | else |
5086 | return {}; |
5087 | } |
5088 | return OriginalTy; |
5089 | } |
5090 | |
5091 | RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, |
5092 | SourceLocation EndLoc, ArrayRef<Expr *> SubExprs) |
5093 | : Expr(RecoveryExprClass, T.getNonReferenceType(), |
5094 | T->isDependentType() ? VK_LValue : getValueKindForType(T), |
5095 | OK_Ordinary), |
5096 | BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) { |
5097 | assert(!T.isNull()); |
5098 | assert(!llvm::is_contained(SubExprs, nullptr)); |
5099 | |
5100 | llvm::copy(SubExprs, getTrailingObjects<Expr *>()); |
5101 | setDependence(computeDependence(E: this)); |
5102 | } |
5103 | |
5104 | RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T, |
5105 | SourceLocation BeginLoc, |
5106 | SourceLocation EndLoc, |
5107 | ArrayRef<Expr *> SubExprs) { |
5108 | void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()), |
5109 | alignof(RecoveryExpr)); |
5110 | return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs); |
5111 | } |
5112 | |
5113 | RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) { |
5114 | void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs), |
5115 | alignof(RecoveryExpr)); |
5116 | return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs); |
5117 | } |
5118 | |
5119 | void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) { |
5120 | assert( |
5121 | NumDims == Dims.size() && |
5122 | "Preallocated number of dimensions is different from the provided one." ); |
5123 | llvm::copy(Dims, getTrailingObjects<Expr *>()); |
5124 | } |
5125 | |
5126 | void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) { |
5127 | assert( |
5128 | NumDims == BR.size() && |
5129 | "Preallocated number of dimensions is different from the provided one." ); |
5130 | llvm::copy(BR, getTrailingObjects<SourceRange>()); |
5131 | } |
5132 | |
5133 | OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op, |
5134 | SourceLocation L, SourceLocation R, |
5135 | ArrayRef<Expr *> Dims) |
5136 | : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L), |
5137 | RPLoc(R), NumDims(Dims.size()) { |
5138 | setBase(Op); |
5139 | setDimensions(Dims); |
5140 | setDependence(computeDependence(E: this)); |
5141 | } |
5142 | |
5143 | OMPArrayShapingExpr * |
5144 | OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op, |
5145 | SourceLocation L, SourceLocation R, |
5146 | ArrayRef<Expr *> Dims, |
5147 | ArrayRef<SourceRange> BracketRanges) { |
5148 | assert(Dims.size() == BracketRanges.size() && |
5149 | "Different number of dimensions and brackets ranges." ); |
5150 | void *Mem = Context.Allocate( |
5151 | Size: totalSizeToAlloc<Expr *, SourceRange>(Counts: Dims.size() + 1, Counts: Dims.size()), |
5152 | Align: alignof(OMPArrayShapingExpr)); |
5153 | auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims); |
5154 | E->setBracketsRanges(BracketRanges); |
5155 | return E; |
5156 | } |
5157 | |
5158 | OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context, |
5159 | unsigned NumDims) { |
5160 | void *Mem = Context.Allocate( |
5161 | Size: totalSizeToAlloc<Expr *, SourceRange>(Counts: NumDims + 1, Counts: NumDims), |
5162 | Align: alignof(OMPArrayShapingExpr)); |
5163 | return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims); |
5164 | } |
5165 | |
5166 | void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) { |
5167 | assert(I < NumIterators && |
5168 | "Idx is greater or equal the number of iterators definitions." ); |
5169 | getTrailingObjects<Decl *>()[I] = D; |
5170 | } |
5171 | |
5172 | void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) { |
5173 | assert(I < NumIterators && |
5174 | "Idx is greater or equal the number of iterators definitions." ); |
5175 | getTrailingObjects< |
5176 | SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + |
5177 | static_cast<int>(RangeLocOffset::AssignLoc)] = Loc; |
5178 | } |
5179 | |
5180 | void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin, |
5181 | SourceLocation ColonLoc, Expr *End, |
5182 | SourceLocation SecondColonLoc, |
5183 | Expr *Step) { |
5184 | assert(I < NumIterators && |
5185 | "Idx is greater or equal the number of iterators definitions." ); |
5186 | getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) + |
5187 | static_cast<int>(RangeExprOffset::Begin)] = |
5188 | Begin; |
5189 | getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) + |
5190 | static_cast<int>(RangeExprOffset::End)] = End; |
5191 | getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) + |
5192 | static_cast<int>(RangeExprOffset::Step)] = Step; |
5193 | getTrailingObjects< |
5194 | SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + |
5195 | static_cast<int>(RangeLocOffset::FirstColonLoc)] = |
5196 | ColonLoc; |
5197 | getTrailingObjects< |
5198 | SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + |
5199 | static_cast<int>(RangeLocOffset::SecondColonLoc)] = |
5200 | SecondColonLoc; |
5201 | } |
5202 | |
5203 | Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) { |
5204 | return getTrailingObjects<Decl *>()[I]; |
5205 | } |
5206 | |
5207 | OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) { |
5208 | IteratorRange Res; |
5209 | Res.Begin = |
5210 | getTrailingObjects<Expr *>()[I * static_cast<int>( |
5211 | RangeExprOffset::Total) + |
5212 | static_cast<int>(RangeExprOffset::Begin)]; |
5213 | Res.End = |
5214 | getTrailingObjects<Expr *>()[I * static_cast<int>( |
5215 | RangeExprOffset::Total) + |
5216 | static_cast<int>(RangeExprOffset::End)]; |
5217 | Res.Step = |
5218 | getTrailingObjects<Expr *>()[I * static_cast<int>( |
5219 | RangeExprOffset::Total) + |
5220 | static_cast<int>(RangeExprOffset::Step)]; |
5221 | return Res; |
5222 | } |
5223 | |
5224 | SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const { |
5225 | return getTrailingObjects< |
5226 | SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + |
5227 | static_cast<int>(RangeLocOffset::AssignLoc)]; |
5228 | } |
5229 | |
5230 | SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const { |
5231 | return getTrailingObjects< |
5232 | SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + |
5233 | static_cast<int>(RangeLocOffset::FirstColonLoc)]; |
5234 | } |
5235 | |
5236 | SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const { |
5237 | return getTrailingObjects< |
5238 | SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) + |
5239 | static_cast<int>(RangeLocOffset::SecondColonLoc)]; |
5240 | } |
5241 | |
5242 | void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) { |
5243 | getTrailingObjects<OMPIteratorHelperData>()[I] = D; |
5244 | } |
5245 | |
5246 | OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) { |
5247 | return getTrailingObjects<OMPIteratorHelperData>()[I]; |
5248 | } |
5249 | |
5250 | const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const { |
5251 | return getTrailingObjects<OMPIteratorHelperData>()[I]; |
5252 | } |
5253 | |
5254 | OMPIteratorExpr::OMPIteratorExpr( |
5255 | QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L, |
5256 | SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data, |
5257 | ArrayRef<OMPIteratorHelperData> Helpers) |
5258 | : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary), |
5259 | IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R), |
5260 | NumIterators(Data.size()) { |
5261 | for (unsigned I = 0, E = Data.size(); I < E; ++I) { |
5262 | const IteratorDefinition &D = Data[I]; |
5263 | setIteratorDeclaration(I, D: D.IteratorDecl); |
5264 | setAssignmentLoc(I, Loc: D.AssignmentLoc); |
5265 | setIteratorRange(I, Begin: D.Range.Begin, ColonLoc: D.ColonLoc, End: D.Range.End, |
5266 | SecondColonLoc: D.SecondColonLoc, Step: D.Range.Step); |
5267 | setHelper(I, D: Helpers[I]); |
5268 | } |
5269 | setDependence(computeDependence(E: this)); |
5270 | } |
5271 | |
5272 | OMPIteratorExpr * |
5273 | OMPIteratorExpr::Create(const ASTContext &Context, QualType T, |
5274 | SourceLocation IteratorKwLoc, SourceLocation L, |
5275 | SourceLocation R, |
5276 | ArrayRef<OMPIteratorExpr::IteratorDefinition> Data, |
5277 | ArrayRef<OMPIteratorHelperData> Helpers) { |
5278 | assert(Data.size() == Helpers.size() && |
5279 | "Data and helpers must have the same size." ); |
5280 | void *Mem = Context.Allocate( |
5281 | Size: totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>( |
5282 | Counts: Data.size(), Counts: Data.size() * static_cast<int>(RangeExprOffset::Total), |
5283 | Counts: Data.size() * static_cast<int>(RangeLocOffset::Total), |
5284 | Counts: Helpers.size()), |
5285 | Align: alignof(OMPIteratorExpr)); |
5286 | return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers); |
5287 | } |
5288 | |
5289 | OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context, |
5290 | unsigned NumIterators) { |
5291 | void *Mem = Context.Allocate( |
5292 | Size: totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>( |
5293 | Counts: NumIterators, Counts: NumIterators * static_cast<int>(RangeExprOffset::Total), |
5294 | Counts: NumIterators * static_cast<int>(RangeLocOffset::Total), Counts: NumIterators), |
5295 | Align: alignof(OMPIteratorExpr)); |
5296 | return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators); |
5297 | } |
5298 | |