1 //- CFLSteensAliasAnalysis.cpp - Unification-based Alias Analysis ---*- 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 // This file implements a CFL-base, summary-based alias analysis algorithm. It 11 // does not depend on types. The algorithm is a mixture of the one described in 12 // "Demand-driven alias analysis for C" by Xin Zheng and Radu Rugina, and "Fast 13 // algorithms for Dyck-CFL-reachability with applications to Alias Analysis" by 14 // Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the papers, we build a 15 // graph of the uses of a variable, where each node is a memory location, and 16 // each edge is an action that happened on that memory location. The "actions" 17 // can be one of Dereference, Reference, or Assign. The precision of this 18 // analysis is roughly the same as that of an one level context-sensitive 19 // Steensgaard's algorithm. 20 // 21 // Two variables are considered as aliasing iff you can reach one value's node 22 // from the other value's node and the language formed by concatenating all of 23 // the edge labels (actions) conforms to a context-free grammar. 24 // 25 // Because this algorithm requires a graph search on each query, we execute the 26 // algorithm outlined in "Fast algorithms..." (mentioned above) 27 // in order to transform the graph into sets of variables that may alias in 28 // ~nlogn time (n = number of variables), which makes queries take constant 29 // time. 30 //===----------------------------------------------------------------------===// 31 32 // N.B. AliasAnalysis as a whole is phrased as a FunctionPass at the moment, and 33 // CFLSteensAA is interprocedural. This is *technically* A Bad Thing, because 34 // FunctionPasses are only allowed to inspect the Function that they're being 35 // run on. Realistically, this likely isn't a problem until we allow 36 // FunctionPasses to run concurrently. 37 38 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 39 #include "CFLGraph.h" 40 #include "StratifiedSets.h" 41 #include "llvm/ADT/DenseMap.h" 42 #include "llvm/ADT/None.h" 43 #include "llvm/ADT/Optional.h" 44 #include "llvm/Analysis/TargetLibraryInfo.h" 45 #include "llvm/IR/Constants.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/Pass.h" 48 #include "llvm/Support/Compiler.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include <algorithm> 53 #include <cassert> 54 #include <memory> 55 #include <tuple> 56 57 using namespace llvm; 58 using namespace llvm::cflaa; 59 60 #define DEBUG_TYPE "cfl-steens-aa" 61 62 CFLSteensAAResult::CFLSteensAAResult(const TargetLibraryInfo &TLI) 63 : AAResultBase(), TLI(TLI) {} 64 CFLSteensAAResult::CFLSteensAAResult(CFLSteensAAResult &&Arg) 65 : AAResultBase(std::move(Arg)), TLI(Arg.TLI) {} 66 CFLSteensAAResult::~CFLSteensAAResult() {} 67 68 /// Information we have about a function and would like to keep around. 69 class CFLSteensAAResult::FunctionInfo { 70 StratifiedSets<InstantiatedValue> Sets; 71 AliasSummary Summary; 72 73 public: 74 FunctionInfo(Function &Fn, const SmallVectorImpl<Value *> &RetVals, 75 StratifiedSets<InstantiatedValue> S); 76 77 const StratifiedSets<InstantiatedValue> &getStratifiedSets() const { 78 return Sets; 79 } 80 const AliasSummary &getAliasSummary() const { return Summary; } 81 }; 82 83 const StratifiedIndex StratifiedLink::SetSentinel = 84 std::numeric_limits<StratifiedIndex>::max(); 85 86 //===----------------------------------------------------------------------===// 87 // Function declarations that require types defined in the namespace above 88 //===----------------------------------------------------------------------===// 89 90 /// Determines whether it would be pointless to add the given Value to our sets. 91 static bool canSkipAddingToSets(Value *Val); 92 93 static bool canSkipAddingToSets(Value *Val) { 94 // Constants can share instances, which may falsely unify multiple 95 // sets, e.g. in 96 // store i32* null, i32** %ptr1 97 // store i32* null, i32** %ptr2 98 // clearly ptr1 and ptr2 should not be unified into the same set, so 99 // we should filter out the (potentially shared) instance to 100 // i32* null. 101 if (isa<Constant>(Val)) { 102 // TODO: Because all of these things are constant, we can determine whether 103 // the data is *actually* mutable at graph building time. This will probably 104 // come for free/cheap with offset awareness. 105 bool CanStoreMutableData = isa<GlobalValue>(Val) || 106 isa<ConstantExpr>(Val) || 107 isa<ConstantAggregate>(Val); 108 return !CanStoreMutableData; 109 } 110 111 return false; 112 } 113 114 CFLSteensAAResult::FunctionInfo::FunctionInfo( 115 Function &Fn, const SmallVectorImpl<Value *> &RetVals, 116 StratifiedSets<InstantiatedValue> S) 117 : Sets(std::move(S)) { 118 // Historically, an arbitrary upper-bound of 50 args was selected. We may want 119 // to remove this if it doesn't really matter in practice. 120 if (Fn.arg_size() > MaxSupportedArgsInSummary) 121 return; 122 123 DenseMap<StratifiedIndex, InterfaceValue> InterfaceMap; 124 125 // Our intention here is to record all InterfaceValues that share the same 126 // StratifiedIndex in RetParamRelations. For each valid InterfaceValue, we 127 // have its StratifiedIndex scanned here and check if the index is presented 128 // in InterfaceMap: if it is not, we add the correspondence to the map; 129 // otherwise, an aliasing relation is found and we add it to 130 // RetParamRelations. 131 132 auto AddToRetParamRelations = [&](unsigned InterfaceIndex, 133 StratifiedIndex SetIndex) { 134 unsigned Level = 0; 135 while (true) { 136 InterfaceValue CurrValue{InterfaceIndex, Level}; 137 138 auto Itr = InterfaceMap.find(SetIndex); 139 if (Itr != InterfaceMap.end()) { 140 if (CurrValue != Itr->second) 141 Summary.RetParamRelations.push_back( 142 ExternalRelation{CurrValue, Itr->second, UnknownOffset}); 143 break; 144 } 145 146 auto &Link = Sets.getLink(SetIndex); 147 InterfaceMap.insert(std::make_pair(SetIndex, CurrValue)); 148 auto ExternalAttrs = getExternallyVisibleAttrs(Link.Attrs); 149 if (ExternalAttrs.any()) 150 Summary.RetParamAttributes.push_back( 151 ExternalAttribute{CurrValue, ExternalAttrs}); 152 153 if (!Link.hasBelow()) 154 break; 155 156 ++Level; 157 SetIndex = Link.Below; 158 } 159 }; 160 161 // Populate RetParamRelations for return values 162 for (auto *RetVal : RetVals) { 163 assert(RetVal != nullptr); 164 assert(RetVal->getType()->isPointerTy()); 165 auto RetInfo = Sets.find(InstantiatedValue{RetVal, 0}); 166 if (RetInfo.hasValue()) 167 AddToRetParamRelations(0, RetInfo->Index); 168 } 169 170 // Populate RetParamRelations for parameters 171 unsigned I = 0; 172 for (auto &Param : Fn.args()) { 173 if (Param.getType()->isPointerTy()) { 174 auto ParamInfo = Sets.find(InstantiatedValue{&Param, 0}); 175 if (ParamInfo.hasValue()) 176 AddToRetParamRelations(I + 1, ParamInfo->Index); 177 } 178 ++I; 179 } 180 } 181 182 // Builds the graph + StratifiedSets for a function. 183 CFLSteensAAResult::FunctionInfo CFLSteensAAResult::buildSetsFrom(Function *Fn) { 184 CFLGraphBuilder<CFLSteensAAResult> GraphBuilder(*this, TLI, *Fn); 185 StratifiedSetsBuilder<InstantiatedValue> SetBuilder; 186 187 // Add all CFLGraph nodes and all Dereference edges to StratifiedSets 188 auto &Graph = GraphBuilder.getCFLGraph(); 189 for (const auto &Mapping : Graph.value_mappings()) { 190 auto Val = Mapping.first; 191 if (canSkipAddingToSets(Val)) 192 continue; 193 auto &ValueInfo = Mapping.second; 194 195 assert(ValueInfo.getNumLevels() > 0); 196 SetBuilder.add(InstantiatedValue{Val, 0}); 197 SetBuilder.noteAttributes(InstantiatedValue{Val, 0}, 198 ValueInfo.getNodeInfoAtLevel(0).Attr); 199 for (unsigned I = 0, E = ValueInfo.getNumLevels() - 1; I < E; ++I) { 200 SetBuilder.add(InstantiatedValue{Val, I + 1}); 201 SetBuilder.noteAttributes(InstantiatedValue{Val, I + 1}, 202 ValueInfo.getNodeInfoAtLevel(I + 1).Attr); 203 SetBuilder.addBelow(InstantiatedValue{Val, I}, 204 InstantiatedValue{Val, I + 1}); 205 } 206 } 207 208 // Add all assign edges to StratifiedSets 209 for (const auto &Mapping : Graph.value_mappings()) { 210 auto Val = Mapping.first; 211 if (canSkipAddingToSets(Val)) 212 continue; 213 auto &ValueInfo = Mapping.second; 214 215 for (unsigned I = 0, E = ValueInfo.getNumLevels(); I < E; ++I) { 216 auto Src = InstantiatedValue{Val, I}; 217 for (auto &Edge : ValueInfo.getNodeInfoAtLevel(I).Edges) 218 SetBuilder.addWith(Src, Edge.Other); 219 } 220 } 221 222 return FunctionInfo(*Fn, GraphBuilder.getReturnValues(), SetBuilder.build()); 223 } 224 225 void CFLSteensAAResult::scan(Function *Fn) { 226 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>())); 227 (void)InsertPair; 228 assert(InsertPair.second && 229 "Trying to scan a function that has already been cached"); 230 231 // Note that we can't do Cache[Fn] = buildSetsFrom(Fn) here: the function call 232 // may get evaluated after operator[], potentially triggering a DenseMap 233 // resize and invalidating the reference returned by operator[] 234 auto FunInfo = buildSetsFrom(Fn); 235 Cache[Fn] = std::move(FunInfo); 236 237 Handles.emplace_front(Fn, this); 238 } 239 240 void CFLSteensAAResult::evict(Function *Fn) { Cache.erase(Fn); } 241 242 /// Ensures that the given function is available in the cache, and returns the 243 /// entry. 244 const Optional<CFLSteensAAResult::FunctionInfo> & 245 CFLSteensAAResult::ensureCached(Function *Fn) { 246 auto Iter = Cache.find(Fn); 247 if (Iter == Cache.end()) { 248 scan(Fn); 249 Iter = Cache.find(Fn); 250 assert(Iter != Cache.end()); 251 assert(Iter->second.hasValue()); 252 } 253 return Iter->second; 254 } 255 256 const AliasSummary *CFLSteensAAResult::getAliasSummary(Function &Fn) { 257 auto &FunInfo = ensureCached(&Fn); 258 if (FunInfo.hasValue()) 259 return &FunInfo->getAliasSummary(); 260 else 261 return nullptr; 262 } 263 264 AliasResult CFLSteensAAResult::query(const MemoryLocation &LocA, 265 const MemoryLocation &LocB) { 266 auto *ValA = const_cast<Value *>(LocA.Ptr); 267 auto *ValB = const_cast<Value *>(LocB.Ptr); 268 269 if (!ValA->getType()->isPointerTy() || !ValB->getType()->isPointerTy()) 270 return NoAlias; 271 272 Function *Fn = nullptr; 273 Function *MaybeFnA = const_cast<Function *>(parentFunctionOfValue(ValA)); 274 Function *MaybeFnB = const_cast<Function *>(parentFunctionOfValue(ValB)); 275 if (!MaybeFnA && !MaybeFnB) { 276 // The only times this is known to happen are when globals + InlineAsm are 277 // involved 278 DEBUG(dbgs() 279 << "CFLSteensAA: could not extract parent function information.\n"); 280 return MayAlias; 281 } 282 283 if (MaybeFnA) { 284 Fn = MaybeFnA; 285 assert((!MaybeFnB || MaybeFnB == MaybeFnA) && 286 "Interprocedural queries not supported"); 287 } else { 288 Fn = MaybeFnB; 289 } 290 291 assert(Fn != nullptr); 292 auto &MaybeInfo = ensureCached(Fn); 293 assert(MaybeInfo.hasValue()); 294 295 auto &Sets = MaybeInfo->getStratifiedSets(); 296 auto MaybeA = Sets.find(InstantiatedValue{ValA, 0}); 297 if (!MaybeA.hasValue()) 298 return MayAlias; 299 300 auto MaybeB = Sets.find(InstantiatedValue{ValB, 0}); 301 if (!MaybeB.hasValue()) 302 return MayAlias; 303 304 auto SetA = *MaybeA; 305 auto SetB = *MaybeB; 306 auto AttrsA = Sets.getLink(SetA.Index).Attrs; 307 auto AttrsB = Sets.getLink(SetB.Index).Attrs; 308 309 // If both values are local (meaning the corresponding set has attribute 310 // AttrNone or AttrEscaped), then we know that CFLSteensAA fully models them: 311 // they may-alias each other if and only if they are in the same set. 312 // If at least one value is non-local (meaning it either is global/argument or 313 // it comes from unknown sources like integer cast), the situation becomes a 314 // bit more interesting. We follow three general rules described below: 315 // - Non-local values may alias each other 316 // - AttrNone values do not alias any non-local values 317 // - AttrEscaped do not alias globals/arguments, but they may alias 318 // AttrUnknown values 319 if (SetA.Index == SetB.Index) 320 return MayAlias; 321 if (AttrsA.none() || AttrsB.none()) 322 return NoAlias; 323 if (hasUnknownOrCallerAttr(AttrsA) || hasUnknownOrCallerAttr(AttrsB)) 324 return MayAlias; 325 if (isGlobalOrArgAttr(AttrsA) && isGlobalOrArgAttr(AttrsB)) 326 return MayAlias; 327 return NoAlias; 328 } 329 330 AnalysisKey CFLSteensAA::Key; 331 332 CFLSteensAAResult CFLSteensAA::run(Function &F, FunctionAnalysisManager &AM) { 333 return CFLSteensAAResult(AM.getResult<TargetLibraryAnalysis>(F)); 334 } 335 336 char CFLSteensAAWrapperPass::ID = 0; 337 INITIALIZE_PASS(CFLSteensAAWrapperPass, "cfl-steens-aa", 338 "Unification-Based CFL Alias Analysis", false, true) 339 340 ImmutablePass *llvm::createCFLSteensAAWrapperPass() { 341 return new CFLSteensAAWrapperPass(); 342 } 343 344 CFLSteensAAWrapperPass::CFLSteensAAWrapperPass() : ImmutablePass(ID) { 345 initializeCFLSteensAAWrapperPassPass(*PassRegistry::getPassRegistry()); 346 } 347 348 void CFLSteensAAWrapperPass::initializePass() { 349 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 350 Result.reset(new CFLSteensAAResult(TLIWP.getTLI())); 351 } 352 353 void CFLSteensAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 354 AU.setPreservesAll(); 355 AU.addRequired<TargetLibraryInfoWrapperPass>(); 356 } 357