1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// 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 // This pass transforms simple global variables that never have their address 10 // taken. If obviously true, it marks read/write globals as constant, deletes 11 // variables only stored to, etc. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/IPO/GlobalOpt.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/ConstantFolding.h" 25 #include "llvm/Analysis/MemoryBuiltins.h" 26 #include "llvm/Analysis/TargetLibraryInfo.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/BinaryFormat/Dwarf.h" 30 #include "llvm/IR/Attributes.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/CallingConv.h" 33 #include "llvm/IR/Constant.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/DebugInfoMetadata.h" 37 #include "llvm/IR/DerivedTypes.h" 38 #include "llvm/IR/Dominators.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GetElementPtrTypeIterator.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalValue.h" 43 #include "llvm/IR/GlobalVariable.h" 44 #include "llvm/IR/IRBuilder.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/Instruction.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/Operator.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Use.h" 53 #include "llvm/IR/User.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/IR/ValueHandle.h" 56 #include "llvm/InitializePasses.h" 57 #include "llvm/Pass.h" 58 #include "llvm/Support/AtomicOrdering.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Transforms/IPO.h" 66 #include "llvm/Transforms/Utils/CtorUtils.h" 67 #include "llvm/Transforms/Utils/Evaluator.h" 68 #include "llvm/Transforms/Utils/GlobalStatus.h" 69 #include "llvm/Transforms/Utils/Local.h" 70 #include <cassert> 71 #include <cstdint> 72 #include <utility> 73 #include <vector> 74 75 using namespace llvm; 76 77 #define DEBUG_TYPE "globalopt" 78 79 STATISTIC(NumMarked , "Number of globals marked constant"); 80 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr"); 81 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars"); 82 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them"); 83 STATISTIC(NumDeleted , "Number of globals deleted"); 84 STATISTIC(NumGlobUses , "Number of global uses devirtualized"); 85 STATISTIC(NumLocalized , "Number of globals localized"); 86 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans"); 87 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc"); 88 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated"); 89 STATISTIC(NumNestRemoved , "Number of nest attributes removed"); 90 STATISTIC(NumAliasesResolved, "Number of global aliases resolved"); 91 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated"); 92 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed"); 93 STATISTIC(NumInternalFunc, "Number of internal functions"); 94 STATISTIC(NumColdCC, "Number of functions marked coldcc"); 95 96 static cl::opt<bool> 97 EnableColdCCStressTest("enable-coldcc-stress-test", 98 cl::desc("Enable stress test of coldcc by adding " 99 "calling conv to all internal functions."), 100 cl::init(false), cl::Hidden); 101 102 static cl::opt<int> ColdCCRelFreq( 103 "coldcc-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 104 cl::desc( 105 "Maximum block frequency, expressed as a percentage of caller's " 106 "entry frequency, for a call site to be considered cold for enabling" 107 "coldcc")); 108 109 /// Is this global variable possibly used by a leak checker as a root? If so, 110 /// we might not really want to eliminate the stores to it. 111 static bool isLeakCheckerRoot(GlobalVariable *GV) { 112 // A global variable is a root if it is a pointer, or could plausibly contain 113 // a pointer. There are two challenges; one is that we could have a struct 114 // the has an inner member which is a pointer. We recurse through the type to 115 // detect these (up to a point). The other is that we may actually be a union 116 // of a pointer and another type, and so our LLVM type is an integer which 117 // gets converted into a pointer, or our type is an [i8 x #] with a pointer 118 // potentially contained here. 119 120 if (GV->hasPrivateLinkage()) 121 return false; 122 123 SmallVector<Type *, 4> Types; 124 Types.push_back(GV->getValueType()); 125 126 unsigned Limit = 20; 127 do { 128 Type *Ty = Types.pop_back_val(); 129 switch (Ty->getTypeID()) { 130 default: break; 131 case Type::PointerTyID: 132 return true; 133 case Type::FixedVectorTyID: 134 case Type::ScalableVectorTyID: 135 if (cast<VectorType>(Ty)->getElementType()->isPointerTy()) 136 return true; 137 break; 138 case Type::ArrayTyID: 139 Types.push_back(cast<ArrayType>(Ty)->getElementType()); 140 break; 141 case Type::StructTyID: { 142 StructType *STy = cast<StructType>(Ty); 143 if (STy->isOpaque()) return true; 144 for (StructType::element_iterator I = STy->element_begin(), 145 E = STy->element_end(); I != E; ++I) { 146 Type *InnerTy = *I; 147 if (isa<PointerType>(InnerTy)) return true; 148 if (isa<StructType>(InnerTy) || isa<ArrayType>(InnerTy) || 149 isa<VectorType>(InnerTy)) 150 Types.push_back(InnerTy); 151 } 152 break; 153 } 154 } 155 if (--Limit == 0) return true; 156 } while (!Types.empty()); 157 return false; 158 } 159 160 /// Given a value that is stored to a global but never read, determine whether 161 /// it's safe to remove the store and the chain of computation that feeds the 162 /// store. 163 static bool IsSafeComputationToRemove( 164 Value *V, function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 165 do { 166 if (isa<Constant>(V)) 167 return true; 168 if (!V->hasOneUse()) 169 return false; 170 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) || 171 isa<GlobalValue>(V)) 172 return false; 173 if (isAllocationFn(V, GetTLI)) 174 return true; 175 176 Instruction *I = cast<Instruction>(V); 177 if (I->mayHaveSideEffects()) 178 return false; 179 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { 180 if (!GEP->hasAllConstantIndices()) 181 return false; 182 } else if (I->getNumOperands() != 1) { 183 return false; 184 } 185 186 V = I->getOperand(0); 187 } while (true); 188 } 189 190 /// This GV is a pointer root. Loop over all users of the global and clean up 191 /// any that obviously don't assign the global a value that isn't dynamically 192 /// allocated. 193 static bool 194 CleanupPointerRootUsers(GlobalVariable *GV, 195 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 196 // A brief explanation of leak checkers. The goal is to find bugs where 197 // pointers are forgotten, causing an accumulating growth in memory 198 // usage over time. The common strategy for leak checkers is to explicitly 199 // allow the memory pointed to by globals at exit. This is popular because it 200 // also solves another problem where the main thread of a C++ program may shut 201 // down before other threads that are still expecting to use those globals. To 202 // handle that case, we expect the program may create a singleton and never 203 // destroy it. 204 205 bool Changed = false; 206 207 // If Dead[n].first is the only use of a malloc result, we can delete its 208 // chain of computation and the store to the global in Dead[n].second. 209 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead; 210 211 // Constants can't be pointers to dynamically allocated memory. 212 for (User *U : llvm::make_early_inc_range(GV->users())) { 213 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 214 Value *V = SI->getValueOperand(); 215 if (isa<Constant>(V)) { 216 Changed = true; 217 SI->eraseFromParent(); 218 } else if (Instruction *I = dyn_cast<Instruction>(V)) { 219 if (I->hasOneUse()) 220 Dead.push_back(std::make_pair(I, SI)); 221 } 222 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) { 223 if (isa<Constant>(MSI->getValue())) { 224 Changed = true; 225 MSI->eraseFromParent(); 226 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) { 227 if (I->hasOneUse()) 228 Dead.push_back(std::make_pair(I, MSI)); 229 } 230 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) { 231 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource()); 232 if (MemSrc && MemSrc->isConstant()) { 233 Changed = true; 234 MTI->eraseFromParent(); 235 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) { 236 if (I->hasOneUse()) 237 Dead.push_back(std::make_pair(I, MTI)); 238 } 239 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 240 if (CE->use_empty()) { 241 CE->destroyConstant(); 242 Changed = true; 243 } 244 } else if (Constant *C = dyn_cast<Constant>(U)) { 245 if (isSafeToDestroyConstant(C)) { 246 C->destroyConstant(); 247 // This could have invalidated UI, start over from scratch. 248 Dead.clear(); 249 CleanupPointerRootUsers(GV, GetTLI); 250 return true; 251 } 252 } 253 } 254 255 for (int i = 0, e = Dead.size(); i != e; ++i) { 256 if (IsSafeComputationToRemove(Dead[i].first, GetTLI)) { 257 Dead[i].second->eraseFromParent(); 258 Instruction *I = Dead[i].first; 259 do { 260 if (isAllocationFn(I, GetTLI)) 261 break; 262 Instruction *J = dyn_cast<Instruction>(I->getOperand(0)); 263 if (!J) 264 break; 265 I->eraseFromParent(); 266 I = J; 267 } while (true); 268 I->eraseFromParent(); 269 Changed = true; 270 } 271 } 272 273 return Changed; 274 } 275 276 /// We just marked GV constant. Loop over all users of the global, cleaning up 277 /// the obvious ones. This is largely just a quick scan over the use list to 278 /// clean up the easy and obvious cruft. This returns true if it made a change. 279 static bool CleanupConstantGlobalUsers(GlobalVariable *GV, 280 const DataLayout &DL) { 281 Constant *Init = GV->getInitializer(); 282 SmallVector<User *, 8> WorkList(GV->users()); 283 SmallPtrSet<User *, 8> Visited; 284 bool Changed = false; 285 286 SmallVector<WeakTrackingVH> MaybeDeadInsts; 287 auto EraseFromParent = [&](Instruction *I) { 288 for (Value *Op : I->operands()) 289 if (auto *OpI = dyn_cast<Instruction>(Op)) 290 MaybeDeadInsts.push_back(OpI); 291 I->eraseFromParent(); 292 Changed = true; 293 }; 294 while (!WorkList.empty()) { 295 User *U = WorkList.pop_back_val(); 296 if (!Visited.insert(U).second) 297 continue; 298 299 if (auto *BO = dyn_cast<BitCastOperator>(U)) 300 append_range(WorkList, BO->users()); 301 if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U)) 302 append_range(WorkList, ASC->users()); 303 else if (auto *GEP = dyn_cast<GEPOperator>(U)) 304 append_range(WorkList, GEP->users()); 305 else if (auto *LI = dyn_cast<LoadInst>(U)) { 306 // A load from zeroinitializer is always zeroinitializer, regardless of 307 // any applied offset. 308 if (Init->isNullValue()) { 309 LI->replaceAllUsesWith(Constant::getNullValue(LI->getType())); 310 EraseFromParent(LI); 311 continue; 312 } 313 314 Value *PtrOp = LI->getPointerOperand(); 315 APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0); 316 PtrOp = PtrOp->stripAndAccumulateConstantOffsets( 317 DL, Offset, /* AllowNonInbounds */ true); 318 if (PtrOp == GV) { 319 if (auto *Value = ConstantFoldLoadFromConst(Init, LI->getType(), 320 Offset, DL)) { 321 LI->replaceAllUsesWith(Value); 322 EraseFromParent(LI); 323 } 324 } 325 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 326 // Store must be unreachable or storing Init into the global. 327 EraseFromParent(SI); 328 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv 329 if (getUnderlyingObject(MI->getRawDest()) == GV) 330 EraseFromParent(MI); 331 } 332 } 333 334 Changed |= 335 RecursivelyDeleteTriviallyDeadInstructionsPermissive(MaybeDeadInsts); 336 GV->removeDeadConstantUsers(); 337 return Changed; 338 } 339 340 static bool isSafeSROAElementUse(Value *V); 341 342 /// Return true if the specified GEP is a safe user of a derived 343 /// expression from a global that we want to SROA. 344 static bool isSafeSROAGEP(User *U) { 345 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we 346 // don't like < 3 operand CE's, and we don't like non-constant integer 347 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some 348 // value of C. 349 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) || 350 !cast<Constant>(U->getOperand(1))->isNullValue()) 351 return false; 352 353 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U); 354 ++GEPI; // Skip over the pointer index. 355 356 // For all other level we require that the indices are constant and inrange. 357 // In particular, consider: A[0][i]. We cannot know that the user isn't doing 358 // invalid things like allowing i to index an out-of-range subscript that 359 // accesses A[1]. This can also happen between different members of a struct 360 // in llvm IR. 361 for (; GEPI != E; ++GEPI) { 362 if (GEPI.isStruct()) 363 continue; 364 365 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand()); 366 if (!IdxVal || (GEPI.isBoundedSequential() && 367 IdxVal->getZExtValue() >= GEPI.getSequentialNumElements())) 368 return false; 369 } 370 371 return llvm::all_of(U->users(), 372 [](User *UU) { return isSafeSROAElementUse(UU); }); 373 } 374 375 /// Return true if the specified instruction is a safe user of a derived 376 /// expression from a global that we want to SROA. 377 static bool isSafeSROAElementUse(Value *V) { 378 // We might have a dead and dangling constant hanging off of here. 379 if (Constant *C = dyn_cast<Constant>(V)) 380 return isSafeToDestroyConstant(C); 381 382 Instruction *I = dyn_cast<Instruction>(V); 383 if (!I) return false; 384 385 // Loads are ok. 386 if (isa<LoadInst>(I)) return true; 387 388 // Stores *to* the pointer are ok. 389 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 390 return SI->getOperand(0) != V; 391 392 // Otherwise, it must be a GEP. Check it and its users are safe to SRA. 393 return isa<GetElementPtrInst>(I) && isSafeSROAGEP(I); 394 } 395 396 /// Look at all uses of the global and decide whether it is safe for us to 397 /// perform this transformation. 398 static bool GlobalUsersSafeToSRA(GlobalValue *GV) { 399 for (User *U : GV->users()) { 400 // The user of the global must be a GEP Inst or a ConstantExpr GEP. 401 if (!isa<GetElementPtrInst>(U) && 402 (!isa<ConstantExpr>(U) || 403 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr)) 404 return false; 405 406 // Check the gep and it's users are safe to SRA 407 if (!isSafeSROAGEP(U)) 408 return false; 409 } 410 411 return true; 412 } 413 414 static bool IsSRASequential(Type *T) { 415 return isa<ArrayType>(T) || isa<VectorType>(T); 416 } 417 static uint64_t GetSRASequentialNumElements(Type *T) { 418 if (ArrayType *AT = dyn_cast<ArrayType>(T)) 419 return AT->getNumElements(); 420 return cast<FixedVectorType>(T)->getNumElements(); 421 } 422 static Type *GetSRASequentialElementType(Type *T) { 423 if (ArrayType *AT = dyn_cast<ArrayType>(T)) 424 return AT->getElementType(); 425 return cast<VectorType>(T)->getElementType(); 426 } 427 static bool CanDoGlobalSRA(GlobalVariable *GV) { 428 Constant *Init = GV->getInitializer(); 429 430 if (isa<StructType>(Init->getType())) { 431 // nothing to check 432 } else if (IsSRASequential(Init->getType())) { 433 if (GetSRASequentialNumElements(Init->getType()) > 16 && 434 GV->hasNUsesOrMore(16)) 435 return false; // It's not worth it. 436 } else 437 return false; 438 439 return GlobalUsersSafeToSRA(GV); 440 } 441 442 /// Copy over the debug info for a variable to its SRA replacements. 443 static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, 444 uint64_t FragmentOffsetInBits, 445 uint64_t FragmentSizeInBits, 446 uint64_t VarSize) { 447 SmallVector<DIGlobalVariableExpression *, 1> GVs; 448 GV->getDebugInfo(GVs); 449 for (auto *GVE : GVs) { 450 DIVariable *Var = GVE->getVariable(); 451 DIExpression *Expr = GVE->getExpression(); 452 // If the FragmentSize is smaller than the variable, 453 // emit a fragment expression. 454 if (FragmentSizeInBits < VarSize) { 455 if (auto E = DIExpression::createFragmentExpression( 456 Expr, FragmentOffsetInBits, FragmentSizeInBits)) 457 Expr = *E; 458 else 459 return; 460 } 461 auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr); 462 NGV->addDebugInfo(NGVE); 463 } 464 } 465 466 /// Perform scalar replacement of aggregates on the specified global variable. 467 /// This opens the door for other optimizations by exposing the behavior of the 468 /// program in a more fine-grained way. We have determined that this 469 /// transformation is safe already. We return the first global variable we 470 /// insert so that the caller can reprocess it. 471 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) { 472 // Make sure this global only has simple uses that we can SRA. 473 if (!CanDoGlobalSRA(GV)) 474 return nullptr; 475 476 assert(GV->hasLocalLinkage()); 477 Constant *Init = GV->getInitializer(); 478 Type *Ty = Init->getType(); 479 uint64_t VarSize = DL.getTypeSizeInBits(Ty); 480 481 std::map<unsigned, GlobalVariable *> NewGlobals; 482 483 // Get the alignment of the global, either explicit or target-specific. 484 Align StartAlignment = 485 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getType()); 486 487 // Loop over all users and create replacement variables for used aggregate 488 // elements. 489 for (User *GEP : GV->users()) { 490 assert(((isa<ConstantExpr>(GEP) && cast<ConstantExpr>(GEP)->getOpcode() == 491 Instruction::GetElementPtr) || 492 isa<GetElementPtrInst>(GEP)) && 493 "NonGEP CE's are not SRAable!"); 494 495 // Ignore the 1th operand, which has to be zero or else the program is quite 496 // broken (undefined). Get the 2nd operand, which is the structure or array 497 // index. 498 unsigned ElementIdx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); 499 if (NewGlobals.count(ElementIdx) == 1) 500 continue; // we`ve already created replacement variable 501 assert(NewGlobals.count(ElementIdx) == 0); 502 503 Type *ElTy = nullptr; 504 if (StructType *STy = dyn_cast<StructType>(Ty)) 505 ElTy = STy->getElementType(ElementIdx); 506 else 507 ElTy = GetSRASequentialElementType(Ty); 508 assert(ElTy); 509 510 Constant *In = Init->getAggregateElement(ElementIdx); 511 assert(In && "Couldn't get element of initializer?"); 512 513 GlobalVariable *NGV = new GlobalVariable( 514 ElTy, false, GlobalVariable::InternalLinkage, In, 515 GV->getName() + "." + Twine(ElementIdx), GV->getThreadLocalMode(), 516 GV->getType()->getAddressSpace()); 517 NGV->setExternallyInitialized(GV->isExternallyInitialized()); 518 NGV->copyAttributesFrom(GV); 519 NewGlobals.insert(std::make_pair(ElementIdx, NGV)); 520 521 if (StructType *STy = dyn_cast<StructType>(Ty)) { 522 const StructLayout &Layout = *DL.getStructLayout(STy); 523 524 // Calculate the known alignment of the field. If the original aggregate 525 // had 256 byte alignment for example, something might depend on that: 526 // propagate info to each field. 527 uint64_t FieldOffset = Layout.getElementOffset(ElementIdx); 528 Align NewAlign = commonAlignment(StartAlignment, FieldOffset); 529 if (NewAlign > DL.getABITypeAlign(STy->getElementType(ElementIdx))) 530 NGV->setAlignment(NewAlign); 531 532 // Copy over the debug info for the variable. 533 uint64_t Size = DL.getTypeAllocSizeInBits(NGV->getValueType()); 534 uint64_t FragmentOffsetInBits = Layout.getElementOffsetInBits(ElementIdx); 535 transferSRADebugInfo(GV, NGV, FragmentOffsetInBits, Size, VarSize); 536 } else { 537 uint64_t EltSize = DL.getTypeAllocSize(ElTy); 538 Align EltAlign = DL.getABITypeAlign(ElTy); 539 uint64_t FragmentSizeInBits = DL.getTypeAllocSizeInBits(ElTy); 540 541 // Calculate the known alignment of the field. If the original aggregate 542 // had 256 byte alignment for example, something might depend on that: 543 // propagate info to each field. 544 Align NewAlign = commonAlignment(StartAlignment, EltSize * ElementIdx); 545 if (NewAlign > EltAlign) 546 NGV->setAlignment(NewAlign); 547 transferSRADebugInfo(GV, NGV, FragmentSizeInBits * ElementIdx, 548 FragmentSizeInBits, VarSize); 549 } 550 } 551 552 if (NewGlobals.empty()) 553 return nullptr; 554 555 Module::GlobalListType &Globals = GV->getParent()->getGlobalList(); 556 for (auto NewGlobalVar : NewGlobals) 557 Globals.push_back(NewGlobalVar.second); 558 559 LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n"); 560 561 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext())); 562 563 // Loop over all of the uses of the global, replacing the constantexpr geps, 564 // with smaller constantexpr geps or direct references. 565 while (!GV->use_empty()) { 566 User *GEP = GV->user_back(); 567 assert(((isa<ConstantExpr>(GEP) && 568 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)|| 569 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!"); 570 571 // Ignore the 1th operand, which has to be zero or else the program is quite 572 // broken (undefined). Get the 2nd operand, which is the structure or array 573 // index. 574 unsigned ElementIdx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); 575 assert(NewGlobals.count(ElementIdx) == 1); 576 577 Value *NewPtr = NewGlobals[ElementIdx]; 578 Type *NewTy = NewGlobals[ElementIdx]->getValueType(); 579 580 // Form a shorter GEP if needed. 581 if (GEP->getNumOperands() > 3) { 582 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) { 583 SmallVector<Constant*, 8> Idxs; 584 Idxs.push_back(NullInt); 585 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) 586 Idxs.push_back(CE->getOperand(i)); 587 NewPtr = 588 ConstantExpr::getGetElementPtr(NewTy, cast<Constant>(NewPtr), Idxs); 589 } else { 590 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP); 591 SmallVector<Value*, 8> Idxs; 592 Idxs.push_back(NullInt); 593 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) 594 Idxs.push_back(GEPI->getOperand(i)); 595 NewPtr = GetElementPtrInst::Create( 596 NewTy, NewPtr, Idxs, GEPI->getName() + "." + Twine(ElementIdx), 597 GEPI); 598 } 599 } 600 GEP->replaceAllUsesWith(NewPtr); 601 602 // We changed the pointer of any memory access user. Recalculate alignments. 603 for (User *U : NewPtr->users()) { 604 if (auto *Load = dyn_cast<LoadInst>(U)) { 605 Align PrefAlign = DL.getPrefTypeAlign(Load->getType()); 606 Align NewAlign = getOrEnforceKnownAlignment(Load->getPointerOperand(), 607 PrefAlign, DL, Load); 608 Load->setAlignment(NewAlign); 609 } 610 if (auto *Store = dyn_cast<StoreInst>(U)) { 611 Align PrefAlign = 612 DL.getPrefTypeAlign(Store->getValueOperand()->getType()); 613 Align NewAlign = getOrEnforceKnownAlignment(Store->getPointerOperand(), 614 PrefAlign, DL, Store); 615 Store->setAlignment(NewAlign); 616 } 617 } 618 619 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP)) 620 GEPI->eraseFromParent(); 621 else 622 cast<ConstantExpr>(GEP)->destroyConstant(); 623 } 624 625 // Delete the old global, now that it is dead. 626 Globals.erase(GV); 627 ++NumSRA; 628 629 assert(NewGlobals.size() > 0); 630 return NewGlobals.begin()->second; 631 } 632 633 /// Return true if all users of the specified value will trap if the value is 634 /// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid 635 /// reprocessing them. 636 static bool AllUsesOfValueWillTrapIfNull(const Value *V, 637 SmallPtrSetImpl<const PHINode*> &PHIs) { 638 for (const User *U : V->users()) { 639 if (const Instruction *I = dyn_cast<Instruction>(U)) { 640 // If null pointer is considered valid, then all uses are non-trapping. 641 // Non address-space 0 globals have already been pruned by the caller. 642 if (NullPointerIsDefined(I->getFunction())) 643 return false; 644 } 645 if (isa<LoadInst>(U)) { 646 // Will trap. 647 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 648 if (SI->getOperand(0) == V) { 649 //cerr << "NONTRAPPING USE: " << *U; 650 return false; // Storing the value. 651 } 652 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) { 653 if (CI->getCalledOperand() != V) { 654 //cerr << "NONTRAPPING USE: " << *U; 655 return false; // Not calling the ptr 656 } 657 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) { 658 if (II->getCalledOperand() != V) { 659 //cerr << "NONTRAPPING USE: " << *U; 660 return false; // Not calling the ptr 661 } 662 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) { 663 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false; 664 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 665 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false; 666 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 667 // If we've already seen this phi node, ignore it, it has already been 668 // checked. 669 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs)) 670 return false; 671 } else if (isa<ICmpInst>(U) && 672 !ICmpInst::isSigned(cast<ICmpInst>(U)->getPredicate()) && 673 isa<LoadInst>(U->getOperand(0)) && 674 isa<ConstantPointerNull>(U->getOperand(1))) { 675 assert(isa<GlobalValue>(cast<LoadInst>(U->getOperand(0)) 676 ->getPointerOperand() 677 ->stripPointerCasts()) && 678 "Should be GlobalVariable"); 679 // This and only this kind of non-signed ICmpInst is to be replaced with 680 // the comparing of the value of the created global init bool later in 681 // optimizeGlobalAddressOfMalloc for the global variable. 682 } else { 683 //cerr << "NONTRAPPING USE: " << *U; 684 return false; 685 } 686 } 687 return true; 688 } 689 690 /// Return true if all uses of any loads from GV will trap if the loaded value 691 /// is null. Note that this also permits comparisons of the loaded value 692 /// against null, as a special case. 693 static bool allUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) { 694 SmallVector<const Value *, 4> Worklist; 695 Worklist.push_back(GV); 696 while (!Worklist.empty()) { 697 const Value *P = Worklist.pop_back_val(); 698 for (auto *U : P->users()) { 699 if (auto *LI = dyn_cast<LoadInst>(U)) { 700 SmallPtrSet<const PHINode *, 8> PHIs; 701 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs)) 702 return false; 703 } else if (auto *SI = dyn_cast<StoreInst>(U)) { 704 // Ignore stores to the global. 705 if (SI->getPointerOperand() != P) 706 return false; 707 } else if (auto *CE = dyn_cast<ConstantExpr>(U)) { 708 if (CE->stripPointerCasts() != GV) 709 return false; 710 // Check further the ConstantExpr. 711 Worklist.push_back(CE); 712 } else { 713 // We don't know or understand this user, bail out. 714 return false; 715 } 716 } 717 } 718 719 return true; 720 } 721 722 /// Get all the loads/store uses for global variable \p GV. 723 static void allUsesOfLoadAndStores(GlobalVariable *GV, 724 SmallVector<Value *, 4> &Uses) { 725 SmallVector<Value *, 4> Worklist; 726 Worklist.push_back(GV); 727 while (!Worklist.empty()) { 728 auto *P = Worklist.pop_back_val(); 729 for (auto *U : P->users()) { 730 if (auto *CE = dyn_cast<ConstantExpr>(U)) { 731 Worklist.push_back(CE); 732 continue; 733 } 734 735 assert((isa<LoadInst>(U) || isa<StoreInst>(U)) && 736 "Expect only load or store instructions"); 737 Uses.push_back(U); 738 } 739 } 740 } 741 742 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { 743 bool Changed = false; 744 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) { 745 Instruction *I = cast<Instruction>(*UI++); 746 // Uses are non-trapping if null pointer is considered valid. 747 // Non address-space 0 globals are already pruned by the caller. 748 if (NullPointerIsDefined(I->getFunction())) 749 return false; 750 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 751 LI->setOperand(0, NewV); 752 Changed = true; 753 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 754 if (SI->getOperand(1) == V) { 755 SI->setOperand(1, NewV); 756 Changed = true; 757 } 758 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 759 CallBase *CB = cast<CallBase>(I); 760 if (CB->getCalledOperand() == V) { 761 // Calling through the pointer! Turn into a direct call, but be careful 762 // that the pointer is not also being passed as an argument. 763 CB->setCalledOperand(NewV); 764 Changed = true; 765 bool PassedAsArg = false; 766 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) 767 if (CB->getArgOperand(i) == V) { 768 PassedAsArg = true; 769 CB->setArgOperand(i, NewV); 770 } 771 772 if (PassedAsArg) { 773 // Being passed as an argument also. Be careful to not invalidate UI! 774 UI = V->user_begin(); 775 } 776 } 777 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 778 Changed |= OptimizeAwayTrappingUsesOfValue(CI, 779 ConstantExpr::getCast(CI->getOpcode(), 780 NewV, CI->getType())); 781 if (CI->use_empty()) { 782 Changed = true; 783 CI->eraseFromParent(); 784 } 785 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 786 // Should handle GEP here. 787 SmallVector<Constant*, 8> Idxs; 788 Idxs.reserve(GEPI->getNumOperands()-1); 789 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end(); 790 i != e; ++i) 791 if (Constant *C = dyn_cast<Constant>(*i)) 792 Idxs.push_back(C); 793 else 794 break; 795 if (Idxs.size() == GEPI->getNumOperands()-1) 796 Changed |= OptimizeAwayTrappingUsesOfValue( 797 GEPI, ConstantExpr::getGetElementPtr(GEPI->getSourceElementType(), 798 NewV, Idxs)); 799 if (GEPI->use_empty()) { 800 Changed = true; 801 GEPI->eraseFromParent(); 802 } 803 } 804 } 805 806 return Changed; 807 } 808 809 /// The specified global has only one non-null value stored into it. If there 810 /// are uses of the loaded value that would trap if the loaded value is 811 /// dynamically null, then we know that they cannot be reachable with a null 812 /// optimize away the load. 813 static bool OptimizeAwayTrappingUsesOfLoads( 814 GlobalVariable *GV, Constant *LV, const DataLayout &DL, 815 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 816 bool Changed = false; 817 818 // Keep track of whether we are able to remove all the uses of the global 819 // other than the store that defines it. 820 bool AllNonStoreUsesGone = true; 821 822 // Replace all uses of loads with uses of uses of the stored value. 823 for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) { 824 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) { 825 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); 826 // If we were able to delete all uses of the loads 827 if (LI->use_empty()) { 828 LI->eraseFromParent(); 829 Changed = true; 830 } else { 831 AllNonStoreUsesGone = false; 832 } 833 } else if (isa<StoreInst>(GlobalUser)) { 834 // Ignore the store that stores "LV" to the global. 835 assert(GlobalUser->getOperand(1) == GV && 836 "Must be storing *to* the global"); 837 } else { 838 AllNonStoreUsesGone = false; 839 840 // If we get here we could have other crazy uses that are transitively 841 // loaded. 842 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) || 843 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) || 844 isa<BitCastInst>(GlobalUser) || 845 isa<GetElementPtrInst>(GlobalUser)) && 846 "Only expect load and stores!"); 847 } 848 } 849 850 if (Changed) { 851 LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV 852 << "\n"); 853 ++NumGlobUses; 854 } 855 856 // If we nuked all of the loads, then none of the stores are needed either, 857 // nor is the global. 858 if (AllNonStoreUsesGone) { 859 if (isLeakCheckerRoot(GV)) { 860 Changed |= CleanupPointerRootUsers(GV, GetTLI); 861 } else { 862 Changed = true; 863 CleanupConstantGlobalUsers(GV, DL); 864 } 865 if (GV->use_empty()) { 866 LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n"); 867 Changed = true; 868 GV->eraseFromParent(); 869 ++NumDeleted; 870 } 871 } 872 return Changed; 873 } 874 875 /// Walk the use list of V, constant folding all of the instructions that are 876 /// foldable. 877 static void ConstantPropUsersOf(Value *V, const DataLayout &DL, 878 TargetLibraryInfo *TLI) { 879 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; ) 880 if (Instruction *I = dyn_cast<Instruction>(*UI++)) 881 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) { 882 I->replaceAllUsesWith(NewC); 883 884 // Advance UI to the next non-I use to avoid invalidating it! 885 // Instructions could multiply use V. 886 while (UI != E && *UI == I) 887 ++UI; 888 if (isInstructionTriviallyDead(I, TLI)) 889 I->eraseFromParent(); 890 } 891 } 892 893 /// This function takes the specified global variable, and transforms the 894 /// program as if it always contained the result of the specified malloc. 895 /// Because it is always the result of the specified malloc, there is no reason 896 /// to actually DO the malloc. Instead, turn the malloc into a global, and any 897 /// loads of GV as uses of the new global. 898 static GlobalVariable * 899 OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy, 900 ConstantInt *NElements, const DataLayout &DL, 901 TargetLibraryInfo *TLI) { 902 LLVM_DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI 903 << '\n'); 904 905 Type *GlobalType; 906 if (NElements->getZExtValue() == 1) 907 GlobalType = AllocTy; 908 else 909 // If we have an array allocation, the global variable is of an array. 910 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue()); 911 912 // Create the new global variable. The contents of the malloc'd memory is 913 // undefined, so initialize with an undef value. 914 GlobalVariable *NewGV = new GlobalVariable( 915 *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage, 916 UndefValue::get(GlobalType), GV->getName() + ".body", nullptr, 917 GV->getThreadLocalMode()); 918 919 // If there are bitcast users of the malloc (which is typical, usually we have 920 // a malloc + bitcast) then replace them with uses of the new global. Update 921 // other users to use the global as well. 922 BitCastInst *TheBC = nullptr; 923 while (!CI->use_empty()) { 924 Instruction *User = cast<Instruction>(CI->user_back()); 925 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 926 if (BCI->getType() == NewGV->getType()) { 927 BCI->replaceAllUsesWith(NewGV); 928 BCI->eraseFromParent(); 929 } else { 930 BCI->setOperand(0, NewGV); 931 } 932 } else { 933 if (!TheBC) 934 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI); 935 User->replaceUsesOfWith(CI, TheBC); 936 } 937 } 938 939 SmallPtrSet<Constant *, 1> RepValues; 940 RepValues.insert(NewGV); 941 942 // If there is a comparison against null, we will insert a global bool to 943 // keep track of whether the global was initialized yet or not. 944 GlobalVariable *InitBool = 945 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false, 946 GlobalValue::InternalLinkage, 947 ConstantInt::getFalse(GV->getContext()), 948 GV->getName()+".init", GV->getThreadLocalMode()); 949 bool InitBoolUsed = false; 950 951 // Loop over all instruction uses of GV, processing them in turn. 952 SmallVector<Value *, 4> Guses; 953 allUsesOfLoadAndStores(GV, Guses); 954 for (auto *U : Guses) { 955 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 956 // The global is initialized when the store to it occurs. If the stored 957 // value is null value, the global bool is set to false, otherwise true. 958 new StoreInst(ConstantInt::getBool( 959 GV->getContext(), 960 !isa<ConstantPointerNull>(SI->getValueOperand())), 961 InitBool, false, Align(1), SI->getOrdering(), 962 SI->getSyncScopeID(), SI); 963 SI->eraseFromParent(); 964 continue; 965 } 966 967 LoadInst *LI = cast<LoadInst>(U); 968 while (!LI->use_empty()) { 969 Use &LoadUse = *LI->use_begin(); 970 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser()); 971 if (!ICI) { 972 auto *CE = ConstantExpr::getBitCast(NewGV, LI->getType()); 973 RepValues.insert(CE); 974 LoadUse.set(CE); 975 continue; 976 } 977 978 // Replace the cmp X, 0 with a use of the bool value. 979 Value *LV = new LoadInst(InitBool->getValueType(), InitBool, 980 InitBool->getName() + ".val", false, Align(1), 981 LI->getOrdering(), LI->getSyncScopeID(), LI); 982 InitBoolUsed = true; 983 switch (ICI->getPredicate()) { 984 default: llvm_unreachable("Unknown ICmp Predicate!"); 985 case ICmpInst::ICMP_ULT: // X < null -> always false 986 LV = ConstantInt::getFalse(GV->getContext()); 987 break; 988 case ICmpInst::ICMP_UGE: // X >= null -> always true 989 LV = ConstantInt::getTrue(GV->getContext()); 990 break; 991 case ICmpInst::ICMP_ULE: 992 case ICmpInst::ICMP_EQ: 993 LV = BinaryOperator::CreateNot(LV, "notinit", ICI); 994 break; 995 case ICmpInst::ICMP_NE: 996 case ICmpInst::ICMP_UGT: 997 break; // no change. 998 } 999 ICI->replaceAllUsesWith(LV); 1000 ICI->eraseFromParent(); 1001 } 1002 LI->eraseFromParent(); 1003 } 1004 1005 // If the initialization boolean was used, insert it, otherwise delete it. 1006 if (!InitBoolUsed) { 1007 while (!InitBool->use_empty()) // Delete initializations 1008 cast<StoreInst>(InitBool->user_back())->eraseFromParent(); 1009 delete InitBool; 1010 } else 1011 GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool); 1012 1013 // Now the GV is dead, nuke it and the malloc.. 1014 GV->eraseFromParent(); 1015 CI->eraseFromParent(); 1016 1017 // To further other optimizations, loop over all users of NewGV and try to 1018 // constant prop them. This will promote GEP instructions with constant 1019 // indices into GEP constant-exprs, which will allow global-opt to hack on it. 1020 for (auto *CE : RepValues) 1021 ConstantPropUsersOf(CE, DL, TLI); 1022 1023 return NewGV; 1024 } 1025 1026 /// Scan the use-list of GV checking to make sure that there are no complex uses 1027 /// of GV. We permit simple things like dereferencing the pointer, but not 1028 /// storing through the address, unless it is to the specified global. 1029 static bool 1030 valueIsOnlyUsedLocallyOrStoredToOneGlobal(const CallInst *CI, 1031 const GlobalVariable *GV) { 1032 SmallPtrSet<const Value *, 4> Visited; 1033 SmallVector<const Value *, 4> Worklist; 1034 Worklist.push_back(CI); 1035 1036 while (!Worklist.empty()) { 1037 const Value *V = Worklist.pop_back_val(); 1038 if (!Visited.insert(V).second) 1039 continue; 1040 1041 for (const Use &VUse : V->uses()) { 1042 const User *U = VUse.getUser(); 1043 if (isa<LoadInst>(U) || isa<CmpInst>(U)) 1044 continue; // Fine, ignore. 1045 1046 if (auto *SI = dyn_cast<StoreInst>(U)) { 1047 if (SI->getValueOperand() == V && 1048 SI->getPointerOperand()->stripPointerCasts() != GV) 1049 return false; // Storing the pointer not into GV... bad. 1050 continue; // Otherwise, storing through it, or storing into GV... fine. 1051 } 1052 1053 if (auto *BCI = dyn_cast<BitCastInst>(U)) { 1054 Worklist.push_back(BCI); 1055 continue; 1056 } 1057 1058 if (auto *GEPI = dyn_cast<GetElementPtrInst>(U)) { 1059 Worklist.push_back(GEPI); 1060 continue; 1061 } 1062 1063 return false; 1064 } 1065 } 1066 1067 return true; 1068 } 1069 1070 /// This function is called when we see a pointer global variable with a single 1071 /// value stored it that is a malloc or cast of malloc. 1072 static bool tryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI, 1073 Type *AllocTy, 1074 AtomicOrdering Ordering, 1075 const DataLayout &DL, 1076 TargetLibraryInfo *TLI) { 1077 // If this is a malloc of an abstract type, don't touch it. 1078 if (!AllocTy->isSized()) 1079 return false; 1080 1081 // We can't optimize this global unless all uses of it are *known* to be 1082 // of the malloc value, not of the null initializer value (consider a use 1083 // that compares the global's value against zero to see if the malloc has 1084 // been reached). To do this, we check to see if all uses of the global 1085 // would trap if the global were null: this proves that they must all 1086 // happen after the malloc. 1087 if (!allUsesOfLoadedValueWillTrapIfNull(GV)) 1088 return false; 1089 1090 // We can't optimize this if the malloc itself is used in a complex way, 1091 // for example, being stored into multiple globals. This allows the 1092 // malloc to be stored into the specified global, loaded, gep, icmp'd. 1093 // These are all things we could transform to using the global for. 1094 if (!valueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV)) 1095 return false; 1096 1097 // If we have a global that is only initialized with a fixed size malloc, 1098 // transform the program to use global memory instead of malloc'd memory. 1099 // This eliminates dynamic allocation, avoids an indirection accessing the 1100 // data, and exposes the resultant global to further GlobalOpt. 1101 // We cannot optimize the malloc if we cannot determine malloc array size. 1102 Value *NElems = getMallocArraySize(CI, DL, TLI, true); 1103 if (!NElems) 1104 return false; 1105 1106 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems)) 1107 // Restrict this transformation to only working on small allocations 1108 // (2048 bytes currently), as we don't want to introduce a 16M global or 1109 // something. 1110 if (NElements->getZExtValue() * DL.getTypeAllocSize(AllocTy) < 2048) { 1111 OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI); 1112 return true; 1113 } 1114 1115 return false; 1116 } 1117 1118 // Try to optimize globals based on the knowledge that only one value (besides 1119 // its initializer) is ever stored to the global. 1120 static bool 1121 optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, 1122 AtomicOrdering Ordering, const DataLayout &DL, 1123 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 1124 // Ignore no-op GEPs and bitcasts. 1125 StoredOnceVal = StoredOnceVal->stripPointerCasts(); 1126 1127 // If we are dealing with a pointer global that is initialized to null and 1128 // only has one (non-null) value stored into it, then we can optimize any 1129 // users of the loaded value (often calls and loads) that would trap if the 1130 // value was null. 1131 if (GV->getInitializer()->getType()->isPointerTy() && 1132 GV->getInitializer()->isNullValue() && 1133 StoredOnceVal->getType()->isPointerTy() && 1134 !NullPointerIsDefined( 1135 nullptr /* F */, 1136 GV->getInitializer()->getType()->getPointerAddressSpace())) { 1137 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { 1138 if (GV->getInitializer()->getType() != SOVC->getType()) 1139 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType()); 1140 1141 // Optimize away any trapping uses of the loaded value. 1142 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI)) 1143 return true; 1144 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, GetTLI)) { 1145 auto *TLI = &GetTLI(*CI->getFunction()); 1146 Type *MallocType = getMallocAllocatedType(CI, TLI); 1147 if (MallocType && tryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, 1148 Ordering, DL, TLI)) 1149 return true; 1150 } 1151 } 1152 1153 return false; 1154 } 1155 1156 /// At this point, we have learned that the only two values ever stored into GV 1157 /// are its initializer and OtherVal. See if we can shrink the global into a 1158 /// boolean and select between the two values whenever it is used. This exposes 1159 /// the values to other scalar optimizations. 1160 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { 1161 Type *GVElType = GV->getValueType(); 1162 1163 // If GVElType is already i1, it is already shrunk. If the type of the GV is 1164 // an FP value, pointer or vector, don't do this optimization because a select 1165 // between them is very expensive and unlikely to lead to later 1166 // simplification. In these cases, we typically end up with "cond ? v1 : v2" 1167 // where v1 and v2 both require constant pool loads, a big loss. 1168 if (GVElType == Type::getInt1Ty(GV->getContext()) || 1169 GVElType->isFloatingPointTy() || 1170 GVElType->isPointerTy() || GVElType->isVectorTy()) 1171 return false; 1172 1173 // Walk the use list of the global seeing if all the uses are load or store. 1174 // If there is anything else, bail out. 1175 for (User *U : GV->users()) 1176 if (!isa<LoadInst>(U) && !isa<StoreInst>(U)) 1177 return false; 1178 1179 LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n"); 1180 1181 // Create the new global, initializing it to false. 1182 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()), 1183 false, 1184 GlobalValue::InternalLinkage, 1185 ConstantInt::getFalse(GV->getContext()), 1186 GV->getName()+".b", 1187 GV->getThreadLocalMode(), 1188 GV->getType()->getAddressSpace()); 1189 NewGV->copyAttributesFrom(GV); 1190 GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV); 1191 1192 Constant *InitVal = GV->getInitializer(); 1193 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) && 1194 "No reason to shrink to bool!"); 1195 1196 SmallVector<DIGlobalVariableExpression *, 1> GVs; 1197 GV->getDebugInfo(GVs); 1198 1199 // If initialized to zero and storing one into the global, we can use a cast 1200 // instead of a select to synthesize the desired value. 1201 bool IsOneZero = false; 1202 bool EmitOneOrZero = true; 1203 auto *CI = dyn_cast<ConstantInt>(OtherVal); 1204 if (CI && CI->getValue().getActiveBits() <= 64) { 1205 IsOneZero = InitVal->isNullValue() && CI->isOne(); 1206 1207 auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer()); 1208 if (CIInit && CIInit->getValue().getActiveBits() <= 64) { 1209 uint64_t ValInit = CIInit->getZExtValue(); 1210 uint64_t ValOther = CI->getZExtValue(); 1211 uint64_t ValMinus = ValOther - ValInit; 1212 1213 for(auto *GVe : GVs){ 1214 DIGlobalVariable *DGV = GVe->getVariable(); 1215 DIExpression *E = GVe->getExpression(); 1216 const DataLayout &DL = GV->getParent()->getDataLayout(); 1217 unsigned SizeInOctets = 1218 DL.getTypeAllocSizeInBits(NewGV->getValueType()) / 8; 1219 1220 // It is expected that the address of global optimized variable is on 1221 // top of the stack. After optimization, value of that variable will 1222 // be ether 0 for initial value or 1 for other value. The following 1223 // expression should return constant integer value depending on the 1224 // value at global object address: 1225 // val * (ValOther - ValInit) + ValInit: 1226 // DW_OP_deref DW_OP_constu <ValMinus> 1227 // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value 1228 SmallVector<uint64_t, 12> Ops = { 1229 dwarf::DW_OP_deref_size, SizeInOctets, 1230 dwarf::DW_OP_constu, ValMinus, 1231 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit, 1232 dwarf::DW_OP_plus}; 1233 bool WithStackValue = true; 1234 E = DIExpression::prependOpcodes(E, Ops, WithStackValue); 1235 DIGlobalVariableExpression *DGVE = 1236 DIGlobalVariableExpression::get(NewGV->getContext(), DGV, E); 1237 NewGV->addDebugInfo(DGVE); 1238 } 1239 EmitOneOrZero = false; 1240 } 1241 } 1242 1243 if (EmitOneOrZero) { 1244 // FIXME: This will only emit address for debugger on which will 1245 // be written only 0 or 1. 1246 for(auto *GV : GVs) 1247 NewGV->addDebugInfo(GV); 1248 } 1249 1250 while (!GV->use_empty()) { 1251 Instruction *UI = cast<Instruction>(GV->user_back()); 1252 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 1253 // Change the store into a boolean store. 1254 bool StoringOther = SI->getOperand(0) == OtherVal; 1255 // Only do this if we weren't storing a loaded value. 1256 Value *StoreVal; 1257 if (StoringOther || SI->getOperand(0) == InitVal) { 1258 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()), 1259 StoringOther); 1260 } else { 1261 // Otherwise, we are storing a previously loaded copy. To do this, 1262 // change the copy from copying the original value to just copying the 1263 // bool. 1264 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); 1265 1266 // If we've already replaced the input, StoredVal will be a cast or 1267 // select instruction. If not, it will be a load of the original 1268 // global. 1269 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 1270 assert(LI->getOperand(0) == GV && "Not a copy!"); 1271 // Insert a new load, to preserve the saved value. 1272 StoreVal = new LoadInst(NewGV->getValueType(), NewGV, 1273 LI->getName() + ".b", false, Align(1), 1274 LI->getOrdering(), LI->getSyncScopeID(), LI); 1275 } else { 1276 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && 1277 "This is not a form that we understand!"); 1278 StoreVal = StoredVal->getOperand(0); 1279 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); 1280 } 1281 } 1282 StoreInst *NSI = 1283 new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(), 1284 SI->getSyncScopeID(), SI); 1285 NSI->setDebugLoc(SI->getDebugLoc()); 1286 } else { 1287 // Change the load into a load of bool then a select. 1288 LoadInst *LI = cast<LoadInst>(UI); 1289 LoadInst *NLI = new LoadInst(NewGV->getValueType(), NewGV, 1290 LI->getName() + ".b", false, Align(1), 1291 LI->getOrdering(), LI->getSyncScopeID(), LI); 1292 Instruction *NSI; 1293 if (IsOneZero) 1294 NSI = new ZExtInst(NLI, LI->getType(), "", LI); 1295 else 1296 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI); 1297 NSI->takeName(LI); 1298 // Since LI is split into two instructions, NLI and NSI both inherit the 1299 // same DebugLoc 1300 NLI->setDebugLoc(LI->getDebugLoc()); 1301 NSI->setDebugLoc(LI->getDebugLoc()); 1302 LI->replaceAllUsesWith(NSI); 1303 } 1304 UI->eraseFromParent(); 1305 } 1306 1307 // Retain the name of the old global variable. People who are debugging their 1308 // programs may expect these variables to be named the same. 1309 NewGV->takeName(GV); 1310 GV->eraseFromParent(); 1311 return true; 1312 } 1313 1314 static bool deleteIfDead( 1315 GlobalValue &GV, SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 1316 GV.removeDeadConstantUsers(); 1317 1318 if (!GV.isDiscardableIfUnused() && !GV.isDeclaration()) 1319 return false; 1320 1321 if (const Comdat *C = GV.getComdat()) 1322 if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C)) 1323 return false; 1324 1325 bool Dead; 1326 if (auto *F = dyn_cast<Function>(&GV)) 1327 Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead(); 1328 else 1329 Dead = GV.use_empty(); 1330 if (!Dead) 1331 return false; 1332 1333 LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n"); 1334 GV.eraseFromParent(); 1335 ++NumDeleted; 1336 return true; 1337 } 1338 1339 static bool isPointerValueDeadOnEntryToFunction( 1340 const Function *F, GlobalValue *GV, 1341 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1342 // Find all uses of GV. We expect them all to be in F, and if we can't 1343 // identify any of the uses we bail out. 1344 // 1345 // On each of these uses, identify if the memory that GV points to is 1346 // used/required/live at the start of the function. If it is not, for example 1347 // if the first thing the function does is store to the GV, the GV can 1348 // possibly be demoted. 1349 // 1350 // We don't do an exhaustive search for memory operations - simply look 1351 // through bitcasts as they're quite common and benign. 1352 const DataLayout &DL = GV->getParent()->getDataLayout(); 1353 SmallVector<LoadInst *, 4> Loads; 1354 SmallVector<StoreInst *, 4> Stores; 1355 for (auto *U : GV->users()) { 1356 if (Operator::getOpcode(U) == Instruction::BitCast) { 1357 for (auto *UU : U->users()) { 1358 if (auto *LI = dyn_cast<LoadInst>(UU)) 1359 Loads.push_back(LI); 1360 else if (auto *SI = dyn_cast<StoreInst>(UU)) 1361 Stores.push_back(SI); 1362 else 1363 return false; 1364 } 1365 continue; 1366 } 1367 1368 Instruction *I = dyn_cast<Instruction>(U); 1369 if (!I) 1370 return false; 1371 assert(I->getParent()->getParent() == F); 1372 1373 if (auto *LI = dyn_cast<LoadInst>(I)) 1374 Loads.push_back(LI); 1375 else if (auto *SI = dyn_cast<StoreInst>(I)) 1376 Stores.push_back(SI); 1377 else 1378 return false; 1379 } 1380 1381 // We have identified all uses of GV into loads and stores. Now check if all 1382 // of them are known not to depend on the value of the global at the function 1383 // entry point. We do this by ensuring that every load is dominated by at 1384 // least one store. 1385 auto &DT = LookupDomTree(*const_cast<Function *>(F)); 1386 1387 // The below check is quadratic. Check we're not going to do too many tests. 1388 // FIXME: Even though this will always have worst-case quadratic time, we 1389 // could put effort into minimizing the average time by putting stores that 1390 // have been shown to dominate at least one load at the beginning of the 1391 // Stores array, making subsequent dominance checks more likely to succeed 1392 // early. 1393 // 1394 // The threshold here is fairly large because global->local demotion is a 1395 // very powerful optimization should it fire. 1396 const unsigned Threshold = 100; 1397 if (Loads.size() * Stores.size() > Threshold) 1398 return false; 1399 1400 for (auto *L : Loads) { 1401 auto *LTy = L->getType(); 1402 if (none_of(Stores, [&](const StoreInst *S) { 1403 auto *STy = S->getValueOperand()->getType(); 1404 // The load is only dominated by the store if DomTree says so 1405 // and the number of bits loaded in L is less than or equal to 1406 // the number of bits stored in S. 1407 return DT.dominates(S, L) && 1408 DL.getTypeStoreSize(LTy).getFixedSize() <= 1409 DL.getTypeStoreSize(STy).getFixedSize(); 1410 })) 1411 return false; 1412 } 1413 // All loads have known dependences inside F, so the global can be localized. 1414 return true; 1415 } 1416 1417 /// C may have non-instruction users. Can all of those users be turned into 1418 /// instructions? 1419 static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C) { 1420 // We don't do this exhaustively. The most common pattern that we really need 1421 // to care about is a constant GEP or constant bitcast - so just looking 1422 // through one single ConstantExpr. 1423 // 1424 // The set of constants that this function returns true for must be able to be 1425 // handled by makeAllConstantUsesInstructions. 1426 for (auto *U : C->users()) { 1427 if (isa<Instruction>(U)) 1428 continue; 1429 if (!isa<ConstantExpr>(U)) 1430 // Non instruction, non-constantexpr user; cannot convert this. 1431 return false; 1432 for (auto *UU : U->users()) 1433 if (!isa<Instruction>(UU)) 1434 // A constantexpr used by another constant. We don't try and recurse any 1435 // further but just bail out at this point. 1436 return false; 1437 } 1438 1439 return true; 1440 } 1441 1442 /// C may have non-instruction users, and 1443 /// allNonInstructionUsersCanBeMadeInstructions has returned true. Convert the 1444 /// non-instruction users to instructions. 1445 static void makeAllConstantUsesInstructions(Constant *C) { 1446 SmallVector<ConstantExpr*,4> Users; 1447 for (auto *U : C->users()) { 1448 if (isa<ConstantExpr>(U)) 1449 Users.push_back(cast<ConstantExpr>(U)); 1450 else 1451 // We should never get here; allNonInstructionUsersCanBeMadeInstructions 1452 // should not have returned true for C. 1453 assert( 1454 isa<Instruction>(U) && 1455 "Can't transform non-constantexpr non-instruction to instruction!"); 1456 } 1457 1458 SmallVector<Value*,4> UUsers; 1459 for (auto *U : Users) { 1460 UUsers.clear(); 1461 append_range(UUsers, U->users()); 1462 for (auto *UU : UUsers) { 1463 Instruction *UI = cast<Instruction>(UU); 1464 Instruction *NewU = U->getAsInstruction(UI); 1465 UI->replaceUsesOfWith(U, NewU); 1466 } 1467 // We've replaced all the uses, so destroy the constant. (destroyConstant 1468 // will update value handles and metadata.) 1469 U->destroyConstant(); 1470 } 1471 } 1472 1473 /// Analyze the specified global variable and optimize 1474 /// it if possible. If we make a change, return true. 1475 static bool 1476 processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, 1477 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1478 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1479 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1480 auto &DL = GV->getParent()->getDataLayout(); 1481 // If this is a first class global and has only one accessing function and 1482 // this function is non-recursive, we replace the global with a local alloca 1483 // in this function. 1484 // 1485 // NOTE: It doesn't make sense to promote non-single-value types since we 1486 // are just replacing static memory to stack memory. 1487 // 1488 // If the global is in different address space, don't bring it to stack. 1489 if (!GS.HasMultipleAccessingFunctions && 1490 GS.AccessingFunction && 1491 GV->getValueType()->isSingleValueType() && 1492 GV->getType()->getAddressSpace() == 0 && 1493 !GV->isExternallyInitialized() && 1494 allNonInstructionUsersCanBeMadeInstructions(GV) && 1495 GS.AccessingFunction->doesNotRecurse() && 1496 isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV, 1497 LookupDomTree)) { 1498 const DataLayout &DL = GV->getParent()->getDataLayout(); 1499 1500 LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n"); 1501 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction 1502 ->getEntryBlock().begin()); 1503 Type *ElemTy = GV->getValueType(); 1504 // FIXME: Pass Global's alignment when globals have alignment 1505 AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(), nullptr, 1506 GV->getName(), &FirstI); 1507 if (!isa<UndefValue>(GV->getInitializer())) 1508 new StoreInst(GV->getInitializer(), Alloca, &FirstI); 1509 1510 makeAllConstantUsesInstructions(GV); 1511 1512 GV->replaceAllUsesWith(Alloca); 1513 GV->eraseFromParent(); 1514 ++NumLocalized; 1515 return true; 1516 } 1517 1518 bool Changed = false; 1519 1520 // If the global is never loaded (but may be stored to), it is dead. 1521 // Delete it now. 1522 if (!GS.IsLoaded) { 1523 LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n"); 1524 1525 if (isLeakCheckerRoot(GV)) { 1526 // Delete any constant stores to the global. 1527 Changed = CleanupPointerRootUsers(GV, GetTLI); 1528 } else { 1529 // Delete any stores we can find to the global. We may not be able to 1530 // make it completely dead though. 1531 Changed = CleanupConstantGlobalUsers(GV, DL); 1532 } 1533 1534 // If the global is dead now, delete it. 1535 if (GV->use_empty()) { 1536 GV->eraseFromParent(); 1537 ++NumDeleted; 1538 Changed = true; 1539 } 1540 return Changed; 1541 1542 } 1543 if (GS.StoredType <= GlobalStatus::InitializerStored) { 1544 LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n"); 1545 1546 // Don't actually mark a global constant if it's atomic because atomic loads 1547 // are implemented by a trivial cmpxchg in some edge-cases and that usually 1548 // requires write access to the variable even if it's not actually changed. 1549 if (GS.Ordering == AtomicOrdering::NotAtomic) { 1550 assert(!GV->isConstant() && "Expected a non-constant global"); 1551 GV->setConstant(true); 1552 Changed = true; 1553 } 1554 1555 // Clean up any obviously simplifiable users now. 1556 Changed |= CleanupConstantGlobalUsers(GV, DL); 1557 1558 // If the global is dead now, just nuke it. 1559 if (GV->use_empty()) { 1560 LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify " 1561 << "all users and delete global!\n"); 1562 GV->eraseFromParent(); 1563 ++NumDeleted; 1564 return true; 1565 } 1566 1567 // Fall through to the next check; see if we can optimize further. 1568 ++NumMarked; 1569 } 1570 if (!GV->getInitializer()->getType()->isSingleValueType()) { 1571 const DataLayout &DL = GV->getParent()->getDataLayout(); 1572 if (SRAGlobal(GV, DL)) 1573 return true; 1574 } 1575 Value *StoredOnceValue = GS.getStoredOnceValue(); 1576 if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) { 1577 // Avoid speculating constant expressions that might trap (div/rem). 1578 auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue); 1579 if (SOVConstant && SOVConstant->canTrap()) 1580 return Changed; 1581 1582 Function &StoreFn = 1583 const_cast<Function &>(*GS.StoredOnceStore->getFunction()); 1584 bool CanHaveNonUndefGlobalInitializer = 1585 GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace( 1586 GV->getType()->getAddressSpace()); 1587 // If the initial value for the global was an undef value, and if only 1588 // one other value was stored into it, we can just change the 1589 // initializer to be the stored value, then delete all stores to the 1590 // global. This allows us to mark it constant. 1591 // This is restricted to address spaces that allow globals to have 1592 // initializers. NVPTX, for example, does not support initializers for 1593 // shared memory (AS 3). 1594 if (SOVConstant && SOVConstant->getType() == GV->getValueType() && 1595 isa<UndefValue>(GV->getInitializer()) && 1596 CanHaveNonUndefGlobalInitializer) { 1597 // Change the initial value here. 1598 GV->setInitializer(SOVConstant); 1599 1600 // Clean up any obviously simplifiable users now. 1601 CleanupConstantGlobalUsers(GV, DL); 1602 1603 if (GV->use_empty()) { 1604 LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to " 1605 << "simplify all users and delete global!\n"); 1606 GV->eraseFromParent(); 1607 ++NumDeleted; 1608 } 1609 ++NumSubstitute; 1610 return true; 1611 } 1612 1613 // Try to optimize globals based on the knowledge that only one value 1614 // (besides its initializer) is ever stored to the global. 1615 if (optimizeOnceStoredGlobal(GV, StoredOnceValue, GS.Ordering, DL, GetTLI)) 1616 return true; 1617 1618 // Otherwise, if the global was not a boolean, we can shrink it to be a 1619 // boolean. Skip this optimization for AS that doesn't allow an initializer. 1620 if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic && 1621 (!isa<UndefValue>(GV->getInitializer()) || 1622 CanHaveNonUndefGlobalInitializer)) { 1623 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) { 1624 ++NumShrunkToBool; 1625 return true; 1626 } 1627 } 1628 } 1629 1630 return Changed; 1631 } 1632 1633 /// Analyze the specified global variable and optimize it if possible. If we 1634 /// make a change, return true. 1635 static bool 1636 processGlobal(GlobalValue &GV, 1637 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1638 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1639 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1640 if (GV.getName().startswith("llvm.")) 1641 return false; 1642 1643 GlobalStatus GS; 1644 1645 if (GlobalStatus::analyzeGlobal(&GV, GS)) 1646 return false; 1647 1648 bool Changed = false; 1649 if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) { 1650 auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global 1651 : GlobalValue::UnnamedAddr::Local; 1652 if (NewUnnamedAddr != GV.getUnnamedAddr()) { 1653 GV.setUnnamedAddr(NewUnnamedAddr); 1654 NumUnnamed++; 1655 Changed = true; 1656 } 1657 } 1658 1659 // Do more involved optimizations if the global is internal. 1660 if (!GV.hasLocalLinkage()) 1661 return Changed; 1662 1663 auto *GVar = dyn_cast<GlobalVariable>(&GV); 1664 if (!GVar) 1665 return Changed; 1666 1667 if (GVar->isConstant() || !GVar->hasInitializer()) 1668 return Changed; 1669 1670 return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) || 1671 Changed; 1672 } 1673 1674 /// Walk all of the direct calls of the specified function, changing them to 1675 /// FastCC. 1676 static void ChangeCalleesToFastCall(Function *F) { 1677 for (User *U : F->users()) { 1678 if (isa<BlockAddress>(U)) 1679 continue; 1680 cast<CallBase>(U)->setCallingConv(CallingConv::Fast); 1681 } 1682 } 1683 1684 static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, 1685 Attribute::AttrKind A) { 1686 unsigned AttrIndex; 1687 if (Attrs.hasAttrSomewhere(A, &AttrIndex)) 1688 return Attrs.removeAttributeAtIndex(C, AttrIndex, A); 1689 return Attrs; 1690 } 1691 1692 static void RemoveAttribute(Function *F, Attribute::AttrKind A) { 1693 F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A)); 1694 for (User *U : F->users()) { 1695 if (isa<BlockAddress>(U)) 1696 continue; 1697 CallBase *CB = cast<CallBase>(U); 1698 CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A)); 1699 } 1700 } 1701 1702 /// Return true if this is a calling convention that we'd like to change. The 1703 /// idea here is that we don't want to mess with the convention if the user 1704 /// explicitly requested something with performance implications like coldcc, 1705 /// GHC, or anyregcc. 1706 static bool hasChangeableCC(Function *F) { 1707 CallingConv::ID CC = F->getCallingConv(); 1708 1709 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc? 1710 if (CC != CallingConv::C && CC != CallingConv::X86_ThisCall) 1711 return false; 1712 1713 // FIXME: Change CC for the whole chain of musttail calls when possible. 1714 // 1715 // Can't change CC of the function that either has musttail calls, or is a 1716 // musttail callee itself 1717 for (User *U : F->users()) { 1718 if (isa<BlockAddress>(U)) 1719 continue; 1720 CallInst* CI = dyn_cast<CallInst>(U); 1721 if (!CI) 1722 continue; 1723 1724 if (CI->isMustTailCall()) 1725 return false; 1726 } 1727 1728 for (BasicBlock &BB : *F) 1729 if (BB.getTerminatingMustTailCall()) 1730 return false; 1731 1732 return true; 1733 } 1734 1735 /// Return true if the block containing the call site has a BlockFrequency of 1736 /// less than ColdCCRelFreq% of the entry block. 1737 static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) { 1738 const BranchProbability ColdProb(ColdCCRelFreq, 100); 1739 auto *CallSiteBB = CB.getParent(); 1740 auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB); 1741 auto CallerEntryFreq = 1742 CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock())); 1743 return CallSiteFreq < CallerEntryFreq * ColdProb; 1744 } 1745 1746 // This function checks if the input function F is cold at all call sites. It 1747 // also looks each call site's containing function, returning false if the 1748 // caller function contains other non cold calls. The input vector AllCallsCold 1749 // contains a list of functions that only have call sites in cold blocks. 1750 static bool 1751 isValidCandidateForColdCC(Function &F, 1752 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 1753 const std::vector<Function *> &AllCallsCold) { 1754 1755 if (F.user_empty()) 1756 return false; 1757 1758 for (User *U : F.users()) { 1759 if (isa<BlockAddress>(U)) 1760 continue; 1761 1762 CallBase &CB = cast<CallBase>(*U); 1763 Function *CallerFunc = CB.getParent()->getParent(); 1764 BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc); 1765 if (!isColdCallSite(CB, CallerBFI)) 1766 return false; 1767 if (!llvm::is_contained(AllCallsCold, CallerFunc)) 1768 return false; 1769 } 1770 return true; 1771 } 1772 1773 static void changeCallSitesToColdCC(Function *F) { 1774 for (User *U : F->users()) { 1775 if (isa<BlockAddress>(U)) 1776 continue; 1777 cast<CallBase>(U)->setCallingConv(CallingConv::Cold); 1778 } 1779 } 1780 1781 // This function iterates over all the call instructions in the input Function 1782 // and checks that all call sites are in cold blocks and are allowed to use the 1783 // coldcc calling convention. 1784 static bool 1785 hasOnlyColdCalls(Function &F, 1786 function_ref<BlockFrequencyInfo &(Function &)> GetBFI) { 1787 for (BasicBlock &BB : F) { 1788 for (Instruction &I : BB) { 1789 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 1790 // Skip over isline asm instructions since they aren't function calls. 1791 if (CI->isInlineAsm()) 1792 continue; 1793 Function *CalledFn = CI->getCalledFunction(); 1794 if (!CalledFn) 1795 return false; 1796 if (!CalledFn->hasLocalLinkage()) 1797 return false; 1798 // Skip over instrinsics since they won't remain as function calls. 1799 if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic) 1800 continue; 1801 // Check if it's valid to use coldcc calling convention. 1802 if (!hasChangeableCC(CalledFn) || CalledFn->isVarArg() || 1803 CalledFn->hasAddressTaken()) 1804 return false; 1805 BlockFrequencyInfo &CallerBFI = GetBFI(F); 1806 if (!isColdCallSite(*CI, CallerBFI)) 1807 return false; 1808 } 1809 } 1810 } 1811 return true; 1812 } 1813 1814 static bool hasMustTailCallers(Function *F) { 1815 for (User *U : F->users()) { 1816 CallBase *CB = dyn_cast<CallBase>(U); 1817 if (!CB) { 1818 assert(isa<BlockAddress>(U) && 1819 "Expected either CallBase or BlockAddress"); 1820 continue; 1821 } 1822 if (CB->isMustTailCall()) 1823 return true; 1824 } 1825 return false; 1826 } 1827 1828 static bool hasInvokeCallers(Function *F) { 1829 for (User *U : F->users()) 1830 if (isa<InvokeInst>(U)) 1831 return true; 1832 return false; 1833 } 1834 1835 static void RemovePreallocated(Function *F) { 1836 RemoveAttribute(F, Attribute::Preallocated); 1837 1838 auto *M = F->getParent(); 1839 1840 IRBuilder<> Builder(M->getContext()); 1841 1842 // Cannot modify users() while iterating over it, so make a copy. 1843 SmallVector<User *, 4> PreallocatedCalls(F->users()); 1844 for (User *U : PreallocatedCalls) { 1845 CallBase *CB = dyn_cast<CallBase>(U); 1846 if (!CB) 1847 continue; 1848 1849 assert( 1850 !CB->isMustTailCall() && 1851 "Shouldn't call RemotePreallocated() on a musttail preallocated call"); 1852 // Create copy of call without "preallocated" operand bundle. 1853 SmallVector<OperandBundleDef, 1> OpBundles; 1854 CB->getOperandBundlesAsDefs(OpBundles); 1855 CallBase *PreallocatedSetup = nullptr; 1856 for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) { 1857 if (It->getTag() == "preallocated") { 1858 PreallocatedSetup = cast<CallBase>(*It->input_begin()); 1859 OpBundles.erase(It); 1860 break; 1861 } 1862 } 1863 assert(PreallocatedSetup && "Did not find preallocated bundle"); 1864 uint64_t ArgCount = 1865 cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue(); 1866 1867 assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) && 1868 "Unknown indirect call type"); 1869 CallBase *NewCB = CallBase::Create(CB, OpBundles, CB); 1870 CB->replaceAllUsesWith(NewCB); 1871 NewCB->takeName(CB); 1872 CB->eraseFromParent(); 1873 1874 Builder.SetInsertPoint(PreallocatedSetup); 1875 auto *StackSave = 1876 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stacksave)); 1877 1878 Builder.SetInsertPoint(NewCB->getNextNonDebugInstruction()); 1879 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackrestore), 1880 StackSave); 1881 1882 // Replace @llvm.call.preallocated.arg() with alloca. 1883 // Cannot modify users() while iterating over it, so make a copy. 1884 // @llvm.call.preallocated.arg() can be called with the same index multiple 1885 // times. So for each @llvm.call.preallocated.arg(), we see if we have 1886 // already created a Value* for the index, and if not, create an alloca and 1887 // bitcast right after the @llvm.call.preallocated.setup() so that it 1888 // dominates all uses. 1889 SmallVector<Value *, 2> ArgAllocas(ArgCount); 1890 SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users()); 1891 for (auto *User : PreallocatedArgs) { 1892 auto *UseCall = cast<CallBase>(User); 1893 assert(UseCall->getCalledFunction()->getIntrinsicID() == 1894 Intrinsic::call_preallocated_arg && 1895 "preallocated token use was not a llvm.call.preallocated.arg"); 1896 uint64_t AllocArgIndex = 1897 cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue(); 1898 Value *AllocaReplacement = ArgAllocas[AllocArgIndex]; 1899 if (!AllocaReplacement) { 1900 auto AddressSpace = UseCall->getType()->getPointerAddressSpace(); 1901 auto *ArgType = 1902 UseCall->getFnAttr(Attribute::Preallocated).getValueAsType(); 1903 auto *InsertBefore = PreallocatedSetup->getNextNonDebugInstruction(); 1904 Builder.SetInsertPoint(InsertBefore); 1905 auto *Alloca = 1906 Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg"); 1907 auto *BitCast = Builder.CreateBitCast( 1908 Alloca, Type::getInt8PtrTy(M->getContext()), UseCall->getName()); 1909 ArgAllocas[AllocArgIndex] = BitCast; 1910 AllocaReplacement = BitCast; 1911 } 1912 1913 UseCall->replaceAllUsesWith(AllocaReplacement); 1914 UseCall->eraseFromParent(); 1915 } 1916 // Remove @llvm.call.preallocated.setup(). 1917 cast<Instruction>(PreallocatedSetup)->eraseFromParent(); 1918 } 1919 } 1920 1921 static bool 1922 OptimizeFunctions(Module &M, 1923 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1924 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1925 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 1926 function_ref<DominatorTree &(Function &)> LookupDomTree, 1927 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 1928 1929 bool Changed = false; 1930 1931 std::vector<Function *> AllCallsCold; 1932 for (Function &F : llvm::make_early_inc_range(M)) 1933 if (hasOnlyColdCalls(F, GetBFI)) 1934 AllCallsCold.push_back(&F); 1935 1936 // Optimize functions. 1937 for (Function &F : llvm::make_early_inc_range(M)) { 1938 // Don't perform global opt pass on naked functions; we don't want fast 1939 // calling conventions for naked functions. 1940 if (F.hasFnAttribute(Attribute::Naked)) 1941 continue; 1942 1943 // Functions without names cannot be referenced outside this module. 1944 if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage()) 1945 F.setLinkage(GlobalValue::InternalLinkage); 1946 1947 if (deleteIfDead(F, NotDiscardableComdats)) { 1948 Changed = true; 1949 continue; 1950 } 1951 1952 // LLVM's definition of dominance allows instructions that are cyclic 1953 // in unreachable blocks, e.g.: 1954 // %pat = select i1 %condition, @global, i16* %pat 1955 // because any instruction dominates an instruction in a block that's 1956 // not reachable from entry. 1957 // So, remove unreachable blocks from the function, because a) there's 1958 // no point in analyzing them and b) GlobalOpt should otherwise grow 1959 // some more complicated logic to break these cycles. 1960 // Removing unreachable blocks might invalidate the dominator so we 1961 // recalculate it. 1962 if (!F.isDeclaration()) { 1963 if (removeUnreachableBlocks(F)) { 1964 auto &DT = LookupDomTree(F); 1965 DT.recalculate(F); 1966 Changed = true; 1967 } 1968 } 1969 1970 Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree); 1971 1972 if (!F.hasLocalLinkage()) 1973 continue; 1974 1975 // If we have an inalloca parameter that we can safely remove the 1976 // inalloca attribute from, do so. This unlocks optimizations that 1977 // wouldn't be safe in the presence of inalloca. 1978 // FIXME: We should also hoist alloca affected by this to the entry 1979 // block if possible. 1980 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) && 1981 !F.hasAddressTaken() && !hasMustTailCallers(&F)) { 1982 RemoveAttribute(&F, Attribute::InAlloca); 1983 Changed = true; 1984 } 1985 1986 // FIXME: handle invokes 1987 // FIXME: handle musttail 1988 if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) { 1989 if (!F.hasAddressTaken() && !hasMustTailCallers(&F) && 1990 !hasInvokeCallers(&F)) { 1991 RemovePreallocated(&F); 1992 Changed = true; 1993 } 1994 continue; 1995 } 1996 1997 if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) { 1998 NumInternalFunc++; 1999 TargetTransformInfo &TTI = GetTTI(F); 2000 // Change the calling convention to coldcc if either stress testing is 2001 // enabled or the target would like to use coldcc on functions which are 2002 // cold at all call sites and the callers contain no other non coldcc 2003 // calls. 2004 if (EnableColdCCStressTest || 2005 (TTI.useColdCCForColdCall(F) && 2006 isValidCandidateForColdCC(F, GetBFI, AllCallsCold))) { 2007 F.setCallingConv(CallingConv::Cold); 2008 changeCallSitesToColdCC(&F); 2009 Changed = true; 2010 NumColdCC++; 2011 } 2012 } 2013 2014 if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) { 2015 // If this function has a calling convention worth changing, is not a 2016 // varargs function, and is only called directly, promote it to use the 2017 // Fast calling convention. 2018 F.setCallingConv(CallingConv::Fast); 2019 ChangeCalleesToFastCall(&F); 2020 ++NumFastCallFns; 2021 Changed = true; 2022 } 2023 2024 if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) && 2025 !F.hasAddressTaken()) { 2026 // The function is not used by a trampoline intrinsic, so it is safe 2027 // to remove the 'nest' attribute. 2028 RemoveAttribute(&F, Attribute::Nest); 2029 ++NumNestRemoved; 2030 Changed = true; 2031 } 2032 } 2033 return Changed; 2034 } 2035 2036 static bool 2037 OptimizeGlobalVars(Module &M, 2038 function_ref<TargetTransformInfo &(Function &)> GetTTI, 2039 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 2040 function_ref<DominatorTree &(Function &)> LookupDomTree, 2041 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 2042 bool Changed = false; 2043 2044 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) { 2045 // Global variables without names cannot be referenced outside this module. 2046 if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage()) 2047 GV.setLinkage(GlobalValue::InternalLinkage); 2048 // Simplify the initializer. 2049 if (GV.hasInitializer()) 2050 if (auto *C = dyn_cast<Constant>(GV.getInitializer())) { 2051 auto &DL = M.getDataLayout(); 2052 // TLI is not used in the case of a Constant, so use default nullptr 2053 // for that optional parameter, since we don't have a Function to 2054 // provide GetTLI anyway. 2055 Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr); 2056 if (New != C) 2057 GV.setInitializer(New); 2058 } 2059 2060 if (deleteIfDead(GV, NotDiscardableComdats)) { 2061 Changed = true; 2062 continue; 2063 } 2064 2065 Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree); 2066 } 2067 return Changed; 2068 } 2069 2070 /// Evaluate a piece of a constantexpr store into a global initializer. This 2071 /// returns 'Init' modified to reflect 'Val' stored into it. At this point, the 2072 /// GEP operands of Addr [0, OpNo) have been stepped into. 2073 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val, 2074 ConstantExpr *Addr, unsigned OpNo) { 2075 // Base case of the recursion. 2076 if (OpNo == Addr->getNumOperands()) { 2077 assert(Val->getType() == Init->getType() && "Type mismatch!"); 2078 return Val; 2079 } 2080 2081 SmallVector<Constant*, 32> Elts; 2082 if (StructType *STy = dyn_cast<StructType>(Init->getType())) { 2083 // Break up the constant into its elements. 2084 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 2085 Elts.push_back(Init->getAggregateElement(i)); 2086 2087 // Replace the element that we are supposed to. 2088 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo)); 2089 unsigned Idx = CU->getZExtValue(); 2090 assert(Idx < STy->getNumElements() && "Struct index out of range!"); 2091 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1); 2092 2093 // Return the modified struct. 2094 return ConstantStruct::get(STy, Elts); 2095 } 2096 2097 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo)); 2098 uint64_t NumElts; 2099 if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) 2100 NumElts = ATy->getNumElements(); 2101 else 2102 NumElts = cast<FixedVectorType>(Init->getType())->getNumElements(); 2103 2104 // Break up the array into elements. 2105 for (uint64_t i = 0, e = NumElts; i != e; ++i) 2106 Elts.push_back(Init->getAggregateElement(i)); 2107 2108 assert(CI->getZExtValue() < NumElts); 2109 Elts[CI->getZExtValue()] = 2110 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1); 2111 2112 if (Init->getType()->isArrayTy()) 2113 return ConstantArray::get(cast<ArrayType>(Init->getType()), Elts); 2114 return ConstantVector::get(Elts); 2115 } 2116 2117 /// We have decided that Addr (which satisfies the predicate 2118 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen. 2119 static void CommitValueTo(Constant *Val, Constant *Addr) { 2120 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) { 2121 assert(GV->hasInitializer()); 2122 GV->setInitializer(Val); 2123 return; 2124 } 2125 2126 ConstantExpr *CE = cast<ConstantExpr>(Addr); 2127 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2128 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2)); 2129 } 2130 2131 /// Given a map of address -> value, where addresses are expected to be some form 2132 /// of either a global or a constant GEP, set the initializer for the address to 2133 /// be the value. This performs mostly the same function as CommitValueTo() 2134 /// and EvaluateStoreInto() but is optimized to be more efficient for the common 2135 /// case where the set of addresses are GEPs sharing the same underlying global, 2136 /// processing the GEPs in batches rather than individually. 2137 /// 2138 /// To give an example, consider the following C++ code adapted from the clang 2139 /// regression tests: 2140 /// struct S { 2141 /// int n = 10; 2142 /// int m = 2 * n; 2143 /// S(int a) : n(a) {} 2144 /// }; 2145 /// 2146 /// template<typename T> 2147 /// struct U { 2148 /// T *r = &q; 2149 /// T q = 42; 2150 /// U *p = this; 2151 /// }; 2152 /// 2153 /// U<S> e; 2154 /// 2155 /// The global static constructor for 'e' will need to initialize 'r' and 'p' of 2156 /// the outer struct, while also initializing the inner 'q' structs 'n' and 'm' 2157 /// members. This batch algorithm will simply use general CommitValueTo() method 2158 /// to handle the complex nested S struct initialization of 'q', before 2159 /// processing the outermost members in a single batch. Using CommitValueTo() to 2160 /// handle member in the outer struct is inefficient when the struct/array is 2161 /// very large as we end up creating and destroy constant arrays for each 2162 /// initialization. 2163 /// For the above case, we expect the following IR to be generated: 2164 /// 2165 /// %struct.U = type { %struct.S*, %struct.S, %struct.U* } 2166 /// %struct.S = type { i32, i32 } 2167 /// @e = global %struct.U { %struct.S* gep inbounds (%struct.U, %struct.U* @e, 2168 /// i64 0, i32 1), 2169 /// %struct.S { i32 42, i32 84 }, %struct.U* @e } 2170 /// The %struct.S { i32 42, i32 84 } inner initializer is treated as a complex 2171 /// constant expression, while the other two elements of @e are "simple". 2172 static void BatchCommitValueTo(const DenseMap<Constant*, Constant*> &Mem) { 2173 SmallVector<std::pair<GlobalVariable*, Constant*>, 32> GVs; 2174 SmallVector<std::pair<ConstantExpr*, Constant*>, 32> ComplexCEs; 2175 SmallVector<std::pair<ConstantExpr*, Constant*>, 32> SimpleCEs; 2176 SimpleCEs.reserve(Mem.size()); 2177 2178 for (const auto &I : Mem) { 2179 if (auto *GV = dyn_cast<GlobalVariable>(I.first)) { 2180 GVs.push_back(std::make_pair(GV, I.second)); 2181 } else { 2182 ConstantExpr *GEP = cast<ConstantExpr>(I.first); 2183 // We don't handle the deeply recursive case using the batch method. 2184 if (GEP->getNumOperands() > 3) 2185 ComplexCEs.push_back(std::make_pair(GEP, I.second)); 2186 else 2187 SimpleCEs.push_back(std::make_pair(GEP, I.second)); 2188 } 2189 } 2190 2191 // The algorithm below doesn't handle cases like nested structs, so use the 2192 // slower fully general method if we have to. 2193 for (auto ComplexCE : ComplexCEs) 2194 CommitValueTo(ComplexCE.second, ComplexCE.first); 2195 2196 for (auto GVPair : GVs) { 2197 assert(GVPair.first->hasInitializer()); 2198 GVPair.first->setInitializer(GVPair.second); 2199 } 2200 2201 if (SimpleCEs.empty()) 2202 return; 2203 2204 // We cache a single global's initializer elements in the case where the 2205 // subsequent address/val pair uses the same one. This avoids throwing away and 2206 // rebuilding the constant struct/vector/array just because one element is 2207 // modified at a time. 2208 SmallVector<Constant *, 32> Elts; 2209 Elts.reserve(SimpleCEs.size()); 2210 GlobalVariable *CurrentGV = nullptr; 2211 2212 auto commitAndSetupCache = [&](GlobalVariable *GV, bool Update) { 2213 Constant *Init = GV->getInitializer(); 2214 Type *Ty = Init->getType(); 2215 if (Update) { 2216 if (CurrentGV) { 2217 assert(CurrentGV && "Expected a GV to commit to!"); 2218 Type *CurrentInitTy = CurrentGV->getInitializer()->getType(); 2219 // We have a valid cache that needs to be committed. 2220 if (StructType *STy = dyn_cast<StructType>(CurrentInitTy)) 2221 CurrentGV->setInitializer(ConstantStruct::get(STy, Elts)); 2222 else if (ArrayType *ArrTy = dyn_cast<ArrayType>(CurrentInitTy)) 2223 CurrentGV->setInitializer(ConstantArray::get(ArrTy, Elts)); 2224 else 2225 CurrentGV->setInitializer(ConstantVector::get(Elts)); 2226 } 2227 if (CurrentGV == GV) 2228 return; 2229 // Need to clear and set up cache for new initializer. 2230 CurrentGV = GV; 2231 Elts.clear(); 2232 unsigned NumElts; 2233 if (auto *STy = dyn_cast<StructType>(Ty)) 2234 NumElts = STy->getNumElements(); 2235 else if (auto *ATy = dyn_cast<ArrayType>(Ty)) 2236 NumElts = ATy->getNumElements(); 2237 else 2238 NumElts = cast<FixedVectorType>(Ty)->getNumElements(); 2239 for (unsigned i = 0, e = NumElts; i != e; ++i) 2240 Elts.push_back(Init->getAggregateElement(i)); 2241 } 2242 }; 2243 2244 for (auto CEPair : SimpleCEs) { 2245 ConstantExpr *GEP = CEPair.first; 2246 Constant *Val = CEPair.second; 2247 2248 GlobalVariable *GV = cast<GlobalVariable>(GEP->getOperand(0)); 2249 commitAndSetupCache(GV, GV != CurrentGV); 2250 ConstantInt *CI = cast<ConstantInt>(GEP->getOperand(2)); 2251 Elts[CI->getZExtValue()] = Val; 2252 } 2253 // The last initializer in the list needs to be committed, others 2254 // will be committed on a new initializer being processed. 2255 commitAndSetupCache(CurrentGV, true); 2256 } 2257 2258 /// Evaluate static constructors in the function, if we can. Return true if we 2259 /// can, false otherwise. 2260 static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, 2261 TargetLibraryInfo *TLI) { 2262 // Call the function. 2263 Evaluator Eval(DL, TLI); 2264 Constant *RetValDummy; 2265 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy, 2266 SmallVector<Constant*, 0>()); 2267 2268 if (EvalSuccess) { 2269 ++NumCtorsEvaluated; 2270 2271 // We succeeded at evaluation: commit the result. 2272 LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" 2273 << F->getName() << "' to " 2274 << Eval.getMutatedMemory().size() << " stores.\n"); 2275 BatchCommitValueTo(Eval.getMutatedMemory()); 2276 for (GlobalVariable *GV : Eval.getInvariants()) 2277 GV->setConstant(true); 2278 } 2279 2280 return EvalSuccess; 2281 } 2282 2283 static int compareNames(Constant *const *A, Constant *const *B) { 2284 Value *AStripped = (*A)->stripPointerCasts(); 2285 Value *BStripped = (*B)->stripPointerCasts(); 2286 return AStripped->getName().compare(BStripped->getName()); 2287 } 2288 2289 static void setUsedInitializer(GlobalVariable &V, 2290 const SmallPtrSetImpl<GlobalValue *> &Init) { 2291 if (Init.empty()) { 2292 V.eraseFromParent(); 2293 return; 2294 } 2295 2296 // Type of pointer to the array of pointers. 2297 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0); 2298 2299 SmallVector<Constant *, 8> UsedArray; 2300 for (GlobalValue *GV : Init) { 2301 Constant *Cast 2302 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy); 2303 UsedArray.push_back(Cast); 2304 } 2305 // Sort to get deterministic order. 2306 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames); 2307 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size()); 2308 2309 Module *M = V.getParent(); 2310 V.removeFromParent(); 2311 GlobalVariable *NV = 2312 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage, 2313 ConstantArray::get(ATy, UsedArray), ""); 2314 NV->takeName(&V); 2315 NV->setSection("llvm.metadata"); 2316 delete &V; 2317 } 2318 2319 namespace { 2320 2321 /// An easy to access representation of llvm.used and llvm.compiler.used. 2322 class LLVMUsed { 2323 SmallPtrSet<GlobalValue *, 4> Used; 2324 SmallPtrSet<GlobalValue *, 4> CompilerUsed; 2325 GlobalVariable *UsedV; 2326 GlobalVariable *CompilerUsedV; 2327 2328 public: 2329 LLVMUsed(Module &M) { 2330 SmallVector<GlobalValue *, 4> Vec; 2331 UsedV = collectUsedGlobalVariables(M, Vec, false); 2332 Used = {Vec.begin(), Vec.end()}; 2333 Vec.clear(); 2334 CompilerUsedV = collectUsedGlobalVariables(M, Vec, true); 2335 CompilerUsed = {Vec.begin(), Vec.end()}; 2336 } 2337 2338 using iterator = SmallPtrSet<GlobalValue *, 4>::iterator; 2339 using used_iterator_range = iterator_range<iterator>; 2340 2341 iterator usedBegin() { return Used.begin(); } 2342 iterator usedEnd() { return Used.end(); } 2343 2344 used_iterator_range used() { 2345 return used_iterator_range(usedBegin(), usedEnd()); 2346 } 2347 2348 iterator compilerUsedBegin() { return CompilerUsed.begin(); } 2349 iterator compilerUsedEnd() { return CompilerUsed.end(); } 2350 2351 used_iterator_range compilerUsed() { 2352 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd()); 2353 } 2354 2355 bool usedCount(GlobalValue *GV) const { return Used.count(GV); } 2356 2357 bool compilerUsedCount(GlobalValue *GV) const { 2358 return CompilerUsed.count(GV); 2359 } 2360 2361 bool usedErase(GlobalValue *GV) { return Used.erase(GV); } 2362 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); } 2363 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; } 2364 2365 bool compilerUsedInsert(GlobalValue *GV) { 2366 return CompilerUsed.insert(GV).second; 2367 } 2368 2369 void syncVariablesAndSets() { 2370 if (UsedV) 2371 setUsedInitializer(*UsedV, Used); 2372 if (CompilerUsedV) 2373 setUsedInitializer(*CompilerUsedV, CompilerUsed); 2374 } 2375 }; 2376 2377 } // end anonymous namespace 2378 2379 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) { 2380 if (GA.use_empty()) // No use at all. 2381 return false; 2382 2383 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) && 2384 "We should have removed the duplicated " 2385 "element from llvm.compiler.used"); 2386 if (!GA.hasOneUse()) 2387 // Strictly more than one use. So at least one is not in llvm.used and 2388 // llvm.compiler.used. 2389 return true; 2390 2391 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used. 2392 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA); 2393 } 2394 2395 static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, 2396 const LLVMUsed &U) { 2397 unsigned N = 2; 2398 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) && 2399 "We should have removed the duplicated " 2400 "element from llvm.compiler.used"); 2401 if (U.usedCount(&V) || U.compilerUsedCount(&V)) 2402 ++N; 2403 return V.hasNUsesOrMore(N); 2404 } 2405 2406 static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) { 2407 if (!GA.hasLocalLinkage()) 2408 return true; 2409 2410 return U.usedCount(&GA) || U.compilerUsedCount(&GA); 2411 } 2412 2413 static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, 2414 bool &RenameTarget) { 2415 RenameTarget = false; 2416 bool Ret = false; 2417 if (hasUseOtherThanLLVMUsed(GA, U)) 2418 Ret = true; 2419 2420 // If the alias is externally visible, we may still be able to simplify it. 2421 if (!mayHaveOtherReferences(GA, U)) 2422 return Ret; 2423 2424 // If the aliasee has internal linkage, give it the name and linkage 2425 // of the alias, and delete the alias. This turns: 2426 // define internal ... @f(...) 2427 // @a = alias ... @f 2428 // into: 2429 // define ... @a(...) 2430 Constant *Aliasee = GA.getAliasee(); 2431 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts()); 2432 if (!Target->hasLocalLinkage()) 2433 return Ret; 2434 2435 // Do not perform the transform if multiple aliases potentially target the 2436 // aliasee. This check also ensures that it is safe to replace the section 2437 // and other attributes of the aliasee with those of the alias. 2438 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U)) 2439 return Ret; 2440 2441 RenameTarget = true; 2442 return true; 2443 } 2444 2445 static bool 2446 OptimizeGlobalAliases(Module &M, 2447 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 2448 bool Changed = false; 2449 LLVMUsed Used(M); 2450 2451 for (GlobalValue *GV : Used.used()) 2452 Used.compilerUsedErase(GV); 2453 2454 for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) { 2455 // Aliases without names cannot be referenced outside this module. 2456 if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage()) 2457 J.setLinkage(GlobalValue::InternalLinkage); 2458 2459 if (deleteIfDead(J, NotDiscardableComdats)) { 2460 Changed = true; 2461 continue; 2462 } 2463 2464 // If the alias can change at link time, nothing can be done - bail out. 2465 if (J.isInterposable()) 2466 continue; 2467 2468 Constant *Aliasee = J.getAliasee(); 2469 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts()); 2470 // We can't trivially replace the alias with the aliasee if the aliasee is 2471 // non-trivial in some way. We also can't replace the alias with the aliasee 2472 // if the aliasee is interposable because aliases point to the local 2473 // definition. 2474 // TODO: Try to handle non-zero GEPs of local aliasees. 2475 if (!Target || Target->isInterposable()) 2476 continue; 2477 Target->removeDeadConstantUsers(); 2478 2479 // Make all users of the alias use the aliasee instead. 2480 bool RenameTarget; 2481 if (!hasUsesToReplace(J, Used, RenameTarget)) 2482 continue; 2483 2484 J.replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J.getType())); 2485 ++NumAliasesResolved; 2486 Changed = true; 2487 2488 if (RenameTarget) { 2489 // Give the aliasee the name, linkage and other attributes of the alias. 2490 Target->takeName(&J); 2491 Target->setLinkage(J.getLinkage()); 2492 Target->setDSOLocal(J.isDSOLocal()); 2493 Target->setVisibility(J.getVisibility()); 2494 Target->setDLLStorageClass(J.getDLLStorageClass()); 2495 2496 if (Used.usedErase(&J)) 2497 Used.usedInsert(Target); 2498 2499 if (Used.compilerUsedErase(&J)) 2500 Used.compilerUsedInsert(Target); 2501 } else if (mayHaveOtherReferences(J, Used)) 2502 continue; 2503 2504 // Delete the alias. 2505 M.getAliasList().erase(&J); 2506 ++NumAliasesRemoved; 2507 Changed = true; 2508 } 2509 2510 Used.syncVariablesAndSets(); 2511 2512 return Changed; 2513 } 2514 2515 static Function * 2516 FindCXAAtExit(Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 2517 // Hack to get a default TLI before we have actual Function. 2518 auto FuncIter = M.begin(); 2519 if (FuncIter == M.end()) 2520 return nullptr; 2521 auto *TLI = &GetTLI(*FuncIter); 2522 2523 LibFunc F = LibFunc_cxa_atexit; 2524 if (!TLI->has(F)) 2525 return nullptr; 2526 2527 Function *Fn = M.getFunction(TLI->getName(F)); 2528 if (!Fn) 2529 return nullptr; 2530 2531 // Now get the actual TLI for Fn. 2532 TLI = &GetTLI(*Fn); 2533 2534 // Make sure that the function has the correct prototype. 2535 if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit) 2536 return nullptr; 2537 2538 return Fn; 2539 } 2540 2541 /// Returns whether the given function is an empty C++ destructor and can 2542 /// therefore be eliminated. 2543 /// Note that we assume that other optimization passes have already simplified 2544 /// the code so we simply check for 'ret'. 2545 static bool cxxDtorIsEmpty(const Function &Fn) { 2546 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and 2547 // nounwind, but that doesn't seem worth doing. 2548 if (Fn.isDeclaration()) 2549 return false; 2550 2551 for (auto &I : Fn.getEntryBlock()) { 2552 if (I.isDebugOrPseudoInst()) 2553 continue; 2554 if (isa<ReturnInst>(I)) 2555 return true; 2556 break; 2557 } 2558 return false; 2559 } 2560 2561 static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) { 2562 /// Itanium C++ ABI p3.3.5: 2563 /// 2564 /// After constructing a global (or local static) object, that will require 2565 /// destruction on exit, a termination function is registered as follows: 2566 /// 2567 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); 2568 /// 2569 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the 2570 /// call f(p) when DSO d is unloaded, before all such termination calls 2571 /// registered before this one. It returns zero if registration is 2572 /// successful, nonzero on failure. 2573 2574 // This pass will look for calls to __cxa_atexit where the function is trivial 2575 // and remove them. 2576 bool Changed = false; 2577 2578 for (User *U : llvm::make_early_inc_range(CXAAtExitFn->users())) { 2579 // We're only interested in calls. Theoretically, we could handle invoke 2580 // instructions as well, but neither llvm-gcc nor clang generate invokes 2581 // to __cxa_atexit. 2582 CallInst *CI = dyn_cast<CallInst>(U); 2583 if (!CI) 2584 continue; 2585 2586 Function *DtorFn = 2587 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts()); 2588 if (!DtorFn || !cxxDtorIsEmpty(*DtorFn)) 2589 continue; 2590 2591 // Just remove the call. 2592 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType())); 2593 CI->eraseFromParent(); 2594 2595 ++NumCXXDtorsRemoved; 2596 2597 Changed |= true; 2598 } 2599 2600 return Changed; 2601 } 2602 2603 static bool optimizeGlobalsInModule( 2604 Module &M, const DataLayout &DL, 2605 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 2606 function_ref<TargetTransformInfo &(Function &)> GetTTI, 2607 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 2608 function_ref<DominatorTree &(Function &)> LookupDomTree) { 2609 SmallPtrSet<const Comdat *, 8> NotDiscardableComdats; 2610 bool Changed = false; 2611 bool LocalChange = true; 2612 while (LocalChange) { 2613 LocalChange = false; 2614 2615 NotDiscardableComdats.clear(); 2616 for (const GlobalVariable &GV : M.globals()) 2617 if (const Comdat *C = GV.getComdat()) 2618 if (!GV.isDiscardableIfUnused() || !GV.use_empty()) 2619 NotDiscardableComdats.insert(C); 2620 for (Function &F : M) 2621 if (const Comdat *C = F.getComdat()) 2622 if (!F.isDefTriviallyDead()) 2623 NotDiscardableComdats.insert(C); 2624 for (GlobalAlias &GA : M.aliases()) 2625 if (const Comdat *C = GA.getComdat()) 2626 if (!GA.isDiscardableIfUnused() || !GA.use_empty()) 2627 NotDiscardableComdats.insert(C); 2628 2629 // Delete functions that are trivially dead, ccc -> fastcc 2630 LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree, 2631 NotDiscardableComdats); 2632 2633 // Optimize global_ctors list. 2634 LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) { 2635 return EvaluateStaticConstructor(F, DL, &GetTLI(*F)); 2636 }); 2637 2638 // Optimize non-address-taken globals. 2639 LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree, 2640 NotDiscardableComdats); 2641 2642 // Resolve aliases, when possible. 2643 LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats); 2644 2645 // Try to remove trivial global destructors if they are not removed 2646 // already. 2647 Function *CXAAtExitFn = FindCXAAtExit(M, GetTLI); 2648 if (CXAAtExitFn) 2649 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn); 2650 2651 Changed |= LocalChange; 2652 } 2653 2654 // TODO: Move all global ctors functions to the end of the module for code 2655 // layout. 2656 2657 return Changed; 2658 } 2659 2660 PreservedAnalyses GlobalOptPass::run(Module &M, ModuleAnalysisManager &AM) { 2661 auto &DL = M.getDataLayout(); 2662 auto &FAM = 2663 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2664 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{ 2665 return FAM.getResult<DominatorTreeAnalysis>(F); 2666 }; 2667 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 2668 return FAM.getResult<TargetLibraryAnalysis>(F); 2669 }; 2670 auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & { 2671 return FAM.getResult<TargetIRAnalysis>(F); 2672 }; 2673 2674 auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & { 2675 return FAM.getResult<BlockFrequencyAnalysis>(F); 2676 }; 2677 2678 if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree)) 2679 return PreservedAnalyses::all(); 2680 return PreservedAnalyses::none(); 2681 } 2682 2683 namespace { 2684 2685 struct GlobalOptLegacyPass : public ModulePass { 2686 static char ID; // Pass identification, replacement for typeid 2687 2688 GlobalOptLegacyPass() : ModulePass(ID) { 2689 initializeGlobalOptLegacyPassPass(*PassRegistry::getPassRegistry()); 2690 } 2691 2692 bool runOnModule(Module &M) override { 2693 if (skipModule(M)) 2694 return false; 2695 2696 auto &DL = M.getDataLayout(); 2697 auto LookupDomTree = [this](Function &F) -> DominatorTree & { 2698 return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 2699 }; 2700 auto GetTLI = [this](Function &F) -> TargetLibraryInfo & { 2701 return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2702 }; 2703 auto GetTTI = [this](Function &F) -> TargetTransformInfo & { 2704 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2705 }; 2706 2707 auto GetBFI = [this](Function &F) -> BlockFrequencyInfo & { 2708 return this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 2709 }; 2710 2711 return optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, 2712 LookupDomTree); 2713 } 2714 2715 void getAnalysisUsage(AnalysisUsage &AU) const override { 2716 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2717 AU.addRequired<TargetTransformInfoWrapperPass>(); 2718 AU.addRequired<DominatorTreeWrapperPass>(); 2719 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 2720 } 2721 }; 2722 2723 } // end anonymous namespace 2724 2725 char GlobalOptLegacyPass::ID = 0; 2726 2727 INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt", 2728 "Global Variable Optimizer", false, false) 2729 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2730 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 2731 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 2732 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2733 INITIALIZE_PASS_END(GlobalOptLegacyPass, "globalopt", 2734 "Global Variable Optimizer", false, false) 2735 2736 ModulePass *llvm::createGlobalOptimizerPass() { 2737 return new GlobalOptLegacyPass(); 2738 } 2739