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