clang 24.0.0git
ThreadSafetyCommon.cpp
Go to the documentation of this file.
1//===- ThreadSafetyCommon.cpp ---------------------------------------------===//
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// Implementation of the interfaces declared in ThreadSafetyCommon.h
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/Attr.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclGroup.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/Type.h"
25#include "clang/Analysis/CFG.h"
26#include "clang/Basic/LLVM.h"
29#include "llvm/ADT/ScopeExit.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/StringRef.h"
32#include <algorithm>
33#include <cassert>
34#include <string>
35#include <utility>
36
37using namespace clang;
38using namespace threadSafety;
39
40// From ThreadSafetyUtil.h
42 switch (CE->getStmtClass()) {
43 case Stmt::IntegerLiteralClass:
44 return toString(cast<IntegerLiteral>(CE)->getValue(), 10, true);
45 case Stmt::StringLiteralClass: {
46 std::string ret("\"");
47 ret += cast<StringLiteral>(CE)->getString();
48 ret += "\"";
49 return ret;
50 }
51 case Stmt::CharacterLiteralClass:
52 case Stmt::CXXNullPtrLiteralExprClass:
53 case Stmt::GNUNullExprClass:
54 case Stmt::CXXBoolLiteralExprClass:
55 case Stmt::FloatingLiteralClass:
56 case Stmt::ImaginaryLiteralClass:
57 case Stmt::ObjCStringLiteralClass:
58 default:
59 return "#lit";
60 }
61}
62
63// Return true if E is a variable that points to an incomplete Phi node.
64static bool isIncompletePhi(const til::SExpr *E) {
65 if (const auto *Ph = dyn_cast<til::Phi>(E))
66 return Ph->status() == til::Phi::PH_Incomplete;
67 return false;
68}
69
70static constexpr std::pair<StringRef, bool> ClassifyCapabilityFallback{
71 /*Kind=*/StringRef("mutex"),
72 /*Reentrant=*/false};
73
74// Returns pair (Kind, Reentrant).
75static std::pair<StringRef, bool> classifyCapability(const TypeDecl &TD) {
76 if (const auto *CA = TD.getAttr<CapabilityAttr>())
77 return {CA->getName(), TD.hasAttr<ReentrantCapabilityAttr>()};
78
80}
81
82// Returns pair (Kind, Reentrant).
83static std::pair<StringRef, bool> classifyCapability(QualType QT) {
84 // We need to look at the declaration of the type of the value to determine
85 // which it is. The type should either be a record or a typedef, or a pointer
86 // or reference thereof.
87 if (const auto *RD = QT->getAsRecordDecl())
88 return classifyCapability(*RD);
89 if (const auto *TT = QT->getAs<TypedefType>())
90 return classifyCapability(*TT->getDecl());
93
95}
96
98 const auto &[Kind, Reentrant] = classifyCapability(QT);
99 *this = CapabilityExpr(E, Kind, Neg, Reentrant);
100}
101
103
104til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) { return SMap.lookup(S); }
105
107 Walker.walk(*this);
108 return Scfg;
109}
110
111/// If CE calls through a function pointer field D, return the member access
112/// through which the field was reached; its base is the implicit object
113/// ('this') for the attributes on the field.
115 const NamedDecl *D) {
116 if (!isa<FieldDecl>(D))
117 return nullptr;
118 // Look through the operators that CallExpr::getCalleeDecl looks through
119 // when it finds D, e.g. in `(*dev->lock)()`.
120 const Expr *Callee = CE->getCallee()->IgnoreParenCasts();
121 while (const auto *UO = dyn_cast<UnaryOperator>(Callee)) {
122 if (UO->getOpcode() != UO_Deref && UO->getOpcode() != UO_AddrOf &&
123 UO->getOpcode() != UO_Plus)
124 break;
125 Callee = UO->getSubExpr()->IgnoreParenCasts();
126 }
127 return dyn_cast<MemberExpr>(Callee);
128}
129
130/// Translate a clang expression in an attribute to a til::SExpr.
131/// Constructs the context from D, DeclExp, and SelfDecl.
132///
133/// \param AttrExp The expression to translate.
134/// \param D The declaration to which the attribute is attached.
135/// \param DeclExp An expression involving the Decl to which the attribute
136/// is attached. E.g. the call to a function.
137/// \param Self S-expression to substitute for a \ref CXXThisExpr in a call,
138/// or argument to a cleanup function.
140 const NamedDecl *D,
141 const Expr *DeclExp,
142 til::SExpr *Self) {
143 // If we are processing a raw attribute expression, with no substitutions.
144 if (!DeclExp && !Self)
145 return translateAttrExpr(AttrExp, nullptr);
146
147 CallingContext Ctx(nullptr, D);
148
149 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
150 // for formal parameters when we call buildMutexID later.
151 if (!DeclExp)
152 /* We'll use Self. */;
153 else if (const auto *ME = dyn_cast<MemberExpr>(DeclExp)) {
154 Ctx.SelfArg = ME->getBase();
155 } else if (const auto *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
156 Ctx.SelfArg = CE->getImplicitObjectArgument();
157 Ctx.NumArgs = CE->getNumArgs();
158 Ctx.FunArgs = CE->getArgs();
159 } else if (const auto *CE = dyn_cast<CallExpr>(DeclExp)) {
160 // Calls to operators that are members need to be treated like member calls.
162 Ctx.SelfArg = CE->getArg(0);
163 Ctx.NumArgs = CE->getNumArgs() - 1;
164 Ctx.FunArgs = CE->getArgs() + 1;
165 } else {
166 if (const MemberExpr *ME = getFunPtrFieldCallee(CE, D))
167 Ctx.SelfArg = ME->getBase();
168 Ctx.NumArgs = CE->getNumArgs();
169 Ctx.FunArgs = CE->getArgs();
170 }
171 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
172 Ctx.SelfArg = nullptr; // Will be set below
173 Ctx.NumArgs = CE->getNumArgs();
174 Ctx.FunArgs = CE->getArgs();
175 }
176
177 // Usually we want to substitute the self-argument for "this", but lambdas
178 // are an exception: "this" on or in a lambda call operator doesn't refer
179 // to the lambda, but to captured "this" in the context it was created in.
180 // This can happen for operator calls and member calls, so fix it up here.
181 if (const auto *CMD = dyn_cast<CXXMethodDecl>(D))
182 if (CMD->getParent()->isLambda())
183 Ctx.SelfArg = nullptr;
184
185 if (Self) {
186 assert(!Ctx.SelfArg && "Ambiguous self argument");
187 assert(isa<FunctionDecl>(D) && "Self argument requires function");
188 if (isa<CXXMethodDecl>(D))
189 Ctx.SelfArg = Self;
190 else
191 Ctx.FunArgs = Self;
192
193 // If the attribute has no arguments, then assume the argument is "this".
194 if (!AttrExp)
195 return CapabilityExpr(
196 Self, cast<CXXMethodDecl>(D)->getFunctionObjectParameterType(),
197 false);
198 else // For most attributes.
199 return translateAttrExpr(AttrExp, &Ctx);
200 }
201
202 // If the attribute has no arguments, then assume the argument is "this".
203 // SelfArg may be null for non-method callees (e.g. function pointers).
204 if (!AttrExp) {
205 if (!Ctx.SelfArg)
206 return CapabilityExpr();
207 return translateAttrExpr(cast<const Expr *>(Ctx.SelfArg), nullptr);
208 }
209
210 // For most attributes.
211 return translateAttrExpr(AttrExp, &Ctx);
212}
213
214/// Translate a clang expression in an attribute to a til::SExpr.
215// This assumes a CallingContext has already been created.
217 CallingContext *Ctx) {
218 if (!AttrExp)
219 return CapabilityExpr();
220
221 if (const auto* SLit = dyn_cast<StringLiteral>(AttrExp)) {
222 if (SLit->getString() == "*")
223 // The "*" expr is a universal lock, which essentially turns off
224 // checks until it is removed from the lockset.
225 return CapabilityExpr(new (Arena) til::Wildcard(), StringRef("wildcard"),
226 /*Neg=*/false, /*Reentrant=*/false);
227 else
228 // Ignore other string literals for now.
229 return CapabilityExpr();
230 }
231
232 bool Neg = false;
233 if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) {
234 if (OE->getOperator() == OO_Exclaim) {
235 Neg = true;
236 AttrExp = OE->getArg(0);
237 }
238 }
239 else if (const auto *UO = dyn_cast<UnaryOperator>(AttrExp)) {
240 if (UO->getOpcode() == UO_LNot) {
241 Neg = true;
242 AttrExp = UO->getSubExpr()->IgnoreImplicit();
243 }
244 }
245
246 const til::SExpr *E = translate(AttrExp, Ctx);
247
248 // Trap mutex expressions like nullptr, or 0.
249 // Any literal value is nonsense.
250 if (!E || isa<til::Literal>(E))
251 return CapabilityExpr();
252
253 // Hack to deal with smart pointers -- strip off top-level pointer casts.
254 if (const auto *CE = dyn_cast<til::Cast>(E)) {
255 if (CE->castOpcode() == til::CAST_objToPtr)
256 E = CE->expr();
257 }
258 return CapabilityExpr(E, AttrExp->getType(), Neg);
259}
260
262 CallingContext *Ctx) {
263 assert(VD);
264
265 // General recursion guard for x = f(x). If we are already in the process of
266 // defining VD, use its pre-assignment value to break the cycle.
267 if (VarsBeingTranslated.contains(VD->getCanonicalDecl()))
268 return new (Arena) til::LiteralPtr(VD);
269
270 // The closure captures state that is updated to correctly translate chains of
271 // aliases. Restore it when we are done with recursive translation.
272 llvm::scope_exit Cleanup([&, RestoreClosure = VarsBeingTranslated.empty()
273 ? LookupLocalVarExpr
274 : nullptr] {
275 VarsBeingTranslated.erase(VD->getCanonicalDecl());
276 if (VarsBeingTranslated.empty())
277 LookupLocalVarExpr = RestoreClosure;
278 });
279 VarsBeingTranslated.insert(VD->getCanonicalDecl());
280
281 QualType Ty = VD->getType();
282 if (!VD->isStaticLocal() && Ty->isPointerType()) {
283 // Substitute local variable aliases with a canonical definition.
284 if (LookupLocalVarExpr) {
285 // Attempt to resolve an alias through the more complex local variable map
286 // lookup. This will fail with complex control-flow graphs (where we
287 // revert to no alias resolution to retain stable variable names).
288 if (const Expr *E = LookupLocalVarExpr(VD)) {
289 til::SExpr *Result = translate(E, Ctx);
290 // Unsupported expression (such as heap allocations) will be undefined;
291 // rather than failing here, we simply revert to the pointer being the
292 // canonical variable.
294 return Result;
295 }
296 }
297 }
298
299 return new (Arena) til::LiteralPtr(VD);
300}
301
302// Translate a clang statement or expression to a TIL expression.
303// Also performs substitution of variables; Ctx provides the context.
304// Dispatches on the type of S.
306 if (!S)
307 return nullptr;
308
309 // Check if S has already been translated and cached.
310 // This handles the lookup of SSA names for DeclRefExprs here.
311 if (til::SExpr *E = lookupStmt(S))
312 return E;
313
314 switch (S->getStmtClass()) {
315 case Stmt::DeclRefExprClass:
316 return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
317 case Stmt::CXXThisExprClass:
318 return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
319 case Stmt::MemberExprClass:
320 return translateMemberExpr(cast<MemberExpr>(S), Ctx);
321 case Stmt::ObjCIvarRefExprClass:
322 return translateObjCIVarRefExpr(cast<ObjCIvarRefExpr>(S), Ctx);
323 case Stmt::CallExprClass:
324 return translateCallExpr(cast<CallExpr>(S), Ctx);
325 case Stmt::CXXMemberCallExprClass:
326 return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
327 case Stmt::CXXOperatorCallExprClass:
328 return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
329 case Stmt::UnaryOperatorClass:
330 return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
331 case Stmt::BinaryOperatorClass:
332 case Stmt::CompoundAssignOperatorClass:
333 return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
334
335 case Stmt::ArraySubscriptExprClass:
336 return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
337 case Stmt::ConditionalOperatorClass:
338 return translateAbstractConditionalOperator(
340 case Stmt::BinaryConditionalOperatorClass:
341 return translateAbstractConditionalOperator(
343
344 // We treat these as no-ops
345 case Stmt::ConstantExprClass:
346 return translate(cast<ConstantExpr>(S)->getSubExpr(), Ctx);
347 case Stmt::ParenExprClass:
348 return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
349 case Stmt::ExprWithCleanupsClass:
350 return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
351 case Stmt::CXXBindTemporaryExprClass:
352 return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
353 case Stmt::MaterializeTemporaryExprClass:
354 return translate(cast<MaterializeTemporaryExpr>(S)->getSubExpr(), Ctx);
355
356 // Collect all literals
357 case Stmt::CharacterLiteralClass:
358 return new (Arena)
360 case Stmt::CXXNullPtrLiteralExprClass:
361 case Stmt::GNUNullExprClass:
362 return new (Arena) til::LiteralT(nullptr);
363 case Stmt::CXXBoolLiteralExprClass:
364 return new (Arena) til::LiteralT(cast<CXXBoolLiteralExpr>(S)->getValue());
365 case Stmt::IntegerLiteralClass: {
366 const auto *IL = cast<IntegerLiteral>(S);
367 const auto *BT = cast<BuiltinType>(IL->getType());
368 const llvm::APInt &Value = IL->getValue();
369 if (BT->isSignedInteger())
370 return new (Arena) til::LiteralT(Value.getSExtValue());
371 else if (BT->isUnsignedInteger())
372 return new (Arena) til::LiteralT(Value.getZExtValue());
373 else
374 llvm_unreachable("Invalid integer type");
375 }
376 case Stmt::StringLiteralClass:
377 return new (Arena) til::LiteralT(cast<StringLiteral>(S)->getBytes());
378 case Stmt::ObjCStringLiteralClass:
379 return new (Arena)
380 til::LiteralT(cast<ObjCStringLiteral>(S)->getString()->getBytes());
381
382 case Stmt::DeclStmtClass:
383 return translateDeclStmt(cast<DeclStmt>(S), Ctx);
384 case Stmt::StmtExprClass:
385 return translateStmtExpr(cast<StmtExpr>(S), Ctx);
386 default:
387 break;
388 }
389 if (const auto *CE = dyn_cast<CastExpr>(S))
390 return translateCastExpr(CE, Ctx);
391
392 return new (Arena) til::Undefined(S);
393}
394
395/// Helper to extract the canonical parameter declaration from a function or
396/// function pointer. This unwraps pointer and reference types to reach the
397/// underlying function prototype.
398static const ParmVarDecl *getCanonicalParamDecl(const Decl *D, unsigned I) {
399 if (const auto *FD = dyn_cast<FunctionDecl>(D))
400 return FD->getCanonicalDecl()->getParamDecl(I);
401 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
402 return MD->getCanonicalDecl()->getParamDecl(I);
403 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
404 if (auto *TSI = DD->getTypeSourceInfo()) {
405 TypeLoc TL = TSI->getTypeLoc();
406 if (auto RTL = TL.getAsAdjusted<ReferenceTypeLoc>())
407 TL = RTL.getPointeeLoc();
408 // A function pointer can be multiple levels deep.
409 while (auto PTL = TL.getAsAdjusted<PointerTypeLoc>())
410 TL = PTL.getPointeeLoc();
411 if (auto FPTL = TL.getAsAdjusted<FunctionProtoTypeLoc>())
412 if (I < FPTL.getNumParams())
413 return FPTL.getParam(I);
414 }
415 }
416 return nullptr;
417}
418
420 if (const auto *V = dyn_cast<til::Variable>(E))
421 return V->clangDecl();
422 if (const auto *Ph = dyn_cast<til::Phi>(E))
423 return Ph->clangDecl();
424 if (const auto *P = dyn_cast<til::Project>(E))
425 return P->clangDecl();
426 if (const auto *L = dyn_cast<til::LiteralPtr>(E))
427 return L->clangDecl();
428 return nullptr;
429}
430
431// The type of the object, pointer or array that E denotes, where the TIL
432// records one; null otherwise.
434 if (auto *VD = getValueDeclFromSExpr(E))
435 return VD->getType();
436 // A decayed array, or a smart pointer, is its operand.
437 if (const auto *C = dyn_cast<til::Cast>(E))
438 return getSExprType(C->expr());
439 if (const auto *AI = dyn_cast<til::ArrayIndex>(E)) {
440 QualType T = getSExprType(AI->array());
441 if (T.isNull())
442 return T;
443 if (const auto *AT = T->getAsArrayTypeUnsafe())
444 return AT->getElementType();
445 return T->getPointeeType();
446 }
447 if (const auto *C = dyn_cast<til::Call>(E))
448 if (const CallExpr *CE = C->clangCallExpr())
449 return CE->getType();
450 return QualType();
451}
452
453// Whether E denotes a pointer to an object rather than the object itself, so
454// that its member is spelled `p->mu`, not `p.mu`. Since `&` and `*` are no-ops
455// in the TIL, this is decided by the translated base, not by the source.
456static bool hasAnyPointerType(const til::SExpr *E) {
457 if (const auto *C = dyn_cast<til::Cast>(E))
458 return C->castOpcode() == til::CAST_objToPtr;
459 // A member reached through arithmetic is reached through a pointer; an
460 // overloaded operator is a Call.
461 if (isa<til::BinaryOp>(E))
462 return true;
464 return !T.isNull() && T->isAnyPointerType();
465}
466
467til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
468 CallingContext *Ctx) {
469 const auto *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
470
471 // Function parameters require substitution and/or renaming.
472 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
473 unsigned I = PV->getFunctionScopeIndex();
474 const DeclContext *D = PV->getDeclContext();
475 if (Ctx && Ctx->FunArgs) {
476 const Decl *Canonical = Ctx->AttrDecl->getCanonicalDecl();
477 bool Match = false;
478 if (const auto *FD = dyn_cast<FunctionDecl>(D))
479 Match = (FD->getCanonicalDecl() == Canonical);
480 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
481 Match = (MD->getCanonicalDecl() == Canonical);
482 else if (getCanonicalParamDecl(Canonical, I) == PV->getCanonicalDecl())
483 Match = true;
484 else
485 llvm_unreachable("ParmVarDecl does not belong to current declaration");
486
487 if (Match) {
488 // Substitute call arguments for references to function parameters
489 if (const Expr *const *FunArgs =
490 dyn_cast<const Expr *const *>(Ctx->FunArgs)) {
491 assert(I < Ctx->NumArgs);
492 return translate(FunArgs[I], Ctx->Prev);
493 }
494
495 assert(I == 0);
496 return cast<til::SExpr *>(Ctx->FunArgs);
497 }
498 }
499 // Map the param back to the param of the original function declaration
500 // for consistent comparisons.
501 if (const auto *PVD = getCanonicalParamDecl(cast<Decl>(D), I))
502 VD = PVD;
503 }
504
505 if (const auto *VarD = dyn_cast<VarDecl>(VD))
506 return translateVariable(VarD, Ctx);
507
508 // A member named through anonymous structs/unions is an IndirectFieldDecl;
509 // name it by its field.
510 const auto *IFD = dyn_cast<IndirectFieldDecl>(VD);
511 if (IFD)
512 VD = IFD->getAnonField();
513
514 // FIXME: A FieldDecl reached via a DeclRefExpr should ideally be modelled as
515 // a MemberExpr with an artificial self in the AST (e.g. ImplicitThisExpr as a
516 // C equivalent of CXXThisExpr). Until such AST support is available, project
517 // the field on the current SelfArg, so implicit member references in C and in
518 // parameter attributes are not lost.
519 if (const auto *FD = dyn_cast<FieldDecl>(VD); FD && Ctx && Ctx->SelfArg) {
520 // Sema lowers a non-member IndirectFieldDecl, from a namespace- or
521 // block-scope anonymous union, to a MemberExpr chain rooted at its VarDecl.
522 assert((!IFD || !IFD->getVarDecl()) &&
523 "non-member IndirectFieldDecl should be a MemberExpr");
524 bool Found;
525 const auto *Owner =
526 cast<FieldDecl>(IFD ? IFD->chain().front() : FD)->getParent();
527 til::SExpr *E = translateFieldOwner(Owner, Ctx, Found);
528 // Project each anonymous member of the chain in turn.
529 if (IFD)
530 for (const NamedDecl *ND : IFD->chain().drop_back())
531 E = translateProject(E, cast<FieldDecl>(ND));
532 til::Project *P = translateProject(E, FD);
533 // Say whose field this is when self does not have it.
534 P->setQualified(!Found);
535 return P;
536 }
537
538 // For non-local variables, treat it as a reference to a named object.
539 return new (Arena) til::LiteralPtr(VD);
540}
541
542/// Translate the object owning \p Owner's field that an attribute names without
543/// a base expression. Normally that is the self argument, the object whose
544/// member carries the attribute. But a field of an enclosing record may be
545/// named from a nested one, anonymous or named, so walk out of the subobject
546/// accesses reaching self (members, array elements, `*`, and `&` back from a
547/// pointer to the object it points to) to the nearest object of type \p Owner,
548/// or derived from it. A pointer member's pointee is not part of the object, so
549/// the walk stops at one. Keep self if there is none, and clear \p Found.
550til::SExpr *SExprBuilder::translateFieldOwner(const RecordDecl *Owner,
551 CallingContext *Ctx,
552 bool &Found) {
553 // An already translated self has no type to check; take it as the owner.
554 Found = true;
555 const auto *SelfArg = dyn_cast_if_present<const Expr *>(Ctx->SelfArg);
556 if (!SelfArg)
557 return translateCXXThisExpr(nullptr, Ctx);
558 Found = false;
559 for (const Expr *E = SelfArg;;) {
560 // Up to casts, E is either the object or a pointer to it. An array of
561 // objects, left by stripping its decay to a pointer, is its element.
562 const Expr *Inner = E->IgnoreParenImpCasts();
563 QualType T = Inner->getType();
564 bool Pointer = T->isAnyPointerType();
565 if (Pointer)
566 T = T->getPointeeType();
567 else if (const auto *AT = T->getAsArrayTypeUnsafe())
568 T = AT->getElementType();
569 if (const auto *RD = T->getAsRecordDecl()) {
570 if (declaresSameEntity(RD, Owner)) {
571 SelfArg = E;
572 Found = true;
573 break;
574 }
575 const auto *CRD = dyn_cast<CXXRecordDecl>(RD);
576 const auto *COwner = dyn_cast<CXXRecordDecl>(Owner);
577 if (CRD && COwner && CRD->hasDefinition() && !CRD->isDependentType() &&
578 CRD->isDerivedFrom(COwner)) {
579 SelfArg = E;
580 Found = true;
581 break;
582 }
583 }
584 const auto *UO = dyn_cast<UnaryOperator>(Inner);
585 if (Pointer) {
586 // Only the address of an object leads back to it.
587 if (!UO || UO->getOpcode() != UO_AddrOf)
588 break;
589 E = UO->getSubExpr();
590 } else if (const auto *ME = dyn_cast<MemberExpr>(Inner)) {
591 E = ME->getBase();
592 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Inner)) {
593 E = ASE->getBase();
594 } else if (UO && UO->getOpcode() == UO_Deref) {
595 E = UO->getSubExpr();
596 } else {
597 break;
598 }
599 }
600 return translate(SelfArg, Ctx->Prev);
601}
602
603til::Project *SExprBuilder::translateProject(til::SExpr *BE,
604 const ValueDecl *D) {
605 til::SExpr *E = new (Arena) til::SApply(BE);
606 til::Project *P = new (Arena) til::Project(E, D);
607 if (hasAnyPointerType(BE))
608 P->setArrow(true);
609 return P;
610}
611
612til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
613 CallingContext *Ctx) {
614 // Substitute for 'this'
615 if (Ctx && Ctx->SelfArg) {
616 if (const auto *SelfArg = dyn_cast<const Expr *>(Ctx->SelfArg))
617 return translate(SelfArg, Ctx->Prev);
618 else
619 return cast<til::SExpr *>(Ctx->SelfArg);
620 }
621 assert(SelfVar && "We have no variable for 'this'!");
622 return SelfVar;
623}
624
625// Grab the very first declaration of virtual method D
627 while (true) {
628 D = D->getCanonicalDecl();
629 auto OverriddenMethods = D->overridden_methods();
630 if (OverriddenMethods.begin() == OverriddenMethods.end())
631 return D; // Method does not override anything
632 // FIXME: this does not work with multiple inheritance.
633 D = *OverriddenMethods.begin();
634 }
635 return nullptr;
636}
637
638til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
639 CallingContext *Ctx) {
640 til::SExpr *BE = translate(ME->getBase(), Ctx);
641
642 const auto *D = cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
643 if (const auto *VD = dyn_cast<CXXMethodDecl>(D))
644 D = getFirstVirtualDecl(VD);
645
646 return translateProject(BE, D);
647}
648
649til::SExpr *SExprBuilder::translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE,
650 CallingContext *Ctx) {
651 til::SExpr *BE = translate(IVRE->getBase(), Ctx);
652 const auto *D = cast<ObjCIvarDecl>(IVRE->getDecl()->getCanonicalDecl());
653 return translateProject(BE, D);
654}
655
656til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
657 CallingContext *Ctx,
658 const Expr *SelfE) {
659 if (CapabilityExprMode) {
660 // Handle LOCK_RETURNED, on a function or a function pointer.
661 if (const auto *D = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
662 const NamedDecl *AttrD = D;
663 if (const auto *FD = dyn_cast<FunctionDecl>(D))
664 AttrD = FD->getMostRecentDecl();
665 if (const auto *At = AttrD->getAttr<LockReturnedAttr>()) {
666 CallingContext LRCallCtx(Ctx);
667 LRCallCtx.AttrDecl = D;
668 LRCallCtx.SelfArg = SelfE;
669 if (!SelfE)
670 if (const MemberExpr *ME = getFunPtrFieldCallee(CE, D))
671 LRCallCtx.SelfArg = ME->getBase();
672 LRCallCtx.NumArgs = CE->getNumArgs();
673 LRCallCtx.FunArgs = CE->getArgs();
674 return const_cast<til::SExpr *>(
675 translateAttrExpr(At->getArg(), &LRCallCtx).sexpr());
676 }
677 }
678 }
679
680 til::SExpr *E = translate(CE->getCallee(), Ctx);
681 // Explicitly propagate Undefined, when the callee couldn't be analyzed.
682 if (isa<til::Undefined>(E))
683 return E;
684 for (const auto *Arg : CE->arguments()) {
685 til::SExpr *A = translate(Arg, Ctx);
686 E = new (Arena) til::Apply(E, A);
687 }
688 return new (Arena) til::Call(E, CE);
689}
690
691til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
692 const CXXMemberCallExpr *ME, CallingContext *Ctx) {
693 if (CapabilityExprMode) {
694 // Ignore calls to get() on smart pointers. A call through a pointer to
695 // member function has no method declaration.
696 const CXXMethodDecl *MD = ME->getMethodDecl();
697 if (ME->getNumArgs() == 0 && MD && MD->getIdentifier() &&
698 MD->getIdentifier()->isStr("get")) {
699 auto *E = translate(ME->getImplicitObjectArgument(), Ctx);
700 return new (Arena) til::Cast(til::CAST_objToPtr, E);
701 // return E;
702 }
703 }
704 return translateCallExpr(cast<CallExpr>(ME), Ctx,
706}
707
708til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
709 const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
710 if (CapabilityExprMode) {
711 // Ignore operator * and operator -> on smart pointers.
713 if (k == OO_Star || k == OO_Arrow) {
714 auto *E = translate(OCE->getArg(0), Ctx);
715 return new (Arena) til::Cast(til::CAST_objToPtr, E);
716 // return E;
717 }
718 }
719 return translateCallExpr(cast<CallExpr>(OCE), Ctx);
720}
721
722til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
723 CallingContext *Ctx) {
724 switch (UO->getOpcode()) {
725 case UO_PostInc:
726 case UO_PostDec:
727 case UO_PreInc:
728 case UO_PreDec:
729 return new (Arena) til::Undefined(UO);
730
731 case UO_AddrOf:
732 if (CapabilityExprMode) {
733 // interpret &Graph::mu_ as an existential.
734 if (const auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) {
735 if (DRE->getDecl()->isCXXInstanceMember()) {
736 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
737 // We interpret this syntax specially, as a wildcard.
738 // Name a member of an anonymous struct/union by its field, as a
739 // projection of it does.
740 const ValueDecl *D = DRE->getDecl();
741 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
742 D = IFD->getAnonField();
743 auto *W = new (Arena) til::Wildcard();
744 return new (Arena) til::Project(W, D);
745 }
746 }
747 }
748 // otherwise, & is a no-op
749 return translate(UO->getSubExpr(), Ctx);
750
751 // We treat these as no-ops
752 case UO_Deref:
753 case UO_Plus:
754 return translate(UO->getSubExpr(), Ctx);
755
756 case UO_Minus:
757 return new (Arena)
758 til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx));
759 case UO_Not:
760 return new (Arena)
761 til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx));
762 case UO_LNot:
763 return new (Arena)
764 til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx));
765
766 // Currently unsupported
767 case UO_Real:
768 case UO_Imag:
769 case UO_Extension:
770 case UO_Coawait:
771 return new (Arena) til::Undefined(UO);
772 }
773 return new (Arena) til::Undefined(UO);
774}
775
776til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op,
777 const BinaryOperator *BO,
778 CallingContext *Ctx, bool Reverse) {
779 til::SExpr *E0 = translate(BO->getLHS(), Ctx);
780 til::SExpr *E1 = translate(BO->getRHS(), Ctx);
781 if (Reverse)
782 return new (Arena) til::BinaryOp(Op, E1, E0);
783 else
784 return new (Arena) til::BinaryOp(Op, E0, E1);
785}
786
787til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
788 const BinaryOperator *BO,
789 CallingContext *Ctx,
790 bool Assign) {
791 const Expr *LHS = BO->getLHS();
792 const Expr *RHS = BO->getRHS();
793 til::SExpr *E0 = translate(LHS, Ctx);
794 til::SExpr *E1 = translate(RHS, Ctx);
795
796 const ValueDecl *VD = nullptr;
797 til::SExpr *CV = nullptr;
798 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
799 VD = DRE->getDecl();
800 CV = lookupVarDecl(VD);
801 }
802
803 if (!Assign) {
804 til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
805 E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
806 E1 = addStatement(E1, nullptr, VD);
807 }
808 if (VD && CV)
809 return updateVarDecl(VD, E1);
810 return new (Arena) til::Store(E0, E1);
811}
812
813til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
814 CallingContext *Ctx) {
815 switch (BO->getOpcode()) {
816 case BO_PtrMemD:
817 case BO_PtrMemI:
818 return new (Arena) til::Undefined(BO);
819
820 case BO_Mul: return translateBinOp(til::BOP_Mul, BO, Ctx);
821 case BO_Div: return translateBinOp(til::BOP_Div, BO, Ctx);
822 case BO_Rem: return translateBinOp(til::BOP_Rem, BO, Ctx);
823 case BO_Add: return translateBinOp(til::BOP_Add, BO, Ctx);
824 case BO_Sub: return translateBinOp(til::BOP_Sub, BO, Ctx);
825 case BO_Shl: return translateBinOp(til::BOP_Shl, BO, Ctx);
826 case BO_Shr: return translateBinOp(til::BOP_Shr, BO, Ctx);
827 case BO_LT: return translateBinOp(til::BOP_Lt, BO, Ctx);
828 case BO_GT: return translateBinOp(til::BOP_Lt, BO, Ctx, true);
829 case BO_LE: return translateBinOp(til::BOP_Leq, BO, Ctx);
830 case BO_GE: return translateBinOp(til::BOP_Leq, BO, Ctx, true);
831 case BO_EQ: return translateBinOp(til::BOP_Eq, BO, Ctx);
832 case BO_NE: return translateBinOp(til::BOP_Neq, BO, Ctx);
833 case BO_Cmp: return translateBinOp(til::BOP_Cmp, BO, Ctx);
834 case BO_And: return translateBinOp(til::BOP_BitAnd, BO, Ctx);
835 case BO_Xor: return translateBinOp(til::BOP_BitXor, BO, Ctx);
836 case BO_Or: return translateBinOp(til::BOP_BitOr, BO, Ctx);
837 case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx);
838 case BO_LOr: return translateBinOp(til::BOP_LogicOr, BO, Ctx);
839
840 case BO_Assign: return translateBinAssign(til::BOP_Eq, BO, Ctx, true);
841 case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx);
842 case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx);
843 case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx);
844 case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx);
845 case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx);
846 case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx);
847 case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx);
848 case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx);
849 case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx);
850 case BO_OrAssign: return translateBinAssign(til::BOP_BitOr, BO, Ctx);
851
852 case BO_Comma:
853 // The clang CFG should have already processed both sides.
854 return translate(BO->getRHS(), Ctx);
855 }
856 return new (Arena) til::Undefined(BO);
857}
858
859til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
860 CallingContext *Ctx) {
861 CastKind K = CE->getCastKind();
862 switch (K) {
863 case CK_LValueToRValue: {
864 if (const auto *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
865 til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
866 if (E0)
867 return E0;
868 }
869 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
870 return E0;
871 // FIXME!! -- get Load working properly
872 // return new (Arena) til::Load(E0);
873 }
874 case CK_ArrayToPointerDecay:
875 // Keep the decay, so that a member of an element is spelled as reached
876 // through the pointer, `arr->mu`, unlike one of the array, `arr[0].mu`.
877 return new (Arena)
878 til::Cast(til::CAST_objToPtr, translate(CE->getSubExpr(), Ctx));
879 case CK_NoOp:
880 case CK_DerivedToBase:
881 case CK_UncheckedDerivedToBase:
882 case CK_FunctionToPointerDecay: {
883 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
884 return E0;
885 }
886 default: {
887 // FIXME: handle different kinds of casts.
888 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
889 if (CapabilityExprMode)
890 return E0;
891 return new (Arena) til::Cast(til::CAST_none, E0);
892 }
893 }
894}
895
897SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
898 CallingContext *Ctx) {
899 til::SExpr *E0 = translate(E->getBase(), Ctx);
900 til::SExpr *E1 = translate(E->getIdx(), Ctx);
901 return new (Arena) til::ArrayIndex(E0, E1);
902}
903
905SExprBuilder::translateAbstractConditionalOperator(
906 const AbstractConditionalOperator *CO, CallingContext *Ctx) {
907 auto *C = translate(CO->getCond(), Ctx);
908 auto *T = translate(CO->getTrueExpr(), Ctx);
909 auto *E = translate(CO->getFalseExpr(), Ctx);
910 return new (Arena) til::IfThenElse(C, T, E);
911}
912
914SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
915 DeclGroupRef DGrp = S->getDeclGroup();
916 for (auto *I : DGrp) {
917 if (auto *VD = dyn_cast_or_null<VarDecl>(I)) {
918 Expr *E = VD->getInit();
919 til::SExpr* SE = translate(E, Ctx);
920
921 // Add local variables with trivial type to the variable map
922 QualType T = VD->getType();
923 if (T.isTrivialType(VD->getASTContext()))
924 return addVarDecl(VD, SE);
925 else {
926 // TODO: add alloca
927 }
928 }
929 }
930 return nullptr;
931}
932
933til::SExpr *SExprBuilder::translateStmtExpr(const StmtExpr *SE,
934 CallingContext *Ctx) {
935 // The value of a statement expression is the value of the last statement,
936 // which must be an expression.
937 const CompoundStmt *CS = SE->getSubStmt();
938 return CS->body_empty() ? new (Arena) til::Undefined(SE)
939 : translate(CS->body_back(), Ctx);
940}
941
942// If (E) is non-trivial, then add it to the current basic block, and
943// update the statement map so that S refers to E. Returns a new variable
944// that refers to E.
945// If E is trivial returns E.
946til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
947 const ValueDecl *VD) {
948 if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))
949 return E;
950 if (VD)
951 E = new (Arena) til::Variable(E, VD);
952 CurrentInstructions.push_back(E);
953 if (S)
954 insertStmt(S, E);
955 return E;
956}
957
958// Returns the current value of VD, if known, and nullptr otherwise.
959til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
960 auto It = LVarIdxMap.find(VD);
961 if (It != LVarIdxMap.end()) {
962 assert(CurrentLVarMap[It->second].first == VD);
963 return CurrentLVarMap[It->second].second;
964 }
965 return nullptr;
966}
967
968// if E is a til::Variable, update its clangDecl.
969static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
970 if (!E)
971 return;
972 if (auto *V = dyn_cast<til::Variable>(E)) {
973 if (!V->clangDecl())
974 V->setClangDecl(VD);
975 }
976}
977
978// Adds a new variable declaration.
979til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
980 maybeUpdateVD(E, VD);
981 LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
982 CurrentLVarMap.makeWritable();
983 CurrentLVarMap.push_back(std::make_pair(VD, E));
984 return E;
985}
986
987// Updates a current variable declaration. (E.g. by assignment)
988til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
989 maybeUpdateVD(E, VD);
990 auto It = LVarIdxMap.find(VD);
991 if (It == LVarIdxMap.end()) {
992 til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
993 til::SExpr *St = new (Arena) til::Store(Ptr, E);
994 return St;
995 }
996 CurrentLVarMap.makeWritable();
997 CurrentLVarMap.elem(It->second).second = E;
998 return E;
999}
1000
1001// Make a Phi node in the current block for the i^th variable in CurrentVarMap.
1002// If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
1003// If E == null, this is a backedge and will be set later.
1004void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
1005 unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
1006 assert(ArgIndex > 0 && ArgIndex < NPreds);
1007
1008 til::SExpr *CurrE = CurrentLVarMap[i].second;
1009 if (CurrE->block() == CurrentBB) {
1010 // We already have a Phi node in the current block,
1011 // so just add the new variable to the Phi node.
1012 auto *Ph = dyn_cast<til::Phi>(CurrE);
1013 assert(Ph && "Expecting Phi node.");
1014 if (E)
1015 Ph->values()[ArgIndex] = E;
1016 return;
1017 }
1018
1019 // Make a new phi node: phi(..., E)
1020 // All phi args up to the current index are set to the current value.
1021 til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
1022 Ph->values().setValues(NPreds, nullptr);
1023 for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
1024 Ph->values()[PIdx] = CurrE;
1025 if (E)
1026 Ph->values()[ArgIndex] = E;
1027 Ph->setClangDecl(CurrentLVarMap[i].first);
1028 // If E is from a back-edge, or either E or CurrE are incomplete, then
1029 // mark this node as incomplete; we may need to remove it later.
1030 if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE))
1032
1033 // Add Phi node to current block, and update CurrentLVarMap[i]
1034 CurrentArguments.push_back(Ph);
1035 if (Ph->status() == til::Phi::PH_Incomplete)
1036 IncompleteArgs.push_back(Ph);
1037
1038 CurrentLVarMap.makeWritable();
1039 CurrentLVarMap.elem(i).second = Ph;
1040}
1041
1042// Merge values from Map into the current variable map.
1043// This will construct Phi nodes in the current basic block as necessary.
1044void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
1045 assert(CurrentBlockInfo && "Not processing a block!");
1046
1047 if (!CurrentLVarMap.valid()) {
1048 // Steal Map, using copy-on-write.
1049 CurrentLVarMap = std::move(Map);
1050 return;
1051 }
1052 if (CurrentLVarMap.sameAs(Map))
1053 return; // Easy merge: maps from different predecessors are unchanged.
1054
1055 unsigned NPreds = CurrentBB->numPredecessors();
1056 unsigned ESz = CurrentLVarMap.size();
1057 unsigned MSz = Map.size();
1058 unsigned Sz = std::min(ESz, MSz);
1059
1060 for (unsigned i = 0; i < Sz; ++i) {
1061 if (CurrentLVarMap[i].first != Map[i].first) {
1062 // We've reached the end of variables in common.
1063 CurrentLVarMap.makeWritable();
1064 CurrentLVarMap.downsize(i);
1065 break;
1066 }
1067 if (CurrentLVarMap[i].second != Map[i].second)
1068 makePhiNodeVar(i, NPreds, Map[i].second);
1069 }
1070 if (ESz > MSz) {
1071 CurrentLVarMap.makeWritable();
1072 CurrentLVarMap.downsize(Map.size());
1073 }
1074}
1075
1076// Merge a back edge into the current variable map.
1077// This will create phi nodes for all variables in the variable map.
1078void SExprBuilder::mergeEntryMapBackEdge() {
1079 // We don't have definitions for variables on the backedge, because we
1080 // haven't gotten that far in the CFG. Thus, when encountering a back edge,
1081 // we conservatively create Phi nodes for all variables. Unnecessary Phi
1082 // nodes will be marked as incomplete, and stripped out at the end.
1083 //
1084 // An Phi node is unnecessary if it only refers to itself and one other
1085 // variable, e.g. x = Phi(y, y, x) can be reduced to x = y.
1086
1087 assert(CurrentBlockInfo && "Not processing a block!");
1088
1089 if (CurrentBlockInfo->HasBackEdges)
1090 return;
1091 CurrentBlockInfo->HasBackEdges = true;
1092
1093 CurrentLVarMap.makeWritable();
1094 unsigned Sz = CurrentLVarMap.size();
1095 unsigned NPreds = CurrentBB->numPredecessors();
1096
1097 for (unsigned i = 0; i < Sz; ++i)
1098 makePhiNodeVar(i, NPreds, nullptr);
1099}
1100
1101// Update the phi nodes that were initially created for a back edge
1102// once the variable definitions have been computed.
1103// I.e., merge the current variable map into the phi nodes for Blk.
1104void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
1105 til::BasicBlock *BB = lookupBlock(Blk);
1106 unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
1107 assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
1108
1109 for (til::SExpr *PE : BB->arguments()) {
1110 auto *Ph = dyn_cast_or_null<til::Phi>(PE);
1111 assert(Ph && "Expecting Phi Node.");
1112 assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
1113
1114 til::SExpr *E = lookupVarDecl(Ph->clangDecl());
1115 assert(E && "Couldn't find local variable for Phi node.");
1116 Ph->values()[ArgIndex] = E;
1117 }
1118}
1119
1120void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D,
1121 const CFGBlock *First) {
1122 // Perform initial setup operations.
1123 unsigned NBlocks = Cfg->getNumBlockIDs();
1124 Scfg = new (Arena) til::SCFG(Arena, NBlocks);
1125
1126 // allocate all basic blocks immediately, to handle forward references.
1127 BBInfo.resize(NBlocks);
1128 BlockMap.resize(NBlocks, nullptr);
1129 // create map from clang blockID to til::BasicBlocks
1130 for (auto *B : *Cfg) {
1131 auto *BB = new (Arena) til::BasicBlock(Arena);
1132 BB->reserveInstructions(B->size());
1133 BlockMap[B->getBlockID()] = BB;
1134 }
1135
1136 CurrentBB = lookupBlock(&Cfg->getEntry());
1137 auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters()
1138 : cast<FunctionDecl>(D)->parameters();
1139 for (auto *Pm : Parms) {
1140 QualType T = Pm->getType();
1141 if (!T.isTrivialType(Pm->getASTContext()))
1142 continue;
1143
1144 // Add parameters to local variable map.
1145 // FIXME: right now we emulate params with loads; that should be fixed.
1146 til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
1147 til::SExpr *Ld = new (Arena) til::Load(Lp);
1148 til::SExpr *V = addStatement(Ld, nullptr, Pm);
1149 addVarDecl(Pm, V);
1150 }
1151}
1152
1153void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
1154 // Initialize TIL basic block and add it to the CFG.
1155 CurrentBB = lookupBlock(B);
1156 CurrentBB->reservePredecessors(B->pred_size());
1157 Scfg->add(CurrentBB);
1158
1159 CurrentBlockInfo = &BBInfo[B->getBlockID()];
1160
1161 // CurrentLVarMap is moved to ExitMap on block exit.
1162 // FIXME: the entry block will hold function parameters.
1163 // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
1164}
1165
1166void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
1167 // Compute CurrentLVarMap on entry from ExitMaps of predecessors
1168
1169 CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]);
1170 BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
1171 assert(PredInfo->UnprocessedSuccessors > 0);
1172
1173 if (--PredInfo->UnprocessedSuccessors == 0)
1174 mergeEntryMap(std::move(PredInfo->ExitMap));
1175 else
1176 mergeEntryMap(PredInfo->ExitMap.clone());
1177
1178 ++CurrentBlockInfo->ProcessedPredecessors;
1179}
1180
1181void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
1182 mergeEntryMapBackEdge();
1183}
1184
1185void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
1186 // The merge*() methods have created arguments.
1187 // Push those arguments onto the basic block.
1188 CurrentBB->arguments().reserve(
1189 static_cast<unsigned>(CurrentArguments.size()), Arena);
1190 for (auto *A : CurrentArguments)
1191 CurrentBB->addArgument(A);
1192}
1193
1194void SExprBuilder::handleStatement(const Stmt *S) {
1195 til::SExpr *E = translate(S, nullptr);
1196 addStatement(E, S);
1197}
1198
1199void SExprBuilder::handleDestructorCall(const VarDecl *VD,
1200 const CXXDestructorDecl *DD) {
1201 til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
1202 til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
1203 til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
1204 til::SExpr *E = new (Arena) til::Call(Ap);
1205 addStatement(E, nullptr);
1206}
1207
1208void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
1209 CurrentBB->instructions().reserve(
1210 static_cast<unsigned>(CurrentInstructions.size()), Arena);
1211 for (auto *V : CurrentInstructions)
1212 CurrentBB->addInstruction(V);
1213
1214 // Create an appropriate terminator
1215 unsigned N = B->succ_size();
1216 auto It = B->succ_begin();
1217 if (N == 1) {
1218 til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
1219 // TODO: set index
1220 unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0;
1221 auto *Tm = new (Arena) til::Goto(BB, Idx);
1222 CurrentBB->setTerminator(Tm);
1223 }
1224 else if (N == 2) {
1225 til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr);
1226 til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
1227 ++It;
1228 til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
1229 // FIXME: make sure these aren't critical edges.
1230 auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
1231 CurrentBB->setTerminator(Tm);
1232 }
1233}
1234
1235void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
1236 ++CurrentBlockInfo->UnprocessedSuccessors;
1237}
1238
1239void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
1240 mergePhiNodesBackEdge(Succ);
1241 ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
1242}
1243
1244void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
1245 CurrentArguments.clear();
1246 CurrentInstructions.clear();
1247 CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
1248 CurrentBB = nullptr;
1249 CurrentBlockInfo = nullptr;
1250}
1251
1252void SExprBuilder::exitCFG(const CFGBlock *Last) {
1253 for (auto *Ph : IncompleteArgs) {
1254 if (Ph->status() == til::Phi::PH_Incomplete)
1256 }
1257
1258 CurrentArguments.clear();
1259 CurrentInstructions.clear();
1260 IncompleteArgs.clear();
1261}
1262
1263#ifndef NDEBUG
1264namespace {
1265
1266class TILPrinter :
1267 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
1268
1269} // namespace
1270
1271namespace clang {
1272namespace threadSafety {
1273
1274void printSCFG(CFGWalker &Walker) {
1275 llvm::BumpPtrAllocator Bpa;
1276 til::MemRegionRef Arena(&Bpa);
1277 SExprBuilder SxBuilder(Arena);
1278 til::SCFG *Scfg = SxBuilder.buildCFG(Walker);
1279 TILPrinter::print(Scfg, llvm::errs());
1280}
1281
1282} // namespace threadSafety
1283} // namespace clang
1284#endif // NDEBUG
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines an enumeration for C++ overloaded operators.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines various enumerations that describe declaration and type specifiers.
static bool isIncompletePhi(const til::SExpr *E)
static const MemberExpr * getFunPtrFieldCallee(const CallExpr *CE, const NamedDecl *D)
If CE calls through a function pointer field D, return the member access through which the field was ...
SExprBuilder::CallingContext CallingContext
static const ParmVarDecl * getCanonicalParamDecl(const Decl *D, unsigned I)
Helper to extract the canonical parameter declaration from a function or function pointer.
static QualType getSExprType(const til::SExpr *E)
static const ValueDecl * getValueDeclFromSExpr(const til::SExpr *E)
static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD)
static bool hasAnyPointerType(const til::SExpr *E)
static const CXXMethodDecl * getFirstVirtualDecl(const CXXMethodDecl *D)
static std::pair< StringRef, bool > classifyCapability(const TypeDecl &TD)
static constexpr std::pair< StringRef, bool > ClassifyCapabilityFallback
C Language Family Type Representation.
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
Opcode getOpcode() const
Definition Expr.h:4152
succ_iterator succ_begin()
Definition CFG.h:1045
unsigned pred_size() const
Definition CFG.h:1066
const Stmt * getTerminatorCondition(bool StripParens=true) const
Definition CFG.cpp:6534
unsigned getBlockID() const
Definition CFG.h:1177
unsigned succ_size() const
Definition CFG.h:1063
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Definition CFG.h:1487
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:773
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:754
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2828
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
arg_range arguments()
Definition Expr.h:3264
Decl * getCalleeDecl()
Definition Expr.h:3189
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
bool body_empty() const
Definition Stmt.h:1795
Stmt * body_back()
Definition Stmt.h:1819
ValueDecl * getDecl()
Definition Expr.h:1383
const DeclGroupRef getDeclGroup() const
Definition Stmt.h:1660
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
QualType getType() const
Definition Expr.h:146
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
NamedDecl * getMostRecentDecl()
Definition Decl.h:503
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition Decl.cpp:1977
ObjCIvarDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition DeclObjC.h:1997
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:611
const Expr * getBase() const
Definition ExprObjC.h:615
Represents a parameter to a function.
Definition Decl.h:1832
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
A (possibly-)qualified type.
Definition TypeBase.h:938
CompoundStmt * getSubStmt()
Definition Expr.h:4681
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1504
Represents a declaration of a type.
Definition Decl.h:3694
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8815
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isPointerOrReferenceType() const
Definition TypeBase.h:8819
bool isAnyPointerType() const
Definition TypeBase.h:8823
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2238
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D, const Expr *DeclExp, til::SExpr *Self=nullptr)
Translate a clang expression in an attribute to a til::SExpr.
til::SExpr * translate(const Stmt *S, CallingContext *Ctx)
til::SExpr * lookupStmt(const Stmt *S)
til::SCFG * buildCFG(CFGWalker &Walker)
til::SExpr * translateVariable(const VarDecl *VD, CallingContext *Ctx)
til::BasicBlock * lookupBlock(const CFGBlock *B)
const InstrArray & arguments() const
unsigned findPredecessorIndex(const BasicBlock *BB) const
Return the index of BB, or Predecessors.size if BB is not a predecessor.
A Literal pointer to an object allocated in memory.
const ValueDecl * clangDecl() const
Return the clang declaration of the variable for this Phi node, if any.
void setClangDecl(const ValueDecl *Cvd)
Set the clang variable associated with this Phi node.
const ValArray & values() const
Project a named slot from a C++ struct or class.
An SCFG is a control-flow graph.
Base class for AST nodes in the typed intermediate language.
BasicBlock * block() const
Returns the block, if this is an instruction in a basic block, otherwise returns null.
void setValues(unsigned Sz, const T &C)
Placeholder for expressions that cannot be represented in the TIL.
Placeholder for a wildcard that matches any other expression.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
void simplifyIncompleteArg(til::Phi *Ph)
TIL_BinaryOpcode
Opcode for binary arithmetic operations.
void printSCFG(CFGWalker &Walker)
std::string getSourceLiteralString(const Expr *CE)
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
CastKind
CastKind - The kind of operation required for a conversion.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
U cast(CodeGen::Address addr)
Definition Address.h:327
Encapsulates the lexical context of a function call.
llvm::PointerUnion< const Expr *const *, til::SExpr * > FunArgs
llvm::PointerUnion< const Expr *, til::SExpr * > SelfArg