Path: blob/main/contrib/llvm-project/clang/lib/Analysis/ThreadSafetyTIL.cpp
35234 views
//===- ThreadSafetyTIL.cpp ------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"9#include "clang/Basic/LLVM.h"10#include "llvm/Support/Casting.h"11#include <cassert>12#include <cstddef>1314using namespace clang;15using namespace threadSafety;16using namespace til;1718StringRef til::getUnaryOpcodeString(TIL_UnaryOpcode Op) {19switch (Op) {20case UOP_Minus: return "-";21case UOP_BitNot: return "~";22case UOP_LogicNot: return "!";23}24return {};25}2627StringRef til::getBinaryOpcodeString(TIL_BinaryOpcode Op) {28switch (Op) {29case BOP_Mul: return "*";30case BOP_Div: return "/";31case BOP_Rem: return "%";32case BOP_Add: return "+";33case BOP_Sub: return "-";34case BOP_Shl: return "<<";35case BOP_Shr: return ">>";36case BOP_BitAnd: return "&";37case BOP_BitXor: return "^";38case BOP_BitOr: return "|";39case BOP_Eq: return "==";40case BOP_Neq: return "!=";41case BOP_Lt: return "<";42case BOP_Leq: return "<=";43case BOP_Cmp: return "<=>";44case BOP_LogicAnd: return "&&";45case BOP_LogicOr: return "||";46}47return {};48}4950SExpr* Future::force() {51Status = FS_evaluating;52Result = compute();53Status = FS_done;54return Result;55}5657unsigned BasicBlock::addPredecessor(BasicBlock *Pred) {58unsigned Idx = Predecessors.size();59Predecessors.reserveCheck(1, Arena);60Predecessors.push_back(Pred);61for (auto *E : Args) {62if (auto *Ph = dyn_cast<Phi>(E)) {63Ph->values().reserveCheck(1, Arena);64Ph->values().push_back(nullptr);65}66}67return Idx;68}6970void BasicBlock::reservePredecessors(unsigned NumPreds) {71Predecessors.reserve(NumPreds, Arena);72for (auto *E : Args) {73if (auto *Ph = dyn_cast<Phi>(E)) {74Ph->values().reserve(NumPreds, Arena);75}76}77}7879// If E is a variable, then trace back through any aliases or redundant80// Phi nodes to find the canonical definition.81const SExpr *til::getCanonicalVal(const SExpr *E) {82while (true) {83if (const auto *V = dyn_cast<Variable>(E)) {84if (V->kind() == Variable::VK_Let) {85E = V->definition();86continue;87}88}89if (const auto *Ph = dyn_cast<Phi>(E)) {90if (Ph->status() == Phi::PH_SingleVal) {91E = Ph->values()[0];92continue;93}94}95break;96}97return E;98}99100// If E is a variable, then trace back through any aliases or redundant101// Phi nodes to find the canonical definition.102// The non-const version will simplify incomplete Phi nodes.103SExpr *til::simplifyToCanonicalVal(SExpr *E) {104while (true) {105if (auto *V = dyn_cast<Variable>(E)) {106if (V->kind() != Variable::VK_Let)107return V;108// Eliminate redundant variables, e.g. x = y, or x = 5,109// but keep anything more complicated.110if (til::ThreadSafetyTIL::isTrivial(V->definition())) {111E = V->definition();112continue;113}114return V;115}116if (auto *Ph = dyn_cast<Phi>(E)) {117if (Ph->status() == Phi::PH_Incomplete)118simplifyIncompleteArg(Ph);119// Eliminate redundant Phi nodes.120if (Ph->status() == Phi::PH_SingleVal) {121E = Ph->values()[0];122continue;123}124}125return E;126}127}128129// Trace the arguments of an incomplete Phi node to see if they have the same130// canonical definition. If so, mark the Phi node as redundant.131// getCanonicalVal() will recursively call simplifyIncompletePhi().132void til::simplifyIncompleteArg(til::Phi *Ph) {133assert(Ph && Ph->status() == Phi::PH_Incomplete);134135// eliminate infinite recursion -- assume that this node is not redundant.136Ph->setStatus(Phi::PH_MultiVal);137138SExpr *E0 = simplifyToCanonicalVal(Ph->values()[0]);139for (unsigned i = 1, n = Ph->values().size(); i < n; ++i) {140SExpr *Ei = simplifyToCanonicalVal(Ph->values()[i]);141if (Ei == Ph)142continue; // Recursive reference to itself. Don't count.143if (Ei != E0) {144return; // Status is already set to MultiVal.145}146}147Ph->setStatus(Phi::PH_SingleVal);148}149150// Renumbers the arguments and instructions to have unique, sequential IDs.151unsigned BasicBlock::renumberInstrs(unsigned ID) {152for (auto *Arg : Args)153Arg->setID(this, ID++);154for (auto *Instr : Instrs)155Instr->setID(this, ID++);156TermInstr->setID(this, ID++);157return ID;158}159160// Sorts the CFGs blocks using a reverse post-order depth-first traversal.161// Each block will be written into the Blocks array in order, and its BlockID162// will be set to the index in the array. Sorting should start from the entry163// block, and ID should be the total number of blocks.164unsigned BasicBlock::topologicalSort(SimpleArray<BasicBlock *> &Blocks,165unsigned ID) {166if (Visited) return ID;167Visited = true;168for (auto *Block : successors())169ID = Block->topologicalSort(Blocks, ID);170// set ID and update block array in place.171// We may lose pointers to unreachable blocks.172assert(ID > 0);173BlockID = --ID;174Blocks[BlockID] = this;175return ID;176}177178// Performs a reverse topological traversal, starting from the exit block and179// following back-edges. The dominator is serialized before any predecessors,180// which guarantees that all blocks are serialized after their dominator and181// before their post-dominator (because it's a reverse topological traversal).182// ID should be initially set to 0.183//184// This sort assumes that (1) dominators have been computed, (2) there are no185// critical edges, and (3) the entry block is reachable from the exit block186// and no blocks are accessible via traversal of back-edges from the exit that187// weren't accessible via forward edges from the entry.188unsigned BasicBlock::topologicalFinalSort(SimpleArray<BasicBlock *> &Blocks,189unsigned ID) {190// Visited is assumed to have been set by the topologicalSort. This pass191// assumes !Visited means that we've visited this node before.192if (!Visited) return ID;193Visited = false;194if (DominatorNode.Parent)195ID = DominatorNode.Parent->topologicalFinalSort(Blocks, ID);196for (auto *Pred : Predecessors)197ID = Pred->topologicalFinalSort(Blocks, ID);198assert(static_cast<size_t>(ID) < Blocks.size());199BlockID = ID++;200Blocks[BlockID] = this;201return ID;202}203204// Computes the immediate dominator of the current block. Assumes that all of205// its predecessors have already computed their dominators. This is achieved206// by visiting the nodes in topological order.207void BasicBlock::computeDominator() {208BasicBlock *Candidate = nullptr;209// Walk backwards from each predecessor to find the common dominator node.210for (auto *Pred : Predecessors) {211// Skip back-edges212if (Pred->BlockID >= BlockID) continue;213// If we don't yet have a candidate for dominator yet, take this one.214if (Candidate == nullptr) {215Candidate = Pred;216continue;217}218// Walk the alternate and current candidate back to find a common ancestor.219auto *Alternate = Pred;220while (Alternate != Candidate) {221if (Candidate->BlockID > Alternate->BlockID)222Candidate = Candidate->DominatorNode.Parent;223else224Alternate = Alternate->DominatorNode.Parent;225}226}227DominatorNode.Parent = Candidate;228DominatorNode.SizeOfSubTree = 1;229}230231// Computes the immediate post-dominator of the current block. Assumes that all232// of its successors have already computed their post-dominators. This is233// achieved visiting the nodes in reverse topological order.234void BasicBlock::computePostDominator() {235BasicBlock *Candidate = nullptr;236// Walk back from each predecessor to find the common post-dominator node.237for (auto *Succ : successors()) {238// Skip back-edges239if (Succ->BlockID <= BlockID) continue;240// If we don't yet have a candidate for post-dominator yet, take this one.241if (Candidate == nullptr) {242Candidate = Succ;243continue;244}245// Walk the alternate and current candidate back to find a common ancestor.246auto *Alternate = Succ;247while (Alternate != Candidate) {248if (Candidate->BlockID < Alternate->BlockID)249Candidate = Candidate->PostDominatorNode.Parent;250else251Alternate = Alternate->PostDominatorNode.Parent;252}253}254PostDominatorNode.Parent = Candidate;255PostDominatorNode.SizeOfSubTree = 1;256}257258// Renumber instructions in all blocks259void SCFG::renumberInstrs() {260unsigned InstrID = 0;261for (auto *Block : Blocks)262InstrID = Block->renumberInstrs(InstrID);263}264265static inline void computeNodeSize(BasicBlock *B,266BasicBlock::TopologyNode BasicBlock::*TN) {267BasicBlock::TopologyNode *N = &(B->*TN);268if (N->Parent) {269BasicBlock::TopologyNode *P = &(N->Parent->*TN);270// Initially set ID relative to the (as yet uncomputed) parent ID271N->NodeID = P->SizeOfSubTree;272P->SizeOfSubTree += N->SizeOfSubTree;273}274}275276static inline void computeNodeID(BasicBlock *B,277BasicBlock::TopologyNode BasicBlock::*TN) {278BasicBlock::TopologyNode *N = &(B->*TN);279if (N->Parent) {280BasicBlock::TopologyNode *P = &(N->Parent->*TN);281N->NodeID += P->NodeID; // Fix NodeIDs relative to starting node.282}283}284285// Normalizes a CFG. Normalization has a few major components:286// 1) Removing unreachable blocks.287// 2) Computing dominators and post-dominators288// 3) Topologically sorting the blocks into the "Blocks" array.289void SCFG::computeNormalForm() {290// Topologically sort the blocks starting from the entry block.291unsigned NumUnreachableBlocks = Entry->topologicalSort(Blocks, Blocks.size());292if (NumUnreachableBlocks > 0) {293// If there were unreachable blocks shift everything down, and delete them.294for (unsigned I = NumUnreachableBlocks, E = Blocks.size(); I < E; ++I) {295unsigned NI = I - NumUnreachableBlocks;296Blocks[NI] = Blocks[I];297Blocks[NI]->BlockID = NI;298// FIXME: clean up predecessor pointers to unreachable blocks?299}300Blocks.drop(NumUnreachableBlocks);301}302303// Compute dominators.304for (auto *Block : Blocks)305Block->computeDominator();306307// Once dominators have been computed, the final sort may be performed.308unsigned NumBlocks = Exit->topologicalFinalSort(Blocks, 0);309assert(static_cast<size_t>(NumBlocks) == Blocks.size());310(void) NumBlocks;311312// Renumber the instructions now that we have a final sort.313renumberInstrs();314315// Compute post-dominators and compute the sizes of each node in the316// dominator tree.317for (auto *Block : Blocks.reverse()) {318Block->computePostDominator();319computeNodeSize(Block, &BasicBlock::DominatorNode);320}321// Compute the sizes of each node in the post-dominator tree and assign IDs in322// the dominator tree.323for (auto *Block : Blocks) {324computeNodeID(Block, &BasicBlock::DominatorNode);325computeNodeSize(Block, &BasicBlock::PostDominatorNode);326}327// Assign IDs in the post-dominator tree.328for (auto *Block : Blocks.reverse()) {329computeNodeID(Block, &BasicBlock::PostDominatorNode);330}331}332333334