xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Transforms/Utils/Local.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- Local.h - Functions to perform local transformations -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions perform various local transformations to the
10 // program.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
15 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
22 #include "llvm/Transforms/Utils/ValueMapper.h"
23 #include <cstdint>
24 
25 namespace llvm {
26 
27 class DataLayout;
28 class Value;
29 class WeakTrackingVH;
30 class WeakVH;
31 template <typename T> class SmallVectorImpl;
32 class AAResults;
33 class AllocaInst;
34 class AssumptionCache;
35 class BasicBlock;
36 class BranchInst;
37 class CallBase;
38 class CallInst;
39 class DbgVariableIntrinsic;
40 class DIBuilder;
41 class DomTreeUpdater;
42 class Function;
43 class Instruction;
44 class InvokeInst;
45 class LoadInst;
46 class MDNode;
47 class MemorySSAUpdater;
48 class PHINode;
49 class StoreInst;
50 class TargetLibraryInfo;
51 class TargetTransformInfo;
52 
53 //===----------------------------------------------------------------------===//
54 //  Local constant propagation.
55 //
56 
57 /// If a terminator instruction is predicated on a constant value, convert it
58 /// into an unconditional branch to the constant destination.
59 /// This is a nontrivial operation because the successors of this basic block
60 /// must have their PHI nodes updated.
61 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
62 /// conditions and indirectbr addresses this might make dead if
63 /// DeleteDeadConditions is true.
64 LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB,
65                                      bool DeleteDeadConditions = false,
66                                      const TargetLibraryInfo *TLI = nullptr,
67                                      DomTreeUpdater *DTU = nullptr);
68 
69 //===----------------------------------------------------------------------===//
70 //  Local dead code elimination.
71 //
72 
73 /// Return true if the result produced by the instruction is not used, and the
74 /// instruction will return. Certain side-effecting instructions are also
75 /// considered dead if there are no uses of the instruction.
76 LLVM_ABI bool
77 isInstructionTriviallyDead(Instruction *I,
78                            const TargetLibraryInfo *TLI = nullptr);
79 
80 /// Return true if the result produced by the instruction would have no side
81 /// effects if it was not used. This is equivalent to checking whether
82 /// isInstructionTriviallyDead would be true if the use count was 0.
83 LLVM_ABI bool
84 wouldInstructionBeTriviallyDead(const Instruction *I,
85                                 const TargetLibraryInfo *TLI = nullptr);
86 
87 /// Return true if the result produced by the instruction has no side effects on
88 /// any paths other than where it is used. This is less conservative than
89 /// wouldInstructionBeTriviallyDead which is based on the assumption
90 /// that the use count will be 0. An example usage of this API is for
91 /// identifying instructions that can be sunk down to use(s).
92 LLVM_ABI bool wouldInstructionBeTriviallyDeadOnUnusedPaths(
93     Instruction *I, const TargetLibraryInfo *TLI = nullptr);
94 
95 /// If the specified value is a trivially dead instruction, delete it.
96 /// If that makes any of its operands trivially dead, delete them too,
97 /// recursively. Return true if any instructions were deleted.
98 LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(
99     Value *V, const TargetLibraryInfo *TLI = nullptr,
100     MemorySSAUpdater *MSSAU = nullptr,
101     std::function<void(Value *)> AboutToDeleteCallback =
102         std::function<void(Value *)>());
103 
104 /// Delete all of the instructions in `DeadInsts`, and all other instructions
105 /// that deleting these in turn causes to be trivially dead.
106 ///
107 /// The initial instructions in the provided vector must all have empty use
108 /// lists and satisfy `isInstructionTriviallyDead`.
109 ///
110 /// `DeadInsts` will be used as scratch storage for this routine and will be
111 /// empty afterward.
112 LLVM_ABI void RecursivelyDeleteTriviallyDeadInstructions(
113     SmallVectorImpl<WeakTrackingVH> &DeadInsts,
114     const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
115     std::function<void(Value *)> AboutToDeleteCallback =
116         std::function<void(Value *)>());
117 
118 /// Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow
119 /// instructions that are not trivially dead. These will be ignored.
120 /// Returns true if any changes were made, i.e. any instructions trivially dead
121 /// were found and deleted.
122 LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(
123     SmallVectorImpl<WeakTrackingVH> &DeadInsts,
124     const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
125     std::function<void(Value *)> AboutToDeleteCallback =
126         std::function<void(Value *)>());
127 
128 /// If the specified value is an effectively dead PHI node, due to being a
129 /// def-use chain of single-use nodes that either forms a cycle or is terminated
130 /// by a trivially dead instruction, delete it. If that makes any of its
131 /// operands trivially dead, delete them too, recursively. Return true if a
132 /// change was made.
133 LLVM_ABI bool
134 RecursivelyDeleteDeadPHINode(PHINode *PN,
135                              const TargetLibraryInfo *TLI = nullptr,
136                              MemorySSAUpdater *MSSAU = nullptr);
137 
138 /// Scan the specified basic block and try to simplify any instructions in it
139 /// and recursively delete dead instructions.
140 ///
141 /// This returns true if it changed the code, note that it can delete
142 /// instructions in other blocks as well in this block.
143 LLVM_ABI bool
144 SimplifyInstructionsInBlock(BasicBlock *BB,
145                             const TargetLibraryInfo *TLI = nullptr);
146 
147 /// Replace all the uses of an SSA value in @llvm.dbg intrinsics with
148 /// undef. This is useful for signaling that a variable, e.g. has been
149 /// found dead and hence it's unavailable at a given program point.
150 /// Returns true if the dbg values have been changed.
151 LLVM_ABI bool replaceDbgUsesWithUndef(Instruction *I);
152 
153 //===----------------------------------------------------------------------===//
154 //  Control Flow Graph Restructuring.
155 //
156 
157 /// BB is a block with one predecessor and its predecessor is known to have one
158 /// successor (BB!). Eliminate the edge between them, moving the instructions in
159 /// the predecessor into BB. This deletes the predecessor block.
160 LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB,
161                                           DomTreeUpdater *DTU = nullptr);
162 
163 /// BB is known to contain an unconditional branch, and contains no instructions
164 /// other than PHI nodes, potential debug intrinsics and the branch. If
165 /// possible, eliminate BB by rewriting all the predecessors to branch to the
166 /// successor block and return true. If we can't transform, return false.
167 LLVM_ABI bool
168 TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
169                                         DomTreeUpdater *DTU = nullptr);
170 
171 /// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
172 /// to be clever about PHI nodes which differ only in the order of the incoming
173 /// values, but instcombine orders them so it usually won't matter.
174 ///
175 /// This overload removes the duplicate PHI nodes directly.
176 LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB);
177 
178 /// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
179 /// to be clever about PHI nodes which differ only in the order of the incoming
180 /// values, but instcombine orders them so it usually won't matter.
181 ///
182 /// This overload collects the PHI nodes to be removed into the ToRemove set.
183 LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB,
184                                          SmallPtrSetImpl<PHINode *> &ToRemove);
185 
186 /// This function is used to do simplification of a CFG.  For example, it
187 /// adjusts branches to branches to eliminate the extra hop, it eliminates
188 /// unreachable basic blocks, and does other peephole optimization of the CFG.
189 /// It returns true if a modification was made, possibly deleting the basic
190 /// block that was pointed to. LoopHeaders is an optional input parameter
191 /// providing the set of loop headers that SimplifyCFG should not eliminate.
192 LLVM_ABI extern cl::opt<bool> RequireAndPreserveDomTree;
193 LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
194                           DomTreeUpdater *DTU = nullptr,
195                           const SimplifyCFGOptions &Options = {},
196                           ArrayRef<WeakVH> LoopHeaders = {});
197 
198 /// This function is used to flatten a CFG. For example, it uses parallel-and
199 /// and parallel-or mode to collapse if-conditions and merge if-regions with
200 /// identical statements.
201 LLVM_ABI bool FlattenCFG(BasicBlock *BB, AAResults *AA = nullptr);
202 
203 /// If this basic block is ONLY a setcc and a branch, and if a predecessor
204 /// branches to us and one of our successors, fold the setcc into the
205 /// predecessor and use logical operations to pick the right destination.
206 LLVM_ABI bool foldBranchToCommonDest(BranchInst *BI,
207                                      llvm::DomTreeUpdater *DTU = nullptr,
208                                      MemorySSAUpdater *MSSAU = nullptr,
209                                      const TargetTransformInfo *TTI = nullptr,
210                                      unsigned BonusInstThreshold = 1);
211 
212 /// This function takes a virtual register computed by an Instruction and
213 /// replaces it with a slot in the stack frame, allocated via alloca.
214 /// This allows the CFG to be changed around without fear of invalidating the
215 /// SSA information for the value. It returns the pointer to the alloca inserted
216 /// to create a stack slot for X.
217 LLVM_ABI AllocaInst *DemoteRegToStack(
218     Instruction &X, bool VolatileLoads = false,
219     std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
220 
221 /// This function takes a virtual register computed by a phi node and replaces
222 /// it with a slot in the stack frame, allocated via alloca. The phi node is
223 /// deleted and it returns the pointer to the alloca inserted.
224 LLVM_ABI AllocaInst *DemotePHIToStack(
225     PHINode *P, std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
226 
227 /// If the specified pointer points to an object that we control, try to modify
228 /// the object's alignment to PrefAlign. Returns a minimum known alignment of
229 /// the value after the operation, which may be lower than PrefAlign.
230 ///
231 /// Increating value alignment isn't often possible though. If alignment is
232 /// important, a more reliable approach is to simply align all global variables
233 /// and allocation instructions to their preferred alignment from the beginning.
234 LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign,
235                                    const DataLayout &DL);
236 
237 /// Try to ensure that the alignment of \p V is at least \p PrefAlign bytes. If
238 /// the owning object can be modified and has an alignment less than \p
239 /// PrefAlign, it will be increased and \p PrefAlign returned. If the alignment
240 /// cannot be increased, the known alignment of the value is returned.
241 ///
242 /// It is not always possible to modify the alignment of the underlying object,
243 /// so if alignment is important, a more reliable approach is to simply align
244 /// all global variables and allocation instructions to their preferred
245 /// alignment from the beginning.
246 LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
247                                           const DataLayout &DL,
248                                           const Instruction *CxtI = nullptr,
249                                           AssumptionCache *AC = nullptr,
250                                           const DominatorTree *DT = nullptr);
251 
252 /// Try to infer an alignment for the specified pointer.
253 inline Align getKnownAlignment(Value *V, const DataLayout &DL,
254                                const Instruction *CxtI = nullptr,
255                                AssumptionCache *AC = nullptr,
256                                const DominatorTree *DT = nullptr) {
257   return getOrEnforceKnownAlignment(V, MaybeAlign(), DL, CxtI, AC, DT);
258 }
259 
260 /// Create a call that matches the invoke \p II in terms of arguments,
261 /// attributes, debug information, etc. The call is not placed in a block and it
262 /// will not have a name. The invoke instruction is not removed, nor are the
263 /// uses replaced by the new call.
264 LLVM_ABI CallInst *createCallMatchingInvoke(InvokeInst *II);
265 
266 /// This function converts the specified invoke into a normal call.
267 LLVM_ABI CallInst *changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr);
268 
269 ///===---------------------------------------------------------------------===//
270 ///  Dbg Intrinsic utilities
271 ///
272 
273 /// Creates and inserts a dbg_value record intrinsic before a store
274 /// that has an associated llvm.dbg.value intrinsic.
275 LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI,
276                                          DIBuilder &Builder);
277 
278 /// Creates and inserts an llvm.dbg.value intrinsic before a store
279 /// that has an associated llvm.dbg.value intrinsic.
280 LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableIntrinsic *DII,
281                                          StoreInst *SI, DIBuilder &Builder);
282 
283 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
284 /// that has an associated llvm.dbg.declare intrinsic.
285 LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
286                                               StoreInst *SI,
287                                               DIBuilder &Builder);
288 LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
289                                               StoreInst *SI,
290                                               DIBuilder &Builder);
291 
292 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
293 /// that has an associated llvm.dbg.declare intrinsic.
294 LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
295                                               LoadInst *LI, DIBuilder &Builder);
296 LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
297                                               LoadInst *LI, DIBuilder &Builder);
298 
299 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
300 /// llvm.dbg.declare intrinsic.
301 LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
302                                               PHINode *LI, DIBuilder &Builder);
303 LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
304                                               PHINode *LI, DIBuilder &Builder);
305 
306 /// Lowers llvm.dbg.declare intrinsics into appropriate set of
307 /// llvm.dbg.value intrinsics.
308 LLVM_ABI bool LowerDbgDeclare(Function &F);
309 
310 /// Propagate dbg.value intrinsics through the newly inserted PHIs.
311 LLVM_ABI void
312 insertDebugValuesForPHIs(BasicBlock *BB,
313                          SmallVectorImpl<PHINode *> &InsertedPHIs);
314 
315 /// Replaces llvm.dbg.declare instruction when the address it
316 /// describes is replaced with a new value. If Deref is true, an
317 /// additional DW_OP_deref is prepended to the expression. If Offset
318 /// is non-zero, a constant displacement is added to the expression
319 /// (between the optional Deref operations). Offset can be negative.
320 LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress,
321                                 DIBuilder &Builder, uint8_t DIExprFlags,
322                                 int Offset);
323 
324 /// Replaces multiple llvm.dbg.value instructions when the alloca it describes
325 /// is replaced with a new value. If Offset is non-zero, a constant displacement
326 /// is added to the expression (after the mandatory Deref). Offset can be
327 /// negative. New llvm.dbg.value instructions are inserted at the locations of
328 /// the instructions they replace.
329 LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
330                                        DIBuilder &Builder, int Offset = 0);
331 
332 /// Assuming the instruction \p I is going to be deleted, attempt to salvage
333 /// debug users of \p I by writing the effect of \p I in a DIExpression. If it
334 /// cannot be salvaged changes its debug uses to undef.
335 LLVM_ABI void salvageDebugInfo(Instruction &I);
336 
337 /// Implementation of salvageDebugInfo, applying only to instructions in
338 /// \p Insns, rather than all debug users from findDbgUsers( \p I).
339 /// Mark undef if salvaging cannot be completed.
340 LLVM_ABI void
341 salvageDebugInfoForDbgValues(Instruction &I,
342                              ArrayRef<DbgVariableIntrinsic *> Insns,
343                              ArrayRef<DbgVariableRecord *> DPInsns);
344 
345 /// Given an instruction \p I and DIExpression \p DIExpr operating on
346 /// it, append the effects of \p I to the DIExpression operand list
347 /// \p Ops, or return \p nullptr if it cannot be salvaged.
348 /// \p CurrentLocOps is the number of SSA values referenced by the
349 /// incoming \p Ops.  \return the first non-constant operand
350 /// implicitly referred to by Ops. If \p I references more than one
351 /// non-constant operand, any additional operands are added to
352 /// \p AdditionalValues.
353 ///
354 /// \example
355 ////
356 ///   I = add %a, i32 1
357 ///
358 ///   Return = %a
359 ///   Ops = llvm::dwarf::DW_OP_lit1 llvm::dwarf::DW_OP_add
360 ///
361 ///   I = add %a, %b
362 ///
363 ///   Return = %a
364 ///   Ops = llvm::dwarf::DW_OP_LLVM_arg0 llvm::dwarf::DW_OP_add
365 ///   AdditionalValues = %b
366 LLVM_ABI Value *
367 salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
368                      SmallVectorImpl<uint64_t> &Ops,
369                      SmallVectorImpl<Value *> &AdditionalValues);
370 
371 /// Point debug users of \p From to \p To or salvage them. Use this function
372 /// only when replacing all uses of \p From with \p To, with a guarantee that
373 /// \p From is going to be deleted.
374 ///
375 /// Follow these rules to prevent use-before-def of \p To:
376 ///   . If \p To is a linked Instruction, set \p DomPoint to \p To.
377 ///   . If \p To is an unlinked Instruction, set \p DomPoint to the Instruction
378 ///     \p To will be inserted after.
379 ///   . If \p To is not an Instruction (e.g a Constant), the choice of
380 ///     \p DomPoint is arbitrary. Pick \p From for simplicity.
381 ///
382 /// If a debug user cannot be preserved without reordering variable updates or
383 /// introducing a use-before-def, it is either salvaged (\ref salvageDebugInfo)
384 /// or deleted. Returns true if any debug users were updated.
385 LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To,
386                                     Instruction &DomPoint, DominatorTree &DT);
387 
388 /// If a terminator in an unreachable basic block has an operand of type
389 /// Instruction, transform it into poison. Return true if any operands
390 /// are changed to poison. Original Values prior to being changed to poison
391 /// are returned in \p PoisonedValues.
392 LLVM_ABI bool
393 handleUnreachableTerminator(Instruction *I,
394                             SmallVectorImpl<Value *> &PoisonedValues);
395 
396 /// Remove all instructions from a basic block other than its terminator
397 /// and any present EH pad instructions. Returns the number of instructions
398 /// that have been removed.
399 LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB);
400 
401 /// Insert an unreachable instruction before the specified
402 /// instruction, making it and the rest of the code in the block dead.
403 LLVM_ABI unsigned changeToUnreachable(Instruction *I,
404                                       bool PreserveLCSSA = false,
405                                       DomTreeUpdater *DTU = nullptr,
406                                       MemorySSAUpdater *MSSAU = nullptr);
407 
408 /// Convert the CallInst to InvokeInst with the specified unwind edge basic
409 /// block.  This also splits the basic block where CI is located, because
410 /// InvokeInst is a terminator instruction.  Returns the newly split basic
411 /// block.
412 LLVM_ABI BasicBlock *
413 changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge,
414                                  DomTreeUpdater *DTU = nullptr);
415 
416 /// Replace 'BB's terminator with one that does not have an unwind successor
417 /// block. Rewrites `invoke` to `call`, etc. Updates any PHIs in unwind
418 /// successor. Returns the instruction that replaced the original terminator,
419 /// which might be a call in case the original terminator was an invoke.
420 ///
421 /// \param BB  Block whose terminator will be replaced.  Its terminator must
422 ///            have an unwind successor.
423 LLVM_ABI Instruction *removeUnwindEdge(BasicBlock *BB,
424                                        DomTreeUpdater *DTU = nullptr);
425 
426 /// Remove all blocks that can not be reached from the function's entry.
427 ///
428 /// Returns true if any basic block was removed.
429 LLVM_ABI bool removeUnreachableBlocks(Function &F,
430                                       DomTreeUpdater *DTU = nullptr,
431                                       MemorySSAUpdater *MSSAU = nullptr);
432 
433 /// Combine the metadata of two instructions so that K can replace J. This
434 /// specifically handles the case of CSE-like transformations. Some
435 /// metadata can only be kept if K dominates J. For this to be correct,
436 /// K cannot be hoisted.
437 ///
438 /// Unknown metadata is removed.
439 LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J,
440                                     bool DoesKMove);
441 
442 /// Combine metadata of two instructions, where instruction J is a memory
443 /// access that has been merged into K. This will intersect alias-analysis
444 /// metadata, while preserving other known metadata.
445 LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J);
446 
447 /// Copy the metadata from the source instruction to the destination (the
448 /// replacement for the source instruction).
449 LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source);
450 
451 /// Patch the replacement so that it is not more restrictive than the value
452 /// being replaced. It assumes that the replacement does not get moved from
453 /// its original position.
454 LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl);
455 
456 // Replace each use of 'From' with 'To', if that use does not belong to basic
457 // block where 'From' is defined. Returns the number of replacements made.
458 LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To);
459 
460 /// Replace each use of 'From' with 'To' if that use is dominated by
461 /// the given edge.  Returns the number of replacements made.
462 LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
463                                            DominatorTree &DT,
464                                            const BasicBlockEdge &Edge);
465 /// Replace each use of 'From' with 'To' if that use is dominated by
466 /// the end of the given BasicBlock. Returns the number of replacements made.
467 LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
468                                            DominatorTree &DT,
469                                            const BasicBlock *BB);
470 /// Replace each use of 'From' with 'To' if that use is dominated by
471 /// the given edge and the callback ShouldReplace returns true. Returns the
472 /// number of replacements made.
473 LLVM_ABI unsigned replaceDominatedUsesWithIf(
474     Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge,
475     function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
476 /// Replace each use of 'From' with 'To' if that use is dominated by
477 /// the end of the given BasicBlock and the callback ShouldReplace returns true.
478 /// Returns the number of replacements made.
479 LLVM_ABI unsigned replaceDominatedUsesWithIf(
480     Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
481     function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
482 
483 /// Return true if this call calls a gc leaf function.
484 ///
485 /// A leaf function is a function that does not safepoint the thread during its
486 /// execution.  During a call or invoke to such a function, the callers stack
487 /// does not have to be made parseable.
488 ///
489 /// Most passes can and should ignore this information, and it is only used
490 /// during lowering by the GC infrastructure.
491 LLVM_ABI bool callsGCLeafFunction(const CallBase *Call,
492                                   const TargetLibraryInfo &TLI);
493 
494 /// Copy a nonnull metadata node to a new load instruction.
495 ///
496 /// This handles mapping it to range metadata if the new load is an integer
497 /// load instead of a pointer load.
498 LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
499                                   LoadInst &NewLI);
500 
501 /// Copy a range metadata node to a new load instruction.
502 ///
503 /// This handles mapping it to nonnull metadata if the new load is a pointer
504 /// load instead of an integer load and the range doesn't cover null.
505 LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
506                                 MDNode *N, LoadInst &NewLI);
507 
508 /// Remove the debug intrinsic instructions for the given instruction.
509 LLVM_ABI void dropDebugUsers(Instruction &I);
510 
511 /// Hoist all of the instructions in the \p IfBlock to the dominant block
512 /// \p DomBlock, by moving its instructions to the insertion point \p InsertPt.
513 ///
514 /// The moved instructions receive the insertion point debug location values
515 /// (DILocations) and their debug intrinsic instructions are removed.
516 LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock,
517                                        Instruction *InsertPt, BasicBlock *BB);
518 
519 /// Given a constant, create a debug information expression.
520 LLVM_ABI DIExpression *getExpressionForConstant(DIBuilder &DIB,
521                                                 const Constant &C, Type &Ty);
522 
523 /// Remap the operands of the debug records attached to \p Inst, and the
524 /// operands of \p Inst itself if it's a debug intrinsic.
525 LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst);
526 
527 //===----------------------------------------------------------------------===//
528 //  Intrinsic pattern matching
529 //
530 
531 /// Try to match a bswap or bitreverse idiom.
532 ///
533 /// If an idiom is matched, an intrinsic call is inserted before \c I. Any added
534 /// instructions are returned in \c InsertedInsts. They will all have been added
535 /// to a basic block.
536 ///
537 /// A bitreverse idiom normally requires around 2*BW nodes to be searched (where
538 /// BW is the bitwidth of the integer type). A bswap idiom requires anywhere up
539 /// to BW / 4 nodes to be searched, so is significantly faster.
540 ///
541 /// This function returns true on a successful match or false otherwise.
542 LLVM_ABI bool
543 recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps,
544                                 bool MatchBitReversals,
545                                 SmallVectorImpl<Instruction *> &InsertedInsts);
546 
547 //===----------------------------------------------------------------------===//
548 //  Sanitizer utilities
549 //
550 
551 /// Given a CallInst, check if it calls a string function known to CodeGen,
552 /// and mark it with NoBuiltin if so.  To be used by sanitizers that intend
553 /// to intercept string functions and want to avoid converting them to target
554 /// specific instructions.
555 LLVM_ABI void
556 maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI,
557                                        const TargetLibraryInfo *TLI);
558 
559 //===----------------------------------------------------------------------===//
560 //  Transform predicates
561 //
562 
563 /// Given an instruction, is it legal to set operand OpIdx to a non-constant
564 /// value?
565 LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I,
566                                             unsigned OpIdx);
567 
568 //===----------------------------------------------------------------------===//
569 //  Value helper functions
570 //
571 
572 /// Invert the given true/false value, possibly reusing an existing copy.
573 LLVM_ABI Value *invertCondition(Value *Condition);
574 
575 //===----------------------------------------------------------------------===//
576 //  Assorted
577 //
578 
579 /// If we can infer one attribute from another on the declaration of a
580 /// function, explicitly materialize the maximal set in the IR.
581 LLVM_ABI bool inferAttributesFromOthers(Function &F);
582 
583 //===----------------------------------------------------------------------===//
584 //  Helpers to track and update flags on instructions.
585 //
586 
587 struct OverflowTracking {
588   bool HasNUW = true;
589   bool HasNSW = true;
590   bool IsDisjoint = true;
591 
592 #ifndef NDEBUG
593   /// Opcode of merged instructions. All instructions passed to mergeFlags must
594   /// have the same opcode.
595   std::optional<unsigned> Opcode;
596 #endif
597 
598   // Note: At the moment, users are responsible to manage AllKnownNonNegative
599   // and AllKnownNonZero manually. AllKnownNonNegative can be true in a case
600   // where one of the operands is negative, but one the operators is not NSW.
601   // AllKnownNonNegative should not be used independently of HasNSW
602   bool AllKnownNonNegative = true;
603   bool AllKnownNonZero = true;
604 
605   OverflowTracking() = default;
606 
607   /// Merge in the no-wrap flags from \p I.
608   LLVM_ABI void mergeFlags(Instruction &I);
609 
610   /// Apply the no-wrap flags to \p I if applicable.
611   LLVM_ABI void applyFlags(Instruction &I);
612 };
613 
614 } // end namespace llvm
615 
616 #endif // LLVM_TRANSFORMS_UTILS_LOCAL_H
617