LLVM 24.0.0git
Local.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DIBuilder.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugInfo.h"
46#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Dominators.h"
50#include "llvm/IR/Function.h"
52#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Intrinsics.h"
58#include "llvm/IR/IntrinsicsWebAssembly.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
62#include "llvm/IR/Metadata.h"
63#include "llvm/IR/Module.h"
66#include "llvm/IR/Type.h"
67#include "llvm/IR/Use.h"
68#include "llvm/IR/User.h"
69#include "llvm/IR/Value.h"
70#include "llvm/IR/ValueHandle.h"
74#include "llvm/Support/Debug.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <iterator>
84#include <map>
85#include <optional>
86#include <utility>
87
88using namespace llvm;
89using namespace llvm::PatternMatch;
90
91#define DEBUG_TYPE "local"
92
93STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
94STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
95
97 "phicse-debug-hash",
98#ifdef EXPENSIVE_CHECKS
99 cl::init(true),
100#else
101 cl::init(false),
102#endif
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
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
114 "max-phi-entries-increase-after-removing-empty-block", cl::init(1000),
116 cl::desc("Stop removing an empty block if removing it will introduce more "
117 "than this number of phi entries in its successor"));
118
119// Max recursion depth for collectBitParts used when detecting bswap and
120// bitreverse idioms.
121static const unsigned BitPartRecursionMaxDepth = 48;
122
123//===----------------------------------------------------------------------===//
124// Local constant propagation.
125//
126
127/// ConstantFoldTerminator - If a terminator instruction is predicated on a
128/// constant value, convert it into an unconditional branch to the constant
129/// destination. This is a nontrivial operation because the successors of this
130/// basic block must have their PHI nodes updated.
131/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
132/// conditions and indirectbr addresses this might make dead if
133/// DeleteDeadConditions is true.
134bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
135 const TargetLibraryInfo *TLI,
136 DomTreeUpdater *DTU) {
137 Instruction *T = BB->getTerminator();
138 IRBuilder<> Builder(T);
139
140 // Branch - See if we are conditional jumping on constant
141 if (auto *BI = dyn_cast<CondBrInst>(T)) {
142 BasicBlock *Dest1 = BI->getSuccessor(0);
143 BasicBlock *Dest2 = BI->getSuccessor(1);
144
145 if (Dest2 == Dest1) { // Conditional branch to same location?
146 // This branch matches something like this:
147 // br bool %cond, label %Dest, label %Dest
148 // and changes it into: br label %Dest
149
150 // Let the basic block know that we are letting go of one copy of it.
151 assert(BI->getParent() && "Terminator not inserted in block!");
152 Dest1->removePredecessor(BI->getParent());
153
154 // Replace the conditional branch with an unconditional one.
155 UncondBrInst *NewBI = Builder.CreateBr(Dest1);
156
157 // Transfer the metadata to the new branch instruction.
158 NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
159 LLVMContext::MD_annotation});
160
161 Value *Cond = BI->getCondition();
162 BI->eraseFromParent();
163 if (DeleteDeadConditions)
165 return true;
166 }
167
168 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
169 // Are we branching on constant?
170 // YES. Change to unconditional branch...
171 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
172 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
173
174 // Let the basic block know that we are letting go of it. Based on this,
175 // it will adjust it's PHI nodes.
176 OldDest->removePredecessor(BB);
177
178 // Replace the conditional branch with an unconditional one.
179 UncondBrInst *NewBI = Builder.CreateBr(Destination);
180
181 // Transfer the metadata to the new branch instruction.
182 NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
183 LLVMContext::MD_annotation});
184
185 BI->eraseFromParent();
186 if (DTU)
187 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
188 return true;
189 }
190
191 return false;
192 }
193
194 if (auto *SI = dyn_cast<SwitchInst>(T)) {
195 // If we are switching on a constant, we can convert the switch to an
196 // unconditional branch.
197 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
198 BasicBlock *DefaultDest = SI->getDefaultDest();
199 BasicBlock *TheOnlyDest = DefaultDest;
200
201 // If the default is unreachable, ignore it when searching for TheOnlyDest.
202 if (SI->defaultDestUnreachable() && SI->getNumCases() > 0)
203 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
204
205 bool Changed = false;
206
207 // Figure out which case it goes to.
208 for (auto It = SI->case_begin(), End = SI->case_end(); It != End;) {
209 // Found case matching a constant operand?
210 if (It->getCaseValue() == CI) {
211 TheOnlyDest = It->getCaseSuccessor();
212 break;
213 }
214
215 // Check to see if this branch is going to the same place as the default
216 // dest. If so, eliminate it as an explicit compare.
217 if (It->getCaseSuccessor() == DefaultDest) {
219 unsigned NCases = SI->getNumCases();
220 // Fold the case metadata into the default if there will be any branches
221 // left, unless the metadata doesn't match the switch.
222 if (NCases > 1 && MD) {
223 // Collect branch weights into a vector.
225 extractFromBranchWeightMD64(MD, Weights);
226
227 // Merge weight of this case to the default weight.
228 unsigned Idx = It->getCaseIndex();
229
230 // Check for and prevent uint64_t overflow by reducing branch weights.
231 if (Weights[0] > UINT64_MAX - Weights[Idx + 1])
232 fitWeights(Weights);
233
234 Weights[0] += Weights[Idx + 1];
235 // Remove weight for this case.
236 std::swap(Weights[Idx + 1], Weights.back());
237 Weights.pop_back();
239 }
240 // Remove this entry.
241 BasicBlock *ParentBB = SI->getParent();
242 DefaultDest->removePredecessor(ParentBB);
243 It = SI->removeCase(It);
244 End = SI->case_end();
245
246 // Removing this case may have made the condition constant. In that
247 // case, update CI and restart iteration through the cases.
248 if (auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {
249 CI = NewCI;
250 It = SI->case_begin();
251 }
252
253 Changed = true;
254 continue;
255 }
256
257 // Otherwise, check to see if the switch only branches to one destination.
258 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
259 // destinations.
260 if (It->getCaseSuccessor() != TheOnlyDest)
261 TheOnlyDest = nullptr;
262
263 // Increment this iterator as we haven't removed the case.
264 ++It;
265 }
266
267 if (CI && !TheOnlyDest) {
268 // Branching on a constant, but not any of the cases, go to the default
269 // successor.
270 TheOnlyDest = SI->getDefaultDest();
271 }
272
273 // If we found a single destination that we can fold the switch into, do so
274 // now.
275 if (TheOnlyDest) {
276 // Insert the new branch.
277 Builder.CreateBr(TheOnlyDest);
278 BasicBlock *BB = SI->getParent();
279
280 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
281
282 // Remove entries from PHI nodes which we no longer branch to...
283 BasicBlock *SuccToKeep = TheOnlyDest;
284 for (BasicBlock *Succ : successors(SI)) {
285 if (DTU && Succ != TheOnlyDest)
286 RemovedSuccessors.insert(Succ);
287 // Found case matching a constant operand?
288 if (Succ == SuccToKeep) {
289 SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest
290 } else {
291 Succ->removePredecessor(BB);
292 }
293 }
294
295 // Delete the old switch.
296 Value *Cond = SI->getCondition();
297 SI->eraseFromParent();
298 if (DeleteDeadConditions)
300 if (DTU) {
301 std::vector<DominatorTree::UpdateType> Updates;
302 Updates.reserve(RemovedSuccessors.size());
303 for (auto *RemovedSuccessor : RemovedSuccessors)
304 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
305 DTU->applyUpdates(Updates);
306 }
307 return true;
308 }
309
310 if (SI->getNumCases() == 1) {
311 // Otherwise, we can fold this switch into a conditional branch
312 // instruction if it has only one non-default destination.
313 auto FirstCase = *SI->case_begin();
314 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
315 FirstCase.getCaseValue(), "cond");
316
317 // Insert the new branch.
318 CondBrInst *NewBr = Builder.CreateCondBr(
319 Cond, FirstCase.getCaseSuccessor(), SI->getDefaultDest());
320 SmallVector<uint32_t> Weights;
321 if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {
322 uint32_t DefWeight = Weights[0];
323 uint32_t CaseWeight = Weights[1];
324 // The TrueWeight should be the weight for the single case of SI.
325 NewBr->setMetadata(LLVMContext::MD_prof,
326 MDBuilder(BB->getContext())
327 .createBranchWeights(CaseWeight, DefWeight));
328 }
329
330 // Update make.implicit metadata to the newly-created conditional branch.
331 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
332 if (MakeImplicitMD)
333 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
334
335 // Delete the old switch.
336 SI->eraseFromParent();
337 return true;
338 }
339 return Changed;
340 }
341
342 if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
343 // indirectbr blockaddress(@F, @BB) -> br label @BB
344 if (auto *BA =
345 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
346 BasicBlock *TheOnlyDest = BA->getBasicBlock();
347 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
348
349 // Insert the new branch.
350 Builder.CreateBr(TheOnlyDest);
351
352 BasicBlock *SuccToKeep = TheOnlyDest;
353 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
354 BasicBlock *DestBB = IBI->getDestination(i);
355 if (DTU && DestBB != TheOnlyDest)
356 RemovedSuccessors.insert(DestBB);
357 if (IBI->getDestination(i) == SuccToKeep) {
358 SuccToKeep = nullptr;
359 } else {
360 DestBB->removePredecessor(BB);
361 }
362 }
363 Value *Address = IBI->getAddress();
364 IBI->eraseFromParent();
365 if (DeleteDeadConditions)
366 // Delete pointer cast instructions.
368
369 // Also zap the blockaddress constant if there are no users remaining,
370 // otherwise the destination is still marked as having its address taken.
371 if (BA->use_empty())
372 BA->destroyConstant();
373
374 // If we didn't find our destination in the IBI successor list, then we
375 // have undefined behavior. Replace the unconditional branch with an
376 // 'unreachable' instruction.
377 if (SuccToKeep) {
379 new UnreachableInst(BB->getContext(), BB);
380 }
381
382 if (DTU) {
383 std::vector<DominatorTree::UpdateType> Updates;
384 Updates.reserve(RemovedSuccessors.size());
385 for (auto *RemovedSuccessor : RemovedSuccessors)
386 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
387 DTU->applyUpdates(Updates);
388 }
389 return true;
390 }
391 }
392
393 return false;
394}
395
396//===----------------------------------------------------------------------===//
397// Local dead code elimination.
398//
399
400/// isInstructionTriviallyDead - Return true if the result produced by the
401/// instruction is not used, and the instruction has no side effects.
402///
404 const TargetLibraryInfo *TLI) {
405 if (!I->use_empty())
406 return false;
408}
409
411 const TargetLibraryInfo *TLI) {
412 if (I->isTerminator())
413 return false;
414
415 // We don't want the landingpad-like instructions removed by anything this
416 // general.
417 if (I->isEHPad())
418 return false;
419
420 if (const DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
421 if (DLI->getLabel())
422 return false;
423 return true;
424 }
425
426 if (auto *CB = dyn_cast<CallBase>(I))
427 if (isRemovableAlloc(CB, TLI))
428 return true;
429
430 if (!I->willReturn()) {
432 if (!II)
433 return false;
434
435 switch (II->getIntrinsicID()) {
436 case Intrinsic::experimental_guard: {
437 // Guards on true are operationally no-ops. In the future we can
438 // consider more sophisticated tradeoffs for guards considering potential
439 // for check widening, but for now we keep things simple.
440 auto *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0));
441 return Cond && Cond->isOne();
442 }
443 // TODO: These intrinsics are not safe to remove, because this may remove
444 // a well-defined trap.
445 case Intrinsic::wasm_trunc_signed:
446 case Intrinsic::wasm_trunc_unsigned:
447 case Intrinsic::ptrauth_auth:
448 case Intrinsic::ptrauth_resign:
449 case Intrinsic::ptrauth_resign_load_relative:
450 return true;
451 default:
452 return false;
453 }
454 }
455
456 if (!I->mayHaveSideEffects())
457 return true;
458
459 // Special case intrinsics that "may have side effects" but can be deleted
460 // when dead.
462 // Safe to delete llvm.stacksave and launder.invariant.group if dead.
463 if (II->getIntrinsicID() == Intrinsic::stacksave ||
464 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
465 return true;
466
467 // Intrinsics declare sideeffects to prevent them from moving, but they are
468 // nops without users.
469 if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
470 II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
471 return true;
472
473 if (II->isLifetimeStartOrEnd()) {
474 auto *Arg = II->getArgOperand(0);
475 if (isa<PoisonValue>(Arg))
476 return true;
477
478 // If the only uses of the alloca are lifetime intrinsics, then the
479 // intrinsics are dead.
480 return llvm::all_of(Arg->uses(), [](Use &Use) {
481 return isa<LifetimeIntrinsic>(Use.getUser());
482 });
483 }
484
485 // Assumptions are dead if their condition is trivially true.
486 if (II->getIntrinsicID() == Intrinsic::assume &&
488 if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
489 return !Cond->isZero();
490
491 return false;
492 }
493
494 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
495 std::optional<fp::ExceptionBehavior> ExBehavior =
496 FPI->getExceptionBehavior();
497 return *ExBehavior != fp::ebStrict;
498 }
499 }
500
501 if (auto *Call = dyn_cast<CallBase>(I)) {
502 if (Value *FreedOp = getFreedOperand(Call, TLI))
503 if (Constant *C = dyn_cast<Constant>(FreedOp))
504 return C->isNullValue() || isa<UndefValue>(C);
505 if (isMathLibCallNoop(Call, TLI))
506 return true;
507 }
508
509 // Non-volatile atomic loads from constants can be removed.
510 if (auto *LI = dyn_cast<LoadInst>(I))
511 if (auto *GV = dyn_cast<GlobalVariable>(
512 LI->getPointerOperand()->stripPointerCasts()))
513 if (!LI->isVolatile() && GV->isConstant())
514 return true;
515
516 return false;
517}
518
519/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
520/// trivially dead instruction, delete it. If that makes any of its operands
521/// trivially dead, delete them too, recursively. Return true if any
522/// instructions were deleted.
524 Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
525 std::function<void(Value *)> AboutToDeleteCallback) {
527 if (!I || !isInstructionTriviallyDead(I, TLI))
528 return false;
529
531 DeadInsts.push_back(I);
532 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
533 AboutToDeleteCallback);
534
535 return true;
536}
537
540 MemorySSAUpdater *MSSAU,
541 std::function<void(Value *)> AboutToDeleteCallback) {
542 unsigned S = 0, E = DeadInsts.size(), Alive = 0;
543 for (; S != E; ++S) {
544 auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
545 if (!I || !isInstructionTriviallyDead(I)) {
546 DeadInsts[S] = nullptr;
547 ++Alive;
548 }
549 }
550 if (Alive == E)
551 return false;
552 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
553 AboutToDeleteCallback);
554 return true;
555}
556
559 MemorySSAUpdater *MSSAU,
560 std::function<void(Value *)> AboutToDeleteCallback) {
561 // Process the dead instruction list until empty.
562 while (!DeadInsts.empty()) {
563 Value *V = DeadInsts.pop_back_val();
565 if (!I)
566 continue;
568 "Live instruction found in dead worklist!");
569 assert(I->use_empty() && "Instructions with uses are not dead.");
570
571 // Don't lose the debug info while deleting the instructions.
573
574 if (AboutToDeleteCallback)
575 AboutToDeleteCallback(I);
576
577 // Null out all of the instruction's operands to see if any operand becomes
578 // dead as we go.
579 for (Use &OpU : I->operands()) {
580 Value *OpV = OpU.get();
581 OpU.set(nullptr);
582
583 if (!OpV->use_empty())
584 continue;
585
586 // If the operand is an instruction that became dead as we nulled out the
587 // operand, and if it is 'trivially' dead, delete it in a future loop
588 // iteration.
589 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
590 if (isInstructionTriviallyDead(OpI, TLI))
591 DeadInsts.push_back(OpI);
592 }
593 if (MSSAU)
594 MSSAU->removeMemoryAccess(I);
595
596 I->eraseFromParent();
597 }
598}
599
600/// areAllUsesEqual - Check whether the uses of a value are all the same.
601/// This is similar to Instruction::hasOneUse() except this will also return
602/// true when there are no uses or multiple uses that all refer to the same
603/// value.
605 Value::user_iterator UI = I->user_begin();
606 Value::user_iterator UE = I->user_end();
607 if (UI == UE)
608 return true;
609
610 User *TheUse = *UI;
611 for (++UI; UI != UE; ++UI) {
612 if (*UI != TheUse)
613 return false;
614 }
615 return true;
616}
617
618/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
619/// dead PHI node, due to being a def-use chain of single-use nodes that
620/// either forms a cycle or is terminated by a trivially dead instruction,
621/// delete it. If that makes any of its operands trivially dead, delete them
622/// too, recursively. Return true if a change was made.
624 PHINode *PN, const TargetLibraryInfo *TLI, llvm::MemorySSAUpdater *MSSAU,
625 SmallPtrSetImpl<PHINode *> *KnownNonDeadPHIs) {
627 SmallVector<PHINode *, 8> VisitedPHIs;
628
629 for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
630 I = cast<Instruction>(*I->user_begin())) {
631 if (I->use_empty())
633
634 // If we find an instruction more than once, we're on a cycle that
635 // won't prove fruitful.
636 if (!Visited.insert(I).second) {
637 // Break the cycle and delete the instruction and its operands.
638 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
640 return true;
641 }
642
643 if (PHINode *CurPN = dyn_cast<PHINode>(I)) {
644 if (KnownNonDeadPHIs && KnownNonDeadPHIs->contains(CurPN))
645 break;
646 VisitedPHIs.push_back(CurPN);
647 }
648 }
649
650 if (KnownNonDeadPHIs)
651 for (PHINode *VisitedPN : VisitedPHIs)
652 KnownNonDeadPHIs->insert(VisitedPN);
653
654 return false;
655}
656
657static bool
660 const DataLayout &DL,
661 const TargetLibraryInfo *TLI) {
662 if (isInstructionTriviallyDead(I, TLI)) {
664
665 // Null out all of the instruction's operands to see if any operand becomes
666 // dead as we go.
667 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
668 Value *OpV = I->getOperand(i);
669 I->setOperand(i, nullptr);
670
671 if (!OpV->use_empty() || I == OpV)
672 continue;
673
674 // If the operand is an instruction that became dead as we nulled out the
675 // operand, and if it is 'trivially' dead, delete it in a future loop
676 // iteration.
677 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
678 if (isInstructionTriviallyDead(OpI, TLI))
679 WorkList.insert(OpI);
680 }
681
682 I->eraseFromParent();
683
684 return true;
685 }
686
687 if (Value *SimpleV = simplifyInstruction(I, DL)) {
688 // Add the users to the worklist. CAREFUL: an instruction can use itself,
689 // in the case of a phi node.
690 for (User *U : I->users()) {
691 if (U != I) {
692 WorkList.insert(cast<Instruction>(U));
693 }
694 }
695
696 // Replace the instruction with its simplified value.
697 bool Changed = false;
698 if (!I->use_empty()) {
699 I->replaceAllUsesWith(SimpleV);
700 Changed = true;
701 }
702 if (isInstructionTriviallyDead(I, TLI)) {
703 I->eraseFromParent();
704 Changed = true;
705 }
706 return Changed;
707 }
708 return false;
709}
710
711/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
712/// simplify any instructions in it and recursively delete dead instructions.
713///
714/// This returns true if it changed the code, note that it can delete
715/// instructions in other blocks as well in this block.
717 const TargetLibraryInfo *TLI) {
718 bool MadeChange = false;
719 const DataLayout &DL = BB->getDataLayout();
720
721#ifndef NDEBUG
722 // In debug builds, ensure that the terminator of the block is never replaced
723 // or deleted by these simplifications. The idea of simplification is that it
724 // cannot introduce new instructions, and there is no way to replace the
725 // terminator of a block without introducing a new instruction.
726 AssertingVH<Instruction> TerminatorVH(&BB->back());
727#endif
728
730 // Iterate over the original function, only adding insts to the worklist
731 // if they actually need to be revisited. This avoids having to pre-init
732 // the worklist with the entire function's worth of instructions.
733 for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
734 BI != E;) {
735 assert(!BI->isTerminator());
736 Instruction *I = &*BI;
737 ++BI;
738
739 // We're visiting this instruction now, so make sure it's not in the
740 // worklist from an earlier visit.
741 if (!WorkList.count(I))
742 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
743 }
744
745 while (!WorkList.empty()) {
746 Instruction *I = WorkList.pop_back_val();
747 MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
748 }
749 return MadeChange;
750}
751
752//===----------------------------------------------------------------------===//
753// Control Flow Graph Restructuring.
754//
755
757 DomTreeUpdater *DTU) {
758
759 // If BB has single-entry PHI nodes, fold them.
760 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
761 Value *NewVal = PN->getIncomingValue(0);
762 // Replace self referencing PHI with poison, it must be dead.
763 if (NewVal == PN) NewVal = PoisonValue::get(PN->getType());
764 PN->replaceAllUsesWith(NewVal);
765 PN->eraseFromParent();
766 }
767
768 BasicBlock *PredBB = DestBB->getSinglePredecessor();
769 assert(PredBB && "Block doesn't have a single predecessor!");
770
771 bool ReplaceEntryBB = PredBB->isEntryBlock();
772
773 // DTU updates: Collect all the edges that enter
774 // PredBB. These dominator edges will be redirected to DestBB.
776
777 if (DTU) {
778 // To avoid processing the same predecessor more than once.
780 Updates.reserve(Updates.size() + 2 * pred_size(PredBB) + 1);
781 for (BasicBlock *PredOfPredBB : predecessors(PredBB))
782 // This predecessor of PredBB may already have DestBB as a successor.
783 if (PredOfPredBB != PredBB)
784 if (SeenPreds.insert(PredOfPredBB).second)
785 Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
786 SeenPreds.clear();
787 for (BasicBlock *PredOfPredBB : predecessors(PredBB))
788 if (SeenPreds.insert(PredOfPredBB).second)
789 Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
790 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
791 }
792
793 // Zap anything that took the address of DestBB. Not doing this will give the
794 // address an invalid value.
795 if (DestBB->hasAddressTaken()) {
796 BlockAddress *BA = BlockAddress::get(DestBB);
797 Constant *Replacement =
798 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
800 BA->getType()));
801 BA->destroyConstant();
802 }
803
804 // Anything that branched to PredBB now branches to DestBB.
805 PredBB->replaceAllUsesWith(DestBB);
806
807 // Splice all the instructions from PredBB to DestBB.
808 PredBB->getTerminator()->eraseFromParent();
809 DestBB->splice(DestBB->begin(), PredBB);
810 new UnreachableInst(PredBB->getContext(), PredBB);
811
812 // If the PredBB is the entry block of the function, move DestBB up to
813 // become the entry block after we erase PredBB.
814 if (ReplaceEntryBB)
815 DestBB->moveAfter(PredBB);
816
817 if (DTU) {
818 assert(PredBB->size() == 1 &&
820 "The successor list of PredBB isn't empty before "
821 "applying corresponding DTU updates.");
822 DTU->applyUpdatesPermissive(Updates);
823 DTU->deleteBB(PredBB);
824 // Recalculation of DomTree is needed when updating a forward DomTree and
825 // the Entry BB is replaced.
826 if (ReplaceEntryBB && DTU->hasDomTree()) {
827 // The entry block was removed and there is no external interface for
828 // the dominator tree to be notified of this change. In this corner-case
829 // we recalculate the entire tree.
830 DTU->recalculate(*(DestBB->getParent()));
831 }
832 }
833
834 else {
835 PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
836 }
837}
838
839/// Return true if we can choose one of these values to use in place of the
840/// other. Note that we will always choose the non-undef value to keep.
841static bool CanMergeValues(Value *First, Value *Second) {
842 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
843}
844
845/// Return true if we can fold BB, an almost-empty BB ending in an unconditional
846/// branch to Succ, into Succ.
847///
848/// Assumption: Succ is the single successor for BB.
849static bool
851 const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
852 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
853
854 LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
855 << Succ->getName() << "\n");
856 // Shortcut, if there is only a single predecessor it must be BB and merging
857 // is always safe
858 if (Succ->getSinglePredecessor())
859 return true;
860
861 // Look at all the phi nodes in Succ, to see if they present a conflict when
862 // merging these blocks
863 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
864 PHINode *PN = cast<PHINode>(I);
865
866 // If the incoming value from BB is again a PHINode in
867 // BB which has the same incoming value for *PI as PN does, we can
868 // merge the phi nodes and then the blocks can still be merged
870 if (BBPN && BBPN->getParent() == BB) {
871 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
872 BasicBlock *IBB = PN->getIncomingBlock(PI);
873 if (BBPreds.count(IBB) &&
875 PN->getIncomingValue(PI))) {
877 << "Can't fold, phi node " << PN->getName() << " in "
878 << Succ->getName() << " is conflicting with "
879 << BBPN->getName() << " with regard to common predecessor "
880 << IBB->getName() << "\n");
881 return false;
882 }
883 }
884 } else {
885 Value* Val = PN->getIncomingValueForBlock(BB);
886 for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
887 // See if the incoming value for the common predecessor is equal to the
888 // one for BB, in which case this phi node will not prevent the merging
889 // of the block.
890 BasicBlock *IBB = PN->getIncomingBlock(PI);
891 if (BBPreds.count(IBB) &&
892 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
893 LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
894 << " in " << Succ->getName()
895 << " is conflicting with regard to common "
896 << "predecessor " << IBB->getName() << "\n");
897 return false;
898 }
899 }
900 }
901 }
902
903 return true;
904}
905
908
909/// Determines the value to use as the phi node input for a block.
910///
911/// Select between \p OldVal any value that we know flows from \p BB
912/// to a particular phi on the basis of which one (if either) is not
913/// undef. Update IncomingValues based on the selected value.
914///
915/// \param OldVal The value we are considering selecting.
916/// \param BB The block that the value flows in from.
917/// \param IncomingValues A map from block-to-value for other phi inputs
918/// that we have examined.
919///
920/// \returns the selected value.
922 IncomingValueMap &IncomingValues) {
923 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
924 if (!isa<UndefValue>(OldVal)) {
925 assert((It != IncomingValues.end() &&
926 (!(It->second) || It->second == OldVal)) &&
927 "Expected OldVal to match incoming value from BB!");
928
929 IncomingValues.insert_or_assign(BB, OldVal);
930 return OldVal;
931 }
932
933 if (It != IncomingValues.end() && It->second)
934 return It->second;
935
936 return OldVal;
937}
938
939/// Create a map from block to value for the operands of a
940/// given phi.
941///
942/// This function initializes the map with UndefValue for all predecessors
943/// in BBPreds, and then updates the map with concrete non-undef values
944/// found in the PHI node.
945///
946/// \param PN The phi we are collecting the map for.
947/// \param BBPreds The list of all predecessor blocks to initialize with Undef.
948/// \param IncomingValues [out] The map from block to value for this phi.
950 const PredBlockVector &BBPreds,
951 IncomingValueMap &IncomingValues) {
952 for (BasicBlock *Pred : BBPreds)
953 IncomingValues[Pred] = nullptr;
954
955 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
956 Value *V = PN->getIncomingValue(i);
957 if (isa<UndefValue>(V))
958 continue;
959
960 BasicBlock *BB = PN->getIncomingBlock(i);
961 auto It = IncomingValues.find(BB);
962 if (It != IncomingValues.end())
963 It->second = V;
964 }
965}
966
967/// Replace the incoming undef values to a phi with the values
968/// from a block-to-value map.
969///
970/// \param PN The phi we are replacing the undefs in.
971/// \param IncomingValues A map from block to value.
973 const IncomingValueMap &IncomingValues) {
974 SmallVector<unsigned> TrueUndefOps;
975 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
976 Value *V = PN->getIncomingValue(i);
977
978 if (!isa<UndefValue>(V)) continue;
979
980 BasicBlock *BB = PN->getIncomingBlock(i);
981 IncomingValueMap::const_iterator It = IncomingValues.find(BB);
982 if (It == IncomingValues.end())
983 continue;
984
985 // Keep track of undef/poison incoming values. Those must match, so we fix
986 // them up below if needed.
987 // Note: this is conservatively correct, but we could try harder and group
988 // the undef values per incoming basic block.
989 if (!It->second) {
990 TrueUndefOps.push_back(i);
991 continue;
992 }
993
994 // There is a defined value for this incoming block, so map this undef
995 // incoming value to the defined value.
996 PN->setIncomingValue(i, It->second);
997 }
998
999 // If there are both undef and poison values incoming, then convert those
1000 // values to undef. It is invalid to have different values for the same
1001 // incoming block.
1002 unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {
1003 return isa<PoisonValue>(PN->getIncomingValue(i));
1004 });
1005 if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
1006 for (unsigned i : TrueUndefOps)
1008 }
1009}
1010
1011// Only when they shares a single common predecessor, return true.
1012// Only handles cases when BB can't be merged while its predecessors can be
1013// redirected.
1014static bool
1016 const SmallPtrSetImpl<BasicBlock *> &BBPreds,
1017 BasicBlock *&CommonPred) {
1018
1019 // There must be phis in BB, otherwise BB will be merged into Succ directly
1020 if (BB->phis().empty() || Succ->phis().empty())
1021 return false;
1022
1023 // BB must have predecessors not shared that can be redirected to Succ
1024 if (!BB->hasNPredecessorsOrMore(2))
1025 return false;
1026
1027 if (any_of(BBPreds, [](const BasicBlock *Pred) {
1028 return isa<IndirectBrInst>(Pred->getTerminator());
1029 }))
1030 return false;
1031
1032 // Get the single common predecessor of both BB and Succ. Return false
1033 // when there are more than one common predecessors.
1034 for (BasicBlock *SuccPred : predecessors(Succ)) {
1035 if (BBPreds.count(SuccPred)) {
1036 if (CommonPred)
1037 return false;
1038 CommonPred = SuccPred;
1039 }
1040 }
1041
1042 return true;
1043}
1044
1045/// Check whether removing \p BB will make the phis in its \p Succ have too
1046/// many incoming entries. This function does not check whether \p BB is
1047/// foldable or not.
1049 // If BB only has one predecessor, then removing it will not introduce more
1050 // incoming edges for phis.
1051 if (BB->hasNPredecessors(1))
1052 return false;
1053 unsigned NumPreds = pred_size(BB);
1054 unsigned NumChangedPhi = 0;
1055 for (auto &Phi : Succ->phis()) {
1056 // If the incoming value is a phi and the phi is defined in BB,
1057 // then removing BB will not increase the total phi entries of the ir.
1058 if (auto *IncomingPhi = dyn_cast<PHINode>(Phi.getIncomingValueForBlock(BB)))
1059 if (IncomingPhi->getParent() == BB)
1060 continue;
1061 // Otherwise, we need to add entries to the phi
1062 NumChangedPhi++;
1063 }
1064 // For every phi that needs to be changed, (NumPreds - 1) new entries will be
1065 // added. If the total increase in phi entries exceeds
1066 // MaxPhiEntriesIncreaseAfterRemovingEmptyBlock, it will be considered as
1067 // introducing too many new phi entries.
1068 return (NumPreds - 1) * NumChangedPhi >
1070}
1071
1072/// Replace a value flowing from a block to a phi with
1073/// potentially multiple instances of that value flowing from the
1074/// block's predecessors to the phi.
1075///
1076/// \param BB The block with the value flowing into the phi.
1077/// \param BBPreds The predecessors of BB.
1078/// \param PN The phi that we are updating.
1079/// \param CommonPred The common predecessor of BB and PN's BasicBlock
1081 const PredBlockVector &BBPreds,
1082 PHINode *PN,
1083 BasicBlock *CommonPred) {
1084 Value *OldVal = PN->removeIncomingValue(BB, false);
1085 assert(OldVal && "No entry in PHI for Pred BB!");
1086
1087 // Map BBPreds to defined values or nullptr (representing undefined values).
1088 IncomingValueMap IncomingValues;
1089
1090 // We are merging two blocks - BB, and the block containing PN - and
1091 // as a result we need to redirect edges from the predecessors of BB
1092 // to go to the block containing PN, and update PN
1093 // accordingly. Since we allow merging blocks in the case where the
1094 // predecessor and successor blocks both share some predecessors,
1095 // and where some of those common predecessors might have undef
1096 // values flowing into PN, we want to rewrite those values to be
1097 // consistent with the non-undef values.
1098
1099 gatherIncomingValuesToPhi(PN, BBPreds, IncomingValues);
1100
1101 // If this incoming value is one of the PHI nodes in BB, the new entries
1102 // in the PHI node are the entries from the old PHI.
1103 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
1104 PHINode *OldValPN = cast<PHINode>(OldVal);
1105 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
1106 // Note that, since we are merging phi nodes and BB and Succ might
1107 // have common predecessors, we could end up with a phi node with
1108 // identical incoming branches. This will be cleaned up later (and
1109 // will trigger asserts if we try to clean it up now, without also
1110 // simplifying the corresponding conditional branch).
1111 BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
1112
1113 if (PredBB == CommonPred)
1114 continue;
1115
1116 Value *PredVal = OldValPN->getIncomingValue(i);
1117 Value *Selected =
1118 selectIncomingValueForBlock(PredVal, PredBB, IncomingValues);
1119
1120 // And add a new incoming value for this predecessor for the
1121 // newly retargeted branch.
1122 PN->addIncoming(Selected, PredBB);
1123 }
1124 if (CommonPred)
1125 PN->addIncoming(OldValPN->getIncomingValueForBlock(CommonPred), BB);
1126
1127 } else {
1128 for (BasicBlock *PredBB : BBPreds) {
1129 // Update existing incoming values in PN for this
1130 // predecessor of BB.
1131 if (PredBB == CommonPred)
1132 continue;
1133
1134 Value *Selected =
1135 selectIncomingValueForBlock(OldVal, PredBB, IncomingValues);
1136
1137 // And add a new incoming value for this predecessor for the
1138 // newly retargeted branch.
1139 PN->addIncoming(Selected, PredBB);
1140 }
1141 if (CommonPred)
1142 PN->addIncoming(OldVal, BB);
1143 }
1144
1145 replaceUndefValuesInPhi(PN, IncomingValues);
1146}
1147
1149 DomTreeUpdater *DTU) {
1150 assert(BB != &BB->getParent()->getEntryBlock() &&
1151 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1152
1153 // We can't simplify infinite loops.
1154 BasicBlock *Succ = cast<UncondBrInst>(BB->getTerminator())->getSuccessor(0);
1155 if (BB == Succ)
1156 return false;
1157
1159
1160 // The single common predecessor of BB and Succ when BB cannot be killed
1161 BasicBlock *CommonPred = nullptr;
1162
1163 bool BBKillable = CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);
1164
1165 // Even if we can not fold BB into Succ, we may be able to redirect the
1166 // predecessors of BB to Succ.
1167 bool BBPhisMergeable = BBKillable || CanRedirectPredsOfEmptyBBToSucc(
1168 BB, Succ, BBPreds, CommonPred);
1169
1170 if ((!BBKillable && !BBPhisMergeable) || introduceTooManyPhiEntries(BB, Succ))
1171 return false;
1172
1173 // Check to see if merging these blocks/phis would cause conflicts for any of
1174 // the phi nodes in BB or Succ. If not, we can safely merge.
1175
1176 // Check for cases where Succ has multiple predecessors and a PHI node in BB
1177 // has uses which will not disappear when the PHI nodes are merged. It is
1178 // possible to handle such cases, but difficult: it requires checking whether
1179 // BB dominates Succ, which is non-trivial to calculate in the case where
1180 // Succ has multiple predecessors. Also, it requires checking whether
1181 // constructing the necessary self-referential PHI node doesn't introduce any
1182 // conflicts; this isn't too difficult, but the previous code for doing this
1183 // was incorrect.
1184 //
1185 // Note that if this check finds a live use, BB dominates Succ, so BB is
1186 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1187 // folding the branch isn't profitable in that case anyway.
1188 if (!Succ->getSinglePredecessor()) {
1189 BasicBlock::iterator BBI = BB->begin();
1190 while (isa<PHINode>(*BBI)) {
1191 for (Use &U : BBI->uses()) {
1192 if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1193 if (PN->getIncomingBlock(U) != BB)
1194 return false;
1195 } else {
1196 return false;
1197 }
1198 }
1199 ++BBI;
1200 }
1201 }
1202
1203 if (BBPhisMergeable && CommonPred)
1204 LLVM_DEBUG(dbgs() << "Found Common Predecessor between: " << BB->getName()
1205 << " and " << Succ->getName() << " : "
1206 << CommonPred->getName() << "\n");
1207
1208 // 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1209 // metadata.
1210 //
1211 // FIXME: This is a stop-gap solution to preserve inner-loop metadata given
1212 // current status (that loop metadata is implemented as metadata attached to
1213 // the branch instruction in the loop latch block). To quote from review
1214 // comments, "the current representation of loop metadata (using a loop latch
1215 // terminator attachment) is known to be fundamentally broken. Loop latches
1216 // are not uniquely associated with loops (both in that a latch can be part of
1217 // multiple loops and a loop may have multiple latches). Loop headers are. The
1218 // solution to this problem is also known: Add support for basic block
1219 // metadata, and attach loop metadata to the loop header."
1220 //
1221 // Why bail out:
1222 // In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is
1223 // the latch for inner-loop (see reason below), so bail out to prerserve
1224 // inner-loop metadata rather than eliminating 'BB' and attaching its metadata
1225 // to this inner-loop.
1226 // - The reason we believe 'BB' and 'BB->Pred' have different inner-most
1227 // loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,
1228 // then 'BB' is the header and latch of 'L' and thereby 'L' must consist of
1229 // one self-looping basic block, which is contradictory with the assumption.
1230 //
1231 // To illustrate how inner-loop metadata is dropped:
1232 //
1233 // CFG Before
1234 //
1235 // BB is while.cond.exit, attached with loop metdata md2.
1236 // BB->Pred is for.body, attached with loop metadata md1.
1237 //
1238 // entry
1239 // |
1240 // v
1241 // ---> while.cond -------------> while.end
1242 // | |
1243 // | v
1244 // | while.body
1245 // | |
1246 // | v
1247 // | for.body <---- (md1)
1248 // | | |______|
1249 // | v
1250 // | while.cond.exit (md2)
1251 // | |
1252 // |_______|
1253 //
1254 // CFG After
1255 //
1256 // while.cond1 is the merge of while.cond.exit and while.cond above.
1257 // for.body is attached with md2, and md1 is dropped.
1258 // If LoopSimplify runs later (as a part of loop pass), it could create
1259 // dedicated exits for inner-loop (essentially adding `while.cond.exit`
1260 // back), but won't it won't see 'md1' nor restore it for the inner-loop.
1261 //
1262 // entry
1263 // |
1264 // v
1265 // ---> while.cond1 -------------> while.end
1266 // | |
1267 // | v
1268 // | while.body
1269 // | |
1270 // | v
1271 // | for.body <---- (md2)
1272 // |_______| |______|
1273 if (Instruction *TI = BB->getTerminatorOrNull())
1274 if (TI->hasNonDebugLocLoopMetadata())
1275 for (BasicBlock *Pred : predecessors(BB))
1276 if (Instruction *PredTI = Pred->getTerminatorOrNull())
1277 if (PredTI->hasNonDebugLocLoopMetadata())
1278 return false;
1279
1280 if (BBKillable)
1281 LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1282 else if (BBPhisMergeable)
1283 LLVM_DEBUG(dbgs() << "Merge Phis in Trivial BB: \n" << *BB);
1284
1286
1287 if (DTU) {
1288 // To avoid processing the same predecessor more than once.
1290 // All predecessors of BB (except the common predecessor) will be moved to
1291 // Succ.
1292 Updates.reserve(Updates.size() + 2 * pred_size(BB) + 1);
1294 predecessors(Succ));
1295 for (auto *PredOfBB : predecessors(BB)) {
1296 // Do not modify those common predecessors of BB and Succ
1297 if (!SuccPreds.contains(PredOfBB))
1298 if (SeenPreds.insert(PredOfBB).second)
1299 Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
1300 }
1301
1302 SeenPreds.clear();
1303
1304 for (auto *PredOfBB : predecessors(BB))
1305 // When BB cannot be killed, do not remove the edge between BB and
1306 // CommonPred.
1307 if (SeenPreds.insert(PredOfBB).second && PredOfBB != CommonPred)
1308 Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
1309
1310 if (BBKillable)
1311 Updates.push_back({DominatorTree::Delete, BB, Succ});
1312 }
1313
1314 if (isa<PHINode>(Succ->begin())) {
1315 // If there is more than one pred of succ, and there are PHI nodes in
1316 // the successor, then we need to add incoming edges for the PHI nodes
1317 //
1318 const PredBlockVector BBPreds(predecessors(BB));
1319
1320 // Loop over all of the PHI nodes in the successor of BB.
1321 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1322 PHINode *PN = cast<PHINode>(I);
1323 redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);
1324 }
1325 }
1326
1327 if (Succ->getSinglePredecessor()) {
1328 // BB is the only predecessor of Succ, so Succ will end up with exactly
1329 // the same predecessors BB had.
1330 // Copy over any phi, debug or lifetime instruction.
1332 Succ->splice(Succ->getFirstNonPHIIt(), BB);
1333 } else {
1334 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1335 // We explicitly check for such uses for merging phis.
1336 assert(PN->use_empty() && "There shouldn't be any uses here!");
1337 PN->eraseFromParent();
1338 }
1339 }
1340
1341 // If the unconditional branch we replaced contains non-debug llvm.loop
1342 // metadata, we add the metadata to the branch instructions in the
1343 // predecessors.
1344 if (Instruction *TI = BB->getTerminatorOrNull())
1345 if (TI->hasNonDebugLocLoopMetadata()) {
1346 MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop);
1347 for (BasicBlock *Pred : predecessors(BB))
1348 Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
1349 }
1350
1351 if (BBKillable) {
1352 // Everything that jumped to BB now goes to Succ.
1353 BB->replaceAllUsesWith(Succ);
1354
1355 if (!Succ->hasName())
1356 Succ->takeName(BB);
1357
1358 // Clear the successor list of BB to match updates applying to DTU later.
1359 if (BB->hasTerminator())
1360 BB->back().eraseFromParent();
1361
1362 new UnreachableInst(BB->getContext(), BB);
1363 assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1364 "applying corresponding DTU updates.");
1365 } else if (BBPhisMergeable) {
1366 // Everything except CommonPred that jumped to BB now goes to Succ.
1367 BB->replaceUsesWithIf(Succ, [BBPreds, CommonPred](Use &U) -> bool {
1368 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))
1369 return UseInst->getParent() != CommonPred &&
1370 BBPreds.contains(UseInst->getParent());
1371 return false;
1372 });
1373 }
1374
1375 if (DTU)
1376 DTU->applyUpdates(Updates);
1377
1378 if (BBKillable)
1379 DeleteDeadBlock(BB, DTU);
1380
1381 return true;
1382}
1383
1384static bool
1387 // This implementation doesn't currently consider undef operands
1388 // specially. Theoretically, two phis which are identical except for
1389 // one having an undef where the other doesn't could be collapsed.
1390
1391 bool Changed = false;
1392
1393 // Examine each PHI.
1394 // Note that increment of I must *NOT* be in the iteration_expression, since
1395 // we don't want to immediately advance when we restart from the beginning.
1396 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {
1397 ++I;
1398 // Is there an identical PHI node in this basic block?
1399 // Note that we only look in the upper square's triangle,
1400 // we already checked that the lower triangle PHI's aren't identical.
1401 for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
1402 if (ToRemove.contains(DuplicatePN))
1403 continue;
1404 if (!DuplicatePN->isIdenticalToWhenDefined(PN))
1405 continue;
1406 // A duplicate. Replace this PHI with the base PHI.
1407 ++NumPHICSEs;
1408 DuplicatePN->replaceAllUsesWith(PN);
1409 ToRemove.insert(DuplicatePN);
1410 Changed = true;
1411
1412 // The RAUW can change PHIs that we already visited.
1413 I = BB->begin();
1414 break; // Start over from the beginning.
1415 }
1416 }
1417 return Changed;
1418}
1419
1420static bool
1423 // This implementation doesn't currently consider undef operands
1424 // specially. Theoretically, two phis which are identical except for
1425 // one having an undef where the other doesn't could be collapsed.
1426
1427 struct PHIDenseMapInfo {
1428 // WARNING: this logic must be kept in sync with
1429 // Instruction::isIdenticalToWhenDefined()!
1430 static unsigned getHashValueImpl(PHINode *PN) {
1431 // Compute a hash value on the operands. Instcombine will likely have
1432 // sorted them, which helps expose duplicates, but we have to check all
1433 // the operands to be safe in case instcombine hasn't run.
1434 return static_cast<unsigned>(
1436 hash_combine_range(PN->blocks())));
1437 }
1438
1439 static unsigned getHashValue(PHINode *PN) {
1440#ifndef NDEBUG
1441 // If -phicse-debug-hash was specified, return a constant -- this
1442 // will force all hashing to collide, so we'll exhaustively search
1443 // the table for a match, and the assertion in isEqual will fire if
1444 // there's a bug causing equal keys to hash differently.
1445 if (PHICSEDebugHash)
1446 return 0;
1447#endif
1448 return getHashValueImpl(PN);
1449 }
1450
1451 static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
1452 return LHS->isIdenticalTo(RHS);
1453 }
1454
1455 static bool isEqual(PHINode *LHS, PHINode *RHS) {
1456 // These comparisons are nontrivial, so assert that equality implies
1457 // hash equality (DenseMap demands this as an invariant).
1458 bool Result = isEqualImpl(LHS, RHS);
1460 return Result;
1461 }
1462 };
1463
1464 // Set of unique PHINodes.
1466 PHISet.reserve(4 * PHICSENumPHISmallSize);
1467
1468 // Examine each PHI.
1469 bool Changed = false;
1470 for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1471 if (ToRemove.contains(PN))
1472 continue;
1473 auto Inserted = PHISet.insert(PN);
1474 if (!Inserted.second) {
1475 // A duplicate. Replace this PHI with its duplicate.
1476 ++NumPHICSEs;
1477 PN->replaceAllUsesWith(*Inserted.first);
1478 ToRemove.insert(PN);
1479 Changed = true;
1480
1481 // The RAUW can change PHIs that we already visited. Start over from the
1482 // beginning.
1483 PHISet.clear();
1484 I = BB->begin();
1485 }
1486 }
1487
1488 return Changed;
1489}
1490
1501
1505 for (PHINode *PN : ToRemove)
1506 PN->eraseFromParent();
1507 return Changed;
1508}
1509
1511 const DataLayout &DL) {
1512 V = V->stripPointerCasts();
1513
1514 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1515 // TODO: Ideally, this function would not be called if PrefAlign is smaller
1516 // than the current alignment, as the known bits calculation should have
1517 // already taken it into account. However, this is not always the case,
1518 // as computeKnownBits() has a depth limit, while stripPointerCasts()
1519 // doesn't.
1520 Align CurrentAlign = AI->getAlign();
1521 if (PrefAlign <= CurrentAlign)
1522 return CurrentAlign;
1523
1524 // If the preferred alignment is greater than the natural stack alignment
1525 // then don't round up. This avoids dynamic stack realignment.
1526 MaybeAlign StackAlign = DL.getStackAlignment();
1527 if (StackAlign && PrefAlign > *StackAlign)
1528 return CurrentAlign;
1529 AI->setAlignment(PrefAlign);
1530 return PrefAlign;
1531 }
1532
1533 if (auto *GV = dyn_cast<GlobalVariable>(V)) {
1534 // TODO: as above, this shouldn't be necessary.
1535 Align CurrentAlign = GV->getPointerAlignment(DL);
1536 if (PrefAlign <= CurrentAlign)
1537 return CurrentAlign;
1538
1539 // If there is a large requested alignment and we can, bump up the alignment
1540 // of the global. If the memory we set aside for the global may not be the
1541 // memory used by the final program then it is impossible for us to reliably
1542 // enforce the preferred alignment.
1543 if (!GV->canIncreaseAlignment())
1544 return CurrentAlign;
1545
1546 if (GV->isThreadLocal()) {
1547 unsigned MaxTLSAlign = GV->getParent()->getMaxTLSAlignment() / CHAR_BIT;
1548 if (MaxTLSAlign && PrefAlign > Align(MaxTLSAlign))
1549 PrefAlign = Align(MaxTLSAlign);
1550 }
1551
1552 GV->setAlignment(PrefAlign);
1553 return PrefAlign;
1554 }
1555
1556 return Align(1);
1557}
1558
1560 const DataLayout &DL,
1561 const Instruction *CxtI,
1562 AssumptionCache *AC,
1563 const DominatorTree *DT) {
1564 assert(V->getType()->isPointerTy() &&
1565 "getOrEnforceKnownAlignment expects a pointer!");
1566
1567 KnownBits Known = computeKnownBits(V, DL, AC, CxtI, DT);
1568 unsigned TrailZ = Known.countMinTrailingZeros();
1569
1570 // Avoid trouble with ridiculously large TrailZ values, such as
1571 // those computed from a null pointer.
1572 // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1573 TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1574
1575 Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1576
1577 if (PrefAlign && *PrefAlign > Alignment)
1578 Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));
1579
1580 // We don't need to make any adjustment.
1581 return Alignment;
1582}
1583
1584///===---------------------------------------------------------------------===//
1585/// Dbg Intrinsic utilities
1586///
1587
1588/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1590 DIExpression *DIExpr,
1591 PHINode *APN) {
1592 // Since we can't guarantee that the original dbg.declare intrinsic
1593 // is removed by LowerDbgDeclare(), we need to make sure that we are
1594 // not inserting the same dbg.value intrinsic over and over.
1595 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
1596 findDbgValues(APN, DbgVariableRecords);
1597 for (DbgVariableRecord *DVR : DbgVariableRecords) {
1598 assert(is_contained(DVR->location_ops(), APN));
1599 if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1600 return true;
1601 }
1602 return false;
1603}
1604
1605/// Check if the alloc size of \p ValTy is large enough to cover the variable
1606/// (or fragment of the variable) described by \p DII.
1607///
1608/// This is primarily intended as a helper for the different
1609/// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted
1610/// describes an alloca'd variable, so we need to use the alloc size of the
1611/// value when doing the comparison. E.g. an i1 value will be identified as
1612/// covering an n-bit fragment, if the store size of i1 is at least n bits.
1614 const DataLayout &DL = DVR->getModule()->getDataLayout();
1615 TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1616 if (std::optional<uint64_t> FragmentSize =
1617 DVR->getExpression()->getActiveBits(DVR->getVariable()))
1618 return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
1619
1620 // We can't always calculate the size of the DI variable (e.g. if it is a
1621 // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1622 // instead.
1623 if (DVR->isAddressOfVariable()) {
1624 // DVR should have exactly 1 location when it is an address.
1625 assert(DVR->getNumVariableLocationOps() == 1 &&
1626 "address of variable must have exactly 1 location operand.");
1627 if (auto *AI =
1629 if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1630 return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1631 }
1632 }
1633 }
1634 // Could not determine size of variable. Conservatively return false.
1635 return false;
1636}
1637
1639 DILocalVariable *DIVar,
1640 DIExpression *DIExpr,
1641 const DebugLoc &NewLoc,
1642 BasicBlock::iterator Instr) {
1644 DbgVariableRecord *DVRec =
1645 new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1646 Instr->getParent()->insertDbgRecordBefore(DVRec, Instr);
1647}
1648
1650 int NumEltDropped = DIExpr->getElements()[0] == dwarf::DW_OP_LLVM_arg ? 3 : 1;
1651 return DIExpression::get(DIExpr->getContext(),
1652 DIExpr->getElements().drop_front(NumEltDropped));
1653}
1654
1656 StoreInst *SI, DIBuilder &Builder) {
1657 assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());
1658 auto *DIVar = DVR->getVariable();
1659 assert(DIVar && "Missing variable");
1660 auto *DIExpr = DVR->getExpression();
1661 Value *DV = SI->getValueOperand();
1662
1663 if (isa<UndefValue>(DV) && !isa<PoisonValue>(DV))
1664 return;
1665
1666 DebugLoc NewLoc = getDebugValueLoc(DVR);
1667
1668 // If the alloca describes the variable itself, i.e. the expression in the
1669 // dbg.declare doesn't start with a dereference, we can perform the
1670 // conversion if the value covers the entire fragment of DII.
1671 // If the alloca describes the *address* of DIVar, i.e. DIExpr is
1672 // *just* a DW_OP_deref, we use DV as is for the dbg.value.
1673 // We conservatively ignore other dereferences, because the following two are
1674 // not equivalent:
1675 // dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1676 // dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1677 // The former is adding 2 to the address of the variable, whereas the latter
1678 // is adding 2 to the value of the variable. As such, we insist on just a
1679 // deref expression.
1680 bool CanConvert =
1681 DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1683 if (CanConvert) {
1684 insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1685 SI->getIterator());
1686 return;
1687 }
1688
1689 // FIXME: If storing to a part of the variable described by the dbg.declare,
1690 // then we want to insert a dbg.value for the corresponding fragment.
1691 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DVR
1692 << '\n');
1693
1694 // For now, when there is a store to parts of the variable (but we do not
1695 // know which part) we insert an dbg.value intrinsic to indicate that we
1696 // know nothing about the variable's content.
1697 DV = PoisonValue::get(DV->getType());
1699 DbgVariableRecord *NewDVR =
1700 new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1701 SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());
1702}
1703
1705 DIBuilder &Builder) {
1706 auto *DIVar = DVR->getVariable();
1707 assert(DIVar && "Missing variable");
1708 auto *DIExpr = DVR->getExpression();
1709 DIExpr = dropInitialDeref(DIExpr);
1710 Value *DV = SI->getValueOperand();
1711
1712 DebugLoc NewLoc = getDebugValueLoc(DVR);
1713
1714 insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1715 SI->getIterator());
1716}
1717
1719 DIBuilder &Builder) {
1720 auto *DIVar = DVR->getVariable();
1721 auto *DIExpr = DVR->getExpression();
1722 assert(DIVar && "Missing variable");
1723
1724 if (!valueCoversEntireFragment(LI->getType(), DVR)) {
1725 // FIXME: If only referring to a part of the variable described by the
1726 // dbg.declare, then we want to insert a DbgVariableRecord for the
1727 // corresponding fragment.
1728 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1729 << *DVR << '\n');
1730 return;
1731 }
1732
1733 DebugLoc NewLoc = getDebugValueLoc(DVR);
1734
1735 // We are now tracking the loaded value instead of the address. In the
1736 // future if multi-location support is added to the IR, it might be
1737 // preferable to keep tracking both the loaded value and the original
1738 // address in case the alloca can not be elided.
1739
1740 // Create a DbgVariableRecord directly and insert.
1742 DbgVariableRecord *DV =
1743 new DbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());
1744 LI->getParent()->insertDbgRecordAfter(DV, LI);
1745}
1746
1747/// Determine whether this debug variable is a not a basic type.
1748/// We strip through DIDerivedType modifiers (typedefs, const, etc.)
1749/// to find the underlying type to decide if it seems perhaps worthwhile to
1750/// do LowerDbgDeclare.
1752 DIType *Ty = DVR->getVariable()->getType();
1753 if (Ty == nullptr)
1754 return true;
1755 // Strip through modifier types to find the underlying type.
1756 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
1757 switch (DTy->getTag()) {
1758 case dwarf::DW_TAG_pointer_type:
1759 case dwarf::DW_TAG_reference_type:
1760 case dwarf::DW_TAG_rvalue_reference_type:
1761 case dwarf::DW_TAG_ptr_to_member_type:
1762 case dwarf::DW_TAG_LLVM_ptrauth_type:
1763 return false;
1764 case dwarf::DW_TAG_typedef:
1765 case dwarf::DW_TAG_const_type:
1766 case dwarf::DW_TAG_volatile_type:
1767 case dwarf::DW_TAG_restrict_type:
1768 case dwarf::DW_TAG_atomic_type:
1769 case dwarf::DW_TAG_immutable_type:
1770 Ty = DTy->getBaseType();
1771 continue;
1772 default:
1773 break;
1774 }
1775 break;
1776 }
1777 return !isa<DIBasicType>(Ty);
1778}
1779
1781 DIBuilder &Builder) {
1782 auto *DIVar = DVR->getVariable();
1783 auto *DIExpr = DVR->getExpression();
1784 assert(DIVar && "Missing variable");
1785
1786 if (PhiHasDebugValue(DIVar, DIExpr, APN))
1787 return;
1788
1789 if (!valueCoversEntireFragment(APN->getType(), DVR)) {
1790 // FIXME: If only referring to a part of the variable described by the
1791 // dbg.declare, then we want to insert a DbgVariableRecord for the
1792 // corresponding fragment.
1793 LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1794 << *DVR << '\n');
1795 return;
1796 }
1797
1798 BasicBlock *BB = APN->getParent();
1799 auto InsertionPt = BB->getFirstInsertionPt();
1800
1801 DebugLoc NewLoc = getDebugValueLoc(DVR);
1802
1803 // The block may be a catchswitch block, which does not have a valid
1804 // insertion point.
1805 // FIXME: Insert DbgVariableRecord markers in the successors when appropriate.
1806 if (InsertionPt != BB->end()) {
1807 insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1808 InsertionPt);
1809 }
1810}
1811
1812/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1813/// of llvm.dbg.value intrinsics.
1815 bool Changed = false;
1816 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1819 for (auto &FI : F) {
1820 for (Instruction &BI : FI) {
1821 if (auto *DDI = dyn_cast<DbgDeclareInst>(&BI))
1822 Dbgs.push_back(DDI);
1823 for (DbgVariableRecord &DVR : filterDbgVars(BI.getDbgRecordRange())) {
1824 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
1825 DVRs.push_back(&DVR);
1826 }
1827 }
1828 }
1829
1830 if (Dbgs.empty() && DVRs.empty())
1831 return Changed;
1832
1833 auto LowerOne = [&](DbgVariableRecord *DDI) {
1834 AllocaInst *AI =
1835 dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
1836 // If this is an alloca for a scalar variable, insert a dbg.value
1837 // at each load and store to the alloca and erase the dbg.declare.
1838 // The dbg.values allow tracking a variable even if it is not
1839 // stored on the stack, while the dbg.declare can only describe
1840 // the stack slot (and at a lexical-scope granularity). Later
1841 // passes will attempt to elide the stack slot.
1842 // Skip VLAs (dynamic allocas) and composite types (arrays/structs) since
1843 // they can't be represented as a single dbg.value.
1844 if (!AI || !isa<Constant>(AI->getArraySize()) || isCompositeType(DDI))
1845 return;
1846
1847 // A volatile load/store means that the alloca can't be elided anyway.
1848 // Just look at direct uses however, and ignore any other instructions.
1849 if (llvm::any_of(AI->users(), [](User *U) -> bool {
1850 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1851 return LI->isVolatile();
1852 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1853 return SI->isVolatile();
1854 return false;
1855 }))
1856 return;
1857
1859 WorkList.push_back(AI);
1860 while (!WorkList.empty()) {
1861 const Value *V = WorkList.pop_back_val();
1862 for (const auto &AIUse : V->uses()) {
1863 User *U = AIUse.getUser();
1864 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1865 if (AIUse.getOperandNo() == 1)
1867 } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1868 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1869 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1870 // This is a call by-value or some other instruction that takes a
1871 // pointer to the variable. Insert a *value* intrinsic that describes
1872 // the variable by dereferencing the alloca.
1873 if (!CI->isLifetimeStartOrEnd()) {
1874 DebugLoc NewLoc = getDebugValueLoc(DDI);
1875 auto *DerefExpr =
1876 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1877 insertDbgValueOrDbgVariableRecord(DIB, AI, DDI->getVariable(),
1878 DerefExpr, NewLoc,
1879 CI->getIterator());
1880 }
1881 } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1882 if (BI->getType()->isPointerTy())
1883 WorkList.push_back(BI);
1884 }
1885 }
1886 }
1887 DDI->eraseFromParent();
1888 Changed = true;
1889 };
1890
1891 for_each(DVRs, LowerOne);
1892
1893 if (Changed)
1894 for (BasicBlock &BB : F)
1896
1897 return Changed;
1898}
1899
1900/// Propagate dbg.value records through the newly inserted PHIs.
1902 SmallVectorImpl<PHINode *> &InsertedPHIs) {
1903 assert(BB && "No BasicBlock to clone DbgVariableRecord(s) from.");
1904 if (InsertedPHIs.size() == 0)
1905 return;
1906
1907 // Map existing PHI nodes to their DbgVariableRecords.
1909 for (auto &I : *BB) {
1910 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1911 for (Value *V : DVR.location_ops())
1912 if (auto *Loc = dyn_cast_or_null<PHINode>(V))
1913 DbgValueMap.insert({Loc, &DVR});
1914 }
1915 }
1916 if (DbgValueMap.size() == 0)
1917 return;
1918
1919 // Map a pair of the destination BB and old DbgVariableRecord to the new
1920 // DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use
1921 // more than one of the inserted PHIs in the same destination BB, we can
1922 // update the same DbgVariableRecord with all the new PHIs instead of creating
1923 // one copy for each.
1925 NewDbgValueMap;
1926 // Then iterate through the new PHIs and look to see if they use one of the
1927 // previously mapped PHIs. If so, create a new DbgVariableRecord that will
1928 // propagate the info through the new PHI. If we use more than one new PHI in
1929 // a single destination BB with the same old dbg.value, merge the updates so
1930 // that we get a single new DbgVariableRecord with all the new PHIs.
1931 for (auto PHI : InsertedPHIs) {
1932 BasicBlock *Parent = PHI->getParent();
1933 // Avoid inserting a debug-info record into an EH block.
1934 if (Parent->getFirstNonPHIIt()->isEHPad())
1935 continue;
1936 for (auto VI : PHI->operand_values()) {
1937 auto V = DbgValueMap.find(VI);
1938 if (V != DbgValueMap.end()) {
1939 DbgVariableRecord *DbgII = cast<DbgVariableRecord>(V->second);
1940 auto NewDI = NewDbgValueMap.find({Parent, DbgII});
1941 if (NewDI == NewDbgValueMap.end()) {
1942 DbgVariableRecord *NewDbgII = DbgII->clone();
1943 NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
1944 }
1945 DbgVariableRecord *NewDbgII = NewDI->second;
1946 // If PHI contains VI as an operand more than once, we may
1947 // replaced it in NewDbgII; confirm that it is present.
1948 if (is_contained(NewDbgII->location_ops(), VI))
1949 NewDbgII->replaceVariableLocationOp(VI, PHI);
1950 }
1951 }
1952 }
1953 // Insert the new DbgVariableRecords into their destination blocks.
1954 for (auto DI : NewDbgValueMap) {
1955 BasicBlock *Parent = DI.first.first;
1956 DbgVariableRecord *NewDbgII = DI.second;
1957 auto InsertionPt = Parent->getFirstInsertionPt();
1958 assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1959
1960 Parent->insertDbgRecordBefore(NewDbgII, InsertionPt);
1961 }
1962}
1963
1965 DIBuilder &Builder, uint8_t DIExprFlags,
1966 int Offset) {
1968
1969 auto ReplaceOne = [&](DbgVariableRecord *DII) {
1970 assert(DII->getVariable() && "Missing variable");
1971 auto *DIExpr = DII->getExpression();
1972 DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
1973 DII->setExpression(DIExpr);
1974 DII->replaceVariableLocationOp(Address, NewAddress);
1975 };
1976
1977 for_each(DVRDeclares, ReplaceOne);
1978
1979 return !DVRDeclares.empty();
1980}
1981
1983 DILocalVariable *DIVar,
1984 DIExpression *DIExpr, Value *NewAddress,
1985 DbgVariableRecord *DVR,
1986 DIBuilder &Builder, int Offset) {
1987 assert(DIVar && "Missing variable");
1988
1989 // This is an alloca-based dbg.value/DbgVariableRecord. The first thing it
1990 // should do with the alloca pointer is dereference it. Otherwise we don't
1991 // know how to handle it and give up.
1992 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1993 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1994 return;
1995
1996 // Insert the offset before the first deref.
1997 if (Offset)
1998 DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
1999
2000 DVR->setExpression(DIExpr);
2001 DVR->replaceVariableLocationOp(0u, NewAddress);
2002}
2003
2005 DIBuilder &Builder, int Offset) {
2007 findDbgValues(AI, DPUsers);
2008
2009 // Replace any DbgVariableRecords that use this alloca.
2010 for (DbgVariableRecord *DVR : DPUsers)
2011 updateOneDbgValueForAlloca(DVR->getDebugLoc(), DVR->getVariable(),
2012 DVR->getExpression(), NewAllocaAddress, DVR,
2013 Builder, Offset);
2014}
2015
2018 findDbgUsers(&I, DbgRecords);
2019 salvageDebugInfoForDbgValues(I, DbgRecords);
2020}
2021
2022/// Salvage the address of \p Assign, which the caller has checked is \p I. An
2023/// address we cannot salvage stays as it is rather than stopping the caller,
2024/// which counts the record as processed either way and goes on to salvage its
2025/// variable location.
2027 assert(Assign.isDbgAssign() && Assign.getAddress() == &I &&
2028 "dbg.assign must use salvaged instruction as its address");
2029 assert(!Assign.getAddressExpression()->getFragmentInfo().has_value() &&
2030 "address-expression shouldn't have fragment info");
2031
2032 // The address component of a dbg.assign cannot be variadic.
2033 uint64_t CurrentLocOps = 0;
2034 SmallVector<Value *, 4> AdditionalValues;
2036 Value *NewAddress =
2037 salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2038
2039 // Keep an address we cannot salvage. If I is deleted, its remaining metadata
2040 // use is replaced with poison.
2041 if (!NewAddress)
2042 return;
2043
2045 Assign.getAddressExpression(), Ops, 0, /*StackValue=*/false);
2046 assert(!SalvagedExpr->getFragmentInfo().has_value() &&
2047 "address-expression shouldn't have fragment info");
2048
2049 SalvagedExpr = SalvagedExpr->foldConstantMath();
2050
2051 // Salvage succeeds if no additional values are required.
2052 if (AdditionalValues.empty()) {
2053 Assign.setAddress(NewAddress);
2054 Assign.setAddressExpression(SalvagedExpr);
2055 } else {
2056 Assign.setKillAddress();
2057 }
2058}
2059
2060/// Rewrite \p DVR's variable location in terms of \p I's operands. Return false
2061/// and leave the record alone when the instruction cannot be salvaged. Return
2062/// true once it can, including when the location ends up killed.
2064 // These are arbitrary chosen limits on the maximum number of values and the
2065 // maximum size of a debug expression we can salvage up to, used for
2066 // performance reasons.
2067 const unsigned MaxDebugArgs = 16;
2068 const unsigned MaxExpressionSize = 128;
2069
2070 // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
2071 // are implicitly pointing out the value as a DWARF memory location
2072 // description.
2073 const bool StackValue = !DVR.isAddressOfVariable();
2074 auto LocationOps = DVR.location_ops();
2075 assert(is_contained(LocationOps, &I) &&
2076 "DbgVariableRecord must use salvaged instruction as its location");
2077 SmallVector<Value *, 4> AdditionalValues;
2078 // 'I' may appear more than once in DVR's location ops, and each use of 'I'
2079 // must be updated in the DIExpression and potentially have additional
2080 // values added; thus we call salvageDebugInfoImpl for each 'I' instance in
2081 // LocationOps.
2082 Value *Replacement = nullptr;
2083 DIExpression *SalvagedExpr = DVR.getExpression();
2084 auto LocIt = find(LocationOps, &I);
2085 while (SalvagedExpr && LocIt != LocationOps.end()) {
2087 unsigned LocationIndex = std::distance(LocationOps.begin(), LocIt);
2088 uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2089 Replacement = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2090 if (!Replacement)
2091 break;
2092 SalvagedExpr = DIExpression::appendOpsToArg(SalvagedExpr, Ops,
2093 LocationIndex, StackValue);
2094 LocIt = std::find(++LocIt, LocationOps.end(), &I);
2095 }
2096 // The failure conditions in salvageDebugInfoImpl do not depend on
2097 // CurrentLocOps, so failure can only occur on the first occurrence.
2098 if (!Replacement)
2099 return false;
2100
2101 SalvagedExpr = SalvagedExpr->foldConstantMath();
2102 DVR.replaceVariableLocationOp(&I, Replacement);
2103 const bool FitsExpressionLimit =
2104 SalvagedExpr->getNumElements() <= MaxExpressionSize;
2105 if (AdditionalValues.empty() && FitsExpressionLimit) {
2106 DVR.setExpression(SalvagedExpr);
2107 } else if (!DVR.isAddressOfVariable() && FitsExpressionLimit &&
2108 DVR.getNumVariableLocationOps() + AdditionalValues.size() <=
2109 MaxDebugArgs) {
2110 DVR.addVariableLocationOps(AdditionalValues, SalvagedExpr);
2111 } else {
2112 // Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
2113 // currently only valid for stack value expressions.
2114 // Also do not salvage if the resulting DIArgList would contain an
2115 // unreasonably large number of values.
2116 DVR.setKillLocation();
2117 }
2118 LLVM_DEBUG(dbgs() << "SALVAGE: " << DVR << '\n');
2119 return true;
2120}
2121
2124 bool ProcessedAnyUse = false;
2125
2126 for (auto *DVR : DbgRecords) {
2127 // replaceVariableLocationOp also updates a matching dbg.assign address, so
2128 // salvage the address before changing the variable location.
2129 if (DVR->isDbgAssign()) {
2130 if (DVR->getAddress() == &I) {
2132 ProcessedAnyUse = true;
2133 }
2134 if (DVR->getValue() != &I)
2135 continue;
2136 }
2137 if (!salvageDbgVariableLocation(I, *DVR))
2138 break;
2139 ProcessedAnyUse = true;
2140 }
2141
2142 if (ProcessedAnyUse)
2143 return;
2144
2145 for (auto *DVR : DbgRecords)
2146 DVR->setKillLocation();
2147}
2148
2150 uint64_t CurrentLocOps,
2152 SmallVectorImpl<Value *> &AdditionalValues) {
2153 unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
2154 // Rewrite a GEP into a DIExpression.
2155 SmallMapVector<Value *, APInt, 4> VariableOffsets;
2156 APInt ConstantOffset(BitWidth, 0);
2157 if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
2158 return nullptr;
2159 if (!VariableOffsets.empty() && !CurrentLocOps) {
2160 Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
2161 CurrentLocOps = 1;
2162 }
2163 for (const auto &Offset : VariableOffsets) {
2164 AdditionalValues.push_back(Offset.first);
2165 assert(Offset.second.isStrictlyPositive() &&
2166 "Expected strictly positive multiplier for offset.");
2167 Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
2168 Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2169 dwarf::DW_OP_plus});
2170 }
2171 DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
2172 return GEP->getOperand(0);
2173}
2174
2176 switch (Opcode) {
2177 case Instruction::Add:
2178 return dwarf::DW_OP_plus;
2179 case Instruction::Sub:
2180 return dwarf::DW_OP_minus;
2181 case Instruction::Mul:
2182 return dwarf::DW_OP_mul;
2183 case Instruction::SDiv:
2184 return dwarf::DW_OP_div;
2185 case Instruction::SRem:
2186 return dwarf::DW_OP_mod;
2187 case Instruction::Or:
2188 return dwarf::DW_OP_or;
2189 case Instruction::And:
2190 return dwarf::DW_OP_and;
2191 case Instruction::Xor:
2192 return dwarf::DW_OP_xor;
2193 case Instruction::Shl:
2194 return dwarf::DW_OP_shl;
2195 case Instruction::LShr:
2196 return dwarf::DW_OP_shr;
2197 case Instruction::AShr:
2198 return dwarf::DW_OP_shra;
2199 default:
2200 // TODO: Salvage from each kind of binop we know about.
2201 return 0;
2202 }
2203}
2204
2205static void handleSSAValueOperands(uint64_t CurrentLocOps,
2207 SmallVectorImpl<Value *> &AdditionalValues,
2208 Instruction *I) {
2209 if (!CurrentLocOps) {
2210 Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
2211 CurrentLocOps = 1;
2212 }
2213 Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
2214 AdditionalValues.push_back(I->getOperand(1));
2215}
2216
2219 SmallVectorImpl<Value *> &AdditionalValues) {
2220 // Handle binary operations with constant integer operands as a special case.
2221 auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
2222 // Values wider than 64 bits cannot be represented within a DIExpression.
2223 if (ConstInt && ConstInt->getBitWidth() > 64)
2224 return nullptr;
2225
2226 Instruction::BinaryOps BinOpcode = BI->getOpcode();
2227 // Push any Constant Int operand onto the expression stack.
2228 if (ConstInt) {
2229 uint64_t Val = ConstInt->getSExtValue();
2230 // Add or Sub Instructions with a constant operand can potentially be
2231 // simplified.
2232 if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2233 uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2235 return BI->getOperand(0);
2236 }
2237 Opcodes.append({dwarf::DW_OP_constu, Val});
2238 } else {
2239 handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, BI);
2240 }
2241
2242 // Add salvaged binary operator to expression stack, if it has a valid
2243 // representation in a DIExpression.
2244 uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);
2245 if (!DwarfBinOp)
2246 return nullptr;
2247 Opcodes.push_back(DwarfBinOp);
2248 return BI->getOperand(0);
2249}
2250
2252 // The signedness of the operation is implicit in the typed stack, signed and
2253 // unsigned instructions map to the same DWARF opcode.
2254 switch (Pred) {
2255 case CmpInst::ICMP_EQ:
2256 return dwarf::DW_OP_eq;
2257 case CmpInst::ICMP_NE:
2258 return dwarf::DW_OP_ne;
2259 case CmpInst::ICMP_UGT:
2260 case CmpInst::ICMP_SGT:
2261 return dwarf::DW_OP_gt;
2262 case CmpInst::ICMP_UGE:
2263 case CmpInst::ICMP_SGE:
2264 return dwarf::DW_OP_ge;
2265 case CmpInst::ICMP_ULT:
2266 case CmpInst::ICMP_SLT:
2267 return dwarf::DW_OP_lt;
2268 case CmpInst::ICMP_ULE:
2269 case CmpInst::ICMP_SLE:
2270 return dwarf::DW_OP_le;
2271 default:
2272 return 0;
2273 }
2274}
2275
2278 SmallVectorImpl<Value *> &AdditionalValues) {
2279 // Handle icmp operations with constant integer operands as a special case.
2280 auto *ConstInt = dyn_cast<ConstantInt>(Icmp->getOperand(1));
2281 // Values wider than 64 bits cannot be represented within a DIExpression.
2282 if (ConstInt && ConstInt->getBitWidth() > 64)
2283 return nullptr;
2284 // Push any Constant Int operand onto the expression stack.
2285 if (ConstInt) {
2286 if (Icmp->isSigned())
2287 Opcodes.push_back(dwarf::DW_OP_consts);
2288 else
2289 Opcodes.push_back(dwarf::DW_OP_constu);
2290 uint64_t Val = ConstInt->getSExtValue();
2291 Opcodes.push_back(Val);
2292 } else {
2293 handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, Icmp);
2294 }
2295
2296 // Add salvaged binary operator to expression stack, if it has a valid
2297 // representation in a DIExpression.
2298 uint64_t DwarfIcmpOp = getDwarfOpForIcmpPred(Icmp->getPredicate());
2299 if (!DwarfIcmpOp)
2300 return nullptr;
2301 Opcodes.push_back(DwarfIcmpOp);
2302 return Icmp->getOperand(0);
2303}
2304
2307 SmallVectorImpl<Value *> &AdditionalValues) {
2308 auto &M = *I.getModule();
2309 auto &DL = M.getDataLayout();
2310
2311 if (auto *CI = dyn_cast<CastInst>(&I)) {
2312 Value *FromValue = CI->getOperand(0);
2313 // No-op casts are irrelevant for debug info.
2314 if (CI->isNoopCast(DL)) {
2315 return FromValue;
2316 }
2317
2318 Type *Type = CI->getType();
2319 if (Type->isPointerTy())
2320 Type = DL.getIntPtrType(Type);
2321 // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
2322 if (Type->isVectorTy() ||
2325 return nullptr;
2326
2327 llvm::Type *FromType = FromValue->getType();
2328 if (FromType->isPointerTy())
2329 FromType = DL.getIntPtrType(FromType);
2330
2331 unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2332 unsigned ToTypeBitSize = Type->getScalarSizeInBits();
2333
2334 auto ExtOps = DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
2335 isa<SExtInst>(&I));
2336 Ops.append(ExtOps.begin(), ExtOps.end());
2337 return FromValue;
2338 }
2339
2340 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
2341 return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues);
2342 if (auto *BI = dyn_cast<BinaryOperator>(&I))
2343 return getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);
2344 if (auto *IC = dyn_cast<ICmpInst>(&I))
2345 return getSalvageOpsForIcmpOp(IC, CurrentLocOps, Ops, AdditionalValues);
2346
2347 // *Not* to do: we should not attempt to salvage load instructions,
2348 // because the validity and lifetime of a dbg.value containing
2349 // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
2350 return nullptr;
2351}
2352
2353/// A replacement for a dbg.value expression.
2354using DbgValReplacement = std::optional<DIExpression *>;
2355
2356/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
2357/// possibly moving/undefing users to prevent use-before-def. Returns true if
2358/// changes are made.
2360 Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
2361 function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {
2362 // Find debug users of From.
2364 findDbgUsers(&From, DPUsers);
2365 if (DPUsers.empty())
2366 return false;
2367
2368 // Prevent use-before-def of To.
2369 bool Changed = false;
2370
2371 SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;
2372 if (isa<Instruction>(&To)) {
2373 bool DomPointAfterFrom = From.getNextNode() == &DomPoint;
2374
2375 // DbgVariableRecord implementation of the above.
2376 for (auto *DVR : DPUsers) {
2377 Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;
2378 Instruction *NextNonDebug = MarkedInstr;
2379
2380 // It's common to see a debug user between From and DomPoint. Move it
2381 // after DomPoint to preserve the variable update without any reordering.
2382 if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2383 LLVM_DEBUG(dbgs() << "MOVE: " << *DVR << '\n');
2384 DVR->removeFromParent();
2385 DomPoint.getParent()->insertDbgRecordAfter(DVR, &DomPoint);
2386 Changed = true;
2387
2388 // Users which otherwise aren't dominated by the replacement value must
2389 // be salvaged or deleted.
2390 } else if (!DT.dominates(&DomPoint, MarkedInstr)) {
2391 UndefOrSalvageDVR.insert(DVR);
2392 }
2393 }
2394 }
2395
2396 // Update debug users without use-before-def risk.
2397 for (auto *DVR : DPUsers) {
2398 if (UndefOrSalvageDVR.count(DVR))
2399 continue;
2400
2401 DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);
2402 if (!DVRepl)
2403 continue;
2404
2405 DVR->replaceVariableLocationOp(&From, &To);
2406 DVR->setExpression(*DVRepl);
2407 LLVM_DEBUG(dbgs() << "REWRITE: " << DVR << '\n');
2408 Changed = true;
2409 }
2410
2411 if (!UndefOrSalvageDVR.empty()) {
2412 // Try to salvage the remaining debug users.
2413 salvageDebugInfo(From);
2414 Changed = true;
2415 }
2416
2417 return Changed;
2418}
2419
2420/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
2421/// losslessly preserve the bits and semantics of the value. This predicate is
2422/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
2423///
2424/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
2425/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
2426/// and also does not allow lossless pointer <-> integer conversions.
2428 Type *ToTy) {
2429 // Trivially compatible types.
2430 if (FromTy == ToTy)
2431 return true;
2432
2433 // Handle compatible pointer <-> integer conversions.
2434 if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
2435 bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
2436 bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
2437 !DL.isNonIntegralPointerType(ToTy);
2438 return SameSize && LosslessConversion;
2439 }
2440
2441 // TODO: This is not exhaustive.
2442 return false;
2443}
2444
2446 Instruction &DomPoint, DominatorTree &DT) {
2447 // Exit early if From has no debug users.
2448 if (!From.isUsedByMetadata())
2449 return false;
2450
2451 assert(&From != &To && "Can't replace something with itself");
2452
2453 Type *FromTy = From.getType();
2454 Type *ToTy = To.getType();
2455
2456 auto IdentityDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2457 return DVR.getExpression();
2458 };
2459
2460 // Handle no-op conversions.
2461 Module &M = *From.getModule();
2462 const DataLayout &DL = M.getDataLayout();
2463 if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
2464 return rewriteDebugUsers(From, To, DomPoint, DT, IdentityDVR);
2465
2466 // Handle integer-to-integer widening and narrowing.
2467 // FIXME: Use DW_OP_convert when it's available everywhere.
2468 if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
2469 uint64_t FromBits = FromTy->getIntegerBitWidth();
2470 uint64_t ToBits = ToTy->getIntegerBitWidth();
2471 assert(FromBits != ToBits && "Unexpected no-op conversion");
2472
2473 // When the width of the result grows, assume that a debugger will only
2474 // access the low `FromBits` bits when inspecting the source variable.
2475 if (FromBits < ToBits)
2476 return rewriteDebugUsers(From, To, DomPoint, DT, IdentityDVR);
2477
2478 // The width of the result has shrunk. Use sign/zero extension to describe
2479 // the source variable's high bits.
2480 auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2481 DILocalVariable *Var = DVR.getVariable();
2482
2483 // Without knowing signedness, sign/zero extension isn't possible.
2484 auto Signedness = Var->getSignedness();
2485 if (!Signedness)
2486 return std::nullopt;
2487
2488 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2489 return DIExpression::appendExt(DVR.getExpression(), ToBits, FromBits,
2490 Signed);
2491 };
2492 return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExtDVR);
2493 }
2494
2495 // TODO: Floating-point conversions, vectors.
2496 return false;
2497}
2498
2500 Instruction *I, SmallVectorImpl<Value *> &PoisonedValues) {
2501 bool Changed = false;
2502 // RemoveDIs: erase debug-info on this instruction manually.
2503 I->dropDbgRecords();
2504 for (Use &U : I->operands()) {
2505 Value *Op = U.get();
2506 if (isa<Instruction>(Op) && !Op->getType()->isTokenTy()) {
2507 U.set(PoisonValue::get(Op->getType()));
2508 PoisonedValues.push_back(Op);
2509 Changed = true;
2510 }
2511 }
2512
2513 return Changed;
2514}
2515
2517 unsigned NumDeadInst = 0;
2518 // Delete the instructions backwards, as it has a reduced likelihood of
2519 // having to update as many def-use and use-def chains.
2520 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2523
2524 while (EndInst != &BB->front()) {
2525 // Delete the next to last instruction.
2526 Instruction *Inst = &*--EndInst->getIterator();
2527 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2529 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2530 // EHPads can't have DbgVariableRecords attached to them, but it might be
2531 // possible for things with token type.
2532 Inst->dropDbgRecords();
2533 EndInst = Inst;
2534 continue;
2535 }
2536 ++NumDeadInst;
2537 // RemoveDIs: erasing debug-info must be done manually.
2538 Inst->dropDbgRecords();
2539 Inst->eraseFromParent();
2540 }
2541 return NumDeadInst;
2542}
2543
2544unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
2545 DomTreeUpdater *DTU,
2546 MemorySSAUpdater *MSSAU) {
2547 BasicBlock *BB = I->getParent();
2548
2549 if (MSSAU)
2550 MSSAU->changeToUnreachable(I);
2551
2552 SmallPtrSet<BasicBlock *, 8> UniqueSuccessors;
2553
2554 // Loop over all of the successors, removing BB's entry from any PHI
2555 // nodes.
2556 for (BasicBlock *Successor : successors(BB)) {
2557 Successor->removePredecessor(BB, PreserveLCSSA);
2558 if (DTU)
2559 UniqueSuccessors.insert(Successor);
2560 }
2561 auto *UI = new UnreachableInst(I->getContext(), I->getIterator());
2562 UI->setDebugLoc(I->getDebugLoc());
2563
2564 // All instructions after this are dead.
2565 unsigned NumInstrsRemoved = 0;
2566 BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
2567 while (BBI != BBE) {
2568 if (!BBI->use_empty())
2569 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
2570 BBI++->eraseFromParent();
2571 ++NumInstrsRemoved;
2572 }
2573 if (DTU) {
2575 Updates.reserve(UniqueSuccessors.size());
2576 for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2577 Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2578 DTU->applyUpdates(Updates);
2579 }
2581 return NumInstrsRemoved;
2582}
2583
2585 SmallVector<Value *, 8> Args(II->args());
2587 II->getOperandBundlesAsDefs(OpBundles);
2588 CallInst *NewCall = CallInst::Create(II->getFunctionType(),
2589 II->getCalledOperand(), Args, OpBundles);
2590 NewCall->setCallingConv(II->getCallingConv());
2591 NewCall->setAttributes(II->getAttributes());
2592 NewCall->copyMetadata(*II);
2593
2594 // If the invoke had profile metadata, try converting them for CallInst.
2595 uint64_t TotalWeight;
2596 if (NewCall->extractProfTotalWeight(TotalWeight)) {
2597 // Set the total weight if it fits into i32, otherwise reset.
2598 MDBuilder MDB(NewCall->getContext());
2599 auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2600 ? nullptr
2601 : MDB.createBranchWeights({uint32_t(TotalWeight)});
2602 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2603 }
2604
2605 return NewCall;
2606}
2607
2608// changeToCall - Convert the specified invoke into a normal call.
2611 NewCall->takeName(II);
2612 NewCall->insertBefore(II->getIterator());
2613 II->replaceAllUsesWith(NewCall);
2614
2615 // Follow the call by a branch to the normal destination.
2616 BasicBlock *NormalDestBB = II->getNormalDest();
2617 auto *BI = UncondBrInst::Create(NormalDestBB, II->getIterator());
2618 // Although it takes place after the call itself, the new branch is still
2619 // performing part of the control-flow functionality of the invoke, so we use
2620 // II's DebugLoc.
2621 BI->setDebugLoc(II->getDebugLoc());
2622
2623 // Update PHI nodes in the unwind destination
2624 BasicBlock *BB = II->getParent();
2625 BasicBlock *UnwindDestBB = II->getUnwindDest();
2626 UnwindDestBB->removePredecessor(BB);
2627 II->eraseFromParent();
2628 if (DTU)
2629 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2630 return NewCall;
2631}
2632
2634 BasicBlock *UnwindEdge,
2635 DomTreeUpdater *DTU) {
2636 BasicBlock *BB = CI->getParent();
2637
2638 // Convert this function call into an invoke instruction. First, split the
2639 // basic block.
2640 BasicBlock *Split = SplitBlock(BB, CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,
2641 CI->getName() + ".noexc");
2642
2643 // Delete the unconditional branch inserted by SplitBlock
2644 BB->back().eraseFromParent();
2645
2646 // Create the new invoke instruction.
2647 SmallVector<Value *, 8> InvokeArgs(CI->args());
2649
2650 CI->getOperandBundlesAsDefs(OpBundles);
2651
2652 // Note: we're round tripping operand bundles through memory here, and that
2653 // can potentially be avoided with a cleverer API design that we do not have
2654 // as of this time.
2655
2656 InvokeInst *II =
2658 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2659 II->setDebugLoc(CI->getDebugLoc());
2660 II->setCallingConv(CI->getCallingConv());
2661 II->setAttributes(CI->getAttributes());
2662 II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));
2663
2664 if (DTU)
2665 DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
2666
2667 // Make sure that anything using the call now uses the invoke! This also
2668 // updates the CallGraph if present, because it uses a WeakTrackingVH.
2670
2671 // Delete the original call
2672 Split->front().eraseFromParent();
2673 return Split;
2674}
2675
2677 DomTreeUpdater *DTU, bool FoldInstsToUnreachable) {
2679 BasicBlock *BB = &F.front();
2680 Worklist.push_back(BB);
2681 Reachable[BB->getNumber()] = true;
2682 bool Changed = false;
2683 do {
2684 BB = Worklist.pop_back_val();
2685
2686 // Do a scan of the basic block, turning any obviously unreachable
2687 // instructions into LLVM unreachable insts. The instruction combining pass
2688 // canonicalizes unreachable insts into stores to null or undef.
2689 // Note that it traverses the whole instruction list, so it may incur
2690 // significant performance overhead.
2691 if (FoldInstsToUnreachable) {
2692 for (Instruction &I : *BB) {
2693 if (auto *CI = dyn_cast<CallInst>(&I)) {
2694 Value *Callee = CI->getCalledOperand();
2695 // Handle intrinsic calls.
2696 if (Function *F = dyn_cast<Function>(Callee)) {
2697 auto IntrinsicID = F->getIntrinsicID();
2698 // Assumptions that are known to be false are equivalent to
2699 // unreachable. Also, if the condition is undefined, then we make
2700 // the choice most beneficial to the optimizer, and choose that to
2701 // also be unreachable.
2702 if (IntrinsicID == Intrinsic::assume) {
2703 if (match(CI->getArgOperand(0),
2704 m_CombineOr(m_Zero(), m_Undef()))) {
2705 // Don't insert a call to llvm.trap right before the
2706 // unreachable.
2707 changeToUnreachable(CI, false, DTU);
2708 Changed = true;
2709 break;
2710 }
2711 } else if (IntrinsicID == Intrinsic::experimental_guard) {
2712 // A call to the guard intrinsic bails out of the current
2713 // compilation unit if the predicate passed to it is false. If the
2714 // predicate is a constant false, then we know the guard will bail
2715 // out of the current compile unconditionally, so all code
2716 // following it is dead.
2717 //
2718 // Note: unlike in llvm.assume, it is not "obviously profitable"
2719 // for guards to treat `undef` as `false` since a guard on `undef`
2720 // can still be useful for widening.
2721 if (match(CI->getArgOperand(0), m_Zero()))
2722 if (!isa<UnreachableInst>(CI->getNextNode())) {
2723 changeToUnreachable(CI->getNextNode(), false, DTU);
2724 Changed = true;
2725 break;
2726 }
2727 }
2728 } else if ((isa<ConstantPointerNull>(Callee) &&
2729 !NullPointerIsDefined(CI->getFunction(),
2730 cast<PointerType>(Callee->getType())
2731 ->getAddressSpace())) ||
2732 isa<UndefValue>(Callee)) {
2733 changeToUnreachable(CI, false, DTU);
2734 Changed = true;
2735 break;
2736 }
2737 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2738 // If we found a call to a no-return function, insert an unreachable
2739 // instruction after it. Make sure there isn't *already* one there
2740 // though.
2741 if (!isa<UnreachableInst>(CI->getNextNode())) {
2742 // Don't insert a call to llvm.trap right before the unreachable.
2743 changeToUnreachable(CI->getNextNode(), false, DTU);
2744 Changed = true;
2745 }
2746 break;
2747 }
2748 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2749 // Store to undef and store to null are undefined and used to signal
2750 // that they should be changed to unreachable by passes that can't
2751 // modify the CFG.
2752
2753 // Don't touch volatile stores.
2754 if (SI->isVolatile())
2755 continue;
2756
2757 Value *Ptr = SI->getOperand(1);
2758
2759 if (isa<UndefValue>(Ptr) ||
2761 !NullPointerIsDefined(SI->getFunction(),
2762 SI->getPointerAddressSpace()))) {
2763 changeToUnreachable(SI, false, DTU);
2764 Changed = true;
2765 break;
2766 }
2767 }
2768 }
2769
2770 Instruction *Terminator = BB->getTerminator();
2771 if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2772 // Turn invokes that call 'nounwind' functions into ordinary calls.
2773 Value *Callee = II->getCalledOperand();
2774 if ((isa<ConstantPointerNull>(Callee) &&
2775 !NullPointerIsDefined(BB->getParent())) ||
2776 isa<UndefValue>(Callee)) {
2777 changeToUnreachable(II, false, DTU);
2778 Changed = true;
2779 } else {
2780 if (II->doesNotReturn() &&
2781 !isa<UnreachableInst>(II->getNormalDest()->front())) {
2782 // If we found an invoke of a no-return function,
2783 // create a new empty basic block with an `unreachable` terminator,
2784 // and set it as the normal destination for the invoke,
2785 // unless that is already the case.
2786 // Note that the original normal destination could have other uses.
2787 BasicBlock *OrigNormalDest = II->getNormalDest();
2788 OrigNormalDest->removePredecessor(II->getParent());
2789 LLVMContext &Ctx = II->getContext();
2790 BasicBlock *UnreachableNormalDest = BasicBlock::Create(
2791 Ctx, OrigNormalDest->getName() + ".unreachable",
2792 II->getFunction(), OrigNormalDest);
2793 Reachable.resize(II->getFunction()->getMaxBlockNumber());
2794 auto *UI = new UnreachableInst(Ctx, UnreachableNormalDest);
2795 UI->setDebugLoc(DebugLoc::getTemporary());
2796 II->setNormalDest(UnreachableNormalDest);
2797 if (DTU)
2798 DTU->applyUpdates(
2799 {{DominatorTree::Delete, BB, OrigNormalDest},
2800 {DominatorTree::Insert, BB, UnreachableNormalDest}});
2801 Changed = true;
2802 }
2803 if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2804 if (II->use_empty() && !II->mayHaveSideEffects()) {
2805 // jump to the normal destination branch.
2806 BasicBlock *NormalDestBB = II->getNormalDest();
2807 BasicBlock *UnwindDestBB = II->getUnwindDest();
2808 UncondBrInst::Create(NormalDestBB, II->getIterator());
2809 UnwindDestBB->removePredecessor(II->getParent());
2810 II->eraseFromParent();
2811 if (DTU)
2812 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2813 } else
2814 changeToCall(II, DTU);
2815 Changed = true;
2816 }
2817 }
2818 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2819 // Remove catchpads which cannot be reached.
2820 struct CatchPadDenseMapInfo {
2821 static unsigned getHashValue(CatchPadInst *CatchPad) {
2822 return static_cast<unsigned>(hash_combine_range(
2823 CatchPad->value_op_begin(), CatchPad->value_op_end()));
2824 }
2825
2826 static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2827 return LHS->isIdenticalTo(RHS);
2828 }
2829 };
2830
2831 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
2832 // Set of unique CatchPads.
2834 CatchPadDenseMapInfo,
2836 HandlerSet;
2838 for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2839 E = CatchSwitch->handler_end();
2840 I != E; ++I) {
2841 BasicBlock *HandlerBB = *I;
2842 if (DTU)
2843 ++NumPerSuccessorCases[HandlerBB];
2844 auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHIIt());
2845 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2846 if (DTU)
2847 --NumPerSuccessorCases[HandlerBB];
2848 CatchSwitch->removeHandler(I);
2849 --I;
2850 --E;
2851 Changed = true;
2852 }
2853 }
2854 if (DTU) {
2855 std::vector<DominatorTree::UpdateType> Updates;
2856 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
2857 if (I.second == 0)
2858 Updates.push_back({DominatorTree::Delete, BB, I.first});
2859 DTU->applyUpdates(Updates);
2860 }
2861 }
2862
2863 Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2864 }
2865 for (BasicBlock *Successor : successors(BB)) {
2866 if (!Reachable[Successor->getNumber()]) {
2867 Worklist.push_back(Successor);
2868 Reachable[Successor->getNumber()] = true;
2869 }
2870 }
2871 } while (!Worklist.empty());
2872 return Changed;
2873}
2874
2876 Instruction *TI = BB->getTerminator();
2877
2878 if (auto *II = dyn_cast<InvokeInst>(TI))
2879 return changeToCall(II, DTU);
2880
2881 Instruction *NewTI;
2882 BasicBlock *UnwindDest;
2883
2884 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2885 NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI->getIterator());
2886 UnwindDest = CRI->getUnwindDest();
2887 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2888 auto *NewCatchSwitch = CatchSwitchInst::Create(
2889 CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2890 CatchSwitch->getName(), CatchSwitch->getIterator());
2891 for (BasicBlock *PadBB : CatchSwitch->handlers())
2892 NewCatchSwitch->addHandler(PadBB);
2893
2894 NewTI = NewCatchSwitch;
2895 UnwindDest = CatchSwitch->getUnwindDest();
2896 } else {
2897 llvm_unreachable("Could not find unwind successor");
2898 }
2899
2900 NewTI->takeName(TI);
2901 NewTI->setDebugLoc(TI->getDebugLoc());
2902 UnwindDest->removePredecessor(BB);
2903 TI->replaceAllUsesWith(NewTI);
2904 TI->eraseFromParent();
2905 if (DTU)
2906 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
2907 return NewTI;
2908}
2909
2910/// removeUnreachableBlocks - Remove blocks that are not reachable, even
2911/// if they are in a dead cycle. Return true if a change was made, false
2912/// otherwise.
2914 MemorySSAUpdater *MSSAU,
2915 bool FoldInstsToUnreachable) {
2916 SmallVector<bool, 16> Reachable(F.getMaxBlockNumber());
2917 bool Changed = markAliveBlocks(F, Reachable, DTU, FoldInstsToUnreachable);
2918
2919 // Are there any blocks left to actually delete?
2920 SmallSetVector<BasicBlock *, 8> BlocksToRemove;
2921 for (BasicBlock &BB : F) {
2922 // Skip reachable basic blocks
2923 if (Reachable[BB.getNumber()])
2924 continue;
2925 // Skip already-deleted blocks
2926 if (DTU && DTU->isBBPendingDeletion(&BB))
2927 continue;
2928 BlocksToRemove.insert(&BB);
2929 }
2930
2931 if (BlocksToRemove.empty())
2932 return Changed;
2933
2934 Changed = true;
2935 NumRemoved += BlocksToRemove.size();
2936
2937 if (MSSAU)
2938 MSSAU->removeBlocks(BlocksToRemove);
2939
2940 DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
2941
2942 return Changed;
2943}
2944
2945/// If AAOnly is set, only intersect alias analysis metadata and preserve other
2946/// known metadata. Unknown metadata is always dropped.
2947static void combineMetadata(Instruction *K, const Instruction *J,
2948 bool DoesKMove, bool AAOnly = false) {
2950 K->getAllMetadataOtherThanDebugLoc(Metadata);
2951 for (const auto &MD : Metadata) {
2952 unsigned Kind = MD.first;
2953 MDNode *JMD = J->getMetadata(Kind);
2954 MDNode *KMD = MD.second;
2955
2956 // TODO: Assert that this switch is exhaustive for fixed MD kinds.
2957 switch (Kind) {
2958 default:
2959 K->setMetadata(Kind, nullptr); // Remove unknown metadata
2960 break;
2961 case LLVMContext::MD_dbg:
2962 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2963 case LLVMContext::MD_DIAssignID:
2964 if (!AAOnly)
2965 K->mergeDIAssignID(J);
2966 break;
2967 case LLVMContext::MD_tbaa:
2968 if (DoesKMove)
2969 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2970 break;
2971 case LLVMContext::MD_alias_scope:
2972 if (DoesKMove)
2973 K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2974 break;
2975 case LLVMContext::MD_noalias:
2976 case LLVMContext::MD_mem_parallel_loop_access:
2977 if (DoesKMove)
2978 K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2979 break;
2980 case LLVMContext::MD_access_group:
2981 if (DoesKMove)
2982 K->setMetadata(LLVMContext::MD_access_group,
2983 intersectAccessGroups(K, J));
2984 break;
2985 case LLVMContext::MD_range:
2986 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
2987 K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2988 break;
2989 case LLVMContext::MD_nofpclass:
2990 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
2991 K->setMetadata(Kind, MDNode::getMostGenericNoFPClass(JMD, KMD));
2992 break;
2993 case LLVMContext::MD_fpmath:
2994 if (!AAOnly)
2995 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2996 break;
2997 case LLVMContext::MD_invariant_load:
2998 case LLVMContext::MD_invariant_group:
2999 // If K moves, only keep the invariant metadata if it is present on
3000 // both instructions; otherwise the invariant would be asserted on a
3001 // path (J's) that never promised it. If K does not move, K stays on
3002 // its original path, so its existing metadata remains valid.
3003 if (DoesKMove)
3004 K->setMetadata(Kind, JMD);
3005 break;
3006 case LLVMContext::MD_nonnull:
3007 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
3008 K->setMetadata(Kind, JMD);
3009 break;
3010 // Keep empty cases for prof, mmra, memprof, and callsite to prevent them
3011 // from being removed as unknown metadata. The actual merging is handled
3012 // separately below.
3013 case LLVMContext::MD_prof:
3014 case LLVMContext::MD_mmra:
3015 case LLVMContext::MD_memprof:
3016 case LLVMContext::MD_callsite:
3017 break;
3018 case LLVMContext::MD_callee_type:
3019 if (!AAOnly) {
3020 K->setMetadata(LLVMContext::MD_callee_type,
3022 }
3023 break;
3024 case LLVMContext::MD_align:
3025 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
3026 K->setMetadata(
3028 break;
3029 case LLVMContext::MD_dereferenceable:
3030 case LLVMContext::MD_dereferenceable_or_null:
3031 if (!AAOnly && DoesKMove)
3032 K->setMetadata(Kind,
3034 break;
3035 case LLVMContext::MD_preserve_access_index:
3036 // Preserve !preserve.access.index in K.
3037 break;
3038 case LLVMContext::MD_noundef:
3039 // If K does move, keep noundef if it is present in both instructions.
3040 if (!AAOnly && DoesKMove)
3041 K->setMetadata(Kind, JMD);
3042 break;
3043 case LLVMContext::MD_nontemporal:
3044 // Preserve !nontemporal if it is present on both instructions.
3045 if (!AAOnly)
3046 K->setMetadata(Kind, JMD);
3047 break;
3048 case LLVMContext::MD_mem_cache_hint:
3049 // Preserve !mem.cache_hint only if it is present and equivalent on both
3050 // instructions.
3051 if (!AAOnly && KMD != JMD)
3052 K->setMetadata(Kind, nullptr);
3053 break;
3054 case LLVMContext::MD_noalias_addrspace:
3055 if (DoesKMove)
3056 K->setMetadata(Kind,
3058 break;
3059 case LLVMContext::MD_nosanitize:
3060 // Preserve !nosanitize if both K and J have it.
3061 K->setMetadata(Kind, JMD);
3062 break;
3063 case LLVMContext::MD_captures:
3064 K->setMetadata(
3066 K->getContext(), MDNode::toCaptureComponents(JMD) |
3068 break;
3069 case LLVMContext::MD_alloc_token:
3070 if (!AAOnly && KMD != JMD)
3071 K->setMetadata(Kind, MDNode::getMergedAllocTokenMetadata(KMD, JMD));
3072 break;
3073 }
3074 }
3075
3076 // Merge MMRAs.
3077 // This is handled separately because we also want to handle cases where K
3078 // doesn't have tags but J does.
3079 auto JMMRA = J->getMetadata(LLVMContext::MD_mmra);
3080 auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);
3081 if (JMMRA || KMMRA) {
3082 K->setMetadata(LLVMContext::MD_mmra,
3083 MMRAMetadata::combine(K->getContext(), JMMRA, KMMRA));
3084 }
3085
3086 // Merge memprof metadata.
3087 // Handle separately to support cases where only one instruction has the
3088 // metadata.
3089 auto *JMemProf = J->getMetadata(LLVMContext::MD_memprof);
3090 auto *KMemProf = K->getMetadata(LLVMContext::MD_memprof);
3091 if (!AAOnly && (JMemProf || KMemProf)) {
3092 K->setMetadata(LLVMContext::MD_memprof,
3093 MDNode::getMergedMemProfMetadata(KMemProf, JMemProf));
3094 }
3095
3096 // Merge callsite metadata.
3097 // Handle separately to support cases where only one instruction has the
3098 // metadata.
3099 auto *JCallSite = J->getMetadata(LLVMContext::MD_callsite);
3100 auto *KCallSite = K->getMetadata(LLVMContext::MD_callsite);
3101 if (!AAOnly && (JCallSite || KCallSite)) {
3102 K->setMetadata(LLVMContext::MD_callsite,
3103 MDNode::getMergedCallsiteMetadata(KCallSite, JCallSite));
3104 }
3105
3106 // Merge prof metadata.
3107 // Handle separately to support cases where only one instruction has the
3108 // metadata.
3109 auto *JProf = J->getMetadata(LLVMContext::MD_prof);
3110 auto *KProf = K->getMetadata(LLVMContext::MD_prof);
3111 if (!AAOnly && (JProf || KProf)) {
3112 K->setMetadata(LLVMContext::MD_prof,
3113 MDNode::getMergedProfMetadata(KProf, JProf, K, J));
3114 }
3115}
3116
3118 bool DoesKMove) {
3119 combineMetadata(K, J, DoesKMove);
3120}
3121
3123 combineMetadata(K, J, /*DoesKMove=*/true, /*AAOnly=*/true);
3124}
3125
3126void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
3128 Source.getAllMetadata(MD);
3129 MDBuilder MDB(Dest.getContext());
3130 Type *NewType = Dest.getType();
3131 const DataLayout &DL = Source.getDataLayout();
3132 for (const auto &MDPair : MD) {
3133 unsigned ID = MDPair.first;
3134 MDNode *N = MDPair.second;
3135 // Note, essentially every kind of metadata should be preserved here! This
3136 // routine is supposed to clone a load instruction changing *only its type*.
3137 // The only metadata it makes sense to drop is metadata which is invalidated
3138 // when the pointer type changes. This should essentially never be the case
3139 // in LLVM, but we explicitly switch over only known metadata to be
3140 // conservatively correct. If you are adding metadata to LLVM which pertains
3141 // to loads, you almost certainly want to add it here.
3142 switch (ID) {
3143 case LLVMContext::MD_dbg:
3144 case LLVMContext::MD_tbaa:
3145 case LLVMContext::MD_prof:
3146 case LLVMContext::MD_fpmath:
3147 case LLVMContext::MD_tbaa_struct:
3148 case LLVMContext::MD_invariant_load:
3149 case LLVMContext::MD_alias_scope:
3150 case LLVMContext::MD_noalias:
3151 case LLVMContext::MD_nontemporal:
3152 case LLVMContext::MD_mem_cache_hint:
3153 case LLVMContext::MD_mem_parallel_loop_access:
3154 case LLVMContext::MD_access_group:
3155 case LLVMContext::MD_noundef:
3156 case LLVMContext::MD_noalias_addrspace:
3157 case LLVMContext::MD_invariant_group:
3158 // All of these directly apply.
3159 Dest.setMetadata(ID, N);
3160 break;
3161
3162 case LLVMContext::MD_nonnull:
3163 copyNonnullMetadata(Source, N, Dest);
3164 break;
3165
3166 case LLVMContext::MD_align:
3167 case LLVMContext::MD_dereferenceable:
3168 case LLVMContext::MD_dereferenceable_or_null:
3169 // These only directly apply if the new type is also a pointer.
3170 if (NewType->isPointerTy())
3171 Dest.setMetadata(ID, N);
3172 break;
3173
3174 case LLVMContext::MD_range:
3175 copyRangeMetadata(DL, Source, N, Dest);
3176 break;
3177
3178 case LLVMContext::MD_nofpclass:
3179 // This only applies if the floating-point type interpretation. This
3180 // should handle degenerate cases like casting between a scalar and single
3181 // element vector.
3182 if (NewType->getScalarType() == Source.getType()->getScalarType())
3183 Dest.setMetadata(ID, N);
3184 break;
3185 }
3186 }
3187}
3188
3190 auto *ReplInst = dyn_cast<Instruction>(Repl);
3191 if (!ReplInst)
3192 return;
3193
3194 // Patch the replacement so that it is not more restrictive than the value
3195 // being replaced.
3196 WithOverflowInst *UnusedWO;
3197 // When replacing the result of a llvm.*.with.overflow intrinsic with a
3198 // overflowing binary operator, nuw/nsw flags may no longer hold.
3199 if (isa<OverflowingBinaryOperator>(ReplInst) &&
3201 ReplInst->dropPoisonGeneratingFlags();
3202 // Note that if 'I' is a load being replaced by some operation,
3203 // for example, by an arithmetic operation, then andIRFlags()
3204 // would just erase all math flags from the original arithmetic
3205 // operation, which is clearly not wanted and not needed.
3206 else if (!isa<LoadInst>(I))
3207 ReplInst->andIRFlags(I);
3208
3209 // Handle attributes.
3210 if (auto *CB1 = dyn_cast<CallBase>(ReplInst)) {
3211 if (auto *CB2 = dyn_cast<CallBase>(I)) {
3212 bool Success = CB1->tryIntersectAttributes(CB2);
3213 assert(Success && "We should not be trying to sink callbases "
3214 "with non-intersectable attributes");
3215 // For NDEBUG Compile.
3216 (void)Success;
3217 }
3218 }
3219
3220 // FIXME: If both the original and replacement value are part of the
3221 // same control-flow region (meaning that the execution of one
3222 // guarantees the execution of the other), then we can combine the
3223 // noalias scopes here and do better than the general conservative
3224 // answer used in combineMetadata().
3225
3226 // In general, GVN unifies expressions over different control-flow
3227 // regions, and so we need a conservative combination of the noalias
3228 // scopes.
3229 combineMetadataForCSE(ReplInst, I, false);
3230}
3231
3232template <typename ShouldReplaceFn>
3233static unsigned replaceDominatedUsesWith(Value *From, Value *To,
3234 const ShouldReplaceFn &ShouldReplace) {
3235 assert(From->getType() == To->getType());
3236
3237 unsigned Count = 0;
3238 for (Use &U : llvm::make_early_inc_range(From->uses())) {
3239 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
3240 if (II && II->getIntrinsicID() == Intrinsic::fake_use)
3241 continue;
3242 if (!ShouldReplace(U))
3243 continue;
3244 LLVM_DEBUG(dbgs() << "Replace dominated use of '";
3245 From->printAsOperand(dbgs());
3246 dbgs() << "' with " << *To << " in " << *U.getUser() << "\n");
3247 U.set(To);
3248 ++Count;
3249 }
3250 return Count;
3251}
3252
3254 assert(From->getType() == To->getType());
3255 auto *BB = From->getParent();
3256 unsigned Count = 0;
3257
3258 for (Use &U : llvm::make_early_inc_range(From->uses())) {
3259 auto *I = cast<Instruction>(U.getUser());
3260 if (I->getParent() == BB)
3261 continue;
3262 U.set(To);
3263 ++Count;
3264 }
3265 return Count;
3266}
3267
3269 DominatorTree &DT,
3270 const BasicBlockEdge &Root) {
3271 auto Dominates = [&](const Use &U) { return DT.dominates(Root, U); };
3272 return ::replaceDominatedUsesWith(From, To, Dominates);
3273}
3274
3276 DominatorTree &DT,
3277 const BasicBlock *BB) {
3278 auto Dominates = [&](const Use &U) { return DT.dominates(BB, U); };
3279 return ::replaceDominatedUsesWith(From, To, Dominates);
3280}
3281
3283 DominatorTree &DT,
3284 const Instruction *I) {
3285 auto Dominates = [&](const Use &U) { return DT.dominates(I, U); };
3286 return ::replaceDominatedUsesWith(From, To, Dominates);
3287}
3288
3290 Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Root,
3291 function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3292 auto DominatesAndShouldReplace = [&](const Use &U) {
3293 return DT.dominates(Root, U) && ShouldReplace(U, To);
3294 };
3295 return ::replaceDominatedUsesWith(From, To, DominatesAndShouldReplace);
3296}
3297
3299 Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
3300 function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3301 auto DominatesAndShouldReplace = [&](const Use &U) {
3302 return DT.dominates(BB, U) && ShouldReplace(U, To);
3303 };
3304 return ::replaceDominatedUsesWith(From, To, DominatesAndShouldReplace);
3305}
3306
3308 Value *From, Value *To, DominatorTree &DT, const Instruction *I,
3309 function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3310 auto DominatesAndShouldReplace = [&](const Use &U) {
3311 return DT.dominates(I, U) && ShouldReplace(U, To);
3312 };
3313 return ::replaceDominatedUsesWith(From, To, DominatesAndShouldReplace);
3314}
3315
3317 const TargetLibraryInfo &TLI) {
3318 // Check if the function is specifically marked as a gc leaf function.
3319 if (Call->hasFnAttr("gc-leaf-function"))
3320 return true;
3321 if (const Function *F = Call->getCalledFunction()) {
3322 if (F->hasFnAttribute("gc-leaf-function"))
3323 return true;
3324
3325 if (auto IID = F->getIntrinsicID()) {
3326 // Most LLVM intrinsics do not take safepoints.
3327 return IID != Intrinsic::experimental_gc_statepoint &&
3328 IID != Intrinsic::experimental_deoptimize &&
3329 IID != Intrinsic::memcpy_element_unordered_atomic &&
3330 IID != Intrinsic::memmove_element_unordered_atomic;
3331 }
3332 }
3333
3334 // Lib calls can be materialized by some passes, and won't be
3335 // marked as 'gc-leaf-function.' All available Libcalls are
3336 // GC-leaf.
3337 return TLI.has(TLI.getLibFunc(*Call));
3338}
3339
3341 LoadInst &NewLI) {
3342 auto *NewTy = NewLI.getType();
3343
3344 // This only directly applies if the new type is also a pointer.
3345 if (NewTy->isPointerTy()) {
3346 NewLI.setMetadata(LLVMContext::MD_nonnull, N);
3347 return;
3348 }
3349
3350 // The only other translation we can do is to integral loads with !range
3351 // metadata.
3352 if (!NewTy->isIntegerTy())
3353 return;
3354
3355 MDBuilder MDB(NewLI.getContext());
3356 const Value *Ptr = OldLI.getPointerOperand();
3357 auto *ITy = cast<IntegerType>(NewTy);
3358 auto *NullInt = ConstantExpr::getPtrToInt(
3360 auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
3361 NewLI.setMetadata(LLVMContext::MD_range,
3362 MDB.createRange(NonNullInt, NullInt));
3363}
3364
3366 MDNode *N, LoadInst &NewLI) {
3367 auto *NewTy = NewLI.getType();
3368 // Simply copy the metadata if the type did not change.
3369 if (NewTy == OldLI.getType()) {
3370 NewLI.setMetadata(LLVMContext::MD_range, N);
3371 return;
3372 }
3373
3374 // Give up unless it is converted to a pointer where there is a single very
3375 // valuable mapping we can do reliably.
3376 // FIXME: It would be nice to propagate this in more ways, but the type
3377 // conversions make it hard.
3378 if (!NewTy->isPointerTy())
3379 return;
3380
3381 unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
3382 if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&
3383 !getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
3384 MDNode *NN = MDNode::get(OldLI.getContext(), {});
3385 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
3386 }
3387}
3388
3391 findDbgUsers(&I, DPUsers);
3392 for (auto *DVR : DPUsers)
3393 DVR->eraseFromParent();
3394}
3395
3397 BasicBlock *BB) {
3398 // Since we are moving the instructions out of its basic block, we do not
3399 // retain their original debug locations (DILocations) and debug intrinsic
3400 // instructions.
3401 //
3402 // Doing so would degrade the debugging experience.
3403 //
3404 // FIXME: Issue #152767: debug info should also be the same as the
3405 // original branch, **if** the user explicitly indicated that (for sampling
3406 // PGO)
3407 //
3408 // Currently, when hoisting the instructions, we take the following actions:
3409 // - Remove their debug intrinsic instructions.
3410 // - Set their debug locations to the values from the insertion point.
3411 //
3412 // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
3413 // need to be deleted, is because there will not be any instructions with a
3414 // DILocation in either branch left after performing the transformation. We
3415 // can only insert a dbg.value after the two branches are joined again.
3416 //
3417 // See PR38762, PR39243 for more details.
3418 //
3419 // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
3420 // encode predicated DIExpressions that yield different results on different
3421 // code paths.
3422
3423 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
3424 Instruction *I = &*II;
3425 I->dropUBImplyingAttrsAndMetadata();
3426 if (I->isUsedByMetadata())
3427 dropDebugUsers(*I);
3428 // RemoveDIs: drop debug-info too as the following code does.
3429 I->dropDbgRecords();
3430 if (I->isDebugOrPseudoInst()) {
3431 // Remove DbgInfo and pseudo probe Intrinsics.
3432 II = I->eraseFromParent();
3433 continue;
3434 }
3435 I->setDebugLoc(InsertPt->getDebugLoc());
3436 ++II;
3437 }
3438 DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),
3439 BB->getTerminator()->getIterator());
3440}
3441
3443 Type &Ty) {
3444 // Create integer constant expression.
3445 auto createIntegerExpression = [&DIB](const Constant &CV) -> DIExpression * {
3446 const APInt &API = cast<ConstantInt>(&CV)->getValue();
3447 std::optional<int64_t> InitIntOpt;
3448 if (API.getBitWidth() == 1)
3449 InitIntOpt = API.tryZExtValue();
3450 else
3451 InitIntOpt = API.trySExtValue();
3452 return InitIntOpt ? DIB.createConstantValueExpression(
3453 static_cast<uint64_t>(*InitIntOpt))
3454 : nullptr;
3455 };
3456
3457 if (isa<ConstantInt>(C))
3458 return createIntegerExpression(C);
3459
3460 auto *FP = dyn_cast<ConstantFP>(&C);
3461 if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
3462 const APFloat &APF = FP->getValueAPF();
3463 APInt const &API = APF.bitcastToAPInt();
3464 if (uint64_t Temp = API.getZExtValue())
3465 return DIB.createConstantValueExpression(Temp);
3466 return DIB.createConstantValueExpression(*API.getRawData());
3467 }
3468
3469 if (!Ty.isPointerTy())
3470 return nullptr;
3471
3473 return DIB.createConstantValueExpression(0);
3474
3475 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(&C))
3476 if (CE->getOpcode() == Instruction::IntToPtr) {
3477 const Value *V = CE->getOperand(0);
3478 if (auto CI = dyn_cast_or_null<ConstantInt>(V))
3479 return createIntegerExpression(*CI);
3480 }
3481 return nullptr;
3482}
3483
3485 auto RemapDebugOperands = [&Mapping](auto *DV, auto Set) {
3486 for (auto *Op : Set) {
3487 auto I = Mapping.find(Op);
3488 if (I != Mapping.end())
3489 DV->replaceVariableLocationOp(Op, I->second, /*AllowEmpty=*/true);
3490 }
3491 };
3492 auto RemapAssignAddress = [&Mapping](auto *DA) {
3493 auto I = Mapping.find(DA->getAddress());
3494 if (I != Mapping.end())
3495 DA->setAddress(I->second);
3496 };
3497 for (DbgVariableRecord &DVR : filterDbgVars(Inst->getDbgRecordRange())) {
3498 RemapDebugOperands(&DVR, DVR.location_ops());
3499 if (DVR.isDbgAssign())
3500 RemapAssignAddress(&DVR);
3501 }
3502}
3503
3504namespace {
3505
3506/// A potential constituent of a bitreverse or bswap expression. See
3507/// collectBitParts for a fuller explanation.
3508struct BitPart {
3509 BitPart(Value *P, unsigned BW) : Provider(P) {
3510 Provenance.resize(BW);
3511 }
3512
3513 /// The Value that this is a bitreverse/bswap of.
3514 Value *Provider;
3515
3516 /// The "provenance" of each bit. Provenance[A] = B means that bit A
3517 /// in Provider becomes bit B in the result of this expression.
3518 SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
3519
3520 enum { Unset = -1 };
3521};
3522
3523} // end anonymous namespace
3524
3525/// Analyze the specified subexpression and see if it is capable of providing
3526/// pieces of a bswap or bitreverse. The subexpression provides a potential
3527/// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
3528/// the output of the expression came from a corresponding bit in some other
3529/// value. This function is recursive, and the end result is a mapping of
3530/// bitnumber to bitnumber. It is the caller's responsibility to validate that
3531/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
3532///
3533/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
3534/// that the expression deposits the low byte of %X into the high byte of the
3535/// result and that all other bits are zero. This expression is accepted and a
3536/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
3537/// [0-7].
3538///
3539/// For vector types, all analysis is performed at the per-element level. No
3540/// cross-element analysis is supported (shuffle/insertion/reduction), and all
3541/// constant masks must be splatted across all elements.
3542///
3543/// To avoid revisiting values, the BitPart results are memoized into the
3544/// provided map. To avoid unnecessary copying of BitParts, BitParts are
3545/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
3546/// store BitParts objects, not pointers. As we need the concept of a nullptr
3547/// BitParts (Value has been analyzed and the analysis failed), we an Optional
3548/// type instead to provide the same functionality.
3549///
3550/// Because we pass around references into \c BPS, we must use a container that
3551/// does not invalidate internal references (std::map instead of DenseMap).
3552static const std::optional<BitPart> &
3553collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
3554 std::map<Value *, std::optional<BitPart>> &BPS, int Depth,
3555 bool &FoundRoot) {
3556 auto [I, Inserted] = BPS.try_emplace(V);
3557 if (!Inserted)
3558 return I->second;
3559
3560 auto &Result = I->second;
3561 auto BitWidth = V->getType()->getScalarSizeInBits();
3562
3563 // Can't do integer/elements > 128 bits.
3564 if (BitWidth > 128)
3565 return Result;
3566
3567 // Prevent stack overflow by limiting the recursion depth
3569 LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
3570 return Result;
3571 }
3572
3573 if (auto *I = dyn_cast<Instruction>(V)) {
3574 Value *X, *Y;
3575 const APInt *C;
3576
3577 // If this is an or instruction, it may be an inner node of the bswap.
3578 if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
3579 // Check we have both sources and they are from the same provider.
3580 const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3581 Depth + 1, FoundRoot);
3582 if (!A || !A->Provider)
3583 return Result;
3584
3585 const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3586 Depth + 1, FoundRoot);
3587 if (!B || A->Provider != B->Provider)
3588 return Result;
3589
3590 // Try and merge the two together.
3591 Result = BitPart(A->Provider, BitWidth);
3592 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
3593 if (A->Provenance[BitIdx] != BitPart::Unset &&
3594 B->Provenance[BitIdx] != BitPart::Unset &&
3595 A->Provenance[BitIdx] != B->Provenance[BitIdx])
3596 return Result = std::nullopt;
3597
3598 if (A->Provenance[BitIdx] == BitPart::Unset)
3599 Result->Provenance[BitIdx] = B->Provenance[BitIdx];
3600 else
3601 Result->Provenance[BitIdx] = A->Provenance[BitIdx];
3602 }
3603
3604 return Result;
3605 }
3606
3607 // If this is a logical shift by a constant, recurse then shift the result.
3608 if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
3609 const APInt &BitShift = *C;
3610
3611 // Ensure the shift amount is defined.
3612 if (BitShift.uge(BitWidth))
3613 return Result;
3614
3615 // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3616 if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
3617 return Result;
3618
3619 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3620 Depth + 1, FoundRoot);
3621 if (!Res)
3622 return Result;
3623 Result = Res;
3624
3625 // Perform the "shift" on BitProvenance.
3626 auto &P = Result->Provenance;
3627 if (I->getOpcode() == Instruction::Shl) {
3628 P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
3629 P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
3630 } else {
3631 P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
3632 P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
3633 }
3634
3635 return Result;
3636 }
3637
3638 // If this is a logical 'and' with a mask that clears bits, recurse then
3639 // unset the appropriate bits.
3640 if (match(V, m_And(m_Value(X), m_APInt(C)))) {
3641 const APInt &AndMask = *C;
3642
3643 // Check that the mask allows a multiple of 8 bits for a bswap, for an
3644 // early exit.
3645 unsigned NumMaskedBits = AndMask.popcount();
3646 if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3647 return Result;
3648
3649 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3650 Depth + 1, FoundRoot);
3651 if (!Res)
3652 return Result;
3653 Result = Res;
3654
3655 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3656 // If the AndMask is zero for this bit, clear the bit.
3657 if (AndMask[BitIdx] == 0)
3658 Result->Provenance[BitIdx] = BitPart::Unset;
3659 return Result;
3660 }
3661
3662 // If this is a zext instruction zero extend the result.
3663 if (match(V, m_ZExt(m_Value(X)))) {
3664 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3665 Depth + 1, FoundRoot);
3666 if (!Res)
3667 return Result;
3668
3669 Result = BitPart(Res->Provider, BitWidth);
3670 auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
3671 for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3672 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3673 for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
3674 Result->Provenance[BitIdx] = BitPart::Unset;
3675 return Result;
3676 }
3677
3678 // If this is a truncate instruction, extract the lower bits.
3679 if (match(V, m_Trunc(m_Value(X)))) {
3680 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3681 Depth + 1, FoundRoot);
3682 if (!Res)
3683 return Result;
3684
3685 Result = BitPart(Res->Provider, BitWidth);
3686 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3687 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3688 return Result;
3689 }
3690
3691 // BITREVERSE - most likely due to us previous matching a partial
3692 // bitreverse.
3693 if (match(V, m_BitReverse(m_Value(X)))) {
3694 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3695 Depth + 1, FoundRoot);
3696 if (!Res)
3697 return Result;
3698
3699 Result = BitPart(Res->Provider, BitWidth);
3700 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3701 Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3702 return Result;
3703 }
3704
3705 // BSWAP - most likely due to us previous matching a partial bswap.
3706 if (match(V, m_BSwap(m_Value(X)))) {
3707 const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3708 Depth + 1, FoundRoot);
3709 if (!Res)
3710 return Result;
3711
3712 unsigned ByteWidth = BitWidth / 8;
3713 Result = BitPart(Res->Provider, BitWidth);
3714 for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3715 unsigned ByteBitOfs = ByteIdx * 8;
3716 for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3717 Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
3718 Res->Provenance[ByteBitOfs + BitIdx];
3719 }
3720 return Result;
3721 }
3722
3723 // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
3724 // amount (modulo).
3725 // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3726 // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3727 if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
3728 match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
3729 // We can treat fshr as a fshl by flipping the modulo amount.
3730 unsigned ModAmt = C->urem(BitWidth);
3731 if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
3732 ModAmt = BitWidth - ModAmt;
3733
3734 // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3735 if (!MatchBitReversals && (ModAmt % 8) != 0)
3736 return Result;
3737
3738 // Check we have both sources and they are from the same provider.
3739 const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3740 Depth + 1, FoundRoot);
3741 if (!LHS || !LHS->Provider)
3742 return Result;
3743
3744 const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3745 Depth + 1, FoundRoot);
3746 if (!RHS || LHS->Provider != RHS->Provider)
3747 return Result;
3748
3749 unsigned StartBitRHS = BitWidth - ModAmt;
3750 Result = BitPart(LHS->Provider, BitWidth);
3751 for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3752 Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
3753 for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3754 Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
3755 return Result;
3756 }
3757 }
3758
3759 // If we've already found a root input value then we're never going to merge
3760 // these back together.
3761 if (FoundRoot)
3762 return Result;
3763
3764 // Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
3765 // be the root input value to the bswap/bitreverse.
3766 FoundRoot = true;
3767 Result = BitPart(V, BitWidth);
3768 for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3769 Result->Provenance[BitIdx] = BitIdx;
3770 return Result;
3771}
3772
3773static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
3774 unsigned BitWidth) {
3775 if (From % 8 != To % 8)
3776 return false;
3777 // Convert from bit indices to byte indices and check for a byte reversal.
3778 From >>= 3;
3779 To >>= 3;
3780 BitWidth >>= 3;
3781 return From == BitWidth - To - 1;
3782}
3783
3784static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
3785 unsigned BitWidth) {
3786 return From == BitWidth - To - 1;
3787}
3788
3790 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
3791 SmallVectorImpl<Instruction *> &InsertedInsts) {
3792 if (!match(I, m_Or(m_Value(), m_Value())) &&
3793 !match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&
3794 !match(I, m_FShr(m_Value(), m_Value(), m_Value())) &&
3795 !match(I, m_BSwap(m_Value())))
3796 return false;
3797 if (!MatchBSwaps && !MatchBitReversals)
3798 return false;
3799 Type *ITy = I->getType();
3800 if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() == 1 ||
3801 ITy->getScalarSizeInBits() > 128)
3802 return false; // Can't do integer/elements > 128 bits.
3803
3804 // Try to find all the pieces corresponding to the bswap.
3805 bool FoundRoot = false;
3806 std::map<Value *, std::optional<BitPart>> BPS;
3807 const auto &Res =
3808 collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
3809 if (!Res)
3810 return false;
3811 ArrayRef<int8_t> BitProvenance = Res->Provenance;
3812 assert(all_of(BitProvenance,
3813 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
3814 "Illegal bit provenance index");
3815
3816 // If the upper bits are zero, then attempt to perform as a truncated op.
3817 Type *DemandedTy = ITy;
3818 if (BitProvenance.back() == BitPart::Unset) {
3819 while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
3820 BitProvenance = BitProvenance.drop_back();
3821 if (BitProvenance.empty())
3822 return false; // TODO - handle null value?
3823 DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
3824 if (auto *IVecTy = dyn_cast<VectorType>(ITy))
3825 DemandedTy = VectorType::get(DemandedTy, IVecTy);
3826 }
3827
3828 // Check BitProvenance hasn't found a source larger than the result type.
3829 unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
3830 if (DemandedBW > ITy->getScalarSizeInBits())
3831 return false;
3832
3833 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
3834 // only byteswap values with an even number of bytes.
3835 APInt DemandedMask = APInt::getAllOnes(DemandedBW);
3836 bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
3837 bool OKForBitReverse = MatchBitReversals;
3838 for (unsigned BitIdx = 0;
3839 (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
3840 if (BitProvenance[BitIdx] == BitPart::Unset) {
3841 DemandedMask.clearBit(BitIdx);
3842 continue;
3843 }
3844 OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
3845 DemandedBW);
3846 OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
3847 BitIdx, DemandedBW);
3848 }
3849
3850 Intrinsic::ID Intrin;
3851 if (OKForBSwap)
3852 Intrin = Intrinsic::bswap;
3853 else if (OKForBitReverse)
3854 Intrin = Intrinsic::bitreverse;
3855 else
3856 return false;
3857
3858 Function *F =
3859 Intrinsic::getOrInsertDeclaration(I->getModule(), Intrin, DemandedTy);
3860 Value *Provider = Res->Provider;
3861
3862 // We may need to truncate the provider.
3863 if (DemandedTy != Provider->getType()) {
3864 auto *Trunc =
3865 CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I->getIterator());
3866 InsertedInsts.push_back(Trunc);
3867 Provider = Trunc;
3868 }
3869
3870 Instruction *Result = CallInst::Create(F, Provider, "rev", I->getIterator());
3871 InsertedInsts.push_back(Result);
3872
3873 if (!DemandedMask.isAllOnes()) {
3874 auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
3875 Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I->getIterator());
3876 InsertedInsts.push_back(Result);
3877 }
3878
3879 // We may need to zeroextend back to the result type.
3880 if (ITy != Result->getType()) {
3881 auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I->getIterator());
3882 InsertedInsts.push_back(ExtInst);
3883 }
3884
3885 return true;
3886}
3887
3888// CodeGen has special handling for some string functions that may replace
3889// them with target-specific intrinsics. Since that'd skip our interceptors
3890// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
3891// we mark affected calls as NoBuiltin, which will disable optimization
3892// in CodeGen.
3894 CallInst *CI, const TargetLibraryInfo *TLI) {
3895 Function *F = CI->getCalledFunction();
3896 if (F && !F->hasLocalLinkage() && F->hasName() &&
3897 TLI->hasOptimizedCodeGen(TLI->getLibFunc(F->getName())) &&
3898 !F->doesNotAccessMemory())
3899 CI->addFnAttr(Attribute::NoBuiltin);
3900}
3901
3903 const auto *Op = I->getOperand(OpIdx);
3904 // We can't have a PHI with a metadata or token type.
3905 if (Op->getType()->isMetadataTy() || Op->getType()->isTokenLikeTy())
3906 return false;
3907
3908 // swifterror pointers can only be used by a load, store, or as a swifterror
3909 // argument; swifterror pointers are not allowed to be used in select or phi
3910 // instructions.
3911 if (Op->isSwiftError())
3912 return false;
3913
3914 // Cannot replace alloca argument with phi/select.
3915 if (I->isLifetimeStartOrEnd())
3916 return false;
3917
3918 // Early exit.
3920 return true;
3921
3922 switch (I->getOpcode()) {
3923 default:
3924 return true;
3925 case Instruction::Call:
3926 case Instruction::Invoke: {
3927 const auto &CB = cast<CallBase>(*I);
3928
3929 // Can't handle inline asm. Skip it.
3930 if (CB.isInlineAsm())
3931 return false;
3932
3933 // Constant bundle operands may need to retain their constant-ness for
3934 // correctness.
3935 if (CB.isBundleOperand(OpIdx))
3936 return false;
3937
3938 if (OpIdx < CB.arg_size()) {
3939 // Some variadic intrinsics require constants in the variadic arguments,
3940 // which currently aren't markable as immarg.
3941 if (isa<IntrinsicInst>(CB) &&
3942 OpIdx >= CB.getFunctionType()->getNumParams()) {
3943 // This is known to be OK for stackmap.
3944 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
3945 }
3946
3947 // gcroot is a special case, since it requires a constant argument which
3948 // isn't also required to be a simple ConstantInt.
3949 if (CB.getIntrinsicID() == Intrinsic::gcroot)
3950 return false;
3951
3952 // threadlocal_address is a special case as it requires its only
3953 // argument to be a thread local global.
3954 if (CB.getIntrinsicID() == Intrinsic::threadlocal_address)
3955 return false;
3956
3957 // Some intrinsic operands are required to be immediates.
3958 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
3959 }
3960
3961 // It is never allowed to replace the call argument to an intrinsic, but it
3962 // may be possible for a call.
3963 return !isa<IntrinsicInst>(CB);
3964 }
3965 case Instruction::ShuffleVector:
3966 // Shufflevector masks are constant.
3967 return OpIdx != 2;
3968 case Instruction::Switch:
3969 case Instruction::ExtractValue:
3970 // All operands apart from the first are constant.
3971 return OpIdx == 0;
3972 case Instruction::InsertValue:
3973 // All operands apart from the first and the second are constant.
3974 return OpIdx < 2;
3975 case Instruction::Alloca:
3976 // Static allocas (constant size in the entry block) are handled by
3977 // prologue/epilogue insertion so they're free anyway. We definitely don't
3978 // want to make them non-constant.
3979 return !cast<AllocaInst>(I)->isStaticAlloca();
3980 case Instruction::GetElementPtr:
3981 if (OpIdx == 0)
3982 return true;
3984 for (auto E = std::next(It, OpIdx); It != E; ++It)
3985 if (It.isStruct())
3986 return false;
3987 return true;
3988 }
3989}
3990
3992 // First: Check if it's a constant
3993 if (Constant *C = dyn_cast<Constant>(Condition))
3994 return ConstantExpr::getNot(C);
3995
3996 // Second: If the condition is already inverted, return the original value
3997 Value *NotCondition;
3998 if (match(Condition, m_Not(m_Value(NotCondition))))
3999 return NotCondition;
4000
4001 BasicBlock *Parent = nullptr;
4002 Instruction *Inst = dyn_cast<Instruction>(Condition);
4003 if (Inst)
4004 Parent = Inst->getParent();
4005 else if (Argument *Arg = dyn_cast<Argument>(Condition))
4006 Parent = &Arg->getParent()->getEntryBlock();
4007 assert(Parent && "Unsupported condition to invert");
4008
4009 // Third: Check all the users for an invert
4010 for (User *U : Condition->users())
4012 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
4013 return I;
4014
4015 // Last option: Create a new instruction
4016 auto *Inverted =
4017 BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
4018 if (Inst && !isa<PHINode>(Inst))
4019 Inverted->insertAfter(Inst->getIterator());
4020 else
4021 Inverted->insertBefore(Parent->getFirstInsertionPt());
4022 return Inverted;
4023}
4024
4026 // Note: We explicitly check for attributes rather than using cover functions
4027 // because some of the cover functions include the logic being implemented.
4028
4029 bool Changed = false;
4030 // readnone + not convergent implies nosync
4031 if (!F.hasFnAttribute(Attribute::NoSync) &&
4032 F.doesNotAccessMemory() && !F.isConvergent()) {
4033 F.setNoSync();
4034 Changed = true;
4035 }
4036
4037 // readonly implies nofree
4038 if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {
4039 F.setDoesNotFreeMemory();
4040 Changed = true;
4041 }
4042
4043 // willreturn implies mustprogress
4044 if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {
4045 F.setMustProgress();
4046 Changed = true;
4047 }
4048
4049 // TODO: There are a bunch of cases of restrictive memory effects we
4050 // can infer by inspecting arguments of argmemonly-ish functions.
4051
4052 return Changed;
4053}
4054
4056#ifndef NDEBUG
4057 if (Opcode)
4058 assert(Opcode == I.getOpcode() &&
4059 "can only use mergeFlags on instructions with matching opcodes");
4060 else
4061 Opcode = I.getOpcode();
4062#endif
4064 HasNUW &= I.hasNoUnsignedWrap();
4065 HasNSW &= I.hasNoSignedWrap();
4066 }
4067 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
4068 IsDisjoint &= DisjointOp->isDisjoint();
4069}
4070
4072 I.dropPoisonGeneratingFlags();
4073 if (I.getOpcode() == Instruction::Add ||
4074 (I.getOpcode() == Instruction::Mul && AllKnownNonZero)) {
4075 if (HasNUW)
4076 I.setHasNoUnsignedWrap();
4077 if (HasNSW && (AllKnownNonNegative || HasNUW))
4078 I.setHasNoSignedWrap();
4079 }
4080 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
4081 DisjointOp->setIsDisjoint(IsDisjoint);
4082}
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
static unsigned getHashValueImpl(SimpleValue Val)
Definition EarlyCSE.cpp:216
static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS)
Definition EarlyCSE.cpp:337
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
SmallDenseMap< BasicBlock *, Value *, 16 > IncomingValueMap
Definition Local.cpp:907
static bool valueCoversEntireFragment(Type *ValTy, DbgVariableRecord *DVR)
Check if the alloc size of ValTy is large enough to cover the variable (or fragment of the variable) ...
Definition Local.cpp:1613
static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy, Type *ToTy)
Check if a bitcast between a value of type FromTy to type ToTy would losslessly preserve the bits and...
Definition Local.cpp:2427
static void salvageDbgAssignAddress(Instruction &I, DbgVariableRecord &Assign)
Salvage the address of Assign, which the caller has checked is I.
Definition Local.cpp:2026
uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode)
Definition Local.cpp:2175
static bool PhiHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, PHINode *APN)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition Local.cpp:1589
static void combineMetadata(Instruction *K, const Instruction *J, bool DoesKMove, bool AAOnly=false)
If AAOnly is set, only intersect alias analysis metadata and preserve other known metadata.
Definition Local.cpp:2947
static void handleSSAValueOperands(uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues, Instruction *I)
Definition Local.cpp:2205
std::optional< DIExpression * > DbgValReplacement
A replacement for a dbg.value expression.
Definition Local.cpp:2354
static bool rewriteDebugUsers(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT, function_ref< DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr)
Point debug users of From to To using exprs given by RewriteExpr, possibly moving/undefing users to p...
Definition Local.cpp:2359
Value * getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2217
static DIExpression * dropInitialDeref(const DIExpression *DIExpr)
Definition Local.cpp:1649
static bool salvageDbgVariableLocation(Instruction &I, DbgVariableRecord &DVR)
Rewrite DVR's variable location in terms of I's operands.
Definition Local.cpp:2063
static void replaceUndefValuesInPhi(PHINode *PN, const IncomingValueMap &IncomingValues)
Replace the incoming undef values to a phi with the values from a block-to-value map.
Definition Local.cpp:972
Value * getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2149
static bool CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ, const SmallPtrSetImpl< BasicBlock * > &BBPreds, BasicBlock *&CommonPred)
Definition Local.cpp:1015
Value * getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2276
static bool CanMergeValues(Value *First, Value *Second)
Return true if we can choose one of these values to use in place of the other.
Definition Local.cpp:841
static bool simplifyAndDCEInstruction(Instruction *I, SmallSetVector< Instruction *, 16 > &WorkList, const DataLayout &DL, const TargetLibraryInfo *TLI)
Definition Local.cpp:658
static bool areAllUsesEqual(Instruction *I)
areAllUsesEqual - Check whether the uses of a value are all the same.
Definition Local.cpp:604
static cl::opt< bool > PHICSEDebugHash("phicse-debug-hash", cl::init(false), cl::Hidden, cl::desc("Perform extra assertion checking to verify that PHINodes's hash " "function is well-behaved w.r.t. its isEqual predicate"))
static void gatherIncomingValuesToPhi(PHINode *PN, const PredBlockVector &BBPreds, IncomingValueMap &IncomingValues)
Create a map from block to value for the operands of a given phi.
Definition Local.cpp:949
uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred)
Definition Local.cpp:2251
static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, unsigned BitWidth)
Definition Local.cpp:3773
static const std::optional< BitPart > & collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, std::map< Value *, std::optional< BitPart > > &BPS, int Depth, bool &FoundRoot)
Analyze the specified subexpression and see if it is capable of providing pieces of a bswap or bitrev...
Definition Local.cpp:3553
static bool EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB, SmallPtrSetImpl< PHINode * > &ToRemove)
Definition Local.cpp:1385
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ, const SmallPtrSetImpl< BasicBlock * > &BBPreds)
Return true if we can fold BB, an almost-empty BB ending in an unconditional branch to Succ,...
Definition Local.cpp:850
static cl::opt< unsigned > PHICSENumPHISmallSize("phicse-num-phi-smallsize", cl::init(32), cl::Hidden, cl::desc("When the basic block contains not more than this number of PHI nodes, " "perform a (faster!) exhaustive search instead of set-driven one."))
static void updateOneDbgValueForAlloca(const DebugLoc &Loc, DILocalVariable *DIVar, DIExpression *DIExpr, Value *NewAddress, DbgVariableRecord *DVR, DIBuilder &Builder, int Offset)
Definition Local.cpp:1982
static bool EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB, SmallPtrSetImpl< PHINode * > &ToRemove)
Definition Local.cpp:1421
static bool markAliveBlocks(Function &F, SmallVectorImpl< bool > &Reachable, DomTreeUpdater *DTU, bool FoldInstsToUnreachable)
Definition Local.cpp:2676
SmallVector< BasicBlock *, 16 > PredBlockVector
Definition Local.cpp:906
static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr, const DebugLoc &NewLoc, BasicBlock::iterator Instr)
Definition Local.cpp:1638
static bool introduceTooManyPhiEntries(BasicBlock *BB, BasicBlock *Succ)
Check whether removing BB will make the phis in its Succ have too many incoming entries.
Definition Local.cpp:1048
static Value * selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, IncomingValueMap &IncomingValues)
Determines the value to use as the phi node input for a block.
Definition Local.cpp:921
static const unsigned BitPartRecursionMaxDepth
Definition Local.cpp:121
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, const PredBlockVector &BBPreds, PHINode *PN, BasicBlock *CommonPred)
Replace a value flowing from a block to a phi with potentially multiple instances of that value flowi...
Definition Local.cpp:1080
static cl::opt< unsigned > MaxPhiEntriesIncreaseAfterRemovingEmptyBlock("max-phi-entries-increase-after-removing-empty-block", cl::init(1000), cl::Hidden, cl::desc("Stop removing an empty block if removing it will introduce more " "than this number of phi entries in its successor"))
static bool isCompositeType(DbgVariableRecord *DVR)
Determine whether this debug variable is a not a basic type.
Definition Local.cpp:1751
static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, unsigned BitWidth)
Definition Local.cpp:3784
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
APInt bitcastToAPInt() const
Definition APFloat.h:1467
Class for arbitrary precision integers.
Definition APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition APInt.h:1573
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:572
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1595
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1583
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
an instruction to allocate memory on the stack
const Value * getArraySize() const
Get the number of elements allocated.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Value handle that asserts if the Value is deleted.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
unsigned getNumber() const
Definition BasicBlock.h:95
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
const Instruction & back() const
Definition BasicBlock.h:471
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:469
const Instruction * getTerminatorOrNull() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:248
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:467
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:644
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
The address of a basic block.
Definition Constants.h:1088
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Conditional Branch instruction.
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
DIExpression * createConstantValueExpression(uint64_t Val)
Create an expression for a variable that does not have an address, but does have a constant value.
Definition DIBuilder.h:987
DWARF expression.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
LLVM_ABI DIExpression * foldConstantMath()
Try to shorten an expression with constant math operations that can be evaluated at compile time.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
ArrayRef< uint64_t > getElements() const
LLVM_ABI std::optional< uint64_t > getActiveBits(DIVariable *Var)
Return the number of bits that have an active value, i.e.
uint64_t getElement(unsigned I) const
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * appendExt(const DIExpression *Expr, unsigned FromSize, unsigned ToSize, bool Signed)
Append a zero- or sign-extension to Expr.
Base class for types.
std::optional< DIBasicType::Signedness > getSignedness() const
Return the signedness of this variable's type, or std::nullopt if this type is neither signed nor uns...
DIType * getType() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
This represents the llvm.dbg.label instruction.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void removeFromParent()
LLVM_ABI Module * getModule()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void addVariableLocationOps(ArrayRef< Value * > NewValues, DIExpression *NewExpr)
Adding a new location operand will always result in this intrinsic using an ArgList,...
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
LLVM_ABI unsigned getNumVariableLocationOps() const
bool isAddressOfVariable() const
Does this describe the address of a local variable.
LLVM_ABI DbgVariableRecord * clone() const
void setExpression(DIExpression *NewExpr)
DIExpression * getExpression() const
DILocalVariable * getVariable() const
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
A debug info location.
Definition DebugLoc.h:126
DILocation * get() const
Get the underlying DILocation.
Definition DebugLoc.h:220
static DebugLoc getTemporary()
Definition DebugLoc.h:152
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
unsigned size() const
Definition DenseMap.h:172
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:134
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
std::pair< iterator, bool > insert_or_assign(const KeyT &Key, V &&Val)
Definition DenseMap.h:342
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
Definition Function.h:793
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
A wrapper class for inspecting calls to intrinsic functions.
Invoke instruction.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
LLVM_ABI MDNode * createRange(const APInt &Lo, const APInt &Hi)
Return metadata describing the range [Lo, Hi).
Definition MDBuilder.cpp:96
Metadata node.
Definition Metadata.h:1069
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
static LLVM_ABI CaptureComponents toCaptureComponents(const MDNode *MD)
Convert !captures metadata to CaptureComponents. MD may be nullptr.
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
static LLVM_ABI MDNode * getMergedAllocTokenMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoFPClass(MDNode *A, MDNode *B)
LLVMContext & getContext() const
Definition Metadata.h:1233
static LLVM_ABI MDNode * fromCaptureComponents(LLVMContext &Ctx, CaptureComponents CC)
Convert CaptureComponents to !captures metadata.
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * combine(LLVMContext &Ctx, const MMRAMetadata &A, const MMRAMetadata &B)
Combines A and B according to MMRA semantics.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
LLVM_ABI void changeToUnreachable(const Instruction *I)
Instruction I will be changed to an unreachable.
LLVM_ABI void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:320
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
Vector takeVector()
Clear the SetVector and return the underlying vector.
Definition SetVector.h:94
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
bool hasOptimizedCodeGen(LibFunc F) const
Tests if the function is both available and a candidate for optimized code generation.
bool has(LibFunc F) const
Tests whether a library function is available.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
value_op_iterator value_op_end()
Definition User.h:288
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:459
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:510
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
Definition Value.h:558
bool use_empty() const
Definition Value.h:346
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition Value.h:798
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:561
iterator_range< use_iterator > uses()
Definition Value.h:380
user_iterator_impl< User > user_iterator
Definition Value.h:391
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:93
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
Changed
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BSwap(const Opnd0 &Op0)
auto m_BitReverse(const Opnd0 &Op0)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
auto m_Value()
Match an arbitrary value and ignore it.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1732
LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
Definition Local.cpp:2516
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
Definition Local.cpp:2633
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:134
LLVM_ABI unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
Definition Local.cpp:3289
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
@ Known
Known to have no common set bits.
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Definition Local.cpp:3253
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition Local.cpp:2609
LLVM_ABI bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition Local.cpp:3126
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition Local.cpp:1704
constexpr from_range_t from_range
bool hasNItemsOrLess(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;})
Returns true if the sequence [Begin, End) has N or less items.
Definition STLExtras.h:2659
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
Definition Local.cpp:3484
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:716
LLVM_ABI bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
LLVM_ABI void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition Local.cpp:1901
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
Definition Local.cpp:2499
LLVM_ABI bool canSimplifyInvokeNoUnwind(const Function *F)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2913
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1148
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3789
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1559
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
Definition Local.cpp:1814
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
Definition Local.cpp:3442
LLVM_ABI CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
Definition Local.cpp:2584
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DbgRecords)
Salvage only the records in DbgRecords instead of finding every debug user of I.
Definition Local.cpp:2122
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
Definition Local.cpp:1655
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2875
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:410
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition Local.cpp:3189
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:623
LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
Definition Local.cpp:3268
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2544
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2445
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2305
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3117
LLVM_ABI void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
Definition Local.cpp:3389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!...
Definition Local.cpp:756
LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
Definition Local.cpp:3396
LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a range metadata node to a new load instruction.
Definition Local.cpp:3365
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI DebugLoc getDebugValueLoc(DbgVariableRecord *DVR)
Produce a DebugLoc to use for each dbg.declare that is promoted to a dbg.value.
LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
Definition Local.cpp:3340
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3902
DWARFExpression::Operation Op
LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple dbg.value records when the alloca it describes is replaced with a new value.
Definition Local.cpp:2004
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
Definition Local.cpp:1510
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
Definition Local.cpp:538
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
Definition DebugInfo.cpp:48
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J)
Combine metadata of two instructions, where instruction J is a memory access that has been merged int...
Definition Local.cpp:3122
LLVM_ABI bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
Definition Local.cpp:4025
LLVM_ABI Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
Definition Local.cpp:3991
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:305
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
LLVM_ABI void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition Local.cpp:3893
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1502
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
Definition Local.cpp:3316
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:285
LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces dbg.declare record when the address it describes is replaced with a new value.
Definition Local.cpp:1964
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NDEBUG
Definition regutils.h:48
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
std::optional< unsigned > Opcode
Opcode of merged instructions.
Definition Local.h:589
LLVM_ABI void mergeFlags(Instruction &I)
Merge in the no-wrap flags from I.
Definition Local.cpp:4055
LLVM_ABI void applyFlags(Instruction &I)
Apply the no-wrap flags to I if applicable.
Definition Local.cpp:4071
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342