LLVM 24.0.0git
Local.h
Go to the documentation of this file.
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"
23#include <cstdint>
24
25namespace llvm {
26
27class DataLayout;
28class Value;
29class WeakTrackingVH;
30class WeakVH;
31template <typename PtrType> class SmallPtrSetImpl;
32template <typename T> class SmallVectorImpl;
33class AAResults;
34class AllocaInst;
35class AssumptionCache;
36class BasicBlock;
37class CallBase;
38class CallInst;
39class CondBrInst;
40class DIBuilder;
41class DomTreeUpdater;
42class FreezeInst;
43class Function;
44class Instruction;
45class InvokeInst;
46class LoadInst;
47class MDNode;
49class PHINode;
50class StoreInst;
53
54//===----------------------------------------------------------------------===//
55// Local constant propagation.
56//
57
58/// If a terminator instruction is predicated on a constant value, convert it
59/// into an unconditional branch to the constant destination.
60/// This is a nontrivial operation because the successors of this basic block
61/// must have their PHI nodes updated.
62/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
63/// conditions and indirectbr addresses this might make dead if
64/// DeleteDeadConditions is true.
66 bool DeleteDeadConditions = false,
67 const TargetLibraryInfo *TLI = nullptr,
68 DomTreeUpdater *DTU = nullptr);
69
70//===----------------------------------------------------------------------===//
71// Local dead code elimination.
72//
73
74/// Return true if the result produced by the instruction is not used, and the
75/// instruction will return. Certain side-effecting instructions are also
76/// considered dead if there are no uses of the instruction.
77LLVM_ABI bool
79 const TargetLibraryInfo *TLI = nullptr);
80
81/// Return true if the result produced by the instruction would have no side
82/// effects if it was not used. This is equivalent to checking whether
83/// isInstructionTriviallyDead would be true if the use count was 0.
84LLVM_ABI bool
86 const TargetLibraryInfo *TLI = nullptr);
87
88/// If the specified value is a trivially dead instruction, delete it.
89/// If that makes any of its operands trivially dead, delete them too,
90/// recursively. Return true if any instructions were deleted.
92 Value *V, const TargetLibraryInfo *TLI = nullptr,
93 MemorySSAUpdater *MSSAU = nullptr,
94 std::function<void(Value *)> AboutToDeleteCallback =
95 std::function<void(Value *)>());
96
97/// Delete all of the instructions in `DeadInsts`, and all other instructions
98/// that deleting these in turn causes to be trivially dead.
99///
100/// The initial instructions in the provided vector must all have empty use
101/// lists and satisfy `isInstructionTriviallyDead`.
102///
103/// `DeadInsts` will be used as scratch storage for this routine and will be
104/// empty afterward.
107 const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
108 std::function<void(Value *)> AboutToDeleteCallback =
109 std::function<void(Value *)>());
110
111/// Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow
112/// instructions that are not trivially dead. These will be ignored.
113/// Returns true if any changes were made, i.e. any instructions trivially dead
114/// were found and deleted.
117 const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
118 std::function<void(Value *)> AboutToDeleteCallback =
119 std::function<void(Value *)>());
120
121/// If the specified value is an effectively dead PHI node, due to being a
122/// def-use chain of single-use nodes that either forms a cycle or is terminated
123/// by a trivially dead instruction, delete it. If that makes any of its
124/// operands trivially dead, delete them too, recursively. Return true if a
125/// change was made.
127 PHINode *PN, const TargetLibraryInfo *TLI = nullptr,
128 MemorySSAUpdater *MSSAU = nullptr,
129 SmallPtrSetImpl<PHINode *> *KnownNonDeadPHIs = nullptr);
130
131/// Scan the specified basic block and try to simplify any instructions in it
132/// and recursively delete dead instructions.
133///
134/// This returns true if it changed the code, note that it can delete
135/// instructions in other blocks as well in this block.
136LLVM_ABI bool
138 const TargetLibraryInfo *TLI = nullptr);
139
140//===----------------------------------------------------------------------===//
141// Control Flow Graph Restructuring.
142//
143
144/// BB is a block with one predecessor and its predecessor is known to have one
145/// successor (BB!). Eliminate the edge between them, moving the instructions in
146/// the predecessor into BB. This deletes the predecessor block.
148 DomTreeUpdater *DTU = nullptr);
149
150/// BB is known to contain an unconditional branch, and contains no instructions
151/// other than PHI nodes, potential debug intrinsics and the branch. If
152/// possible, eliminate BB by rewriting all the predecessors to branch to the
153/// successor block and return true. If we can't transform, return false.
154LLVM_ABI bool
156 DomTreeUpdater *DTU = nullptr);
157
158/// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
159/// to be clever about PHI nodes which differ only in the order of the incoming
160/// values, but instcombine orders them so it usually won't matter.
161///
162/// This overload removes the duplicate PHI nodes directly.
164
165/// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
166/// to be clever about PHI nodes which differ only in the order of the incoming
167/// values, but instcombine orders them so it usually won't matter.
168///
169/// This overload collects the PHI nodes to be removed into the ToRemove set.
172
173/// This function is used to do simplification of a CFG. For example, it
174/// adjusts branches to branches to eliminate the extra hop, it eliminates
175/// unreachable basic blocks, and does other peephole optimization of the CFG.
176/// It returns true if a modification was made, possibly deleting the basic
177/// block that was pointed to. LoopHeaders is an optional input parameter
178/// providing the set of loop headers that SimplifyCFG should not eliminate.
181 DomTreeUpdater *DTU = nullptr,
182 const SimplifyCFGOptions &Options = {},
183 ArrayRef<WeakVH> LoopHeaders = {});
184
185/// This function is used to flatten a CFG. For example, it uses parallel-and
186/// and parallel-or mode to collapse if-conditions and merge if-regions with
187/// identical statements.
188LLVM_ABI bool FlattenCFG(BasicBlock *BB, AAResults *AA = nullptr);
189
190/// If this basic block is ONLY a setcc and a branch, and if a predecessor
191/// branches to us and one of our successors, fold the setcc into the
192/// predecessor and use logical operations to pick the right destination.
194 llvm::DomTreeUpdater *DTU = nullptr,
195 MemorySSAUpdater *MSSAU = nullptr,
196 const TargetTransformInfo *TTI = nullptr,
197 AssumptionCache *AC = nullptr,
198 unsigned BonusInstThreshold = 1);
199
200/// This function takes a virtual register computed by an Instruction and
201/// replaces it with a slot in the stack frame, allocated via alloca.
202/// This allows the CFG to be changed around without fear of invalidating the
203/// SSA information for the value. It returns the pointer to the alloca inserted
204/// to create a stack slot for X.
206 Instruction &X, bool VolatileLoads = false,
207 std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
208
209/// This function takes a virtual register computed by a phi node and replaces
210/// it with a slot in the stack frame, allocated via alloca. The phi node is
211/// deleted and it returns the pointer to the alloca inserted.
213 PHINode *P, std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
214
215/// If the specified pointer points to an object that we control, try to modify
216/// the object's alignment to PrefAlign. Returns a minimum known alignment of
217/// the value after the operation, which may be lower than PrefAlign.
218///
219/// Increating value alignment isn't often possible though. If alignment is
220/// important, a more reliable approach is to simply align all global variables
221/// and allocation instructions to their preferred alignment from the beginning.
223 const DataLayout &DL);
224
225/// Try to ensure that the alignment of \p V is at least \p PrefAlign bytes. If
226/// the owning object can be modified and has an alignment less than \p
227/// PrefAlign, it will be increased and \p PrefAlign returned. If the alignment
228/// cannot be increased, the known alignment of the value is returned.
229///
230/// It is not always possible to modify the alignment of the underlying object,
231/// so if alignment is important, a more reliable approach is to simply align
232/// all global variables and allocation instructions to their preferred
233/// alignment from the beginning.
235 const DataLayout &DL,
236 const Instruction *CtxI = nullptr,
237 AssumptionCache *AC = nullptr,
238 const DominatorTree *DT = nullptr);
239
240/// Try to infer an alignment for the specified pointer.
242 const Instruction *CtxI = nullptr,
243 AssumptionCache *AC = nullptr,
244 const DominatorTree *DT = nullptr) {
245 return getOrEnforceKnownAlignment(V, MaybeAlign(), DL, CtxI, AC, DT);
246}
247
248/// Create a call that matches the invoke \p II in terms of arguments,
249/// attributes, debug information, etc. The call is not placed in a block and it
250/// will not have a name. The invoke instruction is not removed, nor are the
251/// uses replaced by the new call.
252LLVM_ABI CallInst *createCallMatchingInvoke(InvokeInst *II);
253
254/// This function converts the specified invoke into a normal call.
255LLVM_ABI CallInst *changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr);
256
257///===---------------------------------------------------------------------===//
258/// Dbg Intrinsic utilities
259///
260
261/// Creates and inserts a dbg_value record intrinsic before a store
262/// that has an associated llvm.dbg.value intrinsic.
263LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI,
264 DIBuilder &Builder);
265
266/// Inserts a dbg.value record before a store to an alloca'd value
267/// that has an associated dbg.declare record.
268LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
269 StoreInst *SI,
270 DIBuilder &Builder);
271
272/// Inserts a dbg.value record before a load of an alloca'd value
273/// that has an associated dbg.declare record.
274LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
275 LoadInst *LI, DIBuilder &Builder);
276
277/// Inserts a dbg.value record after a phi that has an associated
278/// llvm.dbg.declare record.
279LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
280 PHINode *LI, DIBuilder &Builder);
281
282/// Lowers dbg.declare records into appropriate set of dbg.value records.
284
285/// Propagate dbg.value intrinsics through the newly inserted PHIs.
286LLVM_ABI void
287insertDebugValuesForPHIs(BasicBlock *BB,
288 SmallVectorImpl<PHINode *> &InsertedPHIs);
289
290/// Replaces dbg.declare record when the address it
291/// describes is replaced with a new value. If Deref is true, an
292/// additional DW_OP_deref is prepended to the expression. If Offset
293/// is non-zero, a constant displacement is added to the expression
294/// (between the optional Deref operations). Offset can be negative.
295LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress,
296 DIBuilder &Builder, uint8_t DIExprFlags,
297 int Offset);
298
299/// Replaces multiple dbg.value records when the alloca it describes
300/// is replaced with a new value. If Offset is non-zero, a constant displacement
301/// is added to the expression (after the mandatory Deref). Offset can be
302/// negative. New dbg.value records are inserted at the locations of
303/// the instructions they replace.
304LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
305 DIBuilder &Builder, int Offset = 0);
306
307/// Salvage debug records that use \p I before the instruction is deleted.
308/// Rewrite those uses in terms of its operands where we can, and encode the
309/// instruction's effect in the record's DIExpression. Deleting the instruction
310/// replaces any remaining debug-record uses with poison.
311LLVM_ABI void salvageDebugInfo(Instruction &I);
312
313/// Salvage only the records in \p DbgRecords instead of finding every debug
314/// user of \p I. Every record must be a debug user of the instruction.
315///
316/// Process records in order. For a dbg.assign, salvage a matching address
317/// before its variable location since replacing a variable-location operand
318/// can also replace the address. Stop when a checked variable location cannot
319/// be salvaged. A matching address counts as processed even if salvage leaves
320/// it unchanged. If nothing was processed, call setKillLocation() on every
321/// supplied record.
322LLVM_ABI void
325
326/// Given an instruction \p I and DIExpression \p DIExpr operating on
327/// it, append the effects of \p I to the DIExpression operand list
328/// \p Ops, or return \p nullptr if it cannot be salvaged.
329/// \p CurrentLocOps is the number of SSA values referenced by the
330/// incoming \p Ops. \return the first non-constant operand
331/// implicitly referred to by Ops. If \p I references more than one
332/// non-constant operand, any additional operands are added to
333/// \p AdditionalValues.
334///
335/// \example
336////
337/// I = add %a, i32 1
338///
339/// Return = %a
340/// Ops = llvm::dwarf::DW_OP_lit1 llvm::dwarf::DW_OP_add
341///
342/// I = add %a, %b
343///
344/// Return = %a
345/// Ops = llvm::dwarf::DW_OP_LLVM_arg0 llvm::dwarf::DW_OP_add
346/// AdditionalValues = %b
347LLVM_ABI Value *
348salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
349 SmallVectorImpl<uint64_t> &Ops,
350 SmallVectorImpl<Value *> &AdditionalValues);
351
352/// Point debug users of \p From to \p To or salvage them. Use this function
353/// only when replacing all uses of \p From with \p To, with a guarantee that
354/// \p From is going to be deleted.
355///
356/// Follow these rules to prevent use-before-def of \p To:
357/// . If \p To is a linked Instruction, set \p DomPoint to \p To.
358/// . If \p To is an unlinked Instruction, set \p DomPoint to the Instruction
359/// \p To will be inserted after.
360/// . If \p To is not an Instruction (e.g a Constant), the choice of
361/// \p DomPoint is arbitrary. Pick \p From for simplicity.
362///
363/// If a debug user cannot be preserved without reordering variable updates or
364/// introducing a use-before-def, it is either salvaged (\ref salvageDebugInfo)
365/// or deleted. Returns true if any debug users were updated.
366LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To,
367 Instruction &DomPoint, DominatorTree &DT);
368
369/// If a terminator in an unreachable basic block has an operand of type
370/// Instruction, transform it into poison. Return true if any operands
371/// are changed to poison. Original Values prior to being changed to poison
372/// are returned in \p PoisonedValues.
373LLVM_ABI bool
374handleUnreachableTerminator(Instruction *I,
375 SmallVectorImpl<Value *> &PoisonedValues);
376
377/// Remove all instructions from a basic block other than its terminator
378/// and any present EH pad instructions. Returns the number of instructions
379/// that have been removed.
381
382/// Insert an unreachable instruction before the specified
383/// instruction, making it and the rest of the code in the block dead.
384LLVM_ABI unsigned changeToUnreachable(Instruction *I,
385 bool PreserveLCSSA = false,
386 DomTreeUpdater *DTU = nullptr,
387 MemorySSAUpdater *MSSAU = nullptr);
388
389/// Convert the CallInst to InvokeInst with the specified unwind edge basic
390/// block. This also splits the basic block where CI is located, because
391/// InvokeInst is a terminator instruction. Returns the newly split basic
392/// block.
393LLVM_ABI BasicBlock *
394changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge,
395 DomTreeUpdater *DTU = nullptr);
396
397/// Replace 'BB's terminator with one that does not have an unwind successor
398/// block. Rewrites `invoke` to `call`, etc. Updates any PHIs in unwind
399/// successor. Returns the instruction that replaced the original terminator,
400/// which might be a call in case the original terminator was an invoke.
401///
402/// \param BB Block whose terminator will be replaced. Its terminator must
403/// have an unwind successor.
404LLVM_ABI Instruction *removeUnwindEdge(BasicBlock *BB,
405 DomTreeUpdater *DTU = nullptr);
406
407/// Remove all blocks that can not be reached from the function's entry.
408/// When \p FoldInstsToUnreachable is true, it will also convert obviously
409/// unreachable instructions into unreachable (e.g, store to null).
410///
411/// Returns true if any basic block was removed or any instruction was folded.
413 DomTreeUpdater *DTU = nullptr,
414 MemorySSAUpdater *MSSAU = nullptr,
415 bool FoldInstsToUnreachable = true);
416
417/// Combine the metadata of two instructions so that K can replace J. This
418/// specifically handles the case of CSE-like transformations. Some
419/// metadata can only be kept if K dominates J. For this to be correct,
420/// K cannot be hoisted.
421///
422/// Unknown metadata is removed.
423LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J,
424 bool DoesKMove);
425
426/// Combine metadata of two instructions, where instruction J is a memory
427/// access that has been merged into K. This will intersect alias-analysis
428/// metadata, while preserving other known metadata.
429LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J);
430
431/// Copy the metadata from the source instruction to the destination (the
432/// replacement for the source instruction).
433LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source);
434
435/// Patch the replacement so that it is not more restrictive than the value
436/// being replaced. Unless DoesKMove is set, it assumes that the replacement
437/// does not get moved from its original position.
438LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl,
439 bool DoesKMove = false);
440
441// Replace each use of 'From' with 'To', if that use does not belong to basic
442// block where 'From' is defined. Returns the number of replacements made.
443LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To);
444
445/// Replace each use of 'From' with 'To' if that use is dominated by
446/// the given edge. Returns the number of replacements made.
447LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
448 DominatorTree &DT,
449 const BasicBlockEdge &Edge);
450/// Replace each use of 'From' with 'To' if that use is dominated by
451/// the end of the given BasicBlock. Returns the number of replacements made.
452LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
453 DominatorTree &DT,
454 const BasicBlock *BB);
455/// Replace each use of 'From' with 'To' if that use is dominated by the
456/// given instruction. Returns the number of replacements made.
457LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
458 DominatorTree &DT,
459 const Instruction *I);
460/// Replace each use of 'From' with 'To' if that use is dominated by
461/// the given edge and the callback ShouldReplace returns true. Returns the
462/// number of replacements made.
464 Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge,
465 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
466/// Replace each use of 'From' with 'To' if that use is dominated by
467/// the end of the given BasicBlock and the callback ShouldReplace returns true.
468/// Returns the number of replacements made.
470 Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
471 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
472/// Replace each use of 'From' with 'To' if that use is dominated by
473/// the given instruction and the callback ShouldReplace returns true. Returns
474/// the number of replacements made.
476 Value *From, Value *To, DominatorTree &DT, const Instruction *I,
477 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
478
479/// Return true if this call calls a gc leaf function.
480///
481/// A leaf function is a function that does not safepoint the thread during its
482/// execution. During a call or invoke to such a function, the callers stack
483/// does not have to be made parseable.
484///
485/// Most passes can and should ignore this information, and it is only used
486/// during lowering by the GC infrastructure.
487LLVM_ABI bool callsGCLeafFunction(const CallBase *Call,
488 const TargetLibraryInfo &TLI);
489
490/// Copy a nonnull metadata node to a new load instruction.
491///
492/// This handles mapping it to range metadata if the new load is an integer
493/// load instead of a pointer load.
494LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
495 LoadInst &NewLI);
496
497/// Copy a range metadata node to a new load instruction.
498///
499/// This handles mapping it to nonnull metadata if the new load is a pointer
500/// load instead of an integer load and the range doesn't cover null.
501LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
502 MDNode *N, LoadInst &NewLI);
503
504/// Remove the debug intrinsic instructions for the given instruction.
505LLVM_ABI void dropDebugUsers(Instruction &I);
506
507/// Hoist all of the instructions in the \p IfBlock to the dominant block
508/// \p DomBlock, by moving its instructions to the insertion point \p InsertPt.
509///
510/// The moved instructions receive the insertion point debug location values
511/// (DILocations) and their debug intrinsic instructions are removed.
512LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock,
513 Instruction *InsertPt, BasicBlock *BB);
514
515/// Given a constant, create a debug information expression.
516LLVM_ABI DIExpression *getExpressionForConstant(DIBuilder &DIB,
517 const Constant &C, Type &Ty);
518
519/// Remap the operands of the debug records attached to \p Inst, and the
520/// operands of \p Inst itself if it's a debug intrinsic.
521LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst);
522
523//===----------------------------------------------------------------------===//
524// Intrinsic pattern matching
525//
526
527/// Try to match a bswap or bitreverse idiom.
528///
529/// If an idiom is matched, an intrinsic call is inserted before \c I. Any added
530/// instructions are returned in \c InsertedInsts. They will all have been added
531/// to a basic block.
532///
533/// A bitreverse idiom normally requires around 2*BW nodes to be searched (where
534/// BW is the bitwidth of the integer type). A bswap idiom requires anywhere up
535/// to BW / 4 nodes to be searched, so is significantly faster.
536///
537/// This function returns true on a successful match or false otherwise.
538LLVM_ABI bool
539recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps,
540 bool MatchBitReversals,
541 SmallVectorImpl<Instruction *> &InsertedInsts);
542
543//===----------------------------------------------------------------------===//
544// Sanitizer utilities
545//
546
547/// Given a CallInst, check if it calls a string function known to CodeGen,
548/// and mark it with NoBuiltin if so. To be used by sanitizers that intend
549/// to intercept string functions and want to avoid converting them to target
550/// specific instructions.
551LLVM_ABI void
553 const TargetLibraryInfo *TLI);
554
555//===----------------------------------------------------------------------===//
556// Transform predicates
557//
558
559/// Given an instruction, is it legal to set operand OpIdx to a non-constant
560/// value?
561LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I,
562 unsigned OpIdx);
563
564//===----------------------------------------------------------------------===//
565// Value helper functions
566//
567
568/// Invert the given true/false value, possibly reusing an existing copy.
569LLVM_ABI Value *invertCondition(Value *Condition);
570
571/// Move \p FI right after the definition of its operand, and replace the uses
572/// of the operand that it dominates with \p FI. Users whose operand was
573/// replaced are added to \p Users. Returns whether anything changed, which is
574/// not the case if there is no position to move \p FI to.
575LLVM_ABI bool freezeUsesAfterDef(FreezeInst &FI, DominatorTree &DT,
576 SmallVectorImpl<User *> *Users = nullptr);
577
578//===----------------------------------------------------------------------===//
579// Assorted
580//
581
582/// If we can infer one attribute from another on the declaration of a
583/// function, explicitly materialize the maximal set in the IR.
585
586//===----------------------------------------------------------------------===//
587// Helpers to track and update flags on instructions.
588//
589
591 bool HasNUW = true;
592 bool HasNSW = true;
593 bool IsDisjoint = true;
594
595#ifndef NDEBUG
596 /// Opcode of merged instructions. All instructions passed to mergeFlags must
597 /// have the same opcode.
598 std::optional<unsigned> Opcode;
599#endif
600
601 // Note: At the moment, users are responsible to manage AllKnownNonNegative
602 // and AllKnownNonZero manually. AllKnownNonNegative can be true in a case
603 // where one of the operands is negative, but one the operators is not NSW.
604 // AllKnownNonNegative should not be used independently of HasNSW
606 bool AllKnownNonZero = true;
607
608 OverflowTracking() = default;
609
610 /// Merge in the no-wrap flags from \p I.
612
613 /// Apply the no-wrap flags to \p I if applicable.
615};
616
617} // end namespace llvm
618
619#endif // LLVM_TRANSFORMS_UTILS_LOCAL_H
const TargetLowering & TLI
uint64_t uint64_t
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
Conditional Branch instruction.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This class represents a freeze function that returns random concrete value if an operand is either a ...
Invoke instruction.
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1087
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
Value handle that is nullable, but tries to track the Value.
A nullable Value handle that is nullable.
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
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:2564
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
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:2681
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 bool FlattenCFG(BasicBlock *BB, AAResults *AA=nullptr)
This function is used to flatten a CFG.
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:3360
LLVM_ABI bool freezeUsesAfterDef(FreezeInst &FI, DominatorTree &DT, SmallVectorImpl< User * > *Users=nullptr)
Move FI right after the definition of its operand, and replace the uses of the operand that it domina...
Definition Local.cpp:4096
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:1607
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Definition Local.cpp:3324
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:1837
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition Local.cpp:2657
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:3195
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition Local.cpp:1752
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:3555
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 void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition Local.cpp:1949
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:2547
LLVM_ABI AllocaInst * DemoteRegToStack(Instruction &X, bool VolatileLoads=false, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by an Instruction and replaces it with a slot in the ...
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:2961
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 AllocaInst * DemotePHIToStack(PHINode *P, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by a phi node and replaces it with a slot in the stac...
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:1185
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3860
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
Definition Local.cpp:1865
LLVM_ABI DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
Definition Local.cpp:3513
LLVM_ABI CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
Definition Local.cpp:2632
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:2170
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:1703
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:2923
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl, bool DoesKMove=false)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition Local.cpp:3259
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 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:3339
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:2592
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:2493
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2353
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:3186
LLVM_ABI void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
Definition Local.cpp:3460
TargetTransformInfo TTI
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 cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
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:3467
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:3436
LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
Definition Local.cpp:3411
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:3973
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:2052
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:1558
ArrayRef(const T &OneElt) -> ArrayRef< T >
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
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:241
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:3191
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:4136
LLVM_ABI Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
Definition Local.cpp:4062
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:3964
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1550
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
Definition Local.cpp:3387
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:2012
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
std::optional< unsigned > Opcode
Opcode of merged instructions.
Definition Local.h:598
LLVM_ABI void mergeFlags(Instruction &I)
Merge in the no-wrap flags from I.
Definition Local.cpp:4166
LLVM_ABI void applyFlags(Instruction &I)
Apply the no-wrap flags to I if applicable.
Definition Local.cpp:4182