ValueMapper.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the MapValue function, which is shared by various parts of
  11. // the lib/Transforms/Utils library.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/ValueMapper.h"
  15. #include "llvm/IR/CallSite.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Function.h"
  18. #include "llvm/IR/InlineAsm.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/Metadata.h"
  21. using namespace llvm;
  22. // Out of line method to get vtable etc for class.
  23. void ValueMapTypeRemapper::anchor() {}
  24. void ValueMaterializer::anchor() {}
  25. Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
  26. ValueMapTypeRemapper *TypeMapper,
  27. ValueMaterializer *Materializer) {
  28. ValueToValueMapTy::iterator I = VM.find(V);
  29. // If the value already exists in the map, use it.
  30. if (I != VM.end() && I->second) return I->second;
  31. // If we have a materializer and it can materialize a value, use that.
  32. if (Materializer) {
  33. if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
  34. return VM[V] = NewV;
  35. }
  36. // Global values do not need to be seeded into the VM if they
  37. // are using the identity mapping.
  38. if (isa<GlobalValue>(V))
  39. return VM[V] = const_cast<Value*>(V);
  40. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  41. // Inline asm may need *type* remapping.
  42. FunctionType *NewTy = IA->getFunctionType();
  43. if (TypeMapper) {
  44. NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
  45. if (NewTy != IA->getFunctionType())
  46. V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
  47. IA->hasSideEffects(), IA->isAlignStack());
  48. }
  49. return VM[V] = const_cast<Value*>(V);
  50. }
  51. if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
  52. const Metadata *MD = MDV->getMetadata();
  53. // If this is a module-level metadata and we know that nothing at the module
  54. // level is changing, then use an identity mapping.
  55. if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
  56. return VM[V] = const_cast<Value *>(V);
  57. auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
  58. if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
  59. return VM[V] = const_cast<Value *>(V);
  60. // FIXME: This assert crashes during bootstrap, but I think it should be
  61. // correct. For now, just match behaviour from before the metadata/value
  62. // split.
  63. //
  64. // assert(MappedMD && "Referenced metadata value not in value map");
  65. return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
  66. }
  67. // Okay, this either must be a constant (which may or may not be mappable) or
  68. // is something that is not in the mapping table.
  69. Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
  70. if (!C)
  71. return nullptr;
  72. if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  73. Function *F =
  74. cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
  75. BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
  76. Flags, TypeMapper, Materializer));
  77. return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
  78. }
  79. // Otherwise, we have some other constant to remap. Start by checking to see
  80. // if all operands have an identity remapping.
  81. unsigned OpNo = 0, NumOperands = C->getNumOperands();
  82. Value *Mapped = nullptr;
  83. for (; OpNo != NumOperands; ++OpNo) {
  84. Value *Op = C->getOperand(OpNo);
  85. Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
  86. if (Mapped != C) break;
  87. }
  88. // See if the type mapper wants to remap the type as well.
  89. Type *NewTy = C->getType();
  90. if (TypeMapper)
  91. NewTy = TypeMapper->remapType(NewTy);
  92. // If the result type and all operands match up, then just insert an identity
  93. // mapping.
  94. if (OpNo == NumOperands && NewTy == C->getType())
  95. return VM[V] = C;
  96. // Okay, we need to create a new constant. We've already processed some or
  97. // all of the operands, set them all up now.
  98. SmallVector<Constant*, 8> Ops;
  99. Ops.reserve(NumOperands);
  100. for (unsigned j = 0; j != OpNo; ++j)
  101. Ops.push_back(cast<Constant>(C->getOperand(j)));
  102. // If one of the operands mismatch, push it and the other mapped operands.
  103. if (OpNo != NumOperands) {
  104. Ops.push_back(cast<Constant>(Mapped));
  105. // Map the rest of the operands that aren't processed yet.
  106. for (++OpNo; OpNo != NumOperands; ++OpNo)
  107. Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
  108. Flags, TypeMapper, Materializer));
  109. }
  110. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
  111. return VM[V] = CE->getWithOperands(Ops, NewTy);
  112. if (isa<ConstantArray>(C))
  113. return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
  114. if (isa<ConstantStruct>(C))
  115. return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
  116. if (isa<ConstantVector>(C))
  117. return VM[V] = ConstantVector::get(Ops);
  118. // If this is a no-operand constant, it must be because the type was remapped.
  119. if (isa<UndefValue>(C))
  120. return VM[V] = UndefValue::get(NewTy);
  121. if (isa<ConstantAggregateZero>(C))
  122. return VM[V] = ConstantAggregateZero::get(NewTy);
  123. assert(isa<ConstantPointerNull>(C));
  124. return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
  125. }
  126. static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
  127. Metadata *Val) {
  128. VM.MD()[Key].reset(Val);
  129. return Val;
  130. }
  131. static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
  132. return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
  133. }
  134. static Metadata *MapMetadataImpl(const Metadata *MD,
  135. SmallVectorImpl<MDNode *> &Cycles,
  136. ValueToValueMapTy &VM, RemapFlags Flags,
  137. ValueMapTypeRemapper *TypeMapper,
  138. ValueMaterializer *Materializer);
  139. static Metadata *mapMetadataOp(Metadata *Op, SmallVectorImpl<MDNode *> &Cycles,
  140. ValueToValueMapTy &VM, RemapFlags Flags,
  141. ValueMapTypeRemapper *TypeMapper,
  142. ValueMaterializer *Materializer) {
  143. if (!Op)
  144. return nullptr;
  145. if (Metadata *MappedOp =
  146. MapMetadataImpl(Op, Cycles, VM, Flags, TypeMapper, Materializer))
  147. return MappedOp;
  148. // Use identity map if MappedOp is null and we can ignore missing entries.
  149. if (Flags & RF_IgnoreMissingEntries)
  150. return Op;
  151. // FIXME: This assert crashes during bootstrap, but I think it should be
  152. // correct. For now, just match behaviour from before the metadata/value
  153. // split.
  154. //
  155. // llvm_unreachable("Referenced metadata not in value map!");
  156. return nullptr;
  157. }
  158. /// \brief Remap nodes.
  159. ///
  160. /// Insert \c NewNode in the value map, and then remap \c OldNode's operands.
  161. /// Assumes that \c NewNode is already a clone of \c OldNode.
  162. ///
  163. /// \pre \c NewNode is a clone of \c OldNode.
  164. static bool remap(const MDNode *OldNode, MDNode *NewNode,
  165. SmallVectorImpl<MDNode *> &Cycles, ValueToValueMapTy &VM,
  166. RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
  167. ValueMaterializer *Materializer) {
  168. assert(OldNode->getNumOperands() == NewNode->getNumOperands() &&
  169. "Expected nodes to match");
  170. assert(OldNode->isResolved() && "Expected resolved node");
  171. assert(!NewNode->isUniqued() && "Expected non-uniqued node");
  172. // Map the node upfront so it's available for cyclic references.
  173. mapToMetadata(VM, OldNode, NewNode);
  174. bool AnyChanged = false;
  175. for (unsigned I = 0, E = OldNode->getNumOperands(); I != E; ++I) {
  176. Metadata *Old = OldNode->getOperand(I);
  177. assert(NewNode->getOperand(I) == Old &&
  178. "Expected old operands to already be in place");
  179. Metadata *New = mapMetadataOp(OldNode->getOperand(I), Cycles, VM, Flags,
  180. TypeMapper, Materializer);
  181. if (Old != New) {
  182. AnyChanged = true;
  183. NewNode->replaceOperandWith(I, New);
  184. }
  185. }
  186. return AnyChanged;
  187. }
  188. /// \brief Map a distinct MDNode.
  189. ///
  190. /// Distinct nodes are not uniqued, so they must always recreated.
  191. static Metadata *mapDistinctNode(const MDNode *Node,
  192. SmallVectorImpl<MDNode *> &Cycles,
  193. ValueToValueMapTy &VM, RemapFlags Flags,
  194. ValueMapTypeRemapper *TypeMapper,
  195. ValueMaterializer *Materializer) {
  196. assert(Node->isDistinct() && "Expected distinct node");
  197. MDNode *NewMD = MDNode::replaceWithDistinct(Node->clone());
  198. remap(Node, NewMD, Cycles, VM, Flags, TypeMapper, Materializer);
  199. // Track any cycles beneath this node.
  200. for (Metadata *Op : NewMD->operands())
  201. if (auto *Node = dyn_cast_or_null<MDNode>(Op))
  202. if (!Node->isResolved())
  203. Cycles.push_back(Node);
  204. return NewMD;
  205. }
  206. /// \brief Map a uniqued MDNode.
  207. ///
  208. /// Uniqued nodes may not need to be recreated (they may map to themselves).
  209. static Metadata *mapUniquedNode(const MDNode *Node,
  210. SmallVectorImpl<MDNode *> &Cycles,
  211. ValueToValueMapTy &VM, RemapFlags Flags,
  212. ValueMapTypeRemapper *TypeMapper,
  213. ValueMaterializer *Materializer) {
  214. assert(Node->isUniqued() && "Expected uniqued node");
  215. // Create a temporary node upfront in case we have a metadata cycle.
  216. auto ClonedMD = Node->clone();
  217. if (!remap(Node, ClonedMD.get(), Cycles, VM, Flags, TypeMapper, Materializer))
  218. // No operands changed, so use the identity mapping.
  219. return mapToSelf(VM, Node);
  220. // At least one operand has changed, so uniquify the cloned node.
  221. return mapToMetadata(VM, Node,
  222. MDNode::replaceWithUniqued(std::move(ClonedMD)));
  223. }
  224. static Metadata *MapMetadataImpl(const Metadata *MD,
  225. SmallVectorImpl<MDNode *> &Cycles,
  226. ValueToValueMapTy &VM, RemapFlags Flags,
  227. ValueMapTypeRemapper *TypeMapper,
  228. ValueMaterializer *Materializer) {
  229. // If the value already exists in the map, use it.
  230. if (Metadata *NewMD = VM.MD().lookup(MD).get())
  231. return NewMD;
  232. if (isa<MDString>(MD))
  233. return mapToSelf(VM, MD);
  234. if (isa<ConstantAsMetadata>(MD))
  235. if ((Flags & RF_NoModuleLevelChanges))
  236. return mapToSelf(VM, MD);
  237. if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
  238. Value *MappedV =
  239. MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
  240. if (VMD->getValue() == MappedV ||
  241. (!MappedV && (Flags & RF_IgnoreMissingEntries)))
  242. return mapToSelf(VM, MD);
  243. // FIXME: This assert crashes during bootstrap, but I think it should be
  244. // correct. For now, just match behaviour from before the metadata/value
  245. // split.
  246. //
  247. // assert(MappedV && "Referenced metadata not in value map!");
  248. if (MappedV)
  249. return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
  250. return nullptr;
  251. }
  252. // Note: this cast precedes the Flags check so we always get its associated
  253. // assertion.
  254. const MDNode *Node = cast<MDNode>(MD);
  255. // If this is a module-level metadata and we know that nothing at the
  256. // module level is changing, then use an identity mapping.
  257. if (Flags & RF_NoModuleLevelChanges)
  258. return mapToSelf(VM, MD);
  259. // Require resolved nodes whenever metadata might be remapped.
  260. assert(Node->isResolved() && "Unexpected unresolved node");
  261. if (Node->isDistinct())
  262. return mapDistinctNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
  263. return mapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
  264. }
  265. Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
  266. RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
  267. ValueMaterializer *Materializer) {
  268. SmallVector<MDNode *, 8> Cycles;
  269. Metadata *NewMD =
  270. MapMetadataImpl(MD, Cycles, VM, Flags, TypeMapper, Materializer);
  271. // Resolve cycles underneath MD.
  272. if (NewMD && NewMD != MD) {
  273. if (auto *N = dyn_cast<MDNode>(NewMD))
  274. if (!N->isResolved())
  275. N->resolveCycles();
  276. for (MDNode *N : Cycles)
  277. if (!N->isResolved())
  278. N->resolveCycles();
  279. } else {
  280. // Shouldn't get unresolved cycles if nothing was remapped.
  281. assert(Cycles.empty() && "Expected no unresolved cycles");
  282. }
  283. return NewMD;
  284. }
  285. MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
  286. RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
  287. ValueMaterializer *Materializer) {
  288. return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
  289. TypeMapper, Materializer));
  290. }
  291. /// RemapInstruction - Convert the instruction operands from referencing the
  292. /// current values into those specified by VMap.
  293. ///
  294. void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
  295. RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
  296. ValueMaterializer *Materializer){
  297. // Remap operands.
  298. for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
  299. Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
  300. // If we aren't ignoring missing entries, assert that something happened.
  301. if (V)
  302. *op = V;
  303. else
  304. assert((Flags & RF_IgnoreMissingEntries) &&
  305. "Referenced value not in value map!");
  306. }
  307. // Remap phi nodes' incoming blocks.
  308. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  309. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  310. Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
  311. // If we aren't ignoring missing entries, assert that something happened.
  312. if (V)
  313. PN->setIncomingBlock(i, cast<BasicBlock>(V));
  314. else
  315. assert((Flags & RF_IgnoreMissingEntries) &&
  316. "Referenced block not in value map!");
  317. }
  318. }
  319. // Remap attached metadata.
  320. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  321. I->getAllMetadata(MDs);
  322. for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
  323. MI = MDs.begin(),
  324. ME = MDs.end();
  325. MI != ME; ++MI) {
  326. MDNode *Old = MI->second;
  327. MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
  328. if (New != Old)
  329. I->setMetadata(MI->first, New);
  330. }
  331. if (!TypeMapper)
  332. return;
  333. // If the instruction's type is being remapped, do so now.
  334. if (auto CS = CallSite(I)) {
  335. SmallVector<Type *, 3> Tys;
  336. FunctionType *FTy = CS.getFunctionType();
  337. Tys.reserve(FTy->getNumParams());
  338. for (Type *Ty : FTy->params())
  339. Tys.push_back(TypeMapper->remapType(Ty));
  340. CS.mutateFunctionType(FunctionType::get(
  341. TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
  342. return;
  343. }
  344. if (auto *AI = dyn_cast<AllocaInst>(I))
  345. AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
  346. if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  347. GEP->setSourceElementType(
  348. TypeMapper->remapType(GEP->getSourceElementType()));
  349. GEP->setResultElementType(
  350. TypeMapper->remapType(GEP->getResultElementType()));
  351. }
  352. I->mutateType(TypeMapper->remapType(I->getType()));
  353. }