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