1 //===- Local.cpp - Functions to perform local transformations -------------===// 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 family of functions perform various local transformations to the 10 // program. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Utils/Local.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/DenseMapInfo.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/Hashing.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SetVector.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/ADT/TinyPtrVector.h" 28 #include "llvm/Analysis/AssumeBundleQueries.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/DomTreeUpdater.h" 31 #include "llvm/Analysis/EHPersonalities.h" 32 #include "llvm/Analysis/InstructionSimplify.h" 33 #include "llvm/Analysis/LazyValueInfo.h" 34 #include "llvm/Analysis/MemoryBuiltins.h" 35 #include "llvm/Analysis/MemorySSAUpdater.h" 36 #include "llvm/Analysis/TargetLibraryInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/Analysis/VectorUtils.h" 39 #include "llvm/BinaryFormat/Dwarf.h" 40 #include "llvm/IR/Argument.h" 41 #include "llvm/IR/Attributes.h" 42 #include "llvm/IR/BasicBlock.h" 43 #include "llvm/IR/CFG.h" 44 #include "llvm/IR/Constant.h" 45 #include "llvm/IR/ConstantRange.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DIBuilder.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Dominators.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GetElementPtrTypeIterator.h" 55 #include "llvm/IR/GlobalObject.h" 56 #include "llvm/IR/IRBuilder.h" 57 #include "llvm/IR/InstrTypes.h" 58 #include "llvm/IR/Instruction.h" 59 #include "llvm/IR/Instructions.h" 60 #include "llvm/IR/IntrinsicInst.h" 61 #include "llvm/IR/Intrinsics.h" 62 #include "llvm/IR/LLVMContext.h" 63 #include "llvm/IR/MDBuilder.h" 64 #include "llvm/IR/Metadata.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/Operator.h" 67 #include "llvm/IR/PatternMatch.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/User.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/IR/ValueHandle.h" 73 #include "llvm/Support/Casting.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/ErrorHandling.h" 76 #include "llvm/Support/KnownBits.h" 77 #include "llvm/Support/raw_ostream.h" 78 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 79 #include "llvm/Transforms/Utils/ValueMapper.h" 80 #include <algorithm> 81 #include <cassert> 82 #include <climits> 83 #include <cstdint> 84 #include <iterator> 85 #include <map> 86 #include <utility> 87 88 using namespace llvm; 89 using namespace llvm::PatternMatch; 90 91 #define DEBUG_TYPE "local" 92 93 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed"); 94 95 // Max recursion depth for collectBitParts used when detecting bswap and 96 // bitreverse idioms 97 static const unsigned BitPartRecursionMaxDepth = 64; 98 99 //===----------------------------------------------------------------------===// 100 // Local constant propagation. 101 // 102 103 /// ConstantFoldTerminator - If a terminator instruction is predicated on a 104 /// constant value, convert it into an unconditional branch to the constant 105 /// destination. This is a nontrivial operation because the successors of this 106 /// basic block must have their PHI nodes updated. 107 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch 108 /// conditions and indirectbr addresses this might make dead if 109 /// DeleteDeadConditions is true. 110 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions, 111 const TargetLibraryInfo *TLI, 112 DomTreeUpdater *DTU) { 113 Instruction *T = BB->getTerminator(); 114 IRBuilder<> Builder(T); 115 116 // Branch - See if we are conditional jumping on constant 117 if (auto *BI = dyn_cast<BranchInst>(T)) { 118 if (BI->isUnconditional()) return false; // Can't optimize uncond branch 119 BasicBlock *Dest1 = BI->getSuccessor(0); 120 BasicBlock *Dest2 = BI->getSuccessor(1); 121 122 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) { 123 // Are we branching on constant? 124 // YES. Change to unconditional branch... 125 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2; 126 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1; 127 128 // Let the basic block know that we are letting go of it. Based on this, 129 // it will adjust it's PHI nodes. 130 OldDest->removePredecessor(BB); 131 132 // Replace the conditional branch with an unconditional one. 133 Builder.CreateBr(Destination); 134 BI->eraseFromParent(); 135 if (DTU) 136 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}}); 137 return true; 138 } 139 140 if (Dest2 == Dest1) { // Conditional branch to same location? 141 // This branch matches something like this: 142 // br bool %cond, label %Dest, label %Dest 143 // and changes it into: br label %Dest 144 145 // Let the basic block know that we are letting go of one copy of it. 146 assert(BI->getParent() && "Terminator not inserted in block!"); 147 Dest1->removePredecessor(BI->getParent()); 148 149 // Replace the conditional branch with an unconditional one. 150 Builder.CreateBr(Dest1); 151 Value *Cond = BI->getCondition(); 152 BI->eraseFromParent(); 153 if (DeleteDeadConditions) 154 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI); 155 return true; 156 } 157 return false; 158 } 159 160 if (auto *SI = dyn_cast<SwitchInst>(T)) { 161 // If we are switching on a constant, we can convert the switch to an 162 // unconditional branch. 163 auto *CI = dyn_cast<ConstantInt>(SI->getCondition()); 164 BasicBlock *DefaultDest = SI->getDefaultDest(); 165 BasicBlock *TheOnlyDest = DefaultDest; 166 167 // If the default is unreachable, ignore it when searching for TheOnlyDest. 168 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) && 169 SI->getNumCases() > 0) { 170 TheOnlyDest = SI->case_begin()->getCaseSuccessor(); 171 } 172 173 // Figure out which case it goes to. 174 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) { 175 // Found case matching a constant operand? 176 if (i->getCaseValue() == CI) { 177 TheOnlyDest = i->getCaseSuccessor(); 178 break; 179 } 180 181 // Check to see if this branch is going to the same place as the default 182 // dest. If so, eliminate it as an explicit compare. 183 if (i->getCaseSuccessor() == DefaultDest) { 184 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); 185 unsigned NCases = SI->getNumCases(); 186 // Fold the case metadata into the default if there will be any branches 187 // left, unless the metadata doesn't match the switch. 188 if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) { 189 // Collect branch weights into a vector. 190 SmallVector<uint32_t, 8> Weights; 191 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; 192 ++MD_i) { 193 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); 194 Weights.push_back(CI->getValue().getZExtValue()); 195 } 196 // Merge weight of this case to the default weight. 197 unsigned idx = i->getCaseIndex(); 198 Weights[0] += Weights[idx+1]; 199 // Remove weight for this case. 200 std::swap(Weights[idx+1], Weights.back()); 201 Weights.pop_back(); 202 SI->setMetadata(LLVMContext::MD_prof, 203 MDBuilder(BB->getContext()). 204 createBranchWeights(Weights)); 205 } 206 // Remove this entry. 207 BasicBlock *ParentBB = SI->getParent(); 208 DefaultDest->removePredecessor(ParentBB); 209 i = SI->removeCase(i); 210 e = SI->case_end(); 211 if (DTU) 212 DTU->applyUpdatesPermissive( 213 {{DominatorTree::Delete, ParentBB, DefaultDest}}); 214 continue; 215 } 216 217 // Otherwise, check to see if the switch only branches to one destination. 218 // We do this by reseting "TheOnlyDest" to null when we find two non-equal 219 // destinations. 220 if (i->getCaseSuccessor() != TheOnlyDest) 221 TheOnlyDest = nullptr; 222 223 // Increment this iterator as we haven't removed the case. 224 ++i; 225 } 226 227 if (CI && !TheOnlyDest) { 228 // Branching on a constant, but not any of the cases, go to the default 229 // successor. 230 TheOnlyDest = SI->getDefaultDest(); 231 } 232 233 // If we found a single destination that we can fold the switch into, do so 234 // now. 235 if (TheOnlyDest) { 236 // Insert the new branch. 237 Builder.CreateBr(TheOnlyDest); 238 BasicBlock *BB = SI->getParent(); 239 std::vector <DominatorTree::UpdateType> Updates; 240 if (DTU) 241 Updates.reserve(SI->getNumSuccessors() - 1); 242 243 // Remove entries from PHI nodes which we no longer branch to... 244 for (BasicBlock *Succ : successors(SI)) { 245 // Found case matching a constant operand? 246 if (Succ == TheOnlyDest) { 247 TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest 248 } else { 249 Succ->removePredecessor(BB); 250 if (DTU) 251 Updates.push_back({DominatorTree::Delete, BB, Succ}); 252 } 253 } 254 255 // Delete the old switch. 256 Value *Cond = SI->getCondition(); 257 SI->eraseFromParent(); 258 if (DeleteDeadConditions) 259 RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI); 260 if (DTU) 261 DTU->applyUpdatesPermissive(Updates); 262 return true; 263 } 264 265 if (SI->getNumCases() == 1) { 266 // Otherwise, we can fold this switch into a conditional branch 267 // instruction if it has only one non-default destination. 268 auto FirstCase = *SI->case_begin(); 269 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(), 270 FirstCase.getCaseValue(), "cond"); 271 272 // Insert the new branch. 273 BranchInst *NewBr = Builder.CreateCondBr(Cond, 274 FirstCase.getCaseSuccessor(), 275 SI->getDefaultDest()); 276 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); 277 if (MD && MD->getNumOperands() == 3) { 278 ConstantInt *SICase = 279 mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 280 ConstantInt *SIDef = 281 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1)); 282 assert(SICase && SIDef); 283 // The TrueWeight should be the weight for the single case of SI. 284 NewBr->setMetadata(LLVMContext::MD_prof, 285 MDBuilder(BB->getContext()). 286 createBranchWeights(SICase->getValue().getZExtValue(), 287 SIDef->getValue().getZExtValue())); 288 } 289 290 // Update make.implicit metadata to the newly-created conditional branch. 291 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit); 292 if (MakeImplicitMD) 293 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD); 294 295 // Delete the old switch. 296 SI->eraseFromParent(); 297 return true; 298 } 299 return false; 300 } 301 302 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) { 303 // indirectbr blockaddress(@F, @BB) -> br label @BB 304 if (auto *BA = 305 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) { 306 BasicBlock *TheOnlyDest = BA->getBasicBlock(); 307 std::vector <DominatorTree::UpdateType> Updates; 308 if (DTU) 309 Updates.reserve(IBI->getNumDestinations() - 1); 310 311 // Insert the new branch. 312 Builder.CreateBr(TheOnlyDest); 313 314 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 315 if (IBI->getDestination(i) == TheOnlyDest) { 316 TheOnlyDest = nullptr; 317 } else { 318 BasicBlock *ParentBB = IBI->getParent(); 319 BasicBlock *DestBB = IBI->getDestination(i); 320 DestBB->removePredecessor(ParentBB); 321 if (DTU) 322 Updates.push_back({DominatorTree::Delete, ParentBB, DestBB}); 323 } 324 } 325 Value *Address = IBI->getAddress(); 326 IBI->eraseFromParent(); 327 if (DeleteDeadConditions) 328 // Delete pointer cast instructions. 329 RecursivelyDeleteTriviallyDeadInstructions(Address, TLI); 330 331 // Also zap the blockaddress constant if there are no users remaining, 332 // otherwise the destination is still marked as having its address taken. 333 if (BA->use_empty()) 334 BA->destroyConstant(); 335 336 // If we didn't find our destination in the IBI successor list, then we 337 // have undefined behavior. Replace the unconditional branch with an 338 // 'unreachable' instruction. 339 if (TheOnlyDest) { 340 BB->getTerminator()->eraseFromParent(); 341 new UnreachableInst(BB->getContext(), BB); 342 } 343 344 if (DTU) 345 DTU->applyUpdatesPermissive(Updates); 346 return true; 347 } 348 } 349 350 return false; 351 } 352 353 //===----------------------------------------------------------------------===// 354 // Local dead code elimination. 355 // 356 357 /// isInstructionTriviallyDead - Return true if the result produced by the 358 /// instruction is not used, and the instruction has no side effects. 359 /// 360 bool llvm::isInstructionTriviallyDead(Instruction *I, 361 const TargetLibraryInfo *TLI) { 362 if (!I->use_empty()) 363 return false; 364 return wouldInstructionBeTriviallyDead(I, TLI); 365 } 366 367 bool llvm::wouldInstructionBeTriviallyDead(Instruction *I, 368 const TargetLibraryInfo *TLI) { 369 if (I->isTerminator()) 370 return false; 371 372 // We don't want the landingpad-like instructions removed by anything this 373 // general. 374 if (I->isEHPad()) 375 return false; 376 377 // We don't want debug info removed by anything this general, unless 378 // debug info is empty. 379 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) { 380 if (DDI->getAddress()) 381 return false; 382 return true; 383 } 384 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) { 385 if (DVI->getValue()) 386 return false; 387 return true; 388 } 389 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) { 390 if (DLI->getLabel()) 391 return false; 392 return true; 393 } 394 395 if (!I->mayHaveSideEffects()) 396 return true; 397 398 // Special case intrinsics that "may have side effects" but can be deleted 399 // when dead. 400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 401 // Safe to delete llvm.stacksave and launder.invariant.group if dead. 402 if (II->getIntrinsicID() == Intrinsic::stacksave || 403 II->getIntrinsicID() == Intrinsic::launder_invariant_group) 404 return true; 405 406 if (II->isLifetimeStartOrEnd()) { 407 auto *Arg = II->getArgOperand(1); 408 // Lifetime intrinsics are dead when their right-hand is undef. 409 if (isa<UndefValue>(Arg)) 410 return true; 411 // If the right-hand is an alloc, global, or argument and the only uses 412 // are lifetime intrinsics then the intrinsics are dead. 413 if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg)) 414 return llvm::all_of(Arg->uses(), [](Use &Use) { 415 if (IntrinsicInst *IntrinsicUse = 416 dyn_cast<IntrinsicInst>(Use.getUser())) 417 return IntrinsicUse->isLifetimeStartOrEnd(); 418 return false; 419 }); 420 return false; 421 } 422 423 // Assumptions are dead if their condition is trivially true. Guards on 424 // true are operationally no-ops. In the future we can consider more 425 // sophisticated tradeoffs for guards considering potential for check 426 // widening, but for now we keep things simple. 427 if ((II->getIntrinsicID() == Intrinsic::assume && 428 isAssumeWithEmptyBundle(*II)) || 429 II->getIntrinsicID() == Intrinsic::experimental_guard) { 430 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0))) 431 return !Cond->isZero(); 432 433 return false; 434 } 435 } 436 437 if (isAllocLikeFn(I, TLI)) 438 return true; 439 440 if (CallInst *CI = isFreeCall(I, TLI)) 441 if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0))) 442 return C->isNullValue() || isa<UndefValue>(C); 443 444 if (auto *Call = dyn_cast<CallBase>(I)) 445 if (isMathLibCallNoop(Call, TLI)) 446 return true; 447 448 return false; 449 } 450 451 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a 452 /// trivially dead instruction, delete it. If that makes any of its operands 453 /// trivially dead, delete them too, recursively. Return true if any 454 /// instructions were deleted. 455 bool llvm::RecursivelyDeleteTriviallyDeadInstructions( 456 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU, 457 std::function<void(Value *)> AboutToDeleteCallback) { 458 Instruction *I = dyn_cast<Instruction>(V); 459 if (!I || !isInstructionTriviallyDead(I, TLI)) 460 return false; 461 462 SmallVector<WeakTrackingVH, 16> DeadInsts; 463 DeadInsts.push_back(I); 464 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU, 465 AboutToDeleteCallback); 466 467 return true; 468 } 469 470 bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive( 471 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI, 472 MemorySSAUpdater *MSSAU, 473 std::function<void(Value *)> AboutToDeleteCallback) { 474 unsigned S = 0, E = DeadInsts.size(), Alive = 0; 475 for (; S != E; ++S) { 476 auto *I = cast<Instruction>(DeadInsts[S]); 477 if (!isInstructionTriviallyDead(I)) { 478 DeadInsts[S] = nullptr; 479 ++Alive; 480 } 481 } 482 if (Alive == E) 483 return false; 484 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU, 485 AboutToDeleteCallback); 486 return true; 487 } 488 489 void llvm::RecursivelyDeleteTriviallyDeadInstructions( 490 SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI, 491 MemorySSAUpdater *MSSAU, 492 std::function<void(Value *)> AboutToDeleteCallback) { 493 // Process the dead instruction list until empty. 494 while (!DeadInsts.empty()) { 495 Value *V = DeadInsts.pop_back_val(); 496 Instruction *I = cast_or_null<Instruction>(V); 497 if (!I) 498 continue; 499 assert(isInstructionTriviallyDead(I, TLI) && 500 "Live instruction found in dead worklist!"); 501 assert(I->use_empty() && "Instructions with uses are not dead."); 502 503 // Don't lose the debug info while deleting the instructions. 504 salvageDebugInfo(*I); 505 506 if (AboutToDeleteCallback) 507 AboutToDeleteCallback(I); 508 509 // Null out all of the instruction's operands to see if any operand becomes 510 // dead as we go. 511 for (Use &OpU : I->operands()) { 512 Value *OpV = OpU.get(); 513 OpU.set(nullptr); 514 515 if (!OpV->use_empty()) 516 continue; 517 518 // If the operand is an instruction that became dead as we nulled out the 519 // operand, and if it is 'trivially' dead, delete it in a future loop 520 // iteration. 521 if (Instruction *OpI = dyn_cast<Instruction>(OpV)) 522 if (isInstructionTriviallyDead(OpI, TLI)) 523 DeadInsts.push_back(OpI); 524 } 525 if (MSSAU) 526 MSSAU->removeMemoryAccess(I); 527 528 I->eraseFromParent(); 529 } 530 } 531 532 bool llvm::replaceDbgUsesWithUndef(Instruction *I) { 533 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers; 534 findDbgUsers(DbgUsers, I); 535 for (auto *DII : DbgUsers) { 536 Value *Undef = UndefValue::get(I->getType()); 537 DII->setOperand(0, MetadataAsValue::get(DII->getContext(), 538 ValueAsMetadata::get(Undef))); 539 } 540 return !DbgUsers.empty(); 541 } 542 543 /// areAllUsesEqual - Check whether the uses of a value are all the same. 544 /// This is similar to Instruction::hasOneUse() except this will also return 545 /// true when there are no uses or multiple uses that all refer to the same 546 /// value. 547 static bool areAllUsesEqual(Instruction *I) { 548 Value::user_iterator UI = I->user_begin(); 549 Value::user_iterator UE = I->user_end(); 550 if (UI == UE) 551 return true; 552 553 User *TheUse = *UI; 554 for (++UI; UI != UE; ++UI) { 555 if (*UI != TheUse) 556 return false; 557 } 558 return true; 559 } 560 561 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively 562 /// dead PHI node, due to being a def-use chain of single-use nodes that 563 /// either forms a cycle or is terminated by a trivially dead instruction, 564 /// delete it. If that makes any of its operands trivially dead, delete them 565 /// too, recursively. Return true if a change was made. 566 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN, 567 const TargetLibraryInfo *TLI, 568 llvm::MemorySSAUpdater *MSSAU) { 569 SmallPtrSet<Instruction*, 4> Visited; 570 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects(); 571 I = cast<Instruction>(*I->user_begin())) { 572 if (I->use_empty()) 573 return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU); 574 575 // If we find an instruction more than once, we're on a cycle that 576 // won't prove fruitful. 577 if (!Visited.insert(I).second) { 578 // Break the cycle and delete the instruction and its operands. 579 I->replaceAllUsesWith(UndefValue::get(I->getType())); 580 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU); 581 return true; 582 } 583 } 584 return false; 585 } 586 587 static bool 588 simplifyAndDCEInstruction(Instruction *I, 589 SmallSetVector<Instruction *, 16> &WorkList, 590 const DataLayout &DL, 591 const TargetLibraryInfo *TLI) { 592 if (isInstructionTriviallyDead(I, TLI)) { 593 salvageDebugInfo(*I); 594 595 // Null out all of the instruction's operands to see if any operand becomes 596 // dead as we go. 597 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 598 Value *OpV = I->getOperand(i); 599 I->setOperand(i, nullptr); 600 601 if (!OpV->use_empty() || I == OpV) 602 continue; 603 604 // If the operand is an instruction that became dead as we nulled out the 605 // operand, and if it is 'trivially' dead, delete it in a future loop 606 // iteration. 607 if (Instruction *OpI = dyn_cast<Instruction>(OpV)) 608 if (isInstructionTriviallyDead(OpI, TLI)) 609 WorkList.insert(OpI); 610 } 611 612 I->eraseFromParent(); 613 614 return true; 615 } 616 617 if (Value *SimpleV = SimplifyInstruction(I, DL)) { 618 // Add the users to the worklist. CAREFUL: an instruction can use itself, 619 // in the case of a phi node. 620 for (User *U : I->users()) { 621 if (U != I) { 622 WorkList.insert(cast<Instruction>(U)); 623 } 624 } 625 626 // Replace the instruction with its simplified value. 627 bool Changed = false; 628 if (!I->use_empty()) { 629 I->replaceAllUsesWith(SimpleV); 630 Changed = true; 631 } 632 if (isInstructionTriviallyDead(I, TLI)) { 633 I->eraseFromParent(); 634 Changed = true; 635 } 636 return Changed; 637 } 638 return false; 639 } 640 641 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to 642 /// simplify any instructions in it and recursively delete dead instructions. 643 /// 644 /// This returns true if it changed the code, note that it can delete 645 /// instructions in other blocks as well in this block. 646 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, 647 const TargetLibraryInfo *TLI) { 648 bool MadeChange = false; 649 const DataLayout &DL = BB->getModule()->getDataLayout(); 650 651 #ifndef NDEBUG 652 // In debug builds, ensure that the terminator of the block is never replaced 653 // or deleted by these simplifications. The idea of simplification is that it 654 // cannot introduce new instructions, and there is no way to replace the 655 // terminator of a block without introducing a new instruction. 656 AssertingVH<Instruction> TerminatorVH(&BB->back()); 657 #endif 658 659 SmallSetVector<Instruction *, 16> WorkList; 660 // Iterate over the original function, only adding insts to the worklist 661 // if they actually need to be revisited. This avoids having to pre-init 662 // the worklist with the entire function's worth of instructions. 663 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end()); 664 BI != E;) { 665 assert(!BI->isTerminator()); 666 Instruction *I = &*BI; 667 ++BI; 668 669 // We're visiting this instruction now, so make sure it's not in the 670 // worklist from an earlier visit. 671 if (!WorkList.count(I)) 672 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI); 673 } 674 675 while (!WorkList.empty()) { 676 Instruction *I = WorkList.pop_back_val(); 677 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI); 678 } 679 return MadeChange; 680 } 681 682 //===----------------------------------------------------------------------===// 683 // Control Flow Graph Restructuring. 684 // 685 686 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred, 687 DomTreeUpdater *DTU) { 688 // This only adjusts blocks with PHI nodes. 689 if (!isa<PHINode>(BB->begin())) 690 return; 691 692 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify 693 // them down. This will leave us with single entry phi nodes and other phis 694 // that can be removed. 695 BB->removePredecessor(Pred, true); 696 697 WeakTrackingVH PhiIt = &BB->front(); 698 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) { 699 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt)); 700 Value *OldPhiIt = PhiIt; 701 702 if (!recursivelySimplifyInstruction(PN)) 703 continue; 704 705 // If recursive simplification ended up deleting the next PHI node we would 706 // iterate to, then our iterator is invalid, restart scanning from the top 707 // of the block. 708 if (PhiIt != OldPhiIt) PhiIt = &BB->front(); 709 } 710 if (DTU) 711 DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}}); 712 } 713 714 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, 715 DomTreeUpdater *DTU) { 716 717 // If BB has single-entry PHI nodes, fold them. 718 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) { 719 Value *NewVal = PN->getIncomingValue(0); 720 // Replace self referencing PHI with undef, it must be dead. 721 if (NewVal == PN) NewVal = UndefValue::get(PN->getType()); 722 PN->replaceAllUsesWith(NewVal); 723 PN->eraseFromParent(); 724 } 725 726 BasicBlock *PredBB = DestBB->getSinglePredecessor(); 727 assert(PredBB && "Block doesn't have a single predecessor!"); 728 729 bool ReplaceEntryBB = false; 730 if (PredBB == &DestBB->getParent()->getEntryBlock()) 731 ReplaceEntryBB = true; 732 733 // DTU updates: Collect all the edges that enter 734 // PredBB. These dominator edges will be redirected to DestBB. 735 SmallVector<DominatorTree::UpdateType, 32> Updates; 736 737 if (DTU) { 738 Updates.push_back({DominatorTree::Delete, PredBB, DestBB}); 739 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) { 740 Updates.push_back({DominatorTree::Delete, *I, PredBB}); 741 // This predecessor of PredBB may already have DestBB as a successor. 742 if (llvm::find(successors(*I), DestBB) == succ_end(*I)) 743 Updates.push_back({DominatorTree::Insert, *I, DestBB}); 744 } 745 } 746 747 // Zap anything that took the address of DestBB. Not doing this will give the 748 // address an invalid value. 749 if (DestBB->hasAddressTaken()) { 750 BlockAddress *BA = BlockAddress::get(DestBB); 751 Constant *Replacement = 752 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1); 753 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, 754 BA->getType())); 755 BA->destroyConstant(); 756 } 757 758 // Anything that branched to PredBB now branches to DestBB. 759 PredBB->replaceAllUsesWith(DestBB); 760 761 // Splice all the instructions from PredBB to DestBB. 762 PredBB->getTerminator()->eraseFromParent(); 763 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList()); 764 new UnreachableInst(PredBB->getContext(), PredBB); 765 766 // If the PredBB is the entry block of the function, move DestBB up to 767 // become the entry block after we erase PredBB. 768 if (ReplaceEntryBB) 769 DestBB->moveAfter(PredBB); 770 771 if (DTU) { 772 assert(PredBB->getInstList().size() == 1 && 773 isa<UnreachableInst>(PredBB->getTerminator()) && 774 "The successor list of PredBB isn't empty before " 775 "applying corresponding DTU updates."); 776 DTU->applyUpdatesPermissive(Updates); 777 DTU->deleteBB(PredBB); 778 // Recalculation of DomTree is needed when updating a forward DomTree and 779 // the Entry BB is replaced. 780 if (ReplaceEntryBB && DTU->hasDomTree()) { 781 // The entry block was removed and there is no external interface for 782 // the dominator tree to be notified of this change. In this corner-case 783 // we recalculate the entire tree. 784 DTU->recalculate(*(DestBB->getParent())); 785 } 786 } 787 788 else { 789 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr. 790 } 791 } 792 793 /// Return true if we can choose one of these values to use in place of the 794 /// other. Note that we will always choose the non-undef value to keep. 795 static bool CanMergeValues(Value *First, Value *Second) { 796 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second); 797 } 798 799 /// Return true if we can fold BB, an almost-empty BB ending in an unconditional 800 /// branch to Succ, into Succ. 801 /// 802 /// Assumption: Succ is the single successor for BB. 803 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { 804 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); 805 806 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into " 807 << Succ->getName() << "\n"); 808 // Shortcut, if there is only a single predecessor it must be BB and merging 809 // is always safe 810 if (Succ->getSinglePredecessor()) return true; 811 812 // Make a list of the predecessors of BB 813 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB)); 814 815 // Look at all the phi nodes in Succ, to see if they present a conflict when 816 // merging these blocks 817 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 818 PHINode *PN = cast<PHINode>(I); 819 820 // If the incoming value from BB is again a PHINode in 821 // BB which has the same incoming value for *PI as PN does, we can 822 // merge the phi nodes and then the blocks can still be merged 823 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB)); 824 if (BBPN && BBPN->getParent() == BB) { 825 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) { 826 BasicBlock *IBB = PN->getIncomingBlock(PI); 827 if (BBPreds.count(IBB) && 828 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB), 829 PN->getIncomingValue(PI))) { 830 LLVM_DEBUG(dbgs() 831 << "Can't fold, phi node " << PN->getName() << " in " 832 << Succ->getName() << " is conflicting with " 833 << BBPN->getName() << " with regard to common predecessor " 834 << IBB->getName() << "\n"); 835 return false; 836 } 837 } 838 } else { 839 Value* Val = PN->getIncomingValueForBlock(BB); 840 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) { 841 // See if the incoming value for the common predecessor is equal to the 842 // one for BB, in which case this phi node will not prevent the merging 843 // of the block. 844 BasicBlock *IBB = PN->getIncomingBlock(PI); 845 if (BBPreds.count(IBB) && 846 !CanMergeValues(Val, PN->getIncomingValue(PI))) { 847 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() 848 << " in " << Succ->getName() 849 << " is conflicting with regard to common " 850 << "predecessor " << IBB->getName() << "\n"); 851 return false; 852 } 853 } 854 } 855 } 856 857 return true; 858 } 859 860 using PredBlockVector = SmallVector<BasicBlock *, 16>; 861 using IncomingValueMap = DenseMap<BasicBlock *, Value *>; 862 863 /// Determines the value to use as the phi node input for a block. 864 /// 865 /// Select between \p OldVal any value that we know flows from \p BB 866 /// to a particular phi on the basis of which one (if either) is not 867 /// undef. Update IncomingValues based on the selected value. 868 /// 869 /// \param OldVal The value we are considering selecting. 870 /// \param BB The block that the value flows in from. 871 /// \param IncomingValues A map from block-to-value for other phi inputs 872 /// that we have examined. 873 /// 874 /// \returns the selected value. 875 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, 876 IncomingValueMap &IncomingValues) { 877 if (!isa<UndefValue>(OldVal)) { 878 assert((!IncomingValues.count(BB) || 879 IncomingValues.find(BB)->second == OldVal) && 880 "Expected OldVal to match incoming value from BB!"); 881 882 IncomingValues.insert(std::make_pair(BB, OldVal)); 883 return OldVal; 884 } 885 886 IncomingValueMap::const_iterator It = IncomingValues.find(BB); 887 if (It != IncomingValues.end()) return It->second; 888 889 return OldVal; 890 } 891 892 /// Create a map from block to value for the operands of a 893 /// given phi. 894 /// 895 /// Create a map from block to value for each non-undef value flowing 896 /// into \p PN. 897 /// 898 /// \param PN The phi we are collecting the map for. 899 /// \param IncomingValues [out] The map from block to value for this phi. 900 static void gatherIncomingValuesToPhi(PHINode *PN, 901 IncomingValueMap &IncomingValues) { 902 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 903 BasicBlock *BB = PN->getIncomingBlock(i); 904 Value *V = PN->getIncomingValue(i); 905 906 if (!isa<UndefValue>(V)) 907 IncomingValues.insert(std::make_pair(BB, V)); 908 } 909 } 910 911 /// Replace the incoming undef values to a phi with the values 912 /// from a block-to-value map. 913 /// 914 /// \param PN The phi we are replacing the undefs in. 915 /// \param IncomingValues A map from block to value. 916 static void replaceUndefValuesInPhi(PHINode *PN, 917 const IncomingValueMap &IncomingValues) { 918 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 919 Value *V = PN->getIncomingValue(i); 920 921 if (!isa<UndefValue>(V)) continue; 922 923 BasicBlock *BB = PN->getIncomingBlock(i); 924 IncomingValueMap::const_iterator It = IncomingValues.find(BB); 925 if (It == IncomingValues.end()) continue; 926 927 PN->setIncomingValue(i, It->second); 928 } 929 } 930 931 /// Replace a value flowing from a block to a phi with 932 /// potentially multiple instances of that value flowing from the 933 /// block's predecessors to the phi. 934 /// 935 /// \param BB The block with the value flowing into the phi. 936 /// \param BBPreds The predecessors of BB. 937 /// \param PN The phi that we are updating. 938 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, 939 const PredBlockVector &BBPreds, 940 PHINode *PN) { 941 Value *OldVal = PN->removeIncomingValue(BB, false); 942 assert(OldVal && "No entry in PHI for Pred BB!"); 943 944 IncomingValueMap IncomingValues; 945 946 // We are merging two blocks - BB, and the block containing PN - and 947 // as a result we need to redirect edges from the predecessors of BB 948 // to go to the block containing PN, and update PN 949 // accordingly. Since we allow merging blocks in the case where the 950 // predecessor and successor blocks both share some predecessors, 951 // and where some of those common predecessors might have undef 952 // values flowing into PN, we want to rewrite those values to be 953 // consistent with the non-undef values. 954 955 gatherIncomingValuesToPhi(PN, IncomingValues); 956 957 // If this incoming value is one of the PHI nodes in BB, the new entries 958 // in the PHI node are the entries from the old PHI. 959 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { 960 PHINode *OldValPN = cast<PHINode>(OldVal); 961 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) { 962 // Note that, since we are merging phi nodes and BB and Succ might 963 // have common predecessors, we could end up with a phi node with 964 // identical incoming branches. This will be cleaned up later (and 965 // will trigger asserts if we try to clean it up now, without also 966 // simplifying the corresponding conditional branch). 967 BasicBlock *PredBB = OldValPN->getIncomingBlock(i); 968 Value *PredVal = OldValPN->getIncomingValue(i); 969 Value *Selected = selectIncomingValueForBlock(PredVal, PredBB, 970 IncomingValues); 971 972 // And add a new incoming value for this predecessor for the 973 // newly retargeted branch. 974 PN->addIncoming(Selected, PredBB); 975 } 976 } else { 977 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) { 978 // Update existing incoming values in PN for this 979 // predecessor of BB. 980 BasicBlock *PredBB = BBPreds[i]; 981 Value *Selected = selectIncomingValueForBlock(OldVal, PredBB, 982 IncomingValues); 983 984 // And add a new incoming value for this predecessor for the 985 // newly retargeted branch. 986 PN->addIncoming(Selected, PredBB); 987 } 988 } 989 990 replaceUndefValuesInPhi(PN, IncomingValues); 991 } 992 993 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, 994 DomTreeUpdater *DTU) { 995 assert(BB != &BB->getParent()->getEntryBlock() && 996 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!"); 997 998 // We can't eliminate infinite loops. 999 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0); 1000 if (BB == Succ) return false; 1001 1002 // Check to see if merging these blocks would cause conflicts for any of the 1003 // phi nodes in BB or Succ. If not, we can safely merge. 1004 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; 1005 1006 // Check for cases where Succ has multiple predecessors and a PHI node in BB 1007 // has uses which will not disappear when the PHI nodes are merged. It is 1008 // possible to handle such cases, but difficult: it requires checking whether 1009 // BB dominates Succ, which is non-trivial to calculate in the case where 1010 // Succ has multiple predecessors. Also, it requires checking whether 1011 // constructing the necessary self-referential PHI node doesn't introduce any 1012 // conflicts; this isn't too difficult, but the previous code for doing this 1013 // was incorrect. 1014 // 1015 // Note that if this check finds a live use, BB dominates Succ, so BB is 1016 // something like a loop pre-header (or rarely, a part of an irreducible CFG); 1017 // folding the branch isn't profitable in that case anyway. 1018 if (!Succ->getSinglePredecessor()) { 1019 BasicBlock::iterator BBI = BB->begin(); 1020 while (isa<PHINode>(*BBI)) { 1021 for (Use &U : BBI->uses()) { 1022 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) { 1023 if (PN->getIncomingBlock(U) != BB) 1024 return false; 1025 } else { 1026 return false; 1027 } 1028 } 1029 ++BBI; 1030 } 1031 } 1032 1033 // We cannot fold the block if it's a branch to an already present callbr 1034 // successor because that creates duplicate successors. 1035 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 1036 if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) { 1037 if (Succ == CBI->getDefaultDest()) 1038 return false; 1039 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) 1040 if (Succ == CBI->getIndirectDest(i)) 1041 return false; 1042 } 1043 } 1044 1045 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB); 1046 1047 SmallVector<DominatorTree::UpdateType, 32> Updates; 1048 if (DTU) { 1049 Updates.push_back({DominatorTree::Delete, BB, Succ}); 1050 // All predecessors of BB will be moved to Succ. 1051 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 1052 Updates.push_back({DominatorTree::Delete, *I, BB}); 1053 // This predecessor of BB may already have Succ as a successor. 1054 if (llvm::find(successors(*I), Succ) == succ_end(*I)) 1055 Updates.push_back({DominatorTree::Insert, *I, Succ}); 1056 } 1057 } 1058 1059 if (isa<PHINode>(Succ->begin())) { 1060 // If there is more than one pred of succ, and there are PHI nodes in 1061 // the successor, then we need to add incoming edges for the PHI nodes 1062 // 1063 const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB)); 1064 1065 // Loop over all of the PHI nodes in the successor of BB. 1066 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 1067 PHINode *PN = cast<PHINode>(I); 1068 1069 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN); 1070 } 1071 } 1072 1073 if (Succ->getSinglePredecessor()) { 1074 // BB is the only predecessor of Succ, so Succ will end up with exactly 1075 // the same predecessors BB had. 1076 1077 // Copy over any phi, debug or lifetime instruction. 1078 BB->getTerminator()->eraseFromParent(); 1079 Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(), 1080 BB->getInstList()); 1081 } else { 1082 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { 1083 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs. 1084 assert(PN->use_empty() && "There shouldn't be any uses here!"); 1085 PN->eraseFromParent(); 1086 } 1087 } 1088 1089 // If the unconditional branch we replaced contains llvm.loop metadata, we 1090 // add the metadata to the branch instructions in the predecessors. 1091 unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop"); 1092 Instruction *TI = BB->getTerminator(); 1093 if (TI) 1094 if (MDNode *LoopMD = TI->getMetadata(LoopMDKind)) 1095 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 1096 BasicBlock *Pred = *PI; 1097 Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD); 1098 } 1099 1100 // Everything that jumped to BB now goes to Succ. 1101 BB->replaceAllUsesWith(Succ); 1102 if (!Succ->hasName()) Succ->takeName(BB); 1103 1104 // Clear the successor list of BB to match updates applying to DTU later. 1105 if (BB->getTerminator()) 1106 BB->getInstList().pop_back(); 1107 new UnreachableInst(BB->getContext(), BB); 1108 assert(succ_empty(BB) && "The successor list of BB isn't empty before " 1109 "applying corresponding DTU updates."); 1110 1111 if (DTU) { 1112 DTU->applyUpdatesPermissive(Updates); 1113 DTU->deleteBB(BB); 1114 } else { 1115 BB->eraseFromParent(); // Delete the old basic block. 1116 } 1117 return true; 1118 } 1119 1120 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) { 1121 // This implementation doesn't currently consider undef operands 1122 // specially. Theoretically, two phis which are identical except for 1123 // one having an undef where the other doesn't could be collapsed. 1124 1125 struct PHIDenseMapInfo { 1126 static PHINode *getEmptyKey() { 1127 return DenseMapInfo<PHINode *>::getEmptyKey(); 1128 } 1129 1130 static PHINode *getTombstoneKey() { 1131 return DenseMapInfo<PHINode *>::getTombstoneKey(); 1132 } 1133 1134 static unsigned getHashValue(PHINode *PN) { 1135 // Compute a hash value on the operands. Instcombine will likely have 1136 // sorted them, which helps expose duplicates, but we have to check all 1137 // the operands to be safe in case instcombine hasn't run. 1138 return static_cast<unsigned>(hash_combine( 1139 hash_combine_range(PN->value_op_begin(), PN->value_op_end()), 1140 hash_combine_range(PN->block_begin(), PN->block_end()))); 1141 } 1142 1143 static bool isEqual(PHINode *LHS, PHINode *RHS) { 1144 if (LHS == getEmptyKey() || LHS == getTombstoneKey() || 1145 RHS == getEmptyKey() || RHS == getTombstoneKey()) 1146 return LHS == RHS; 1147 return LHS->isIdenticalTo(RHS); 1148 } 1149 }; 1150 1151 // Set of unique PHINodes. 1152 DenseSet<PHINode *, PHIDenseMapInfo> PHISet; 1153 1154 // Examine each PHI. 1155 bool Changed = false; 1156 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) { 1157 auto Inserted = PHISet.insert(PN); 1158 if (!Inserted.second) { 1159 // A duplicate. Replace this PHI with its duplicate. 1160 PN->replaceAllUsesWith(*Inserted.first); 1161 PN->eraseFromParent(); 1162 Changed = true; 1163 1164 // The RAUW can change PHIs that we already visited. Start over from the 1165 // beginning. 1166 PHISet.clear(); 1167 I = BB->begin(); 1168 } 1169 } 1170 1171 return Changed; 1172 } 1173 1174 /// enforceKnownAlignment - If the specified pointer points to an object that 1175 /// we control, modify the object's alignment to PrefAlign. This isn't 1176 /// often possible though. If alignment is important, a more reliable approach 1177 /// is to simply align all global variables and allocation instructions to 1178 /// their preferred alignment from the beginning. 1179 static Align enforceKnownAlignment(Value *V, Align Alignment, Align PrefAlign, 1180 const DataLayout &DL) { 1181 assert(PrefAlign > Alignment); 1182 1183 V = V->stripPointerCasts(); 1184 1185 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1186 // TODO: ideally, computeKnownBits ought to have used 1187 // AllocaInst::getAlignment() in its computation already, making 1188 // the below max redundant. But, as it turns out, 1189 // stripPointerCasts recurses through infinite layers of bitcasts, 1190 // while computeKnownBits is not allowed to traverse more than 6 1191 // levels. 1192 Alignment = std::max(AI->getAlign(), Alignment); 1193 if (PrefAlign <= Alignment) 1194 return Alignment; 1195 1196 // If the preferred alignment is greater than the natural stack alignment 1197 // then don't round up. This avoids dynamic stack realignment. 1198 if (DL.exceedsNaturalStackAlignment(PrefAlign)) 1199 return Alignment; 1200 AI->setAlignment(PrefAlign); 1201 return PrefAlign; 1202 } 1203 1204 if (auto *GO = dyn_cast<GlobalObject>(V)) { 1205 // TODO: as above, this shouldn't be necessary. 1206 Alignment = max(GO->getAlign(), Alignment); 1207 if (PrefAlign <= Alignment) 1208 return Alignment; 1209 1210 // If there is a large requested alignment and we can, bump up the alignment 1211 // of the global. If the memory we set aside for the global may not be the 1212 // memory used by the final program then it is impossible for us to reliably 1213 // enforce the preferred alignment. 1214 if (!GO->canIncreaseAlignment()) 1215 return Alignment; 1216 1217 GO->setAlignment(PrefAlign); 1218 return PrefAlign; 1219 } 1220 1221 return Alignment; 1222 } 1223 1224 Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, 1225 const DataLayout &DL, 1226 const Instruction *CxtI, 1227 AssumptionCache *AC, 1228 const DominatorTree *DT) { 1229 assert(V->getType()->isPointerTy() && 1230 "getOrEnforceKnownAlignment expects a pointer!"); 1231 1232 KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT); 1233 unsigned TrailZ = Known.countMinTrailingZeros(); 1234 1235 // Avoid trouble with ridiculously large TrailZ values, such as 1236 // those computed from a null pointer. 1237 // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent). 1238 TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent); 1239 1240 Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ)); 1241 1242 if (PrefAlign && *PrefAlign > Alignment) 1243 Alignment = enforceKnownAlignment(V, Alignment, *PrefAlign, DL); 1244 1245 // We don't need to make any adjustment. 1246 return Alignment; 1247 } 1248 1249 ///===---------------------------------------------------------------------===// 1250 /// Dbg Intrinsic utilities 1251 /// 1252 1253 /// See if there is a dbg.value intrinsic for DIVar for the PHI node. 1254 static bool PhiHasDebugValue(DILocalVariable *DIVar, 1255 DIExpression *DIExpr, 1256 PHINode *APN) { 1257 // Since we can't guarantee that the original dbg.declare instrinsic 1258 // is removed by LowerDbgDeclare(), we need to make sure that we are 1259 // not inserting the same dbg.value intrinsic over and over. 1260 SmallVector<DbgValueInst *, 1> DbgValues; 1261 findDbgValues(DbgValues, APN); 1262 for (auto *DVI : DbgValues) { 1263 assert(DVI->getValue() == APN); 1264 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr)) 1265 return true; 1266 } 1267 return false; 1268 } 1269 1270 /// Check if the alloc size of \p ValTy is large enough to cover the variable 1271 /// (or fragment of the variable) described by \p DII. 1272 /// 1273 /// This is primarily intended as a helper for the different 1274 /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is 1275 /// converted describes an alloca'd variable, so we need to use the 1276 /// alloc size of the value when doing the comparison. E.g. an i1 value will be 1277 /// identified as covering an n-bit fragment, if the store size of i1 is at 1278 /// least n bits. 1279 static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) { 1280 const DataLayout &DL = DII->getModule()->getDataLayout(); 1281 uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy); 1282 if (auto FragmentSize = DII->getFragmentSizeInBits()) 1283 return ValueSize >= *FragmentSize; 1284 // We can't always calculate the size of the DI variable (e.g. if it is a 1285 // VLA). Try to use the size of the alloca that the dbg intrinsic describes 1286 // intead. 1287 if (DII->isAddressOfVariable()) 1288 if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation())) 1289 if (auto FragmentSize = AI->getAllocationSizeInBits(DL)) 1290 return ValueSize >= *FragmentSize; 1291 // Could not determine size of variable. Conservatively return false. 1292 return false; 1293 } 1294 1295 /// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted 1296 /// to a dbg.value. Because no machine insts can come from debug intrinsics, 1297 /// only the scope and inlinedAt is significant. Zero line numbers are used in 1298 /// case this DebugLoc leaks into any adjacent instructions. 1299 static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) { 1300 // Original dbg.declare must have a location. 1301 DebugLoc DeclareLoc = DII->getDebugLoc(); 1302 MDNode *Scope = DeclareLoc.getScope(); 1303 DILocation *InlinedAt = DeclareLoc.getInlinedAt(); 1304 // Produce an unknown location with the correct scope / inlinedAt fields. 1305 return DebugLoc::get(0, 0, Scope, InlinedAt); 1306 } 1307 1308 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value 1309 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic. 1310 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, 1311 StoreInst *SI, DIBuilder &Builder) { 1312 assert(DII->isAddressOfVariable()); 1313 auto *DIVar = DII->getVariable(); 1314 assert(DIVar && "Missing variable"); 1315 auto *DIExpr = DII->getExpression(); 1316 Value *DV = SI->getValueOperand(); 1317 1318 DebugLoc NewLoc = getDebugValueLoc(DII, SI); 1319 1320 if (!valueCoversEntireFragment(DV->getType(), DII)) { 1321 // FIXME: If storing to a part of the variable described by the dbg.declare, 1322 // then we want to insert a dbg.value for the corresponding fragment. 1323 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " 1324 << *DII << '\n'); 1325 // For now, when there is a store to parts of the variable (but we do not 1326 // know which part) we insert an dbg.value instrinsic to indicate that we 1327 // know nothing about the variable's content. 1328 DV = UndefValue::get(DV->getType()); 1329 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI); 1330 return; 1331 } 1332 1333 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI); 1334 } 1335 1336 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value 1337 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic. 1338 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, 1339 LoadInst *LI, DIBuilder &Builder) { 1340 auto *DIVar = DII->getVariable(); 1341 auto *DIExpr = DII->getExpression(); 1342 assert(DIVar && "Missing variable"); 1343 1344 if (!valueCoversEntireFragment(LI->getType(), DII)) { 1345 // FIXME: If only referring to a part of the variable described by the 1346 // dbg.declare, then we want to insert a dbg.value for the corresponding 1347 // fragment. 1348 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " 1349 << *DII << '\n'); 1350 return; 1351 } 1352 1353 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr); 1354 1355 // We are now tracking the loaded value instead of the address. In the 1356 // future if multi-location support is added to the IR, it might be 1357 // preferable to keep tracking both the loaded value and the original 1358 // address in case the alloca can not be elided. 1359 Instruction *DbgValue = Builder.insertDbgValueIntrinsic( 1360 LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr); 1361 DbgValue->insertAfter(LI); 1362 } 1363 1364 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated 1365 /// llvm.dbg.declare or llvm.dbg.addr intrinsic. 1366 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, 1367 PHINode *APN, DIBuilder &Builder) { 1368 auto *DIVar = DII->getVariable(); 1369 auto *DIExpr = DII->getExpression(); 1370 assert(DIVar && "Missing variable"); 1371 1372 if (PhiHasDebugValue(DIVar, DIExpr, APN)) 1373 return; 1374 1375 if (!valueCoversEntireFragment(APN->getType(), DII)) { 1376 // FIXME: If only referring to a part of the variable described by the 1377 // dbg.declare, then we want to insert a dbg.value for the corresponding 1378 // fragment. 1379 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " 1380 << *DII << '\n'); 1381 return; 1382 } 1383 1384 BasicBlock *BB = APN->getParent(); 1385 auto InsertionPt = BB->getFirstInsertionPt(); 1386 1387 DebugLoc NewLoc = getDebugValueLoc(DII, nullptr); 1388 1389 // The block may be a catchswitch block, which does not have a valid 1390 // insertion point. 1391 // FIXME: Insert dbg.value markers in the successors when appropriate. 1392 if (InsertionPt != BB->end()) 1393 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt); 1394 } 1395 1396 /// Determine whether this alloca is either a VLA or an array. 1397 static bool isArray(AllocaInst *AI) { 1398 return AI->isArrayAllocation() || 1399 (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy()); 1400 } 1401 1402 /// Determine whether this alloca is a structure. 1403 static bool isStructure(AllocaInst *AI) { 1404 return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy(); 1405 } 1406 1407 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set 1408 /// of llvm.dbg.value intrinsics. 1409 bool llvm::LowerDbgDeclare(Function &F) { 1410 bool Changed = false; 1411 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false); 1412 SmallVector<DbgDeclareInst *, 4> Dbgs; 1413 for (auto &FI : F) 1414 for (Instruction &BI : FI) 1415 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI)) 1416 Dbgs.push_back(DDI); 1417 1418 if (Dbgs.empty()) 1419 return Changed; 1420 1421 for (auto &I : Dbgs) { 1422 DbgDeclareInst *DDI = I; 1423 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress()); 1424 // If this is an alloca for a scalar variable, insert a dbg.value 1425 // at each load and store to the alloca and erase the dbg.declare. 1426 // The dbg.values allow tracking a variable even if it is not 1427 // stored on the stack, while the dbg.declare can only describe 1428 // the stack slot (and at a lexical-scope granularity). Later 1429 // passes will attempt to elide the stack slot. 1430 if (!AI || isArray(AI) || isStructure(AI)) 1431 continue; 1432 1433 // A volatile load/store means that the alloca can't be elided anyway. 1434 if (llvm::any_of(AI->users(), [](User *U) -> bool { 1435 if (LoadInst *LI = dyn_cast<LoadInst>(U)) 1436 return LI->isVolatile(); 1437 if (StoreInst *SI = dyn_cast<StoreInst>(U)) 1438 return SI->isVolatile(); 1439 return false; 1440 })) 1441 continue; 1442 1443 SmallVector<const Value *, 8> WorkList; 1444 WorkList.push_back(AI); 1445 while (!WorkList.empty()) { 1446 const Value *V = WorkList.pop_back_val(); 1447 for (auto &AIUse : V->uses()) { 1448 User *U = AIUse.getUser(); 1449 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1450 if (AIUse.getOperandNo() == 1) 1451 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 1452 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 1453 ConvertDebugDeclareToDebugValue(DDI, LI, DIB); 1454 } else if (CallInst *CI = dyn_cast<CallInst>(U)) { 1455 // This is a call by-value or some other instruction that takes a 1456 // pointer to the variable. Insert a *value* intrinsic that describes 1457 // the variable by dereferencing the alloca. 1458 if (!CI->isLifetimeStartOrEnd()) { 1459 DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr); 1460 auto *DerefExpr = 1461 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref); 1462 DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr, 1463 NewLoc, CI); 1464 } 1465 } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) { 1466 if (BI->getType()->isPointerTy()) 1467 WorkList.push_back(BI); 1468 } 1469 } 1470 } 1471 DDI->eraseFromParent(); 1472 Changed = true; 1473 } 1474 1475 if (Changed) 1476 for (BasicBlock &BB : F) 1477 RemoveRedundantDbgInstrs(&BB); 1478 1479 return Changed; 1480 } 1481 1482 /// Propagate dbg.value intrinsics through the newly inserted PHIs. 1483 void llvm::insertDebugValuesForPHIs(BasicBlock *BB, 1484 SmallVectorImpl<PHINode *> &InsertedPHIs) { 1485 assert(BB && "No BasicBlock to clone dbg.value(s) from."); 1486 if (InsertedPHIs.size() == 0) 1487 return; 1488 1489 // Map existing PHI nodes to their dbg.values. 1490 ValueToValueMapTy DbgValueMap; 1491 for (auto &I : *BB) { 1492 if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) { 1493 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation())) 1494 DbgValueMap.insert({Loc, DbgII}); 1495 } 1496 } 1497 if (DbgValueMap.size() == 0) 1498 return; 1499 1500 // Then iterate through the new PHIs and look to see if they use one of the 1501 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will 1502 // propagate the info through the new PHI. 1503 LLVMContext &C = BB->getContext(); 1504 for (auto PHI : InsertedPHIs) { 1505 BasicBlock *Parent = PHI->getParent(); 1506 // Avoid inserting an intrinsic into an EH block. 1507 if (Parent->getFirstNonPHI()->isEHPad()) 1508 continue; 1509 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI)); 1510 for (auto VI : PHI->operand_values()) { 1511 auto V = DbgValueMap.find(VI); 1512 if (V != DbgValueMap.end()) { 1513 auto *DbgII = cast<DbgVariableIntrinsic>(V->second); 1514 Instruction *NewDbgII = DbgII->clone(); 1515 NewDbgII->setOperand(0, PhiMAV); 1516 auto InsertionPt = Parent->getFirstInsertionPt(); 1517 assert(InsertionPt != Parent->end() && "Ill-formed basic block"); 1518 NewDbgII->insertBefore(&*InsertionPt); 1519 } 1520 } 1521 } 1522 } 1523 1524 /// Finds all intrinsics declaring local variables as living in the memory that 1525 /// 'V' points to. This may include a mix of dbg.declare and 1526 /// dbg.addr intrinsics. 1527 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) { 1528 // This function is hot. Check whether the value has any metadata to avoid a 1529 // DenseMap lookup. 1530 if (!V->isUsedByMetadata()) 1531 return {}; 1532 auto *L = LocalAsMetadata::getIfExists(V); 1533 if (!L) 1534 return {}; 1535 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L); 1536 if (!MDV) 1537 return {}; 1538 1539 TinyPtrVector<DbgVariableIntrinsic *> Declares; 1540 for (User *U : MDV->users()) { 1541 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U)) 1542 if (DII->isAddressOfVariable()) 1543 Declares.push_back(DII); 1544 } 1545 1546 return Declares; 1547 } 1548 1549 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) { 1550 TinyPtrVector<DbgDeclareInst *> DDIs; 1551 for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V)) 1552 if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI)) 1553 DDIs.push_back(DDI); 1554 return DDIs; 1555 } 1556 1557 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) { 1558 // This function is hot. Check whether the value has any metadata to avoid a 1559 // DenseMap lookup. 1560 if (!V->isUsedByMetadata()) 1561 return; 1562 if (auto *L = LocalAsMetadata::getIfExists(V)) 1563 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) 1564 for (User *U : MDV->users()) 1565 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U)) 1566 DbgValues.push_back(DVI); 1567 } 1568 1569 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers, 1570 Value *V) { 1571 // This function is hot. Check whether the value has any metadata to avoid a 1572 // DenseMap lookup. 1573 if (!V->isUsedByMetadata()) 1574 return; 1575 if (auto *L = LocalAsMetadata::getIfExists(V)) 1576 if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) 1577 for (User *U : MDV->users()) 1578 if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U)) 1579 DbgUsers.push_back(DII); 1580 } 1581 1582 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress, 1583 DIBuilder &Builder, uint8_t DIExprFlags, 1584 int Offset) { 1585 auto DbgAddrs = FindDbgAddrUses(Address); 1586 for (DbgVariableIntrinsic *DII : DbgAddrs) { 1587 DebugLoc Loc = DII->getDebugLoc(); 1588 auto *DIVar = DII->getVariable(); 1589 auto *DIExpr = DII->getExpression(); 1590 assert(DIVar && "Missing variable"); 1591 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset); 1592 // Insert llvm.dbg.declare immediately before DII, and remove old 1593 // llvm.dbg.declare. 1594 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, DII); 1595 DII->eraseFromParent(); 1596 } 1597 return !DbgAddrs.empty(); 1598 } 1599 1600 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress, 1601 DIBuilder &Builder, int Offset) { 1602 DebugLoc Loc = DVI->getDebugLoc(); 1603 auto *DIVar = DVI->getVariable(); 1604 auto *DIExpr = DVI->getExpression(); 1605 assert(DIVar && "Missing variable"); 1606 1607 // This is an alloca-based llvm.dbg.value. The first thing it should do with 1608 // the alloca pointer is dereference it. Otherwise we don't know how to handle 1609 // it and give up. 1610 if (!DIExpr || DIExpr->getNumElements() < 1 || 1611 DIExpr->getElement(0) != dwarf::DW_OP_deref) 1612 return; 1613 1614 // Insert the offset before the first deref. 1615 // We could just change the offset argument of dbg.value, but it's unsigned... 1616 if (Offset) 1617 DIExpr = DIExpression::prepend(DIExpr, 0, Offset); 1618 1619 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI); 1620 DVI->eraseFromParent(); 1621 } 1622 1623 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, 1624 DIBuilder &Builder, int Offset) { 1625 if (auto *L = LocalAsMetadata::getIfExists(AI)) 1626 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L)) 1627 for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) { 1628 Use &U = *UI++; 1629 if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser())) 1630 replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset); 1631 } 1632 } 1633 1634 /// Wrap \p V in a ValueAsMetadata instance. 1635 static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) { 1636 return MetadataAsValue::get(C, ValueAsMetadata::get(V)); 1637 } 1638 1639 /// Where possible to salvage debug information for \p I do so 1640 /// and return True. If not possible mark undef and return False. 1641 void llvm::salvageDebugInfo(Instruction &I) { 1642 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers; 1643 findDbgUsers(DbgUsers, &I); 1644 salvageDebugInfoForDbgValues(I, DbgUsers); 1645 } 1646 1647 void llvm::salvageDebugInfoForDbgValues( 1648 Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) { 1649 auto &Ctx = I.getContext(); 1650 bool Salvaged = false; 1651 auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); }; 1652 1653 for (auto *DII : DbgUsers) { 1654 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they 1655 // are implicitly pointing out the value as a DWARF memory location 1656 // description. 1657 bool StackValue = isa<DbgValueInst>(DII); 1658 1659 DIExpression *DIExpr = 1660 salvageDebugInfoImpl(I, DII->getExpression(), StackValue); 1661 1662 // salvageDebugInfoImpl should fail on examining the first element of 1663 // DbgUsers, or none of them. 1664 if (!DIExpr) 1665 break; 1666 1667 DII->setOperand(0, wrapMD(I.getOperand(0))); 1668 DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr)); 1669 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n'); 1670 Salvaged = true; 1671 } 1672 1673 if (Salvaged) 1674 return; 1675 1676 for (auto *DII : DbgUsers) { 1677 Value *Undef = UndefValue::get(I.getType()); 1678 DII->setOperand(0, MetadataAsValue::get(DII->getContext(), 1679 ValueAsMetadata::get(Undef))); 1680 } 1681 } 1682 1683 DIExpression *llvm::salvageDebugInfoImpl(Instruction &I, 1684 DIExpression *SrcDIExpr, 1685 bool WithStackValue) { 1686 auto &M = *I.getModule(); 1687 auto &DL = M.getDataLayout(); 1688 1689 // Apply a vector of opcodes to the source DIExpression. 1690 auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * { 1691 DIExpression *DIExpr = SrcDIExpr; 1692 if (!Ops.empty()) { 1693 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue); 1694 } 1695 return DIExpr; 1696 }; 1697 1698 // Apply the given offset to the source DIExpression. 1699 auto applyOffset = [&](uint64_t Offset) -> DIExpression * { 1700 SmallVector<uint64_t, 8> Ops; 1701 DIExpression::appendOffset(Ops, Offset); 1702 return doSalvage(Ops); 1703 }; 1704 1705 // initializer-list helper for applying operators to the source DIExpression. 1706 auto applyOps = [&](ArrayRef<uint64_t> Opcodes) -> DIExpression * { 1707 SmallVector<uint64_t, 8> Ops(Opcodes.begin(), Opcodes.end()); 1708 return doSalvage(Ops); 1709 }; 1710 1711 if (auto *CI = dyn_cast<CastInst>(&I)) { 1712 // No-op casts are irrelevant for debug info. 1713 if (CI->isNoopCast(DL)) 1714 return SrcDIExpr; 1715 1716 Type *Type = CI->getType(); 1717 // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged. 1718 if (Type->isVectorTy() || 1719 !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I))) 1720 return nullptr; 1721 1722 Value *FromValue = CI->getOperand(0); 1723 unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits(); 1724 unsigned ToTypeBitSize = Type->getScalarSizeInBits(); 1725 1726 return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize, 1727 isa<SExtInst>(&I))); 1728 } 1729 1730 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 1731 unsigned BitWidth = 1732 M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace()); 1733 // Rewrite a constant GEP into a DIExpression. 1734 APInt Offset(BitWidth, 0); 1735 if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) { 1736 return applyOffset(Offset.getSExtValue()); 1737 } else { 1738 return nullptr; 1739 } 1740 } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) { 1741 // Rewrite binary operations with constant integer operands. 1742 auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1)); 1743 if (!ConstInt || ConstInt->getBitWidth() > 64) 1744 return nullptr; 1745 1746 uint64_t Val = ConstInt->getSExtValue(); 1747 switch (BI->getOpcode()) { 1748 case Instruction::Add: 1749 return applyOffset(Val); 1750 case Instruction::Sub: 1751 return applyOffset(-int64_t(Val)); 1752 case Instruction::Mul: 1753 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul}); 1754 case Instruction::SDiv: 1755 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div}); 1756 case Instruction::SRem: 1757 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod}); 1758 case Instruction::Or: 1759 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or}); 1760 case Instruction::And: 1761 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and}); 1762 case Instruction::Xor: 1763 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor}); 1764 case Instruction::Shl: 1765 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl}); 1766 case Instruction::LShr: 1767 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr}); 1768 case Instruction::AShr: 1769 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra}); 1770 default: 1771 // TODO: Salvage constants from each kind of binop we know about. 1772 return nullptr; 1773 } 1774 // *Not* to do: we should not attempt to salvage load instructions, 1775 // because the validity and lifetime of a dbg.value containing 1776 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples. 1777 } 1778 return nullptr; 1779 } 1780 1781 /// A replacement for a dbg.value expression. 1782 using DbgValReplacement = Optional<DIExpression *>; 1783 1784 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr, 1785 /// possibly moving/undefing users to prevent use-before-def. Returns true if 1786 /// changes are made. 1787 static bool rewriteDebugUsers( 1788 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT, 1789 function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) { 1790 // Find debug users of From. 1791 SmallVector<DbgVariableIntrinsic *, 1> Users; 1792 findDbgUsers(Users, &From); 1793 if (Users.empty()) 1794 return false; 1795 1796 // Prevent use-before-def of To. 1797 bool Changed = false; 1798 SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage; 1799 if (isa<Instruction>(&To)) { 1800 bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint; 1801 1802 for (auto *DII : Users) { 1803 // It's common to see a debug user between From and DomPoint. Move it 1804 // after DomPoint to preserve the variable update without any reordering. 1805 if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) { 1806 LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n'); 1807 DII->moveAfter(&DomPoint); 1808 Changed = true; 1809 1810 // Users which otherwise aren't dominated by the replacement value must 1811 // be salvaged or deleted. 1812 } else if (!DT.dominates(&DomPoint, DII)) { 1813 UndefOrSalvage.insert(DII); 1814 } 1815 } 1816 } 1817 1818 // Update debug users without use-before-def risk. 1819 for (auto *DII : Users) { 1820 if (UndefOrSalvage.count(DII)) 1821 continue; 1822 1823 LLVMContext &Ctx = DII->getContext(); 1824 DbgValReplacement DVR = RewriteExpr(*DII); 1825 if (!DVR) 1826 continue; 1827 1828 DII->setOperand(0, wrapValueInMetadata(Ctx, &To)); 1829 DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR)); 1830 LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n'); 1831 Changed = true; 1832 } 1833 1834 if (!UndefOrSalvage.empty()) { 1835 // Try to salvage the remaining debug users. 1836 salvageDebugInfo(From); 1837 Changed = true; 1838 } 1839 1840 return Changed; 1841 } 1842 1843 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would 1844 /// losslessly preserve the bits and semantics of the value. This predicate is 1845 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result. 1846 /// 1847 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it 1848 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>, 1849 /// and also does not allow lossless pointer <-> integer conversions. 1850 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy, 1851 Type *ToTy) { 1852 // Trivially compatible types. 1853 if (FromTy == ToTy) 1854 return true; 1855 1856 // Handle compatible pointer <-> integer conversions. 1857 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) { 1858 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy); 1859 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) && 1860 !DL.isNonIntegralPointerType(ToTy); 1861 return SameSize && LosslessConversion; 1862 } 1863 1864 // TODO: This is not exhaustive. 1865 return false; 1866 } 1867 1868 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To, 1869 Instruction &DomPoint, DominatorTree &DT) { 1870 // Exit early if From has no debug users. 1871 if (!From.isUsedByMetadata()) 1872 return false; 1873 1874 assert(&From != &To && "Can't replace something with itself"); 1875 1876 Type *FromTy = From.getType(); 1877 Type *ToTy = To.getType(); 1878 1879 auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement { 1880 return DII.getExpression(); 1881 }; 1882 1883 // Handle no-op conversions. 1884 Module &M = *From.getModule(); 1885 const DataLayout &DL = M.getDataLayout(); 1886 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy)) 1887 return rewriteDebugUsers(From, To, DomPoint, DT, Identity); 1888 1889 // Handle integer-to-integer widening and narrowing. 1890 // FIXME: Use DW_OP_convert when it's available everywhere. 1891 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) { 1892 uint64_t FromBits = FromTy->getPrimitiveSizeInBits(); 1893 uint64_t ToBits = ToTy->getPrimitiveSizeInBits(); 1894 assert(FromBits != ToBits && "Unexpected no-op conversion"); 1895 1896 // When the width of the result grows, assume that a debugger will only 1897 // access the low `FromBits` bits when inspecting the source variable. 1898 if (FromBits < ToBits) 1899 return rewriteDebugUsers(From, To, DomPoint, DT, Identity); 1900 1901 // The width of the result has shrunk. Use sign/zero extension to describe 1902 // the source variable's high bits. 1903 auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement { 1904 DILocalVariable *Var = DII.getVariable(); 1905 1906 // Without knowing signedness, sign/zero extension isn't possible. 1907 auto Signedness = Var->getSignedness(); 1908 if (!Signedness) 1909 return None; 1910 1911 bool Signed = *Signedness == DIBasicType::Signedness::Signed; 1912 return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits, 1913 Signed); 1914 }; 1915 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt); 1916 } 1917 1918 // TODO: Floating-point conversions, vectors. 1919 return false; 1920 } 1921 1922 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) { 1923 unsigned NumDeadInst = 0; 1924 // Delete the instructions backwards, as it has a reduced likelihood of 1925 // having to update as many def-use and use-def chains. 1926 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. 1927 while (EndInst != &BB->front()) { 1928 // Delete the next to last instruction. 1929 Instruction *Inst = &*--EndInst->getIterator(); 1930 if (!Inst->use_empty() && !Inst->getType()->isTokenTy()) 1931 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); 1932 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) { 1933 EndInst = Inst; 1934 continue; 1935 } 1936 if (!isa<DbgInfoIntrinsic>(Inst)) 1937 ++NumDeadInst; 1938 Inst->eraseFromParent(); 1939 } 1940 return NumDeadInst; 1941 } 1942 1943 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap, 1944 bool PreserveLCSSA, DomTreeUpdater *DTU, 1945 MemorySSAUpdater *MSSAU) { 1946 BasicBlock *BB = I->getParent(); 1947 std::vector <DominatorTree::UpdateType> Updates; 1948 1949 if (MSSAU) 1950 MSSAU->changeToUnreachable(I); 1951 1952 // Loop over all of the successors, removing BB's entry from any PHI 1953 // nodes. 1954 if (DTU) 1955 Updates.reserve(BB->getTerminator()->getNumSuccessors()); 1956 for (BasicBlock *Successor : successors(BB)) { 1957 Successor->removePredecessor(BB, PreserveLCSSA); 1958 if (DTU) 1959 Updates.push_back({DominatorTree::Delete, BB, Successor}); 1960 } 1961 // Insert a call to llvm.trap right before this. This turns the undefined 1962 // behavior into a hard fail instead of falling through into random code. 1963 if (UseLLVMTrap) { 1964 Function *TrapFn = 1965 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap); 1966 CallInst *CallTrap = CallInst::Create(TrapFn, "", I); 1967 CallTrap->setDebugLoc(I->getDebugLoc()); 1968 } 1969 auto *UI = new UnreachableInst(I->getContext(), I); 1970 UI->setDebugLoc(I->getDebugLoc()); 1971 1972 // All instructions after this are dead. 1973 unsigned NumInstrsRemoved = 0; 1974 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end(); 1975 while (BBI != BBE) { 1976 if (!BBI->use_empty()) 1977 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 1978 BB->getInstList().erase(BBI++); 1979 ++NumInstrsRemoved; 1980 } 1981 if (DTU) 1982 DTU->applyUpdatesPermissive(Updates); 1983 return NumInstrsRemoved; 1984 } 1985 1986 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) { 1987 SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end()); 1988 SmallVector<OperandBundleDef, 1> OpBundles; 1989 II->getOperandBundlesAsDefs(OpBundles); 1990 CallInst *NewCall = CallInst::Create(II->getFunctionType(), 1991 II->getCalledOperand(), Args, OpBundles); 1992 NewCall->setCallingConv(II->getCallingConv()); 1993 NewCall->setAttributes(II->getAttributes()); 1994 NewCall->setDebugLoc(II->getDebugLoc()); 1995 NewCall->copyMetadata(*II); 1996 1997 // If the invoke had profile metadata, try converting them for CallInst. 1998 uint64_t TotalWeight; 1999 if (NewCall->extractProfTotalWeight(TotalWeight)) { 2000 // Set the total weight if it fits into i32, otherwise reset. 2001 MDBuilder MDB(NewCall->getContext()); 2002 auto NewWeights = uint32_t(TotalWeight) != TotalWeight 2003 ? nullptr 2004 : MDB.createBranchWeights({uint32_t(TotalWeight)}); 2005 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights); 2006 } 2007 2008 return NewCall; 2009 } 2010 2011 /// changeToCall - Convert the specified invoke into a normal call. 2012 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) { 2013 CallInst *NewCall = createCallMatchingInvoke(II); 2014 NewCall->takeName(II); 2015 NewCall->insertBefore(II); 2016 II->replaceAllUsesWith(NewCall); 2017 2018 // Follow the call by a branch to the normal destination. 2019 BasicBlock *NormalDestBB = II->getNormalDest(); 2020 BranchInst::Create(NormalDestBB, II); 2021 2022 // Update PHI nodes in the unwind destination 2023 BasicBlock *BB = II->getParent(); 2024 BasicBlock *UnwindDestBB = II->getUnwindDest(); 2025 UnwindDestBB->removePredecessor(BB); 2026 II->eraseFromParent(); 2027 if (DTU) 2028 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}}); 2029 } 2030 2031 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI, 2032 BasicBlock *UnwindEdge) { 2033 BasicBlock *BB = CI->getParent(); 2034 2035 // Convert this function call into an invoke instruction. First, split the 2036 // basic block. 2037 BasicBlock *Split = 2038 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc"); 2039 2040 // Delete the unconditional branch inserted by splitBasicBlock 2041 BB->getInstList().pop_back(); 2042 2043 // Create the new invoke instruction. 2044 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end()); 2045 SmallVector<OperandBundleDef, 1> OpBundles; 2046 2047 CI->getOperandBundlesAsDefs(OpBundles); 2048 2049 // Note: we're round tripping operand bundles through memory here, and that 2050 // can potentially be avoided with a cleverer API design that we do not have 2051 // as of this time. 2052 2053 InvokeInst *II = 2054 InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split, 2055 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB); 2056 II->setDebugLoc(CI->getDebugLoc()); 2057 II->setCallingConv(CI->getCallingConv()); 2058 II->setAttributes(CI->getAttributes()); 2059 2060 // Make sure that anything using the call now uses the invoke! This also 2061 // updates the CallGraph if present, because it uses a WeakTrackingVH. 2062 CI->replaceAllUsesWith(II); 2063 2064 // Delete the original call 2065 Split->getInstList().pop_front(); 2066 return Split; 2067 } 2068 2069 static bool markAliveBlocks(Function &F, 2070 SmallPtrSetImpl<BasicBlock *> &Reachable, 2071 DomTreeUpdater *DTU = nullptr) { 2072 SmallVector<BasicBlock*, 128> Worklist; 2073 BasicBlock *BB = &F.front(); 2074 Worklist.push_back(BB); 2075 Reachable.insert(BB); 2076 bool Changed = false; 2077 do { 2078 BB = Worklist.pop_back_val(); 2079 2080 // Do a quick scan of the basic block, turning any obviously unreachable 2081 // instructions into LLVM unreachable insts. The instruction combining pass 2082 // canonicalizes unreachable insts into stores to null or undef. 2083 for (Instruction &I : *BB) { 2084 if (auto *CI = dyn_cast<CallInst>(&I)) { 2085 Value *Callee = CI->getCalledOperand(); 2086 // Handle intrinsic calls. 2087 if (Function *F = dyn_cast<Function>(Callee)) { 2088 auto IntrinsicID = F->getIntrinsicID(); 2089 // Assumptions that are known to be false are equivalent to 2090 // unreachable. Also, if the condition is undefined, then we make the 2091 // choice most beneficial to the optimizer, and choose that to also be 2092 // unreachable. 2093 if (IntrinsicID == Intrinsic::assume) { 2094 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) { 2095 // Don't insert a call to llvm.trap right before the unreachable. 2096 changeToUnreachable(CI, false, false, DTU); 2097 Changed = true; 2098 break; 2099 } 2100 } else if (IntrinsicID == Intrinsic::experimental_guard) { 2101 // A call to the guard intrinsic bails out of the current 2102 // compilation unit if the predicate passed to it is false. If the 2103 // predicate is a constant false, then we know the guard will bail 2104 // out of the current compile unconditionally, so all code following 2105 // it is dead. 2106 // 2107 // Note: unlike in llvm.assume, it is not "obviously profitable" for 2108 // guards to treat `undef` as `false` since a guard on `undef` can 2109 // still be useful for widening. 2110 if (match(CI->getArgOperand(0), m_Zero())) 2111 if (!isa<UnreachableInst>(CI->getNextNode())) { 2112 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false, 2113 false, DTU); 2114 Changed = true; 2115 break; 2116 } 2117 } 2118 } else if ((isa<ConstantPointerNull>(Callee) && 2119 !NullPointerIsDefined(CI->getFunction())) || 2120 isa<UndefValue>(Callee)) { 2121 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU); 2122 Changed = true; 2123 break; 2124 } 2125 if (CI->doesNotReturn() && !CI->isMustTailCall()) { 2126 // If we found a call to a no-return function, insert an unreachable 2127 // instruction after it. Make sure there isn't *already* one there 2128 // though. 2129 if (!isa<UnreachableInst>(CI->getNextNode())) { 2130 // Don't insert a call to llvm.trap right before the unreachable. 2131 changeToUnreachable(CI->getNextNode(), false, false, DTU); 2132 Changed = true; 2133 } 2134 break; 2135 } 2136 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 2137 // Store to undef and store to null are undefined and used to signal 2138 // that they should be changed to unreachable by passes that can't 2139 // modify the CFG. 2140 2141 // Don't touch volatile stores. 2142 if (SI->isVolatile()) continue; 2143 2144 Value *Ptr = SI->getOperand(1); 2145 2146 if (isa<UndefValue>(Ptr) || 2147 (isa<ConstantPointerNull>(Ptr) && 2148 !NullPointerIsDefined(SI->getFunction(), 2149 SI->getPointerAddressSpace()))) { 2150 changeToUnreachable(SI, true, false, DTU); 2151 Changed = true; 2152 break; 2153 } 2154 } 2155 } 2156 2157 Instruction *Terminator = BB->getTerminator(); 2158 if (auto *II = dyn_cast<InvokeInst>(Terminator)) { 2159 // Turn invokes that call 'nounwind' functions into ordinary calls. 2160 Value *Callee = II->getCalledOperand(); 2161 if ((isa<ConstantPointerNull>(Callee) && 2162 !NullPointerIsDefined(BB->getParent())) || 2163 isa<UndefValue>(Callee)) { 2164 changeToUnreachable(II, true, false, DTU); 2165 Changed = true; 2166 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) { 2167 if (II->use_empty() && II->onlyReadsMemory()) { 2168 // jump to the normal destination branch. 2169 BasicBlock *NormalDestBB = II->getNormalDest(); 2170 BasicBlock *UnwindDestBB = II->getUnwindDest(); 2171 BranchInst::Create(NormalDestBB, II); 2172 UnwindDestBB->removePredecessor(II->getParent()); 2173 II->eraseFromParent(); 2174 if (DTU) 2175 DTU->applyUpdatesPermissive( 2176 {{DominatorTree::Delete, BB, UnwindDestBB}}); 2177 } else 2178 changeToCall(II, DTU); 2179 Changed = true; 2180 } 2181 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) { 2182 // Remove catchpads which cannot be reached. 2183 struct CatchPadDenseMapInfo { 2184 static CatchPadInst *getEmptyKey() { 2185 return DenseMapInfo<CatchPadInst *>::getEmptyKey(); 2186 } 2187 2188 static CatchPadInst *getTombstoneKey() { 2189 return DenseMapInfo<CatchPadInst *>::getTombstoneKey(); 2190 } 2191 2192 static unsigned getHashValue(CatchPadInst *CatchPad) { 2193 return static_cast<unsigned>(hash_combine_range( 2194 CatchPad->value_op_begin(), CatchPad->value_op_end())); 2195 } 2196 2197 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) { 2198 if (LHS == getEmptyKey() || LHS == getTombstoneKey() || 2199 RHS == getEmptyKey() || RHS == getTombstoneKey()) 2200 return LHS == RHS; 2201 return LHS->isIdenticalTo(RHS); 2202 } 2203 }; 2204 2205 // Set of unique CatchPads. 2206 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4, 2207 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>> 2208 HandlerSet; 2209 detail::DenseSetEmpty Empty; 2210 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(), 2211 E = CatchSwitch->handler_end(); 2212 I != E; ++I) { 2213 BasicBlock *HandlerBB = *I; 2214 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI()); 2215 if (!HandlerSet.insert({CatchPad, Empty}).second) { 2216 CatchSwitch->removeHandler(I); 2217 --I; 2218 --E; 2219 Changed = true; 2220 } 2221 } 2222 } 2223 2224 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU); 2225 for (BasicBlock *Successor : successors(BB)) 2226 if (Reachable.insert(Successor).second) 2227 Worklist.push_back(Successor); 2228 } while (!Worklist.empty()); 2229 return Changed; 2230 } 2231 2232 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) { 2233 Instruction *TI = BB->getTerminator(); 2234 2235 if (auto *II = dyn_cast<InvokeInst>(TI)) { 2236 changeToCall(II, DTU); 2237 return; 2238 } 2239 2240 Instruction *NewTI; 2241 BasicBlock *UnwindDest; 2242 2243 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 2244 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI); 2245 UnwindDest = CRI->getUnwindDest(); 2246 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) { 2247 auto *NewCatchSwitch = CatchSwitchInst::Create( 2248 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(), 2249 CatchSwitch->getName(), CatchSwitch); 2250 for (BasicBlock *PadBB : CatchSwitch->handlers()) 2251 NewCatchSwitch->addHandler(PadBB); 2252 2253 NewTI = NewCatchSwitch; 2254 UnwindDest = CatchSwitch->getUnwindDest(); 2255 } else { 2256 llvm_unreachable("Could not find unwind successor"); 2257 } 2258 2259 NewTI->takeName(TI); 2260 NewTI->setDebugLoc(TI->getDebugLoc()); 2261 UnwindDest->removePredecessor(BB); 2262 TI->replaceAllUsesWith(NewTI); 2263 TI->eraseFromParent(); 2264 if (DTU) 2265 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}}); 2266 } 2267 2268 /// removeUnreachableBlocks - Remove blocks that are not reachable, even 2269 /// if they are in a dead cycle. Return true if a change was made, false 2270 /// otherwise. 2271 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU, 2272 MemorySSAUpdater *MSSAU) { 2273 SmallPtrSet<BasicBlock *, 16> Reachable; 2274 bool Changed = markAliveBlocks(F, Reachable, DTU); 2275 2276 // If there are unreachable blocks in the CFG... 2277 if (Reachable.size() == F.size()) 2278 return Changed; 2279 2280 assert(Reachable.size() < F.size()); 2281 NumRemoved += F.size() - Reachable.size(); 2282 2283 SmallSetVector<BasicBlock *, 8> DeadBlockSet; 2284 for (BasicBlock &BB : F) { 2285 // Skip reachable basic blocks 2286 if (Reachable.count(&BB)) 2287 continue; 2288 DeadBlockSet.insert(&BB); 2289 } 2290 2291 if (MSSAU) 2292 MSSAU->removeBlocks(DeadBlockSet); 2293 2294 // Loop over all of the basic blocks that are not reachable, dropping all of 2295 // their internal references. Update DTU if available. 2296 std::vector<DominatorTree::UpdateType> Updates; 2297 for (auto *BB : DeadBlockSet) { 2298 for (BasicBlock *Successor : successors(BB)) { 2299 if (!DeadBlockSet.count(Successor)) 2300 Successor->removePredecessor(BB); 2301 if (DTU) 2302 Updates.push_back({DominatorTree::Delete, BB, Successor}); 2303 } 2304 BB->dropAllReferences(); 2305 if (DTU) { 2306 Instruction *TI = BB->getTerminator(); 2307 assert(TI && "Basic block should have a terminator"); 2308 // Terminators like invoke can have users. We have to replace their users, 2309 // before removing them. 2310 if (!TI->use_empty()) 2311 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 2312 TI->eraseFromParent(); 2313 new UnreachableInst(BB->getContext(), BB); 2314 assert(succ_empty(BB) && "The successor list of BB isn't empty before " 2315 "applying corresponding DTU updates."); 2316 } 2317 } 2318 2319 if (DTU) { 2320 DTU->applyUpdatesPermissive(Updates); 2321 bool Deleted = false; 2322 for (auto *BB : DeadBlockSet) { 2323 if (DTU->isBBPendingDeletion(BB)) 2324 --NumRemoved; 2325 else 2326 Deleted = true; 2327 DTU->deleteBB(BB); 2328 } 2329 if (!Deleted) 2330 return false; 2331 } else { 2332 for (auto *BB : DeadBlockSet) 2333 BB->eraseFromParent(); 2334 } 2335 2336 return true; 2337 } 2338 2339 void llvm::combineMetadata(Instruction *K, const Instruction *J, 2340 ArrayRef<unsigned> KnownIDs, bool DoesKMove) { 2341 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 2342 K->dropUnknownNonDebugMetadata(KnownIDs); 2343 K->getAllMetadataOtherThanDebugLoc(Metadata); 2344 for (const auto &MD : Metadata) { 2345 unsigned Kind = MD.first; 2346 MDNode *JMD = J->getMetadata(Kind); 2347 MDNode *KMD = MD.second; 2348 2349 switch (Kind) { 2350 default: 2351 K->setMetadata(Kind, nullptr); // Remove unknown metadata 2352 break; 2353 case LLVMContext::MD_dbg: 2354 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg"); 2355 case LLVMContext::MD_tbaa: 2356 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD)); 2357 break; 2358 case LLVMContext::MD_alias_scope: 2359 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD)); 2360 break; 2361 case LLVMContext::MD_noalias: 2362 case LLVMContext::MD_mem_parallel_loop_access: 2363 K->setMetadata(Kind, MDNode::intersect(JMD, KMD)); 2364 break; 2365 case LLVMContext::MD_access_group: 2366 K->setMetadata(LLVMContext::MD_access_group, 2367 intersectAccessGroups(K, J)); 2368 break; 2369 case LLVMContext::MD_range: 2370 2371 // If K does move, use most generic range. Otherwise keep the range of 2372 // K. 2373 if (DoesKMove) 2374 // FIXME: If K does move, we should drop the range info and nonnull. 2375 // Currently this function is used with DoesKMove in passes 2376 // doing hoisting/sinking and the current behavior of using the 2377 // most generic range is correct in those cases. 2378 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD)); 2379 break; 2380 case LLVMContext::MD_fpmath: 2381 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD)); 2382 break; 2383 case LLVMContext::MD_invariant_load: 2384 // Only set the !invariant.load if it is present in both instructions. 2385 K->setMetadata(Kind, JMD); 2386 break; 2387 case LLVMContext::MD_nonnull: 2388 // If K does move, keep nonull if it is present in both instructions. 2389 if (DoesKMove) 2390 K->setMetadata(Kind, JMD); 2391 break; 2392 case LLVMContext::MD_invariant_group: 2393 // Preserve !invariant.group in K. 2394 break; 2395 case LLVMContext::MD_align: 2396 K->setMetadata(Kind, 2397 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); 2398 break; 2399 case LLVMContext::MD_dereferenceable: 2400 case LLVMContext::MD_dereferenceable_or_null: 2401 K->setMetadata(Kind, 2402 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); 2403 break; 2404 case LLVMContext::MD_preserve_access_index: 2405 // Preserve !preserve.access.index in K. 2406 break; 2407 } 2408 } 2409 // Set !invariant.group from J if J has it. If both instructions have it 2410 // then we will just pick it from J - even when they are different. 2411 // Also make sure that K is load or store - f.e. combining bitcast with load 2412 // could produce bitcast with invariant.group metadata, which is invalid. 2413 // FIXME: we should try to preserve both invariant.group md if they are 2414 // different, but right now instruction can only have one invariant.group. 2415 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group)) 2416 if (isa<LoadInst>(K) || isa<StoreInst>(K)) 2417 K->setMetadata(LLVMContext::MD_invariant_group, JMD); 2418 } 2419 2420 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J, 2421 bool KDominatesJ) { 2422 unsigned KnownIDs[] = { 2423 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 2424 LLVMContext::MD_noalias, LLVMContext::MD_range, 2425 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull, 2426 LLVMContext::MD_invariant_group, LLVMContext::MD_align, 2427 LLVMContext::MD_dereferenceable, 2428 LLVMContext::MD_dereferenceable_or_null, 2429 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index}; 2430 combineMetadata(K, J, KnownIDs, KDominatesJ); 2431 } 2432 2433 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) { 2434 SmallVector<std::pair<unsigned, MDNode *>, 8> MD; 2435 Source.getAllMetadata(MD); 2436 MDBuilder MDB(Dest.getContext()); 2437 Type *NewType = Dest.getType(); 2438 const DataLayout &DL = Source.getModule()->getDataLayout(); 2439 for (const auto &MDPair : MD) { 2440 unsigned ID = MDPair.first; 2441 MDNode *N = MDPair.second; 2442 // Note, essentially every kind of metadata should be preserved here! This 2443 // routine is supposed to clone a load instruction changing *only its type*. 2444 // The only metadata it makes sense to drop is metadata which is invalidated 2445 // when the pointer type changes. This should essentially never be the case 2446 // in LLVM, but we explicitly switch over only known metadata to be 2447 // conservatively correct. If you are adding metadata to LLVM which pertains 2448 // to loads, you almost certainly want to add it here. 2449 switch (ID) { 2450 case LLVMContext::MD_dbg: 2451 case LLVMContext::MD_tbaa: 2452 case LLVMContext::MD_prof: 2453 case LLVMContext::MD_fpmath: 2454 case LLVMContext::MD_tbaa_struct: 2455 case LLVMContext::MD_invariant_load: 2456 case LLVMContext::MD_alias_scope: 2457 case LLVMContext::MD_noalias: 2458 case LLVMContext::MD_nontemporal: 2459 case LLVMContext::MD_mem_parallel_loop_access: 2460 case LLVMContext::MD_access_group: 2461 // All of these directly apply. 2462 Dest.setMetadata(ID, N); 2463 break; 2464 2465 case LLVMContext::MD_nonnull: 2466 copyNonnullMetadata(Source, N, Dest); 2467 break; 2468 2469 case LLVMContext::MD_align: 2470 case LLVMContext::MD_dereferenceable: 2471 case LLVMContext::MD_dereferenceable_or_null: 2472 // These only directly apply if the new type is also a pointer. 2473 if (NewType->isPointerTy()) 2474 Dest.setMetadata(ID, N); 2475 break; 2476 2477 case LLVMContext::MD_range: 2478 copyRangeMetadata(DL, Source, N, Dest); 2479 break; 2480 } 2481 } 2482 } 2483 2484 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) { 2485 auto *ReplInst = dyn_cast<Instruction>(Repl); 2486 if (!ReplInst) 2487 return; 2488 2489 // Patch the replacement so that it is not more restrictive than the value 2490 // being replaced. 2491 // Note that if 'I' is a load being replaced by some operation, 2492 // for example, by an arithmetic operation, then andIRFlags() 2493 // would just erase all math flags from the original arithmetic 2494 // operation, which is clearly not wanted and not needed. 2495 if (!isa<LoadInst>(I)) 2496 ReplInst->andIRFlags(I); 2497 2498 // FIXME: If both the original and replacement value are part of the 2499 // same control-flow region (meaning that the execution of one 2500 // guarantees the execution of the other), then we can combine the 2501 // noalias scopes here and do better than the general conservative 2502 // answer used in combineMetadata(). 2503 2504 // In general, GVN unifies expressions over different control-flow 2505 // regions, and so we need a conservative combination of the noalias 2506 // scopes. 2507 static const unsigned KnownIDs[] = { 2508 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 2509 LLVMContext::MD_noalias, LLVMContext::MD_range, 2510 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, 2511 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull, 2512 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index}; 2513 combineMetadata(ReplInst, I, KnownIDs, false); 2514 } 2515 2516 template <typename RootType, typename DominatesFn> 2517 static unsigned replaceDominatedUsesWith(Value *From, Value *To, 2518 const RootType &Root, 2519 const DominatesFn &Dominates) { 2520 assert(From->getType() == To->getType()); 2521 2522 unsigned Count = 0; 2523 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); 2524 UI != UE;) { 2525 Use &U = *UI++; 2526 if (!Dominates(Root, U)) 2527 continue; 2528 U.set(To); 2529 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName() 2530 << "' as " << *To << " in " << *U << "\n"); 2531 ++Count; 2532 } 2533 return Count; 2534 } 2535 2536 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) { 2537 assert(From->getType() == To->getType()); 2538 auto *BB = From->getParent(); 2539 unsigned Count = 0; 2540 2541 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); 2542 UI != UE;) { 2543 Use &U = *UI++; 2544 auto *I = cast<Instruction>(U.getUser()); 2545 if (I->getParent() == BB) 2546 continue; 2547 U.set(To); 2548 ++Count; 2549 } 2550 return Count; 2551 } 2552 2553 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, 2554 DominatorTree &DT, 2555 const BasicBlockEdge &Root) { 2556 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) { 2557 return DT.dominates(Root, U); 2558 }; 2559 return ::replaceDominatedUsesWith(From, To, Root, Dominates); 2560 } 2561 2562 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, 2563 DominatorTree &DT, 2564 const BasicBlock *BB) { 2565 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) { 2566 auto *I = cast<Instruction>(U.getUser())->getParent(); 2567 return DT.properlyDominates(BB, I); 2568 }; 2569 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates); 2570 } 2571 2572 bool llvm::callsGCLeafFunction(const CallBase *Call, 2573 const TargetLibraryInfo &TLI) { 2574 // Check if the function is specifically marked as a gc leaf function. 2575 if (Call->hasFnAttr("gc-leaf-function")) 2576 return true; 2577 if (const Function *F = Call->getCalledFunction()) { 2578 if (F->hasFnAttribute("gc-leaf-function")) 2579 return true; 2580 2581 if (auto IID = F->getIntrinsicID()) 2582 // Most LLVM intrinsics do not take safepoints. 2583 return IID != Intrinsic::experimental_gc_statepoint && 2584 IID != Intrinsic::experimental_deoptimize; 2585 } 2586 2587 // Lib calls can be materialized by some passes, and won't be 2588 // marked as 'gc-leaf-function.' All available Libcalls are 2589 // GC-leaf. 2590 LibFunc LF; 2591 if (TLI.getLibFunc(*Call, LF)) { 2592 return TLI.has(LF); 2593 } 2594 2595 return false; 2596 } 2597 2598 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, 2599 LoadInst &NewLI) { 2600 auto *NewTy = NewLI.getType(); 2601 2602 // This only directly applies if the new type is also a pointer. 2603 if (NewTy->isPointerTy()) { 2604 NewLI.setMetadata(LLVMContext::MD_nonnull, N); 2605 return; 2606 } 2607 2608 // The only other translation we can do is to integral loads with !range 2609 // metadata. 2610 if (!NewTy->isIntegerTy()) 2611 return; 2612 2613 MDBuilder MDB(NewLI.getContext()); 2614 const Value *Ptr = OldLI.getPointerOperand(); 2615 auto *ITy = cast<IntegerType>(NewTy); 2616 auto *NullInt = ConstantExpr::getPtrToInt( 2617 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy); 2618 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1)); 2619 NewLI.setMetadata(LLVMContext::MD_range, 2620 MDB.createRange(NonNullInt, NullInt)); 2621 } 2622 2623 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, 2624 MDNode *N, LoadInst &NewLI) { 2625 auto *NewTy = NewLI.getType(); 2626 2627 // Give up unless it is converted to a pointer where there is a single very 2628 // valuable mapping we can do reliably. 2629 // FIXME: It would be nice to propagate this in more ways, but the type 2630 // conversions make it hard. 2631 if (!NewTy->isPointerTy()) 2632 return; 2633 2634 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy); 2635 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) { 2636 MDNode *NN = MDNode::get(OldLI.getContext(), None); 2637 NewLI.setMetadata(LLVMContext::MD_nonnull, NN); 2638 } 2639 } 2640 2641 void llvm::dropDebugUsers(Instruction &I) { 2642 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers; 2643 findDbgUsers(DbgUsers, &I); 2644 for (auto *DII : DbgUsers) 2645 DII->eraseFromParent(); 2646 } 2647 2648 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, 2649 BasicBlock *BB) { 2650 // Since we are moving the instructions out of its basic block, we do not 2651 // retain their original debug locations (DILocations) and debug intrinsic 2652 // instructions. 2653 // 2654 // Doing so would degrade the debugging experience and adversely affect the 2655 // accuracy of profiling information. 2656 // 2657 // Currently, when hoisting the instructions, we take the following actions: 2658 // - Remove their debug intrinsic instructions. 2659 // - Set their debug locations to the values from the insertion point. 2660 // 2661 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values 2662 // need to be deleted, is because there will not be any instructions with a 2663 // DILocation in either branch left after performing the transformation. We 2664 // can only insert a dbg.value after the two branches are joined again. 2665 // 2666 // See PR38762, PR39243 for more details. 2667 // 2668 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to 2669 // encode predicated DIExpressions that yield different results on different 2670 // code paths. 2671 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) { 2672 Instruction *I = &*II; 2673 I->dropUnknownNonDebugMetadata(); 2674 if (I->isUsedByMetadata()) 2675 dropDebugUsers(*I); 2676 if (isa<DbgInfoIntrinsic>(I)) { 2677 // Remove DbgInfo Intrinsics. 2678 II = I->eraseFromParent(); 2679 continue; 2680 } 2681 I->setDebugLoc(InsertPt->getDebugLoc()); 2682 ++II; 2683 } 2684 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(), 2685 BB->begin(), 2686 BB->getTerminator()->getIterator()); 2687 } 2688 2689 namespace { 2690 2691 /// A potential constituent of a bitreverse or bswap expression. See 2692 /// collectBitParts for a fuller explanation. 2693 struct BitPart { 2694 BitPart(Value *P, unsigned BW) : Provider(P) { 2695 Provenance.resize(BW); 2696 } 2697 2698 /// The Value that this is a bitreverse/bswap of. 2699 Value *Provider; 2700 2701 /// The "provenance" of each bit. Provenance[A] = B means that bit A 2702 /// in Provider becomes bit B in the result of this expression. 2703 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128. 2704 2705 enum { Unset = -1 }; 2706 }; 2707 2708 } // end anonymous namespace 2709 2710 /// Analyze the specified subexpression and see if it is capable of providing 2711 /// pieces of a bswap or bitreverse. The subexpression provides a potential 2712 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in 2713 /// the output of the expression came from a corresponding bit in some other 2714 /// value. This function is recursive, and the end result is a mapping of 2715 /// bitnumber to bitnumber. It is the caller's responsibility to validate that 2716 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse. 2717 /// 2718 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know 2719 /// that the expression deposits the low byte of %X into the high byte of the 2720 /// result and that all other bits are zero. This expression is accepted and a 2721 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to 2722 /// [0-7]. 2723 /// 2724 /// To avoid revisiting values, the BitPart results are memoized into the 2725 /// provided map. To avoid unnecessary copying of BitParts, BitParts are 2726 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to 2727 /// store BitParts objects, not pointers. As we need the concept of a nullptr 2728 /// BitParts (Value has been analyzed and the analysis failed), we an Optional 2729 /// type instead to provide the same functionality. 2730 /// 2731 /// Because we pass around references into \c BPS, we must use a container that 2732 /// does not invalidate internal references (std::map instead of DenseMap). 2733 static const Optional<BitPart> & 2734 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, 2735 std::map<Value *, Optional<BitPart>> &BPS, int Depth) { 2736 auto I = BPS.find(V); 2737 if (I != BPS.end()) 2738 return I->second; 2739 2740 auto &Result = BPS[V] = None; 2741 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 2742 2743 // Prevent stack overflow by limiting the recursion depth 2744 if (Depth == BitPartRecursionMaxDepth) { 2745 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n"); 2746 return Result; 2747 } 2748 2749 if (Instruction *I = dyn_cast<Instruction>(V)) { 2750 // If this is an or instruction, it may be an inner node of the bswap. 2751 if (I->getOpcode() == Instruction::Or) { 2752 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps, 2753 MatchBitReversals, BPS, Depth + 1); 2754 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps, 2755 MatchBitReversals, BPS, Depth + 1); 2756 if (!A || !B) 2757 return Result; 2758 2759 // Try and merge the two together. 2760 if (!A->Provider || A->Provider != B->Provider) 2761 return Result; 2762 2763 Result = BitPart(A->Provider, BitWidth); 2764 for (unsigned i = 0; i < A->Provenance.size(); ++i) { 2765 if (A->Provenance[i] != BitPart::Unset && 2766 B->Provenance[i] != BitPart::Unset && 2767 A->Provenance[i] != B->Provenance[i]) 2768 return Result = None; 2769 2770 if (A->Provenance[i] == BitPart::Unset) 2771 Result->Provenance[i] = B->Provenance[i]; 2772 else 2773 Result->Provenance[i] = A->Provenance[i]; 2774 } 2775 2776 return Result; 2777 } 2778 2779 // If this is a logical shift by a constant, recurse then shift the result. 2780 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) { 2781 unsigned BitShift = 2782 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U); 2783 // Ensure the shift amount is defined. 2784 if (BitShift > BitWidth) 2785 return Result; 2786 2787 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2788 MatchBitReversals, BPS, Depth + 1); 2789 if (!Res) 2790 return Result; 2791 Result = Res; 2792 2793 // Perform the "shift" on BitProvenance. 2794 auto &P = Result->Provenance; 2795 if (I->getOpcode() == Instruction::Shl) { 2796 P.erase(std::prev(P.end(), BitShift), P.end()); 2797 P.insert(P.begin(), BitShift, BitPart::Unset); 2798 } else { 2799 P.erase(P.begin(), std::next(P.begin(), BitShift)); 2800 P.insert(P.end(), BitShift, BitPart::Unset); 2801 } 2802 2803 return Result; 2804 } 2805 2806 // If this is a logical 'and' with a mask that clears bits, recurse then 2807 // unset the appropriate bits. 2808 if (I->getOpcode() == Instruction::And && 2809 isa<ConstantInt>(I->getOperand(1))) { 2810 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1); 2811 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue(); 2812 2813 // Check that the mask allows a multiple of 8 bits for a bswap, for an 2814 // early exit. 2815 unsigned NumMaskedBits = AndMask.countPopulation(); 2816 if (!MatchBitReversals && NumMaskedBits % 8 != 0) 2817 return Result; 2818 2819 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2820 MatchBitReversals, BPS, Depth + 1); 2821 if (!Res) 2822 return Result; 2823 Result = Res; 2824 2825 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1) 2826 // If the AndMask is zero for this bit, clear the bit. 2827 if ((AndMask & Bit) == 0) 2828 Result->Provenance[i] = BitPart::Unset; 2829 return Result; 2830 } 2831 2832 // If this is a zext instruction zero extend the result. 2833 if (I->getOpcode() == Instruction::ZExt) { 2834 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2835 MatchBitReversals, BPS, Depth + 1); 2836 if (!Res) 2837 return Result; 2838 2839 Result = BitPart(Res->Provider, BitWidth); 2840 auto NarrowBitWidth = 2841 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth(); 2842 for (unsigned i = 0; i < NarrowBitWidth; ++i) 2843 Result->Provenance[i] = Res->Provenance[i]; 2844 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i) 2845 Result->Provenance[i] = BitPart::Unset; 2846 return Result; 2847 } 2848 } 2849 2850 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be 2851 // the input value to the bswap/bitreverse. 2852 Result = BitPart(V, BitWidth); 2853 for (unsigned i = 0; i < BitWidth; ++i) 2854 Result->Provenance[i] = i; 2855 return Result; 2856 } 2857 2858 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, 2859 unsigned BitWidth) { 2860 if (From % 8 != To % 8) 2861 return false; 2862 // Convert from bit indices to byte indices and check for a byte reversal. 2863 From >>= 3; 2864 To >>= 3; 2865 BitWidth >>= 3; 2866 return From == BitWidth - To - 1; 2867 } 2868 2869 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, 2870 unsigned BitWidth) { 2871 return From == BitWidth - To - 1; 2872 } 2873 2874 bool llvm::recognizeBSwapOrBitReverseIdiom( 2875 Instruction *I, bool MatchBSwaps, bool MatchBitReversals, 2876 SmallVectorImpl<Instruction *> &InsertedInsts) { 2877 if (Operator::getOpcode(I) != Instruction::Or) 2878 return false; 2879 if (!MatchBSwaps && !MatchBitReversals) 2880 return false; 2881 IntegerType *ITy = dyn_cast<IntegerType>(I->getType()); 2882 if (!ITy || ITy->getBitWidth() > 128) 2883 return false; // Can't do vectors or integers > 128 bits. 2884 unsigned BW = ITy->getBitWidth(); 2885 2886 unsigned DemandedBW = BW; 2887 IntegerType *DemandedTy = ITy; 2888 if (I->hasOneUse()) { 2889 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) { 2890 DemandedTy = cast<IntegerType>(Trunc->getType()); 2891 DemandedBW = DemandedTy->getBitWidth(); 2892 } 2893 } 2894 2895 // Try to find all the pieces corresponding to the bswap. 2896 std::map<Value *, Optional<BitPart>> BPS; 2897 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0); 2898 if (!Res) 2899 return false; 2900 auto &BitProvenance = Res->Provenance; 2901 2902 // Now, is the bit permutation correct for a bswap or a bitreverse? We can 2903 // only byteswap values with an even number of bytes. 2904 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true; 2905 for (unsigned i = 0; i < DemandedBW; ++i) { 2906 OKForBSwap &= 2907 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW); 2908 OKForBitReverse &= 2909 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW); 2910 } 2911 2912 Intrinsic::ID Intrin; 2913 if (OKForBSwap && MatchBSwaps) 2914 Intrin = Intrinsic::bswap; 2915 else if (OKForBitReverse && MatchBitReversals) 2916 Intrin = Intrinsic::bitreverse; 2917 else 2918 return false; 2919 2920 if (ITy != DemandedTy) { 2921 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy); 2922 Value *Provider = Res->Provider; 2923 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType()); 2924 // We may need to truncate the provider. 2925 if (DemandedTy != ProviderTy) { 2926 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy, 2927 "trunc", I); 2928 InsertedInsts.push_back(Trunc); 2929 Provider = Trunc; 2930 } 2931 auto *CI = CallInst::Create(F, Provider, "rev", I); 2932 InsertedInsts.push_back(CI); 2933 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I); 2934 InsertedInsts.push_back(ExtInst); 2935 return true; 2936 } 2937 2938 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy); 2939 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I)); 2940 return true; 2941 } 2942 2943 // CodeGen has special handling for some string functions that may replace 2944 // them with target-specific intrinsics. Since that'd skip our interceptors 2945 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses, 2946 // we mark affected calls as NoBuiltin, which will disable optimization 2947 // in CodeGen. 2948 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin( 2949 CallInst *CI, const TargetLibraryInfo *TLI) { 2950 Function *F = CI->getCalledFunction(); 2951 LibFunc Func; 2952 if (F && !F->hasLocalLinkage() && F->hasName() && 2953 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) && 2954 !F->doesNotAccessMemory()) 2955 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin); 2956 } 2957 2958 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) { 2959 // We can't have a PHI with a metadata type. 2960 if (I->getOperand(OpIdx)->getType()->isMetadataTy()) 2961 return false; 2962 2963 // Early exit. 2964 if (!isa<Constant>(I->getOperand(OpIdx))) 2965 return true; 2966 2967 switch (I->getOpcode()) { 2968 default: 2969 return true; 2970 case Instruction::Call: 2971 case Instruction::Invoke: { 2972 const auto &CB = cast<CallBase>(*I); 2973 2974 // Can't handle inline asm. Skip it. 2975 if (CB.isInlineAsm()) 2976 return false; 2977 2978 // Constant bundle operands may need to retain their constant-ness for 2979 // correctness. 2980 if (CB.isBundleOperand(OpIdx)) 2981 return false; 2982 2983 if (OpIdx < CB.getNumArgOperands()) { 2984 // Some variadic intrinsics require constants in the variadic arguments, 2985 // which currently aren't markable as immarg. 2986 if (isa<IntrinsicInst>(CB) && 2987 OpIdx >= CB.getFunctionType()->getNumParams()) { 2988 // This is known to be OK for stackmap. 2989 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap; 2990 } 2991 2992 // gcroot is a special case, since it requires a constant argument which 2993 // isn't also required to be a simple ConstantInt. 2994 if (CB.getIntrinsicID() == Intrinsic::gcroot) 2995 return false; 2996 2997 // Some intrinsic operands are required to be immediates. 2998 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg); 2999 } 3000 3001 // It is never allowed to replace the call argument to an intrinsic, but it 3002 // may be possible for a call. 3003 return !isa<IntrinsicInst>(CB); 3004 } 3005 case Instruction::ShuffleVector: 3006 // Shufflevector masks are constant. 3007 return OpIdx != 2; 3008 case Instruction::Switch: 3009 case Instruction::ExtractValue: 3010 // All operands apart from the first are constant. 3011 return OpIdx == 0; 3012 case Instruction::InsertValue: 3013 // All operands apart from the first and the second are constant. 3014 return OpIdx < 2; 3015 case Instruction::Alloca: 3016 // Static allocas (constant size in the entry block) are handled by 3017 // prologue/epilogue insertion so they're free anyway. We definitely don't 3018 // want to make them non-constant. 3019 return !cast<AllocaInst>(I)->isStaticAlloca(); 3020 case Instruction::GetElementPtr: 3021 if (OpIdx == 0) 3022 return true; 3023 gep_type_iterator It = gep_type_begin(I); 3024 for (auto E = std::next(It, OpIdx); It != E; ++It) 3025 if (It.isStruct()) 3026 return false; 3027 return true; 3028 } 3029 } 3030 3031 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>; 3032 AllocaInst *llvm::findAllocaForValue(Value *V, 3033 AllocaForValueMapTy &AllocaForValue) { 3034 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) 3035 return AI; 3036 // See if we've already calculated (or started to calculate) alloca for a 3037 // given value. 3038 AllocaForValueMapTy::iterator I = AllocaForValue.find(V); 3039 if (I != AllocaForValue.end()) 3040 return I->second; 3041 // Store 0 while we're calculating alloca for value V to avoid 3042 // infinite recursion if the value references itself. 3043 AllocaForValue[V] = nullptr; 3044 AllocaInst *Res = nullptr; 3045 if (CastInst *CI = dyn_cast<CastInst>(V)) 3046 Res = findAllocaForValue(CI->getOperand(0), AllocaForValue); 3047 else if (PHINode *PN = dyn_cast<PHINode>(V)) { 3048 for (Value *IncValue : PN->incoming_values()) { 3049 // Allow self-referencing phi-nodes. 3050 if (IncValue == PN) 3051 continue; 3052 AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue); 3053 // AI for incoming values should exist and should all be equal. 3054 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res)) 3055 return nullptr; 3056 Res = IncValueAI; 3057 } 3058 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) { 3059 Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue); 3060 } else { 3061 LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: " 3062 << *V << "\n"); 3063 } 3064 if (Res) 3065 AllocaForValue[V] = Res; 3066 return Res; 3067 } 3068 3069 Value *llvm::invertCondition(Value *Condition) { 3070 // First: Check if it's a constant 3071 if (Constant *C = dyn_cast<Constant>(Condition)) 3072 return ConstantExpr::getNot(C); 3073 3074 // Second: If the condition is already inverted, return the original value 3075 Value *NotCondition; 3076 if (match(Condition, m_Not(m_Value(NotCondition)))) 3077 return NotCondition; 3078 3079 BasicBlock *Parent = nullptr; 3080 Instruction *Inst = dyn_cast<Instruction>(Condition); 3081 if (Inst) 3082 Parent = Inst->getParent(); 3083 else if (Argument *Arg = dyn_cast<Argument>(Condition)) 3084 Parent = &Arg->getParent()->getEntryBlock(); 3085 assert(Parent && "Unsupported condition to invert"); 3086 3087 // Third: Check all the users for an invert 3088 for (User *U : Condition->users()) 3089 if (Instruction *I = dyn_cast<Instruction>(U)) 3090 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition)))) 3091 return I; 3092 3093 // Last option: Create a new instruction 3094 auto *Inverted = 3095 BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv"); 3096 if (Inst && !isa<PHINode>(Inst)) 3097 Inverted->insertAfter(Inst); 3098 else 3099 Inverted->insertBefore(&*Parent->getFirstInsertionPt()); 3100 return Inverted; 3101 } 3102