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