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 13 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h" 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" 21 #include "clang/AST/OperationKinds.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/Type.h" 24 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h" 25 #include "clang/Analysis/CFG.h" 26 #include "clang/Basic/LLVM.h" 27 #include "clang/Basic/OperatorKinds.h" 28 #include "clang/Basic/Specifiers.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/Support/Casting.h" 31 #include <algorithm> 32 #include <cassert> 33 #include <string> 34 #include <utility> 35 36 using namespace clang; 37 using namespace threadSafety; 38 39 // From ThreadSafetyUtil.h 40 std::string threadSafety::getSourceLiteralString(const Expr *CE) { 41 switch (CE->getStmtClass()) { 42 case Stmt::IntegerLiteralClass: 43 return cast<IntegerLiteral>(CE)->getValue().toString(10, true); 44 case Stmt::StringLiteralClass: { 45 std::string ret("\""); 46 ret += cast<StringLiteral>(CE)->getString(); 47 ret += "\""; 48 return ret; 49 } 50 case Stmt::CharacterLiteralClass: 51 case Stmt::CXXNullPtrLiteralExprClass: 52 case Stmt::GNUNullExprClass: 53 case Stmt::CXXBoolLiteralExprClass: 54 case Stmt::FloatingLiteralClass: 55 case Stmt::ImaginaryLiteralClass: 56 case Stmt::ObjCStringLiteralClass: 57 default: 58 return "#lit"; 59 } 60 } 61 62 // Return true if E is a variable that points to an incomplete Phi node. 63 static bool isIncompletePhi(const til::SExpr *E) { 64 if (const auto *Ph = dyn_cast<til::Phi>(E)) 65 return Ph->status() == til::Phi::PH_Incomplete; 66 return false; 67 } 68 69 using CallingContext = SExprBuilder::CallingContext; 70 71 til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) { 72 auto It = SMap.find(S); 73 if (It != SMap.end()) 74 return It->second; 75 return nullptr; 76 } 77 78 til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) { 79 Walker.walk(*this); 80 return Scfg; 81 } 82 83 static bool isCalleeArrow(const Expr *E) { 84 const auto *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts()); 85 return ME ? ME->isArrow() : false; 86 } 87 88 /// Translate a clang expression in an attribute to a til::SExpr. 89 /// Constructs the context from D, DeclExp, and SelfDecl. 90 /// 91 /// \param AttrExp The expression to translate. 92 /// \param D The declaration to which the attribute is attached. 93 /// \param DeclExp An expression involving the Decl to which the attribute 94 /// is attached. E.g. the call to a function. 95 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp, 96 const NamedDecl *D, 97 const Expr *DeclExp, 98 VarDecl *SelfDecl) { 99 // If we are processing a raw attribute expression, with no substitutions. 100 if (!DeclExp) 101 return translateAttrExpr(AttrExp, nullptr); 102 103 CallingContext Ctx(nullptr, D); 104 105 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute 106 // for formal parameters when we call buildMutexID later. 107 if (const auto *ME = dyn_cast<MemberExpr>(DeclExp)) { 108 Ctx.SelfArg = ME->getBase(); 109 Ctx.SelfArrow = ME->isArrow(); 110 } else if (const auto *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) { 111 Ctx.SelfArg = CE->getImplicitObjectArgument(); 112 Ctx.SelfArrow = isCalleeArrow(CE->getCallee()); 113 Ctx.NumArgs = CE->getNumArgs(); 114 Ctx.FunArgs = CE->getArgs(); 115 } else if (const auto *CE = dyn_cast<CallExpr>(DeclExp)) { 116 Ctx.NumArgs = CE->getNumArgs(); 117 Ctx.FunArgs = CE->getArgs(); 118 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(DeclExp)) { 119 Ctx.SelfArg = nullptr; // Will be set below 120 Ctx.NumArgs = CE->getNumArgs(); 121 Ctx.FunArgs = CE->getArgs(); 122 } else if (D && isa<CXXDestructorDecl>(D)) { 123 // There's no such thing as a "destructor call" in the AST. 124 Ctx.SelfArg = DeclExp; 125 } 126 127 // Hack to handle constructors, where self cannot be recovered from 128 // the expression. 129 if (SelfDecl && !Ctx.SelfArg) { 130 DeclRefExpr SelfDRE(SelfDecl->getASTContext(), SelfDecl, false, 131 SelfDecl->getType(), VK_LValue, 132 SelfDecl->getLocation()); 133 Ctx.SelfArg = &SelfDRE; 134 135 // If the attribute has no arguments, then assume the argument is "this". 136 if (!AttrExp) 137 return translateAttrExpr(Ctx.SelfArg, nullptr); 138 else // For most attributes. 139 return translateAttrExpr(AttrExp, &Ctx); 140 } 141 142 // If the attribute has no arguments, then assume the argument is "this". 143 if (!AttrExp) 144 return translateAttrExpr(Ctx.SelfArg, nullptr); 145 else // For most attributes. 146 return translateAttrExpr(AttrExp, &Ctx); 147 } 148 149 /// Translate a clang expression in an attribute to a til::SExpr. 150 // This assumes a CallingContext has already been created. 151 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp, 152 CallingContext *Ctx) { 153 if (!AttrExp) 154 return CapabilityExpr(nullptr, false); 155 156 if (const auto* SLit = dyn_cast<StringLiteral>(AttrExp)) { 157 if (SLit->getString() == StringRef("*")) 158 // The "*" expr is a universal lock, which essentially turns off 159 // checks until it is removed from the lockset. 160 return CapabilityExpr(new (Arena) til::Wildcard(), false); 161 else 162 // Ignore other string literals for now. 163 return CapabilityExpr(nullptr, false); 164 } 165 166 bool Neg = false; 167 if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) { 168 if (OE->getOperator() == OO_Exclaim) { 169 Neg = true; 170 AttrExp = OE->getArg(0); 171 } 172 } 173 else if (const auto *UO = dyn_cast<UnaryOperator>(AttrExp)) { 174 if (UO->getOpcode() == UO_LNot) { 175 Neg = true; 176 AttrExp = UO->getSubExpr(); 177 } 178 } 179 180 til::SExpr *E = translate(AttrExp, Ctx); 181 182 // Trap mutex expressions like nullptr, or 0. 183 // Any literal value is nonsense. 184 if (!E || isa<til::Literal>(E)) 185 return CapabilityExpr(nullptr, false); 186 187 // Hack to deal with smart pointers -- strip off top-level pointer casts. 188 if (const auto *CE = dyn_cast_or_null<til::Cast>(E)) { 189 if (CE->castOpcode() == til::CAST_objToPtr) 190 return CapabilityExpr(CE->expr(), Neg); 191 } 192 return CapabilityExpr(E, Neg); 193 } 194 195 // Translate a clang statement or expression to a TIL expression. 196 // Also performs substitution of variables; Ctx provides the context. 197 // Dispatches on the type of S. 198 til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) { 199 if (!S) 200 return nullptr; 201 202 // Check if S has already been translated and cached. 203 // This handles the lookup of SSA names for DeclRefExprs here. 204 if (til::SExpr *E = lookupStmt(S)) 205 return E; 206 207 switch (S->getStmtClass()) { 208 case Stmt::DeclRefExprClass: 209 return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx); 210 case Stmt::CXXThisExprClass: 211 return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx); 212 case Stmt::MemberExprClass: 213 return translateMemberExpr(cast<MemberExpr>(S), Ctx); 214 case Stmt::ObjCIvarRefExprClass: 215 return translateObjCIVarRefExpr(cast<ObjCIvarRefExpr>(S), Ctx); 216 case Stmt::CallExprClass: 217 return translateCallExpr(cast<CallExpr>(S), Ctx); 218 case Stmt::CXXMemberCallExprClass: 219 return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx); 220 case Stmt::CXXOperatorCallExprClass: 221 return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx); 222 case Stmt::UnaryOperatorClass: 223 return translateUnaryOperator(cast<UnaryOperator>(S), Ctx); 224 case Stmt::BinaryOperatorClass: 225 case Stmt::CompoundAssignOperatorClass: 226 return translateBinaryOperator(cast<BinaryOperator>(S), Ctx); 227 228 case Stmt::ArraySubscriptExprClass: 229 return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx); 230 case Stmt::ConditionalOperatorClass: 231 return translateAbstractConditionalOperator( 232 cast<ConditionalOperator>(S), Ctx); 233 case Stmt::BinaryConditionalOperatorClass: 234 return translateAbstractConditionalOperator( 235 cast<BinaryConditionalOperator>(S), Ctx); 236 237 // We treat these as no-ops 238 case Stmt::ConstantExprClass: 239 return translate(cast<ConstantExpr>(S)->getSubExpr(), Ctx); 240 case Stmt::ParenExprClass: 241 return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx); 242 case Stmt::ExprWithCleanupsClass: 243 return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx); 244 case Stmt::CXXBindTemporaryExprClass: 245 return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx); 246 case Stmt::MaterializeTemporaryExprClass: 247 return translate(cast<MaterializeTemporaryExpr>(S)->GetTemporaryExpr(), 248 Ctx); 249 250 // Collect all literals 251 case Stmt::CharacterLiteralClass: 252 case Stmt::CXXNullPtrLiteralExprClass: 253 case Stmt::GNUNullExprClass: 254 case Stmt::CXXBoolLiteralExprClass: 255 case Stmt::FloatingLiteralClass: 256 case Stmt::ImaginaryLiteralClass: 257 case Stmt::IntegerLiteralClass: 258 case Stmt::StringLiteralClass: 259 case Stmt::ObjCStringLiteralClass: 260 return new (Arena) til::Literal(cast<Expr>(S)); 261 262 case Stmt::DeclStmtClass: 263 return translateDeclStmt(cast<DeclStmt>(S), Ctx); 264 default: 265 break; 266 } 267 if (const auto *CE = dyn_cast<CastExpr>(S)) 268 return translateCastExpr(CE, Ctx); 269 270 return new (Arena) til::Undefined(S); 271 } 272 273 til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE, 274 CallingContext *Ctx) { 275 const auto *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl()); 276 277 // Function parameters require substitution and/or renaming. 278 if (const auto *PV = dyn_cast_or_null<ParmVarDecl>(VD)) { 279 const auto *FD = 280 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl(); 281 unsigned I = PV->getFunctionScopeIndex(); 282 283 if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) { 284 // Substitute call arguments for references to function parameters 285 assert(I < Ctx->NumArgs); 286 return translate(Ctx->FunArgs[I], Ctx->Prev); 287 } 288 // Map the param back to the param of the original function declaration 289 // for consistent comparisons. 290 VD = FD->getParamDecl(I); 291 } 292 293 // For non-local variables, treat it as a reference to a named object. 294 return new (Arena) til::LiteralPtr(VD); 295 } 296 297 til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE, 298 CallingContext *Ctx) { 299 // Substitute for 'this' 300 if (Ctx && Ctx->SelfArg) 301 return translate(Ctx->SelfArg, Ctx->Prev); 302 assert(SelfVar && "We have no variable for 'this'!"); 303 return SelfVar; 304 } 305 306 static const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) { 307 if (const auto *V = dyn_cast<til::Variable>(E)) 308 return V->clangDecl(); 309 if (const auto *Ph = dyn_cast<til::Phi>(E)) 310 return Ph->clangDecl(); 311 if (const auto *P = dyn_cast<til::Project>(E)) 312 return P->clangDecl(); 313 if (const auto *L = dyn_cast<til::LiteralPtr>(E)) 314 return L->clangDecl(); 315 return nullptr; 316 } 317 318 static bool hasAnyPointerType(const til::SExpr *E) { 319 auto *VD = getValueDeclFromSExpr(E); 320 if (VD && VD->getType()->isAnyPointerType()) 321 return true; 322 if (const auto *C = dyn_cast<til::Cast>(E)) 323 return C->castOpcode() == til::CAST_objToPtr; 324 325 return false; 326 } 327 328 // Grab the very first declaration of virtual method D 329 static const CXXMethodDecl *getFirstVirtualDecl(const CXXMethodDecl *D) { 330 while (true) { 331 D = D->getCanonicalDecl(); 332 auto OverriddenMethods = D->overridden_methods(); 333 if (OverriddenMethods.begin() == OverriddenMethods.end()) 334 return D; // Method does not override anything 335 // FIXME: this does not work with multiple inheritance. 336 D = *OverriddenMethods.begin(); 337 } 338 return nullptr; 339 } 340 341 til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME, 342 CallingContext *Ctx) { 343 til::SExpr *BE = translate(ME->getBase(), Ctx); 344 til::SExpr *E = new (Arena) til::SApply(BE); 345 346 const auto *D = cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl()); 347 if (const auto *VD = dyn_cast<CXXMethodDecl>(D)) 348 D = getFirstVirtualDecl(VD); 349 350 til::Project *P = new (Arena) til::Project(E, D); 351 if (hasAnyPointerType(BE)) 352 P->setArrow(true); 353 return P; 354 } 355 356 til::SExpr *SExprBuilder::translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE, 357 CallingContext *Ctx) { 358 til::SExpr *BE = translate(IVRE->getBase(), Ctx); 359 til::SExpr *E = new (Arena) til::SApply(BE); 360 361 const auto *D = cast<ObjCIvarDecl>(IVRE->getDecl()->getCanonicalDecl()); 362 363 til::Project *P = new (Arena) til::Project(E, D); 364 if (hasAnyPointerType(BE)) 365 P->setArrow(true); 366 return P; 367 } 368 369 til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE, 370 CallingContext *Ctx, 371 const Expr *SelfE) { 372 if (CapabilityExprMode) { 373 // Handle LOCK_RETURNED 374 if (const FunctionDecl *FD = CE->getDirectCallee()) { 375 FD = FD->getMostRecentDecl(); 376 if (LockReturnedAttr *At = FD->getAttr<LockReturnedAttr>()) { 377 CallingContext LRCallCtx(Ctx); 378 LRCallCtx.AttrDecl = CE->getDirectCallee(); 379 LRCallCtx.SelfArg = SelfE; 380 LRCallCtx.NumArgs = CE->getNumArgs(); 381 LRCallCtx.FunArgs = CE->getArgs(); 382 return const_cast<til::SExpr *>( 383 translateAttrExpr(At->getArg(), &LRCallCtx).sexpr()); 384 } 385 } 386 } 387 388 til::SExpr *E = translate(CE->getCallee(), Ctx); 389 for (const auto *Arg : CE->arguments()) { 390 til::SExpr *A = translate(Arg, Ctx); 391 E = new (Arena) til::Apply(E, A); 392 } 393 return new (Arena) til::Call(E, CE); 394 } 395 396 til::SExpr *SExprBuilder::translateCXXMemberCallExpr( 397 const CXXMemberCallExpr *ME, CallingContext *Ctx) { 398 if (CapabilityExprMode) { 399 // Ignore calls to get() on smart pointers. 400 if (ME->getMethodDecl()->getNameAsString() == "get" && 401 ME->getNumArgs() == 0) { 402 auto *E = translate(ME->getImplicitObjectArgument(), Ctx); 403 return new (Arena) til::Cast(til::CAST_objToPtr, E); 404 // return E; 405 } 406 } 407 return translateCallExpr(cast<CallExpr>(ME), Ctx, 408 ME->getImplicitObjectArgument()); 409 } 410 411 til::SExpr *SExprBuilder::translateCXXOperatorCallExpr( 412 const CXXOperatorCallExpr *OCE, CallingContext *Ctx) { 413 if (CapabilityExprMode) { 414 // Ignore operator * and operator -> on smart pointers. 415 OverloadedOperatorKind k = OCE->getOperator(); 416 if (k == OO_Star || k == OO_Arrow) { 417 auto *E = translate(OCE->getArg(0), Ctx); 418 return new (Arena) til::Cast(til::CAST_objToPtr, E); 419 // return E; 420 } 421 } 422 return translateCallExpr(cast<CallExpr>(OCE), Ctx); 423 } 424 425 til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO, 426 CallingContext *Ctx) { 427 switch (UO->getOpcode()) { 428 case UO_PostInc: 429 case UO_PostDec: 430 case UO_PreInc: 431 case UO_PreDec: 432 return new (Arena) til::Undefined(UO); 433 434 case UO_AddrOf: 435 if (CapabilityExprMode) { 436 // interpret &Graph::mu_ as an existential. 437 if (const auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) { 438 if (DRE->getDecl()->isCXXInstanceMember()) { 439 // This is a pointer-to-member expression, e.g. &MyClass::mu_. 440 // We interpret this syntax specially, as a wildcard. 441 auto *W = new (Arena) til::Wildcard(); 442 return new (Arena) til::Project(W, DRE->getDecl()); 443 } 444 } 445 } 446 // otherwise, & is a no-op 447 return translate(UO->getSubExpr(), Ctx); 448 449 // We treat these as no-ops 450 case UO_Deref: 451 case UO_Plus: 452 return translate(UO->getSubExpr(), Ctx); 453 454 case UO_Minus: 455 return new (Arena) 456 til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx)); 457 case UO_Not: 458 return new (Arena) 459 til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx)); 460 case UO_LNot: 461 return new (Arena) 462 til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx)); 463 464 // Currently unsupported 465 case UO_Real: 466 case UO_Imag: 467 case UO_Extension: 468 case UO_Coawait: 469 return new (Arena) til::Undefined(UO); 470 } 471 return new (Arena) til::Undefined(UO); 472 } 473 474 til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op, 475 const BinaryOperator *BO, 476 CallingContext *Ctx, bool Reverse) { 477 til::SExpr *E0 = translate(BO->getLHS(), Ctx); 478 til::SExpr *E1 = translate(BO->getRHS(), Ctx); 479 if (Reverse) 480 return new (Arena) til::BinaryOp(Op, E1, E0); 481 else 482 return new (Arena) til::BinaryOp(Op, E0, E1); 483 } 484 485 til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op, 486 const BinaryOperator *BO, 487 CallingContext *Ctx, 488 bool Assign) { 489 const Expr *LHS = BO->getLHS(); 490 const Expr *RHS = BO->getRHS(); 491 til::SExpr *E0 = translate(LHS, Ctx); 492 til::SExpr *E1 = translate(RHS, Ctx); 493 494 const ValueDecl *VD = nullptr; 495 til::SExpr *CV = nullptr; 496 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 497 VD = DRE->getDecl(); 498 CV = lookupVarDecl(VD); 499 } 500 501 if (!Assign) { 502 til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0); 503 E1 = new (Arena) til::BinaryOp(Op, Arg, E1); 504 E1 = addStatement(E1, nullptr, VD); 505 } 506 if (VD && CV) 507 return updateVarDecl(VD, E1); 508 return new (Arena) til::Store(E0, E1); 509 } 510 511 til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO, 512 CallingContext *Ctx) { 513 switch (BO->getOpcode()) { 514 case BO_PtrMemD: 515 case BO_PtrMemI: 516 return new (Arena) til::Undefined(BO); 517 518 case BO_Mul: return translateBinOp(til::BOP_Mul, BO, Ctx); 519 case BO_Div: return translateBinOp(til::BOP_Div, BO, Ctx); 520 case BO_Rem: return translateBinOp(til::BOP_Rem, BO, Ctx); 521 case BO_Add: return translateBinOp(til::BOP_Add, BO, Ctx); 522 case BO_Sub: return translateBinOp(til::BOP_Sub, BO, Ctx); 523 case BO_Shl: return translateBinOp(til::BOP_Shl, BO, Ctx); 524 case BO_Shr: return translateBinOp(til::BOP_Shr, BO, Ctx); 525 case BO_LT: return translateBinOp(til::BOP_Lt, BO, Ctx); 526 case BO_GT: return translateBinOp(til::BOP_Lt, BO, Ctx, true); 527 case BO_LE: return translateBinOp(til::BOP_Leq, BO, Ctx); 528 case BO_GE: return translateBinOp(til::BOP_Leq, BO, Ctx, true); 529 case BO_EQ: return translateBinOp(til::BOP_Eq, BO, Ctx); 530 case BO_NE: return translateBinOp(til::BOP_Neq, BO, Ctx); 531 case BO_Cmp: return translateBinOp(til::BOP_Cmp, BO, Ctx); 532 case BO_And: return translateBinOp(til::BOP_BitAnd, BO, Ctx); 533 case BO_Xor: return translateBinOp(til::BOP_BitXor, BO, Ctx); 534 case BO_Or: return translateBinOp(til::BOP_BitOr, BO, Ctx); 535 case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx); 536 case BO_LOr: return translateBinOp(til::BOP_LogicOr, BO, Ctx); 537 538 case BO_Assign: return translateBinAssign(til::BOP_Eq, BO, Ctx, true); 539 case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx); 540 case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx); 541 case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx); 542 case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx); 543 case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx); 544 case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx); 545 case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx); 546 case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx); 547 case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx); 548 case BO_OrAssign: return translateBinAssign(til::BOP_BitOr, BO, Ctx); 549 550 case BO_Comma: 551 // The clang CFG should have already processed both sides. 552 return translate(BO->getRHS(), Ctx); 553 } 554 return new (Arena) til::Undefined(BO); 555 } 556 557 til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE, 558 CallingContext *Ctx) { 559 CastKind K = CE->getCastKind(); 560 switch (K) { 561 case CK_LValueToRValue: { 562 if (const auto *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 563 til::SExpr *E0 = lookupVarDecl(DRE->getDecl()); 564 if (E0) 565 return E0; 566 } 567 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx); 568 return E0; 569 // FIXME!! -- get Load working properly 570 // return new (Arena) til::Load(E0); 571 } 572 case CK_NoOp: 573 case CK_DerivedToBase: 574 case CK_UncheckedDerivedToBase: 575 case CK_ArrayToPointerDecay: 576 case CK_FunctionToPointerDecay: { 577 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx); 578 return E0; 579 } 580 default: { 581 // FIXME: handle different kinds of casts. 582 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx); 583 if (CapabilityExprMode) 584 return E0; 585 return new (Arena) til::Cast(til::CAST_none, E0); 586 } 587 } 588 } 589 590 til::SExpr * 591 SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E, 592 CallingContext *Ctx) { 593 til::SExpr *E0 = translate(E->getBase(), Ctx); 594 til::SExpr *E1 = translate(E->getIdx(), Ctx); 595 return new (Arena) til::ArrayIndex(E0, E1); 596 } 597 598 til::SExpr * 599 SExprBuilder::translateAbstractConditionalOperator( 600 const AbstractConditionalOperator *CO, CallingContext *Ctx) { 601 auto *C = translate(CO->getCond(), Ctx); 602 auto *T = translate(CO->getTrueExpr(), Ctx); 603 auto *E = translate(CO->getFalseExpr(), Ctx); 604 return new (Arena) til::IfThenElse(C, T, E); 605 } 606 607 til::SExpr * 608 SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) { 609 DeclGroupRef DGrp = S->getDeclGroup(); 610 for (auto I : DGrp) { 611 if (auto *VD = dyn_cast_or_null<VarDecl>(I)) { 612 Expr *E = VD->getInit(); 613 til::SExpr* SE = translate(E, Ctx); 614 615 // Add local variables with trivial type to the variable map 616 QualType T = VD->getType(); 617 if (T.isTrivialType(VD->getASTContext())) 618 return addVarDecl(VD, SE); 619 else { 620 // TODO: add alloca 621 } 622 } 623 } 624 return nullptr; 625 } 626 627 // If (E) is non-trivial, then add it to the current basic block, and 628 // update the statement map so that S refers to E. Returns a new variable 629 // that refers to E. 630 // If E is trivial returns E. 631 til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S, 632 const ValueDecl *VD) { 633 if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E)) 634 return E; 635 if (VD) 636 E = new (Arena) til::Variable(E, VD); 637 CurrentInstructions.push_back(E); 638 if (S) 639 insertStmt(S, E); 640 return E; 641 } 642 643 // Returns the current value of VD, if known, and nullptr otherwise. 644 til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) { 645 auto It = LVarIdxMap.find(VD); 646 if (It != LVarIdxMap.end()) { 647 assert(CurrentLVarMap[It->second].first == VD); 648 return CurrentLVarMap[It->second].second; 649 } 650 return nullptr; 651 } 652 653 // if E is a til::Variable, update its clangDecl. 654 static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) { 655 if (!E) 656 return; 657 if (auto *V = dyn_cast<til::Variable>(E)) { 658 if (!V->clangDecl()) 659 V->setClangDecl(VD); 660 } 661 } 662 663 // Adds a new variable declaration. 664 til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) { 665 maybeUpdateVD(E, VD); 666 LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size())); 667 CurrentLVarMap.makeWritable(); 668 CurrentLVarMap.push_back(std::make_pair(VD, E)); 669 return E; 670 } 671 672 // Updates a current variable declaration. (E.g. by assignment) 673 til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) { 674 maybeUpdateVD(E, VD); 675 auto It = LVarIdxMap.find(VD); 676 if (It == LVarIdxMap.end()) { 677 til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD); 678 til::SExpr *St = new (Arena) til::Store(Ptr, E); 679 return St; 680 } 681 CurrentLVarMap.makeWritable(); 682 CurrentLVarMap.elem(It->second).second = E; 683 return E; 684 } 685 686 // Make a Phi node in the current block for the i^th variable in CurrentVarMap. 687 // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E. 688 // If E == null, this is a backedge and will be set later. 689 void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) { 690 unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors; 691 assert(ArgIndex > 0 && ArgIndex < NPreds); 692 693 til::SExpr *CurrE = CurrentLVarMap[i].second; 694 if (CurrE->block() == CurrentBB) { 695 // We already have a Phi node in the current block, 696 // so just add the new variable to the Phi node. 697 auto *Ph = dyn_cast<til::Phi>(CurrE); 698 assert(Ph && "Expecting Phi node."); 699 if (E) 700 Ph->values()[ArgIndex] = E; 701 return; 702 } 703 704 // Make a new phi node: phi(..., E) 705 // All phi args up to the current index are set to the current value. 706 til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds); 707 Ph->values().setValues(NPreds, nullptr); 708 for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx) 709 Ph->values()[PIdx] = CurrE; 710 if (E) 711 Ph->values()[ArgIndex] = E; 712 Ph->setClangDecl(CurrentLVarMap[i].first); 713 // If E is from a back-edge, or either E or CurrE are incomplete, then 714 // mark this node as incomplete; we may need to remove it later. 715 if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE)) 716 Ph->setStatus(til::Phi::PH_Incomplete); 717 718 // Add Phi node to current block, and update CurrentLVarMap[i] 719 CurrentArguments.push_back(Ph); 720 if (Ph->status() == til::Phi::PH_Incomplete) 721 IncompleteArgs.push_back(Ph); 722 723 CurrentLVarMap.makeWritable(); 724 CurrentLVarMap.elem(i).second = Ph; 725 } 726 727 // Merge values from Map into the current variable map. 728 // This will construct Phi nodes in the current basic block as necessary. 729 void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) { 730 assert(CurrentBlockInfo && "Not processing a block!"); 731 732 if (!CurrentLVarMap.valid()) { 733 // Steal Map, using copy-on-write. 734 CurrentLVarMap = std::move(Map); 735 return; 736 } 737 if (CurrentLVarMap.sameAs(Map)) 738 return; // Easy merge: maps from different predecessors are unchanged. 739 740 unsigned NPreds = CurrentBB->numPredecessors(); 741 unsigned ESz = CurrentLVarMap.size(); 742 unsigned MSz = Map.size(); 743 unsigned Sz = std::min(ESz, MSz); 744 745 for (unsigned i = 0; i < Sz; ++i) { 746 if (CurrentLVarMap[i].first != Map[i].first) { 747 // We've reached the end of variables in common. 748 CurrentLVarMap.makeWritable(); 749 CurrentLVarMap.downsize(i); 750 break; 751 } 752 if (CurrentLVarMap[i].second != Map[i].second) 753 makePhiNodeVar(i, NPreds, Map[i].second); 754 } 755 if (ESz > MSz) { 756 CurrentLVarMap.makeWritable(); 757 CurrentLVarMap.downsize(Map.size()); 758 } 759 } 760 761 // Merge a back edge into the current variable map. 762 // This will create phi nodes for all variables in the variable map. 763 void SExprBuilder::mergeEntryMapBackEdge() { 764 // We don't have definitions for variables on the backedge, because we 765 // haven't gotten that far in the CFG. Thus, when encountering a back edge, 766 // we conservatively create Phi nodes for all variables. Unnecessary Phi 767 // nodes will be marked as incomplete, and stripped out at the end. 768 // 769 // An Phi node is unnecessary if it only refers to itself and one other 770 // variable, e.g. x = Phi(y, y, x) can be reduced to x = y. 771 772 assert(CurrentBlockInfo && "Not processing a block!"); 773 774 if (CurrentBlockInfo->HasBackEdges) 775 return; 776 CurrentBlockInfo->HasBackEdges = true; 777 778 CurrentLVarMap.makeWritable(); 779 unsigned Sz = CurrentLVarMap.size(); 780 unsigned NPreds = CurrentBB->numPredecessors(); 781 782 for (unsigned i = 0; i < Sz; ++i) 783 makePhiNodeVar(i, NPreds, nullptr); 784 } 785 786 // Update the phi nodes that were initially created for a back edge 787 // once the variable definitions have been computed. 788 // I.e., merge the current variable map into the phi nodes for Blk. 789 void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) { 790 til::BasicBlock *BB = lookupBlock(Blk); 791 unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors; 792 assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors()); 793 794 for (til::SExpr *PE : BB->arguments()) { 795 auto *Ph = dyn_cast_or_null<til::Phi>(PE); 796 assert(Ph && "Expecting Phi Node."); 797 assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge."); 798 799 til::SExpr *E = lookupVarDecl(Ph->clangDecl()); 800 assert(E && "Couldn't find local variable for Phi node."); 801 Ph->values()[ArgIndex] = E; 802 } 803 } 804 805 void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D, 806 const CFGBlock *First) { 807 // Perform initial setup operations. 808 unsigned NBlocks = Cfg->getNumBlockIDs(); 809 Scfg = new (Arena) til::SCFG(Arena, NBlocks); 810 811 // allocate all basic blocks immediately, to handle forward references. 812 BBInfo.resize(NBlocks); 813 BlockMap.resize(NBlocks, nullptr); 814 // create map from clang blockID to til::BasicBlocks 815 for (auto *B : *Cfg) { 816 auto *BB = new (Arena) til::BasicBlock(Arena); 817 BB->reserveInstructions(B->size()); 818 BlockMap[B->getBlockID()] = BB; 819 } 820 821 CurrentBB = lookupBlock(&Cfg->getEntry()); 822 auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters() 823 : cast<FunctionDecl>(D)->parameters(); 824 for (auto *Pm : Parms) { 825 QualType T = Pm->getType(); 826 if (!T.isTrivialType(Pm->getASTContext())) 827 continue; 828 829 // Add parameters to local variable map. 830 // FIXME: right now we emulate params with loads; that should be fixed. 831 til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm); 832 til::SExpr *Ld = new (Arena) til::Load(Lp); 833 til::SExpr *V = addStatement(Ld, nullptr, Pm); 834 addVarDecl(Pm, V); 835 } 836 } 837 838 void SExprBuilder::enterCFGBlock(const CFGBlock *B) { 839 // Initialize TIL basic block and add it to the CFG. 840 CurrentBB = lookupBlock(B); 841 CurrentBB->reservePredecessors(B->pred_size()); 842 Scfg->add(CurrentBB); 843 844 CurrentBlockInfo = &BBInfo[B->getBlockID()]; 845 846 // CurrentLVarMap is moved to ExitMap on block exit. 847 // FIXME: the entry block will hold function parameters. 848 // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized."); 849 } 850 851 void SExprBuilder::handlePredecessor(const CFGBlock *Pred) { 852 // Compute CurrentLVarMap on entry from ExitMaps of predecessors 853 854 CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]); 855 BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()]; 856 assert(PredInfo->UnprocessedSuccessors > 0); 857 858 if (--PredInfo->UnprocessedSuccessors == 0) 859 mergeEntryMap(std::move(PredInfo->ExitMap)); 860 else 861 mergeEntryMap(PredInfo->ExitMap.clone()); 862 863 ++CurrentBlockInfo->ProcessedPredecessors; 864 } 865 866 void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) { 867 mergeEntryMapBackEdge(); 868 } 869 870 void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) { 871 // The merge*() methods have created arguments. 872 // Push those arguments onto the basic block. 873 CurrentBB->arguments().reserve( 874 static_cast<unsigned>(CurrentArguments.size()), Arena); 875 for (auto *A : CurrentArguments) 876 CurrentBB->addArgument(A); 877 } 878 879 void SExprBuilder::handleStatement(const Stmt *S) { 880 til::SExpr *E = translate(S, nullptr); 881 addStatement(E, S); 882 } 883 884 void SExprBuilder::handleDestructorCall(const VarDecl *VD, 885 const CXXDestructorDecl *DD) { 886 til::SExpr *Sf = new (Arena) til::LiteralPtr(VD); 887 til::SExpr *Dr = new (Arena) til::LiteralPtr(DD); 888 til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf); 889 til::SExpr *E = new (Arena) til::Call(Ap); 890 addStatement(E, nullptr); 891 } 892 893 void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) { 894 CurrentBB->instructions().reserve( 895 static_cast<unsigned>(CurrentInstructions.size()), Arena); 896 for (auto *V : CurrentInstructions) 897 CurrentBB->addInstruction(V); 898 899 // Create an appropriate terminator 900 unsigned N = B->succ_size(); 901 auto It = B->succ_begin(); 902 if (N == 1) { 903 til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr; 904 // TODO: set index 905 unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0; 906 auto *Tm = new (Arena) til::Goto(BB, Idx); 907 CurrentBB->setTerminator(Tm); 908 } 909 else if (N == 2) { 910 til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr); 911 til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr; 912 ++It; 913 til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr; 914 // FIXME: make sure these aren't critical edges. 915 auto *Tm = new (Arena) til::Branch(C, BB1, BB2); 916 CurrentBB->setTerminator(Tm); 917 } 918 } 919 920 void SExprBuilder::handleSuccessor(const CFGBlock *Succ) { 921 ++CurrentBlockInfo->UnprocessedSuccessors; 922 } 923 924 void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) { 925 mergePhiNodesBackEdge(Succ); 926 ++BBInfo[Succ->getBlockID()].ProcessedPredecessors; 927 } 928 929 void SExprBuilder::exitCFGBlock(const CFGBlock *B) { 930 CurrentArguments.clear(); 931 CurrentInstructions.clear(); 932 CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap); 933 CurrentBB = nullptr; 934 CurrentBlockInfo = nullptr; 935 } 936 937 void SExprBuilder::exitCFG(const CFGBlock *Last) { 938 for (auto *Ph : IncompleteArgs) { 939 if (Ph->status() == til::Phi::PH_Incomplete) 940 simplifyIncompleteArg(Ph); 941 } 942 943 CurrentArguments.clear(); 944 CurrentInstructions.clear(); 945 IncompleteArgs.clear(); 946 } 947 948 /* 949 namespace { 950 951 class TILPrinter : 952 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {}; 953 954 } // namespace 955 956 namespace clang { 957 namespace threadSafety { 958 959 void printSCFG(CFGWalker &Walker) { 960 llvm::BumpPtrAllocator Bpa; 961 til::MemRegionRef Arena(&Bpa); 962 SExprBuilder SxBuilder(Arena); 963 til::SCFG *Scfg = SxBuilder.buildCFG(Walker); 964 TILPrinter::print(Scfg, llvm::errs()); 965 } 966 967 } // namespace threadSafety 968 } // namespace clang 969 */ 970