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 std::pair<unsigned, unsigned> 1923 llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) { 1924 unsigned NumDeadInst = 0; 1925 unsigned NumDeadDbgInst = 0; 1926 // Delete the instructions backwards, as it has a reduced likelihood of 1927 // having to update as many def-use and use-def chains. 1928 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. 1929 while (EndInst != &BB->front()) { 1930 // Delete the next to last instruction. 1931 Instruction *Inst = &*--EndInst->getIterator(); 1932 if (!Inst->use_empty() && !Inst->getType()->isTokenTy()) 1933 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); 1934 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) { 1935 EndInst = Inst; 1936 continue; 1937 } 1938 if (isa<DbgInfoIntrinsic>(Inst)) 1939 ++NumDeadDbgInst; 1940 else 1941 ++NumDeadInst; 1942 Inst->eraseFromParent(); 1943 } 1944 return {NumDeadInst, NumDeadDbgInst}; 1945 } 1946 1947 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap, 1948 bool PreserveLCSSA, DomTreeUpdater *DTU, 1949 MemorySSAUpdater *MSSAU) { 1950 BasicBlock *BB = I->getParent(); 1951 std::vector <DominatorTree::UpdateType> Updates; 1952 1953 if (MSSAU) 1954 MSSAU->changeToUnreachable(I); 1955 1956 // Loop over all of the successors, removing BB's entry from any PHI 1957 // nodes. 1958 if (DTU) 1959 Updates.reserve(BB->getTerminator()->getNumSuccessors()); 1960 for (BasicBlock *Successor : successors(BB)) { 1961 Successor->removePredecessor(BB, PreserveLCSSA); 1962 if (DTU) 1963 Updates.push_back({DominatorTree::Delete, BB, Successor}); 1964 } 1965 // Insert a call to llvm.trap right before this. This turns the undefined 1966 // behavior into a hard fail instead of falling through into random code. 1967 if (UseLLVMTrap) { 1968 Function *TrapFn = 1969 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap); 1970 CallInst *CallTrap = CallInst::Create(TrapFn, "", I); 1971 CallTrap->setDebugLoc(I->getDebugLoc()); 1972 } 1973 auto *UI = new UnreachableInst(I->getContext(), I); 1974 UI->setDebugLoc(I->getDebugLoc()); 1975 1976 // All instructions after this are dead. 1977 unsigned NumInstrsRemoved = 0; 1978 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end(); 1979 while (BBI != BBE) { 1980 if (!BBI->use_empty()) 1981 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 1982 BB->getInstList().erase(BBI++); 1983 ++NumInstrsRemoved; 1984 } 1985 if (DTU) 1986 DTU->applyUpdatesPermissive(Updates); 1987 return NumInstrsRemoved; 1988 } 1989 1990 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) { 1991 SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end()); 1992 SmallVector<OperandBundleDef, 1> OpBundles; 1993 II->getOperandBundlesAsDefs(OpBundles); 1994 CallInst *NewCall = CallInst::Create(II->getFunctionType(), 1995 II->getCalledOperand(), Args, OpBundles); 1996 NewCall->setCallingConv(II->getCallingConv()); 1997 NewCall->setAttributes(II->getAttributes()); 1998 NewCall->setDebugLoc(II->getDebugLoc()); 1999 NewCall->copyMetadata(*II); 2000 2001 // If the invoke had profile metadata, try converting them for CallInst. 2002 uint64_t TotalWeight; 2003 if (NewCall->extractProfTotalWeight(TotalWeight)) { 2004 // Set the total weight if it fits into i32, otherwise reset. 2005 MDBuilder MDB(NewCall->getContext()); 2006 auto NewWeights = uint32_t(TotalWeight) != TotalWeight 2007 ? nullptr 2008 : MDB.createBranchWeights({uint32_t(TotalWeight)}); 2009 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights); 2010 } 2011 2012 return NewCall; 2013 } 2014 2015 /// changeToCall - Convert the specified invoke into a normal call. 2016 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) { 2017 CallInst *NewCall = createCallMatchingInvoke(II); 2018 NewCall->takeName(II); 2019 NewCall->insertBefore(II); 2020 II->replaceAllUsesWith(NewCall); 2021 2022 // Follow the call by a branch to the normal destination. 2023 BasicBlock *NormalDestBB = II->getNormalDest(); 2024 BranchInst::Create(NormalDestBB, II); 2025 2026 // Update PHI nodes in the unwind destination 2027 BasicBlock *BB = II->getParent(); 2028 BasicBlock *UnwindDestBB = II->getUnwindDest(); 2029 UnwindDestBB->removePredecessor(BB); 2030 II->eraseFromParent(); 2031 if (DTU) 2032 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}}); 2033 } 2034 2035 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI, 2036 BasicBlock *UnwindEdge) { 2037 BasicBlock *BB = CI->getParent(); 2038 2039 // Convert this function call into an invoke instruction. First, split the 2040 // basic block. 2041 BasicBlock *Split = 2042 BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc"); 2043 2044 // Delete the unconditional branch inserted by splitBasicBlock 2045 BB->getInstList().pop_back(); 2046 2047 // Create the new invoke instruction. 2048 SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end()); 2049 SmallVector<OperandBundleDef, 1> OpBundles; 2050 2051 CI->getOperandBundlesAsDefs(OpBundles); 2052 2053 // Note: we're round tripping operand bundles through memory here, and that 2054 // can potentially be avoided with a cleverer API design that we do not have 2055 // as of this time. 2056 2057 InvokeInst *II = 2058 InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split, 2059 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB); 2060 II->setDebugLoc(CI->getDebugLoc()); 2061 II->setCallingConv(CI->getCallingConv()); 2062 II->setAttributes(CI->getAttributes()); 2063 2064 // Make sure that anything using the call now uses the invoke! This also 2065 // updates the CallGraph if present, because it uses a WeakTrackingVH. 2066 CI->replaceAllUsesWith(II); 2067 2068 // Delete the original call 2069 Split->getInstList().pop_front(); 2070 return Split; 2071 } 2072 2073 static bool markAliveBlocks(Function &F, 2074 SmallPtrSetImpl<BasicBlock *> &Reachable, 2075 DomTreeUpdater *DTU = nullptr) { 2076 SmallVector<BasicBlock*, 128> Worklist; 2077 BasicBlock *BB = &F.front(); 2078 Worklist.push_back(BB); 2079 Reachable.insert(BB); 2080 bool Changed = false; 2081 do { 2082 BB = Worklist.pop_back_val(); 2083 2084 // Do a quick scan of the basic block, turning any obviously unreachable 2085 // instructions into LLVM unreachable insts. The instruction combining pass 2086 // canonicalizes unreachable insts into stores to null or undef. 2087 for (Instruction &I : *BB) { 2088 if (auto *CI = dyn_cast<CallInst>(&I)) { 2089 Value *Callee = CI->getCalledOperand(); 2090 // Handle intrinsic calls. 2091 if (Function *F = dyn_cast<Function>(Callee)) { 2092 auto IntrinsicID = F->getIntrinsicID(); 2093 // Assumptions that are known to be false are equivalent to 2094 // unreachable. Also, if the condition is undefined, then we make the 2095 // choice most beneficial to the optimizer, and choose that to also be 2096 // unreachable. 2097 if (IntrinsicID == Intrinsic::assume) { 2098 if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) { 2099 // Don't insert a call to llvm.trap right before the unreachable. 2100 changeToUnreachable(CI, false, false, DTU); 2101 Changed = true; 2102 break; 2103 } 2104 } else if (IntrinsicID == Intrinsic::experimental_guard) { 2105 // A call to the guard intrinsic bails out of the current 2106 // compilation unit if the predicate passed to it is false. If the 2107 // predicate is a constant false, then we know the guard will bail 2108 // out of the current compile unconditionally, so all code following 2109 // it is dead. 2110 // 2111 // Note: unlike in llvm.assume, it is not "obviously profitable" for 2112 // guards to treat `undef` as `false` since a guard on `undef` can 2113 // still be useful for widening. 2114 if (match(CI->getArgOperand(0), m_Zero())) 2115 if (!isa<UnreachableInst>(CI->getNextNode())) { 2116 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false, 2117 false, DTU); 2118 Changed = true; 2119 break; 2120 } 2121 } 2122 } else if ((isa<ConstantPointerNull>(Callee) && 2123 !NullPointerIsDefined(CI->getFunction())) || 2124 isa<UndefValue>(Callee)) { 2125 changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU); 2126 Changed = true; 2127 break; 2128 } 2129 if (CI->doesNotReturn() && !CI->isMustTailCall()) { 2130 // If we found a call to a no-return function, insert an unreachable 2131 // instruction after it. Make sure there isn't *already* one there 2132 // though. 2133 if (!isa<UnreachableInst>(CI->getNextNode())) { 2134 // Don't insert a call to llvm.trap right before the unreachable. 2135 changeToUnreachable(CI->getNextNode(), false, false, DTU); 2136 Changed = true; 2137 } 2138 break; 2139 } 2140 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 2141 // Store to undef and store to null are undefined and used to signal 2142 // that they should be changed to unreachable by passes that can't 2143 // modify the CFG. 2144 2145 // Don't touch volatile stores. 2146 if (SI->isVolatile()) continue; 2147 2148 Value *Ptr = SI->getOperand(1); 2149 2150 if (isa<UndefValue>(Ptr) || 2151 (isa<ConstantPointerNull>(Ptr) && 2152 !NullPointerIsDefined(SI->getFunction(), 2153 SI->getPointerAddressSpace()))) { 2154 changeToUnreachable(SI, true, false, DTU); 2155 Changed = true; 2156 break; 2157 } 2158 } 2159 } 2160 2161 Instruction *Terminator = BB->getTerminator(); 2162 if (auto *II = dyn_cast<InvokeInst>(Terminator)) { 2163 // Turn invokes that call 'nounwind' functions into ordinary calls. 2164 Value *Callee = II->getCalledOperand(); 2165 if ((isa<ConstantPointerNull>(Callee) && 2166 !NullPointerIsDefined(BB->getParent())) || 2167 isa<UndefValue>(Callee)) { 2168 changeToUnreachable(II, true, false, DTU); 2169 Changed = true; 2170 } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) { 2171 if (II->use_empty() && II->onlyReadsMemory()) { 2172 // jump to the normal destination branch. 2173 BasicBlock *NormalDestBB = II->getNormalDest(); 2174 BasicBlock *UnwindDestBB = II->getUnwindDest(); 2175 BranchInst::Create(NormalDestBB, II); 2176 UnwindDestBB->removePredecessor(II->getParent()); 2177 II->eraseFromParent(); 2178 if (DTU) 2179 DTU->applyUpdatesPermissive( 2180 {{DominatorTree::Delete, BB, UnwindDestBB}}); 2181 } else 2182 changeToCall(II, DTU); 2183 Changed = true; 2184 } 2185 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) { 2186 // Remove catchpads which cannot be reached. 2187 struct CatchPadDenseMapInfo { 2188 static CatchPadInst *getEmptyKey() { 2189 return DenseMapInfo<CatchPadInst *>::getEmptyKey(); 2190 } 2191 2192 static CatchPadInst *getTombstoneKey() { 2193 return DenseMapInfo<CatchPadInst *>::getTombstoneKey(); 2194 } 2195 2196 static unsigned getHashValue(CatchPadInst *CatchPad) { 2197 return static_cast<unsigned>(hash_combine_range( 2198 CatchPad->value_op_begin(), CatchPad->value_op_end())); 2199 } 2200 2201 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) { 2202 if (LHS == getEmptyKey() || LHS == getTombstoneKey() || 2203 RHS == getEmptyKey() || RHS == getTombstoneKey()) 2204 return LHS == RHS; 2205 return LHS->isIdenticalTo(RHS); 2206 } 2207 }; 2208 2209 // Set of unique CatchPads. 2210 SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4, 2211 CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>> 2212 HandlerSet; 2213 detail::DenseSetEmpty Empty; 2214 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(), 2215 E = CatchSwitch->handler_end(); 2216 I != E; ++I) { 2217 BasicBlock *HandlerBB = *I; 2218 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI()); 2219 if (!HandlerSet.insert({CatchPad, Empty}).second) { 2220 CatchSwitch->removeHandler(I); 2221 --I; 2222 --E; 2223 Changed = true; 2224 } 2225 } 2226 } 2227 2228 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU); 2229 for (BasicBlock *Successor : successors(BB)) 2230 if (Reachable.insert(Successor).second) 2231 Worklist.push_back(Successor); 2232 } while (!Worklist.empty()); 2233 return Changed; 2234 } 2235 2236 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) { 2237 Instruction *TI = BB->getTerminator(); 2238 2239 if (auto *II = dyn_cast<InvokeInst>(TI)) { 2240 changeToCall(II, DTU); 2241 return; 2242 } 2243 2244 Instruction *NewTI; 2245 BasicBlock *UnwindDest; 2246 2247 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 2248 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI); 2249 UnwindDest = CRI->getUnwindDest(); 2250 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) { 2251 auto *NewCatchSwitch = CatchSwitchInst::Create( 2252 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(), 2253 CatchSwitch->getName(), CatchSwitch); 2254 for (BasicBlock *PadBB : CatchSwitch->handlers()) 2255 NewCatchSwitch->addHandler(PadBB); 2256 2257 NewTI = NewCatchSwitch; 2258 UnwindDest = CatchSwitch->getUnwindDest(); 2259 } else { 2260 llvm_unreachable("Could not find unwind successor"); 2261 } 2262 2263 NewTI->takeName(TI); 2264 NewTI->setDebugLoc(TI->getDebugLoc()); 2265 UnwindDest->removePredecessor(BB); 2266 TI->replaceAllUsesWith(NewTI); 2267 TI->eraseFromParent(); 2268 if (DTU) 2269 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}}); 2270 } 2271 2272 /// removeUnreachableBlocks - Remove blocks that are not reachable, even 2273 /// if they are in a dead cycle. Return true if a change was made, false 2274 /// otherwise. 2275 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU, 2276 MemorySSAUpdater *MSSAU) { 2277 SmallPtrSet<BasicBlock *, 16> Reachable; 2278 bool Changed = markAliveBlocks(F, Reachable, DTU); 2279 2280 // If there are unreachable blocks in the CFG... 2281 if (Reachable.size() == F.size()) 2282 return Changed; 2283 2284 assert(Reachable.size() < F.size()); 2285 NumRemoved += F.size() - Reachable.size(); 2286 2287 SmallSetVector<BasicBlock *, 8> DeadBlockSet; 2288 for (BasicBlock &BB : F) { 2289 // Skip reachable basic blocks 2290 if (Reachable.count(&BB)) 2291 continue; 2292 DeadBlockSet.insert(&BB); 2293 } 2294 2295 if (MSSAU) 2296 MSSAU->removeBlocks(DeadBlockSet); 2297 2298 // Loop over all of the basic blocks that are not reachable, dropping all of 2299 // their internal references. Update DTU if available. 2300 std::vector<DominatorTree::UpdateType> Updates; 2301 for (auto *BB : DeadBlockSet) { 2302 for (BasicBlock *Successor : successors(BB)) { 2303 if (!DeadBlockSet.count(Successor)) 2304 Successor->removePredecessor(BB); 2305 if (DTU) 2306 Updates.push_back({DominatorTree::Delete, BB, Successor}); 2307 } 2308 BB->dropAllReferences(); 2309 if (DTU) { 2310 Instruction *TI = BB->getTerminator(); 2311 assert(TI && "Basic block should have a terminator"); 2312 // Terminators like invoke can have users. We have to replace their users, 2313 // before removing them. 2314 if (!TI->use_empty()) 2315 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 2316 TI->eraseFromParent(); 2317 new UnreachableInst(BB->getContext(), BB); 2318 assert(succ_empty(BB) && "The successor list of BB isn't empty before " 2319 "applying corresponding DTU updates."); 2320 } 2321 } 2322 2323 if (DTU) { 2324 DTU->applyUpdatesPermissive(Updates); 2325 bool Deleted = false; 2326 for (auto *BB : DeadBlockSet) { 2327 if (DTU->isBBPendingDeletion(BB)) 2328 --NumRemoved; 2329 else 2330 Deleted = true; 2331 DTU->deleteBB(BB); 2332 } 2333 if (!Deleted) 2334 return false; 2335 } else { 2336 for (auto *BB : DeadBlockSet) 2337 BB->eraseFromParent(); 2338 } 2339 2340 return true; 2341 } 2342 2343 void llvm::combineMetadata(Instruction *K, const Instruction *J, 2344 ArrayRef<unsigned> KnownIDs, bool DoesKMove) { 2345 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 2346 K->dropUnknownNonDebugMetadata(KnownIDs); 2347 K->getAllMetadataOtherThanDebugLoc(Metadata); 2348 for (const auto &MD : Metadata) { 2349 unsigned Kind = MD.first; 2350 MDNode *JMD = J->getMetadata(Kind); 2351 MDNode *KMD = MD.second; 2352 2353 switch (Kind) { 2354 default: 2355 K->setMetadata(Kind, nullptr); // Remove unknown metadata 2356 break; 2357 case LLVMContext::MD_dbg: 2358 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg"); 2359 case LLVMContext::MD_tbaa: 2360 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD)); 2361 break; 2362 case LLVMContext::MD_alias_scope: 2363 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD)); 2364 break; 2365 case LLVMContext::MD_noalias: 2366 case LLVMContext::MD_mem_parallel_loop_access: 2367 K->setMetadata(Kind, MDNode::intersect(JMD, KMD)); 2368 break; 2369 case LLVMContext::MD_access_group: 2370 K->setMetadata(LLVMContext::MD_access_group, 2371 intersectAccessGroups(K, J)); 2372 break; 2373 case LLVMContext::MD_range: 2374 2375 // If K does move, use most generic range. Otherwise keep the range of 2376 // K. 2377 if (DoesKMove) 2378 // FIXME: If K does move, we should drop the range info and nonnull. 2379 // Currently this function is used with DoesKMove in passes 2380 // doing hoisting/sinking and the current behavior of using the 2381 // most generic range is correct in those cases. 2382 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD)); 2383 break; 2384 case LLVMContext::MD_fpmath: 2385 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD)); 2386 break; 2387 case LLVMContext::MD_invariant_load: 2388 // Only set the !invariant.load if it is present in both instructions. 2389 K->setMetadata(Kind, JMD); 2390 break; 2391 case LLVMContext::MD_nonnull: 2392 // If K does move, keep nonull if it is present in both instructions. 2393 if (DoesKMove) 2394 K->setMetadata(Kind, JMD); 2395 break; 2396 case LLVMContext::MD_invariant_group: 2397 // Preserve !invariant.group in K. 2398 break; 2399 case LLVMContext::MD_align: 2400 K->setMetadata(Kind, 2401 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); 2402 break; 2403 case LLVMContext::MD_dereferenceable: 2404 case LLVMContext::MD_dereferenceable_or_null: 2405 K->setMetadata(Kind, 2406 MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD)); 2407 break; 2408 case LLVMContext::MD_preserve_access_index: 2409 // Preserve !preserve.access.index in K. 2410 break; 2411 } 2412 } 2413 // Set !invariant.group from J if J has it. If both instructions have it 2414 // then we will just pick it from J - even when they are different. 2415 // Also make sure that K is load or store - f.e. combining bitcast with load 2416 // could produce bitcast with invariant.group metadata, which is invalid. 2417 // FIXME: we should try to preserve both invariant.group md if they are 2418 // different, but right now instruction can only have one invariant.group. 2419 if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group)) 2420 if (isa<LoadInst>(K) || isa<StoreInst>(K)) 2421 K->setMetadata(LLVMContext::MD_invariant_group, JMD); 2422 } 2423 2424 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J, 2425 bool KDominatesJ) { 2426 unsigned KnownIDs[] = { 2427 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 2428 LLVMContext::MD_noalias, LLVMContext::MD_range, 2429 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull, 2430 LLVMContext::MD_invariant_group, LLVMContext::MD_align, 2431 LLVMContext::MD_dereferenceable, 2432 LLVMContext::MD_dereferenceable_or_null, 2433 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index}; 2434 combineMetadata(K, J, KnownIDs, KDominatesJ); 2435 } 2436 2437 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) { 2438 SmallVector<std::pair<unsigned, MDNode *>, 8> MD; 2439 Source.getAllMetadata(MD); 2440 MDBuilder MDB(Dest.getContext()); 2441 Type *NewType = Dest.getType(); 2442 const DataLayout &DL = Source.getModule()->getDataLayout(); 2443 for (const auto &MDPair : MD) { 2444 unsigned ID = MDPair.first; 2445 MDNode *N = MDPair.second; 2446 // Note, essentially every kind of metadata should be preserved here! This 2447 // routine is supposed to clone a load instruction changing *only its type*. 2448 // The only metadata it makes sense to drop is metadata which is invalidated 2449 // when the pointer type changes. This should essentially never be the case 2450 // in LLVM, but we explicitly switch over only known metadata to be 2451 // conservatively correct. If you are adding metadata to LLVM which pertains 2452 // to loads, you almost certainly want to add it here. 2453 switch (ID) { 2454 case LLVMContext::MD_dbg: 2455 case LLVMContext::MD_tbaa: 2456 case LLVMContext::MD_prof: 2457 case LLVMContext::MD_fpmath: 2458 case LLVMContext::MD_tbaa_struct: 2459 case LLVMContext::MD_invariant_load: 2460 case LLVMContext::MD_alias_scope: 2461 case LLVMContext::MD_noalias: 2462 case LLVMContext::MD_nontemporal: 2463 case LLVMContext::MD_mem_parallel_loop_access: 2464 case LLVMContext::MD_access_group: 2465 // All of these directly apply. 2466 Dest.setMetadata(ID, N); 2467 break; 2468 2469 case LLVMContext::MD_nonnull: 2470 copyNonnullMetadata(Source, N, Dest); 2471 break; 2472 2473 case LLVMContext::MD_align: 2474 case LLVMContext::MD_dereferenceable: 2475 case LLVMContext::MD_dereferenceable_or_null: 2476 // These only directly apply if the new type is also a pointer. 2477 if (NewType->isPointerTy()) 2478 Dest.setMetadata(ID, N); 2479 break; 2480 2481 case LLVMContext::MD_range: 2482 copyRangeMetadata(DL, Source, N, Dest); 2483 break; 2484 } 2485 } 2486 } 2487 2488 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) { 2489 auto *ReplInst = dyn_cast<Instruction>(Repl); 2490 if (!ReplInst) 2491 return; 2492 2493 // Patch the replacement so that it is not more restrictive than the value 2494 // being replaced. 2495 // Note that if 'I' is a load being replaced by some operation, 2496 // for example, by an arithmetic operation, then andIRFlags() 2497 // would just erase all math flags from the original arithmetic 2498 // operation, which is clearly not wanted and not needed. 2499 if (!isa<LoadInst>(I)) 2500 ReplInst->andIRFlags(I); 2501 2502 // FIXME: If both the original and replacement value are part of the 2503 // same control-flow region (meaning that the execution of one 2504 // guarantees the execution of the other), then we can combine the 2505 // noalias scopes here and do better than the general conservative 2506 // answer used in combineMetadata(). 2507 2508 // In general, GVN unifies expressions over different control-flow 2509 // regions, and so we need a conservative combination of the noalias 2510 // scopes. 2511 static const unsigned KnownIDs[] = { 2512 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 2513 LLVMContext::MD_noalias, LLVMContext::MD_range, 2514 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, 2515 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull, 2516 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index}; 2517 combineMetadata(ReplInst, I, KnownIDs, false); 2518 } 2519 2520 template <typename RootType, typename DominatesFn> 2521 static unsigned replaceDominatedUsesWith(Value *From, Value *To, 2522 const RootType &Root, 2523 const DominatesFn &Dominates) { 2524 assert(From->getType() == To->getType()); 2525 2526 unsigned Count = 0; 2527 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); 2528 UI != UE;) { 2529 Use &U = *UI++; 2530 if (!Dominates(Root, U)) 2531 continue; 2532 U.set(To); 2533 LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName() 2534 << "' as " << *To << " in " << *U << "\n"); 2535 ++Count; 2536 } 2537 return Count; 2538 } 2539 2540 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) { 2541 assert(From->getType() == To->getType()); 2542 auto *BB = From->getParent(); 2543 unsigned Count = 0; 2544 2545 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); 2546 UI != UE;) { 2547 Use &U = *UI++; 2548 auto *I = cast<Instruction>(U.getUser()); 2549 if (I->getParent() == BB) 2550 continue; 2551 U.set(To); 2552 ++Count; 2553 } 2554 return Count; 2555 } 2556 2557 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, 2558 DominatorTree &DT, 2559 const BasicBlockEdge &Root) { 2560 auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) { 2561 return DT.dominates(Root, U); 2562 }; 2563 return ::replaceDominatedUsesWith(From, To, Root, Dominates); 2564 } 2565 2566 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, 2567 DominatorTree &DT, 2568 const BasicBlock *BB) { 2569 auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) { 2570 auto *I = cast<Instruction>(U.getUser())->getParent(); 2571 return DT.properlyDominates(BB, I); 2572 }; 2573 return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates); 2574 } 2575 2576 bool llvm::callsGCLeafFunction(const CallBase *Call, 2577 const TargetLibraryInfo &TLI) { 2578 // Check if the function is specifically marked as a gc leaf function. 2579 if (Call->hasFnAttr("gc-leaf-function")) 2580 return true; 2581 if (const Function *F = Call->getCalledFunction()) { 2582 if (F->hasFnAttribute("gc-leaf-function")) 2583 return true; 2584 2585 if (auto IID = F->getIntrinsicID()) 2586 // Most LLVM intrinsics do not take safepoints. 2587 return IID != Intrinsic::experimental_gc_statepoint && 2588 IID != Intrinsic::experimental_deoptimize; 2589 } 2590 2591 // Lib calls can be materialized by some passes, and won't be 2592 // marked as 'gc-leaf-function.' All available Libcalls are 2593 // GC-leaf. 2594 LibFunc LF; 2595 if (TLI.getLibFunc(*Call, LF)) { 2596 return TLI.has(LF); 2597 } 2598 2599 return false; 2600 } 2601 2602 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, 2603 LoadInst &NewLI) { 2604 auto *NewTy = NewLI.getType(); 2605 2606 // This only directly applies if the new type is also a pointer. 2607 if (NewTy->isPointerTy()) { 2608 NewLI.setMetadata(LLVMContext::MD_nonnull, N); 2609 return; 2610 } 2611 2612 // The only other translation we can do is to integral loads with !range 2613 // metadata. 2614 if (!NewTy->isIntegerTy()) 2615 return; 2616 2617 MDBuilder MDB(NewLI.getContext()); 2618 const Value *Ptr = OldLI.getPointerOperand(); 2619 auto *ITy = cast<IntegerType>(NewTy); 2620 auto *NullInt = ConstantExpr::getPtrToInt( 2621 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy); 2622 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1)); 2623 NewLI.setMetadata(LLVMContext::MD_range, 2624 MDB.createRange(NonNullInt, NullInt)); 2625 } 2626 2627 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, 2628 MDNode *N, LoadInst &NewLI) { 2629 auto *NewTy = NewLI.getType(); 2630 2631 // Give up unless it is converted to a pointer where there is a single very 2632 // valuable mapping we can do reliably. 2633 // FIXME: It would be nice to propagate this in more ways, but the type 2634 // conversions make it hard. 2635 if (!NewTy->isPointerTy()) 2636 return; 2637 2638 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy); 2639 if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) { 2640 MDNode *NN = MDNode::get(OldLI.getContext(), None); 2641 NewLI.setMetadata(LLVMContext::MD_nonnull, NN); 2642 } 2643 } 2644 2645 void llvm::dropDebugUsers(Instruction &I) { 2646 SmallVector<DbgVariableIntrinsic *, 1> DbgUsers; 2647 findDbgUsers(DbgUsers, &I); 2648 for (auto *DII : DbgUsers) 2649 DII->eraseFromParent(); 2650 } 2651 2652 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, 2653 BasicBlock *BB) { 2654 // Since we are moving the instructions out of its basic block, we do not 2655 // retain their original debug locations (DILocations) and debug intrinsic 2656 // instructions. 2657 // 2658 // Doing so would degrade the debugging experience and adversely affect the 2659 // accuracy of profiling information. 2660 // 2661 // Currently, when hoisting the instructions, we take the following actions: 2662 // - Remove their debug intrinsic instructions. 2663 // - Set their debug locations to the values from the insertion point. 2664 // 2665 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values 2666 // need to be deleted, is because there will not be any instructions with a 2667 // DILocation in either branch left after performing the transformation. We 2668 // can only insert a dbg.value after the two branches are joined again. 2669 // 2670 // See PR38762, PR39243 for more details. 2671 // 2672 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to 2673 // encode predicated DIExpressions that yield different results on different 2674 // code paths. 2675 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) { 2676 Instruction *I = &*II; 2677 I->dropUnknownNonDebugMetadata(); 2678 if (I->isUsedByMetadata()) 2679 dropDebugUsers(*I); 2680 if (isa<DbgInfoIntrinsic>(I)) { 2681 // Remove DbgInfo Intrinsics. 2682 II = I->eraseFromParent(); 2683 continue; 2684 } 2685 I->setDebugLoc(InsertPt->getDebugLoc()); 2686 ++II; 2687 } 2688 DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(), 2689 BB->begin(), 2690 BB->getTerminator()->getIterator()); 2691 } 2692 2693 namespace { 2694 2695 /// A potential constituent of a bitreverse or bswap expression. See 2696 /// collectBitParts for a fuller explanation. 2697 struct BitPart { 2698 BitPart(Value *P, unsigned BW) : Provider(P) { 2699 Provenance.resize(BW); 2700 } 2701 2702 /// The Value that this is a bitreverse/bswap of. 2703 Value *Provider; 2704 2705 /// The "provenance" of each bit. Provenance[A] = B means that bit A 2706 /// in Provider becomes bit B in the result of this expression. 2707 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128. 2708 2709 enum { Unset = -1 }; 2710 }; 2711 2712 } // end anonymous namespace 2713 2714 /// Analyze the specified subexpression and see if it is capable of providing 2715 /// pieces of a bswap or bitreverse. The subexpression provides a potential 2716 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in 2717 /// the output of the expression came from a corresponding bit in some other 2718 /// value. This function is recursive, and the end result is a mapping of 2719 /// bitnumber to bitnumber. It is the caller's responsibility to validate that 2720 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse. 2721 /// 2722 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know 2723 /// that the expression deposits the low byte of %X into the high byte of the 2724 /// result and that all other bits are zero. This expression is accepted and a 2725 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to 2726 /// [0-7]. 2727 /// 2728 /// To avoid revisiting values, the BitPart results are memoized into the 2729 /// provided map. To avoid unnecessary copying of BitParts, BitParts are 2730 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to 2731 /// store BitParts objects, not pointers. As we need the concept of a nullptr 2732 /// BitParts (Value has been analyzed and the analysis failed), we an Optional 2733 /// type instead to provide the same functionality. 2734 /// 2735 /// Because we pass around references into \c BPS, we must use a container that 2736 /// does not invalidate internal references (std::map instead of DenseMap). 2737 static const Optional<BitPart> & 2738 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, 2739 std::map<Value *, Optional<BitPart>> &BPS, int Depth) { 2740 auto I = BPS.find(V); 2741 if (I != BPS.end()) 2742 return I->second; 2743 2744 auto &Result = BPS[V] = None; 2745 auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 2746 2747 // Prevent stack overflow by limiting the recursion depth 2748 if (Depth == BitPartRecursionMaxDepth) { 2749 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n"); 2750 return Result; 2751 } 2752 2753 if (Instruction *I = dyn_cast<Instruction>(V)) { 2754 // If this is an or instruction, it may be an inner node of the bswap. 2755 if (I->getOpcode() == Instruction::Or) { 2756 auto &A = collectBitParts(I->getOperand(0), MatchBSwaps, 2757 MatchBitReversals, BPS, Depth + 1); 2758 auto &B = collectBitParts(I->getOperand(1), MatchBSwaps, 2759 MatchBitReversals, BPS, Depth + 1); 2760 if (!A || !B) 2761 return Result; 2762 2763 // Try and merge the two together. 2764 if (!A->Provider || A->Provider != B->Provider) 2765 return Result; 2766 2767 Result = BitPart(A->Provider, BitWidth); 2768 for (unsigned i = 0; i < A->Provenance.size(); ++i) { 2769 if (A->Provenance[i] != BitPart::Unset && 2770 B->Provenance[i] != BitPart::Unset && 2771 A->Provenance[i] != B->Provenance[i]) 2772 return Result = None; 2773 2774 if (A->Provenance[i] == BitPart::Unset) 2775 Result->Provenance[i] = B->Provenance[i]; 2776 else 2777 Result->Provenance[i] = A->Provenance[i]; 2778 } 2779 2780 return Result; 2781 } 2782 2783 // If this is a logical shift by a constant, recurse then shift the result. 2784 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) { 2785 unsigned BitShift = 2786 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U); 2787 // Ensure the shift amount is defined. 2788 if (BitShift > BitWidth) 2789 return Result; 2790 2791 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2792 MatchBitReversals, BPS, Depth + 1); 2793 if (!Res) 2794 return Result; 2795 Result = Res; 2796 2797 // Perform the "shift" on BitProvenance. 2798 auto &P = Result->Provenance; 2799 if (I->getOpcode() == Instruction::Shl) { 2800 P.erase(std::prev(P.end(), BitShift), P.end()); 2801 P.insert(P.begin(), BitShift, BitPart::Unset); 2802 } else { 2803 P.erase(P.begin(), std::next(P.begin(), BitShift)); 2804 P.insert(P.end(), BitShift, BitPart::Unset); 2805 } 2806 2807 return Result; 2808 } 2809 2810 // If this is a logical 'and' with a mask that clears bits, recurse then 2811 // unset the appropriate bits. 2812 if (I->getOpcode() == Instruction::And && 2813 isa<ConstantInt>(I->getOperand(1))) { 2814 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1); 2815 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue(); 2816 2817 // Check that the mask allows a multiple of 8 bits for a bswap, for an 2818 // early exit. 2819 unsigned NumMaskedBits = AndMask.countPopulation(); 2820 if (!MatchBitReversals && NumMaskedBits % 8 != 0) 2821 return Result; 2822 2823 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2824 MatchBitReversals, BPS, Depth + 1); 2825 if (!Res) 2826 return Result; 2827 Result = Res; 2828 2829 for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1) 2830 // If the AndMask is zero for this bit, clear the bit. 2831 if ((AndMask & Bit) == 0) 2832 Result->Provenance[i] = BitPart::Unset; 2833 return Result; 2834 } 2835 2836 // If this is a zext instruction zero extend the result. 2837 if (I->getOpcode() == Instruction::ZExt) { 2838 auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps, 2839 MatchBitReversals, BPS, Depth + 1); 2840 if (!Res) 2841 return Result; 2842 2843 Result = BitPart(Res->Provider, BitWidth); 2844 auto NarrowBitWidth = 2845 cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth(); 2846 for (unsigned i = 0; i < NarrowBitWidth; ++i) 2847 Result->Provenance[i] = Res->Provenance[i]; 2848 for (unsigned i = NarrowBitWidth; i < BitWidth; ++i) 2849 Result->Provenance[i] = BitPart::Unset; 2850 return Result; 2851 } 2852 } 2853 2854 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be 2855 // the input value to the bswap/bitreverse. 2856 Result = BitPart(V, BitWidth); 2857 for (unsigned i = 0; i < BitWidth; ++i) 2858 Result->Provenance[i] = i; 2859 return Result; 2860 } 2861 2862 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, 2863 unsigned BitWidth) { 2864 if (From % 8 != To % 8) 2865 return false; 2866 // Convert from bit indices to byte indices and check for a byte reversal. 2867 From >>= 3; 2868 To >>= 3; 2869 BitWidth >>= 3; 2870 return From == BitWidth - To - 1; 2871 } 2872 2873 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, 2874 unsigned BitWidth) { 2875 return From == BitWidth - To - 1; 2876 } 2877 2878 bool llvm::recognizeBSwapOrBitReverseIdiom( 2879 Instruction *I, bool MatchBSwaps, bool MatchBitReversals, 2880 SmallVectorImpl<Instruction *> &InsertedInsts) { 2881 if (Operator::getOpcode(I) != Instruction::Or) 2882 return false; 2883 if (!MatchBSwaps && !MatchBitReversals) 2884 return false; 2885 IntegerType *ITy = dyn_cast<IntegerType>(I->getType()); 2886 if (!ITy || ITy->getBitWidth() > 128) 2887 return false; // Can't do vectors or integers > 128 bits. 2888 unsigned BW = ITy->getBitWidth(); 2889 2890 unsigned DemandedBW = BW; 2891 IntegerType *DemandedTy = ITy; 2892 if (I->hasOneUse()) { 2893 if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) { 2894 DemandedTy = cast<IntegerType>(Trunc->getType()); 2895 DemandedBW = DemandedTy->getBitWidth(); 2896 } 2897 } 2898 2899 // Try to find all the pieces corresponding to the bswap. 2900 std::map<Value *, Optional<BitPart>> BPS; 2901 auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0); 2902 if (!Res) 2903 return false; 2904 auto &BitProvenance = Res->Provenance; 2905 2906 // Now, is the bit permutation correct for a bswap or a bitreverse? We can 2907 // only byteswap values with an even number of bytes. 2908 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true; 2909 for (unsigned i = 0; i < DemandedBW; ++i) { 2910 OKForBSwap &= 2911 bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW); 2912 OKForBitReverse &= 2913 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW); 2914 } 2915 2916 Intrinsic::ID Intrin; 2917 if (OKForBSwap && MatchBSwaps) 2918 Intrin = Intrinsic::bswap; 2919 else if (OKForBitReverse && MatchBitReversals) 2920 Intrin = Intrinsic::bitreverse; 2921 else 2922 return false; 2923 2924 if (ITy != DemandedTy) { 2925 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy); 2926 Value *Provider = Res->Provider; 2927 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType()); 2928 // We may need to truncate the provider. 2929 if (DemandedTy != ProviderTy) { 2930 auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy, 2931 "trunc", I); 2932 InsertedInsts.push_back(Trunc); 2933 Provider = Trunc; 2934 } 2935 auto *CI = CallInst::Create(F, Provider, "rev", I); 2936 InsertedInsts.push_back(CI); 2937 auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I); 2938 InsertedInsts.push_back(ExtInst); 2939 return true; 2940 } 2941 2942 Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy); 2943 InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I)); 2944 return true; 2945 } 2946 2947 // CodeGen has special handling for some string functions that may replace 2948 // them with target-specific intrinsics. Since that'd skip our interceptors 2949 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses, 2950 // we mark affected calls as NoBuiltin, which will disable optimization 2951 // in CodeGen. 2952 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin( 2953 CallInst *CI, const TargetLibraryInfo *TLI) { 2954 Function *F = CI->getCalledFunction(); 2955 LibFunc Func; 2956 if (F && !F->hasLocalLinkage() && F->hasName() && 2957 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) && 2958 !F->doesNotAccessMemory()) 2959 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin); 2960 } 2961 2962 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) { 2963 // We can't have a PHI with a metadata type. 2964 if (I->getOperand(OpIdx)->getType()->isMetadataTy()) 2965 return false; 2966 2967 // Early exit. 2968 if (!isa<Constant>(I->getOperand(OpIdx))) 2969 return true; 2970 2971 switch (I->getOpcode()) { 2972 default: 2973 return true; 2974 case Instruction::Call: 2975 case Instruction::Invoke: { 2976 const auto &CB = cast<CallBase>(*I); 2977 2978 // Can't handle inline asm. Skip it. 2979 if (CB.isInlineAsm()) 2980 return false; 2981 2982 // Constant bundle operands may need to retain their constant-ness for 2983 // correctness. 2984 if (CB.isBundleOperand(OpIdx)) 2985 return false; 2986 2987 if (OpIdx < CB.getNumArgOperands()) { 2988 // Some variadic intrinsics require constants in the variadic arguments, 2989 // which currently aren't markable as immarg. 2990 if (isa<IntrinsicInst>(CB) && 2991 OpIdx >= CB.getFunctionType()->getNumParams()) { 2992 // This is known to be OK for stackmap. 2993 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap; 2994 } 2995 2996 // gcroot is a special case, since it requires a constant argument which 2997 // isn't also required to be a simple ConstantInt. 2998 if (CB.getIntrinsicID() == Intrinsic::gcroot) 2999 return false; 3000 3001 // Some intrinsic operands are required to be immediates. 3002 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg); 3003 } 3004 3005 // It is never allowed to replace the call argument to an intrinsic, but it 3006 // may be possible for a call. 3007 return !isa<IntrinsicInst>(CB); 3008 } 3009 case Instruction::ShuffleVector: 3010 // Shufflevector masks are constant. 3011 return OpIdx != 2; 3012 case Instruction::Switch: 3013 case Instruction::ExtractValue: 3014 // All operands apart from the first are constant. 3015 return OpIdx == 0; 3016 case Instruction::InsertValue: 3017 // All operands apart from the first and the second are constant. 3018 return OpIdx < 2; 3019 case Instruction::Alloca: 3020 // Static allocas (constant size in the entry block) are handled by 3021 // prologue/epilogue insertion so they're free anyway. We definitely don't 3022 // want to make them non-constant. 3023 return !cast<AllocaInst>(I)->isStaticAlloca(); 3024 case Instruction::GetElementPtr: 3025 if (OpIdx == 0) 3026 return true; 3027 gep_type_iterator It = gep_type_begin(I); 3028 for (auto E = std::next(It, OpIdx); It != E; ++It) 3029 if (It.isStruct()) 3030 return false; 3031 return true; 3032 } 3033 } 3034 3035 Value *llvm::invertCondition(Value *Condition) { 3036 // First: Check if it's a constant 3037 if (Constant *C = dyn_cast<Constant>(Condition)) 3038 return ConstantExpr::getNot(C); 3039 3040 // Second: If the condition is already inverted, return the original value 3041 Value *NotCondition; 3042 if (match(Condition, m_Not(m_Value(NotCondition)))) 3043 return NotCondition; 3044 3045 BasicBlock *Parent = nullptr; 3046 Instruction *Inst = dyn_cast<Instruction>(Condition); 3047 if (Inst) 3048 Parent = Inst->getParent(); 3049 else if (Argument *Arg = dyn_cast<Argument>(Condition)) 3050 Parent = &Arg->getParent()->getEntryBlock(); 3051 assert(Parent && "Unsupported condition to invert"); 3052 3053 // Third: Check all the users for an invert 3054 for (User *U : Condition->users()) 3055 if (Instruction *I = dyn_cast<Instruction>(U)) 3056 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition)))) 3057 return I; 3058 3059 // Last option: Create a new instruction 3060 auto *Inverted = 3061 BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv"); 3062 if (Inst && !isa<PHINode>(Inst)) 3063 Inverted->insertAfter(Inst); 3064 else 3065 Inverted->insertBefore(&*Parent->getFirstInsertionPt()); 3066 return Inverted; 3067 } 3068