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