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