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