Cloning.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Cloning.h - Clone various parts of LLVM programs ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines various functions that are used to clone chunks of LLVM
  15. // code for various purposes. This varies from copying whole modules into new
  16. // modules, to cloning functions with different arguments, to inlining
  17. // functions, to copying basic blocks to support loop unrolling or superblock
  18. // formation, etc.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_TRANSFORMS_UTILS_CLONING_H
  22. #define LLVM_TRANSFORMS_UTILS_CLONING_H
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Analysis/AssumptionCache.h"
  26. #include "llvm/Analysis/InlineCost.h"
  27. #include "llvm/IR/ValueHandle.h"
  28. #include "llvm/Transforms/Utils/ValueMapper.h"
  29. #include <functional>
  30. #include <memory>
  31. #include <vector>
  32. namespace llvm {
  33. class AAResults;
  34. class AllocaInst;
  35. class BasicBlock;
  36. class BlockFrequencyInfo;
  37. class CallInst;
  38. class CallGraph;
  39. class DebugInfoFinder;
  40. class DominatorTree;
  41. class Function;
  42. class Instruction;
  43. class InvokeInst;
  44. class Loop;
  45. class LoopInfo;
  46. class Module;
  47. class ProfileSummaryInfo;
  48. class ReturnInst;
  49. class DomTreeUpdater;
  50. /// Return an exact copy of the specified module
  51. std::unique_ptr<Module> CloneModule(const Module &M);
  52. std::unique_ptr<Module> CloneModule(const Module &M, ValueToValueMapTy &VMap);
  53. /// Return a copy of the specified module. The ShouldCloneDefinition function
  54. /// controls whether a specific GlobalValue's definition is cloned. If the
  55. /// function returns false, the module copy will contain an external reference
  56. /// in place of the global definition.
  57. std::unique_ptr<Module>
  58. CloneModule(const Module &M, ValueToValueMapTy &VMap,
  59. function_ref<bool(const GlobalValue *)> ShouldCloneDefinition);
  60. /// This struct can be used to capture information about code
  61. /// being cloned, while it is being cloned.
  62. struct ClonedCodeInfo {
  63. /// This is set to true if the cloned code contains a normal call instruction.
  64. bool ContainsCalls = false;
  65. /// This is set to true if the cloned code contains a 'dynamic' alloca.
  66. /// Dynamic allocas are allocas that are either not in the entry block or they
  67. /// are in the entry block but are not a constant size.
  68. bool ContainsDynamicAllocas = false;
  69. /// All cloned call sites that have operand bundles attached are appended to
  70. /// this vector. This vector may contain nulls or undefs if some of the
  71. /// originally inserted callsites were DCE'ed after they were cloned.
  72. std::vector<WeakTrackingVH> OperandBundleCallSites;
  73. ClonedCodeInfo() = default;
  74. };
  75. /// Return a copy of the specified basic block, but without
  76. /// embedding the block into a particular function. The block returned is an
  77. /// exact copy of the specified basic block, without any remapping having been
  78. /// performed. Because of this, this is only suitable for applications where
  79. /// the basic block will be inserted into the same function that it was cloned
  80. /// from (loop unrolling would use this, for example).
  81. ///
  82. /// Also, note that this function makes a direct copy of the basic block, and
  83. /// can thus produce illegal LLVM code. In particular, it will copy any PHI
  84. /// nodes from the original block, even though there are no predecessors for the
  85. /// newly cloned block (thus, phi nodes will have to be updated). Also, this
  86. /// block will branch to the old successors of the original block: these
  87. /// successors will have to have any PHI nodes updated to account for the new
  88. /// incoming edges.
  89. ///
  90. /// The correlation between instructions in the source and result basic blocks
  91. /// is recorded in the VMap map.
  92. ///
  93. /// If you have a particular suffix you'd like to use to add to any cloned
  94. /// names, specify it as the optional third parameter.
  95. ///
  96. /// If you would like the basic block to be auto-inserted into the end of a
  97. /// function, you can specify it as the optional fourth parameter.
  98. ///
  99. /// If you would like to collect additional information about the cloned
  100. /// function, you can specify a ClonedCodeInfo object with the optional fifth
  101. /// parameter.
  102. BasicBlock *CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
  103. const Twine &NameSuffix = "", Function *F = nullptr,
  104. ClonedCodeInfo *CodeInfo = nullptr,
  105. DebugInfoFinder *DIFinder = nullptr);
  106. /// Return a copy of the specified function and add it to that
  107. /// function's module. Also, any references specified in the VMap are changed
  108. /// to refer to their mapped value instead of the original one. If any of the
  109. /// arguments to the function are in the VMap, the arguments are deleted from
  110. /// the resultant function. The VMap is updated to include mappings from all of
  111. /// the instructions and basicblocks in the function from their old to new
  112. /// values. The final argument captures information about the cloned code if
  113. /// non-null.
  114. ///
  115. /// VMap contains no non-identity GlobalValue mappings and debug info metadata
  116. /// will not be cloned.
  117. ///
  118. Function *CloneFunction(Function *F, ValueToValueMapTy &VMap,
  119. ClonedCodeInfo *CodeInfo = nullptr);
  120. /// Clone OldFunc into NewFunc, transforming the old arguments into references
  121. /// to VMap values. Note that if NewFunc already has basic blocks, the ones
  122. /// cloned into it will be added to the end of the function. This function
  123. /// fills in a list of return instructions, and can optionally remap types
  124. /// and/or append the specified suffix to all values cloned.
  125. ///
  126. /// If ModuleLevelChanges is false, VMap contains no non-identity GlobalValue
  127. /// mappings.
  128. ///
  129. void CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
  130. ValueToValueMapTy &VMap, bool ModuleLevelChanges,
  131. SmallVectorImpl<ReturnInst*> &Returns,
  132. const char *NameSuffix = "",
  133. ClonedCodeInfo *CodeInfo = nullptr,
  134. ValueMapTypeRemapper *TypeMapper = nullptr,
  135. ValueMaterializer *Materializer = nullptr);
  136. void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
  137. const Instruction *StartingInst,
  138. ValueToValueMapTy &VMap, bool ModuleLevelChanges,
  139. SmallVectorImpl<ReturnInst *> &Returns,
  140. const char *NameSuffix = "",
  141. ClonedCodeInfo *CodeInfo = nullptr);
  142. /// This works exactly like CloneFunctionInto,
  143. /// except that it does some simple constant prop and DCE on the fly. The
  144. /// effect of this is to copy significantly less code in cases where (for
  145. /// example) a function call with constant arguments is inlined, and those
  146. /// constant arguments cause a significant amount of code in the callee to be
  147. /// dead. Since this doesn't produce an exactly copy of the input, it can't be
  148. /// used for things like CloneFunction or CloneModule.
  149. ///
  150. /// If ModuleLevelChanges is false, VMap contains no non-identity GlobalValue
  151. /// mappings.
  152. ///
  153. void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
  154. ValueToValueMapTy &VMap, bool ModuleLevelChanges,
  155. SmallVectorImpl<ReturnInst*> &Returns,
  156. const char *NameSuffix = "",
  157. ClonedCodeInfo *CodeInfo = nullptr,
  158. Instruction *TheCall = nullptr);
  159. /// This class captures the data input to the InlineFunction call, and records
  160. /// the auxiliary results produced by it.
  161. class InlineFunctionInfo {
  162. public:
  163. explicit InlineFunctionInfo(
  164. CallGraph *cg = nullptr,
  165. function_ref<AssumptionCache &(Function &)> GetAssumptionCache = nullptr,
  166. ProfileSummaryInfo *PSI = nullptr,
  167. BlockFrequencyInfo *CallerBFI = nullptr,
  168. BlockFrequencyInfo *CalleeBFI = nullptr)
  169. : CG(cg), GetAssumptionCache(GetAssumptionCache), PSI(PSI),
  170. CallerBFI(CallerBFI), CalleeBFI(CalleeBFI) {}
  171. /// If non-null, InlineFunction will update the callgraph to reflect the
  172. /// changes it makes.
  173. CallGraph *CG;
  174. function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
  175. ProfileSummaryInfo *PSI;
  176. BlockFrequencyInfo *CallerBFI, *CalleeBFI;
  177. /// InlineFunction fills this in with all static allocas that get copied into
  178. /// the caller.
  179. SmallVector<AllocaInst *, 4> StaticAllocas;
  180. /// InlineFunction fills this in with callsites that were inlined from the
  181. /// callee. This is only filled in if CG is non-null.
  182. SmallVector<WeakTrackingVH, 8> InlinedCalls;
  183. /// All of the new call sites inlined into the caller.
  184. ///
  185. /// 'InlineFunction' fills this in by scanning the inlined instructions, and
  186. /// only if CG is null. If CG is non-null, instead the value handle
  187. /// `InlinedCalls` above is used.
  188. SmallVector<CallBase *, 8> InlinedCallSites;
  189. void reset() {
  190. StaticAllocas.clear();
  191. InlinedCalls.clear();
  192. InlinedCallSites.clear();
  193. }
  194. };
  195. /// This function inlines the called function into the basic
  196. /// block of the caller. This returns false if it is not possible to inline
  197. /// this call. The program is still in a well defined state if this occurs
  198. /// though.
  199. ///
  200. /// Note that this only does one level of inlining. For example, if the
  201. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  202. /// exists in the instruction stream. Similarly this will inline a recursive
  203. /// function by one level.
  204. ///
  205. /// Note that while this routine is allowed to cleanup and optimize the
  206. /// *inlined* code to minimize the actual inserted code, it must not delete
  207. /// code in the caller as users of this routine may have pointers to
  208. /// instructions in the caller that need to remain stable.
  209. ///
  210. /// If ForwardVarArgsTo is passed, inlining a function with varargs is allowed
  211. /// and all varargs at the callsite will be passed to any calls to
  212. /// ForwardVarArgsTo. The caller of InlineFunction has to make sure any varargs
  213. /// are only used by ForwardVarArgsTo.
  214. InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
  215. AAResults *CalleeAAR = nullptr,
  216. bool InsertLifetime = true,
  217. Function *ForwardVarArgsTo = nullptr);
  218. /// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
  219. /// Blocks.
  220. ///
  221. /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
  222. /// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
  223. /// Note: Only innermost loops are supported.
  224. Loop *cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
  225. Loop *OrigLoop, ValueToValueMapTy &VMap,
  226. const Twine &NameSuffix, LoopInfo *LI,
  227. DominatorTree *DT,
  228. SmallVectorImpl<BasicBlock *> &Blocks);
  229. /// Remaps instructions in \p Blocks using the mapping in \p VMap.
  230. void remapInstructionsInBlocks(const SmallVectorImpl<BasicBlock *> &Blocks,
  231. ValueToValueMapTy &VMap);
  232. /// Split edge between BB and PredBB and duplicate all non-Phi instructions
  233. /// from BB between its beginning and the StopAt instruction into the split
  234. /// block. Phi nodes are not duplicated, but their uses are handled correctly:
  235. /// we replace them with the uses of corresponding Phi inputs. ValueMapping
  236. /// is used to map the original instructions from BB to their newly-created
  237. /// copies. Returns the split block.
  238. BasicBlock *DuplicateInstructionsInSplitBetween(BasicBlock *BB,
  239. BasicBlock *PredBB,
  240. Instruction *StopAt,
  241. ValueToValueMapTy &ValueMapping,
  242. DomTreeUpdater &DTU);
  243. /// Updates profile information by adjusting the entry count by adding
  244. /// entryDelta then scaling callsite information by the new count divided by the
  245. /// old count. VMap is used during inlinng to also update the new clone
  246. void updateProfileCallee(
  247. Function *Callee, int64_t entryDelta,
  248. const ValueMap<const Value *, WeakTrackingVH> *VMap = nullptr);
  249. /// Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified
  250. /// basic blocks and extract their scope. These are candidates for duplication
  251. /// when cloning.
  252. void identifyNoAliasScopesToClone(
  253. ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes);
  254. /// Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified
  255. /// instruction range and extract their scope. These are candidates for
  256. /// duplication when cloning.
  257. void identifyNoAliasScopesToClone(
  258. BasicBlock::iterator Start, BasicBlock::iterator End,
  259. SmallVectorImpl<MDNode *> &NoAliasDeclScopes);
  260. /// Duplicate the specified list of noalias decl scopes.
  261. /// The 'Ext' string is added as an extension to the name.
  262. /// Afterwards, the ClonedScopes contains the mapping of the original scope
  263. /// MDNode onto the cloned scope.
  264. /// Be aware that the cloned scopes are still part of the original scope domain.
  265. void cloneNoAliasScopes(
  266. ArrayRef<MDNode *> NoAliasDeclScopes,
  267. DenseMap<MDNode *, MDNode *> &ClonedScopes,
  268. StringRef Ext, LLVMContext &Context);
  269. /// Adapt the metadata for the specified instruction according to the
  270. /// provided mapping. This is normally used after cloning an instruction, when
  271. /// some noalias scopes needed to be cloned.
  272. void adaptNoAliasScopes(
  273. llvm::Instruction *I, const DenseMap<MDNode *, MDNode *> &ClonedScopes,
  274. LLVMContext &Context);
  275. /// Clone the specified noalias decl scopes. Then adapt all instructions in the
  276. /// NewBlocks basicblocks to the cloned versions.
  277. /// 'Ext' will be added to the duplicate scope names.
  278. void cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
  279. ArrayRef<BasicBlock *> NewBlocks,
  280. LLVMContext &Context, StringRef Ext);
  281. /// Clone the specified noalias decl scopes. Then adapt all instructions in the
  282. /// [IStart, IEnd] (IEnd included !) range to the cloned versions. 'Ext' will be
  283. /// added to the duplicate scope names.
  284. void cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
  285. Instruction *IStart, Instruction *IEnd,
  286. LLVMContext &Context, StringRef Ext);
  287. } // end namespace llvm
  288. #endif // LLVM_TRANSFORMS_UTILS_CLONING_H
  289. #ifdef __GNUC__
  290. #pragma GCC diagnostic pop
  291. #endif