IRMover.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  1. //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
  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. #include "llvm/Linker/IRMover.h"
  9. #include "LinkDiagnosticInfo.h"
  10. #include "llvm/ADT/SetVector.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/IR/Constants.h"
  14. #include "llvm/IR/DebugInfo.h"
  15. #include "llvm/IR/DiagnosticPrinter.h"
  16. #include "llvm/IR/GVMaterializer.h"
  17. #include "llvm/IR/Intrinsics.h"
  18. #include "llvm/IR/PseudoProbe.h"
  19. #include "llvm/IR/TypeFinder.h"
  20. #include "llvm/Object/ModuleSymbolTable.h"
  21. #include "llvm/Support/Error.h"
  22. #include "llvm/Support/Path.h"
  23. #include "llvm/Transforms/Utils/Cloning.h"
  24. #include <utility>
  25. using namespace llvm;
  26. //===----------------------------------------------------------------------===//
  27. // TypeMap implementation.
  28. //===----------------------------------------------------------------------===//
  29. namespace {
  30. class TypeMapTy : public ValueMapTypeRemapper {
  31. /// This is a mapping from a source type to a destination type to use.
  32. DenseMap<Type *, Type *> MappedTypes;
  33. /// When checking to see if two subgraphs are isomorphic, we speculatively
  34. /// add types to MappedTypes, but keep track of them here in case we need to
  35. /// roll back.
  36. SmallVector<Type *, 16> SpeculativeTypes;
  37. SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
  38. /// This is a list of non-opaque structs in the source module that are mapped
  39. /// to an opaque struct in the destination module.
  40. SmallVector<StructType *, 16> SrcDefinitionsToResolve;
  41. /// This is the set of opaque types in the destination modules who are
  42. /// getting a body from the source module.
  43. SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
  44. public:
  45. TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
  46. : DstStructTypesSet(DstStructTypesSet) {}
  47. IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
  48. /// Indicate that the specified type in the destination module is conceptually
  49. /// equivalent to the specified type in the source module.
  50. void addTypeMapping(Type *DstTy, Type *SrcTy);
  51. /// Produce a body for an opaque type in the dest module from a type
  52. /// definition in the source module.
  53. void linkDefinedTypeBodies();
  54. /// Return the mapped type to use for the specified input type from the
  55. /// source module.
  56. Type *get(Type *SrcTy);
  57. Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
  58. void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
  59. FunctionType *get(FunctionType *T) {
  60. return cast<FunctionType>(get((Type *)T));
  61. }
  62. private:
  63. Type *remapType(Type *SrcTy) override { return get(SrcTy); }
  64. bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
  65. };
  66. }
  67. void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
  68. assert(SpeculativeTypes.empty());
  69. assert(SpeculativeDstOpaqueTypes.empty());
  70. // Check to see if these types are recursively isomorphic and establish a
  71. // mapping between them if so.
  72. if (!areTypesIsomorphic(DstTy, SrcTy)) {
  73. // Oops, they aren't isomorphic. Just discard this request by rolling out
  74. // any speculative mappings we've established.
  75. for (Type *Ty : SpeculativeTypes)
  76. MappedTypes.erase(Ty);
  77. SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
  78. SpeculativeDstOpaqueTypes.size());
  79. for (StructType *Ty : SpeculativeDstOpaqueTypes)
  80. DstResolvedOpaqueTypes.erase(Ty);
  81. } else {
  82. // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
  83. // and all its descendants to lower amount of renaming in LLVM context
  84. // Renaming occurs because we load all source modules to the same context
  85. // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
  86. // As a result we may get several different types in the destination
  87. // module, which are in fact the same.
  88. for (Type *Ty : SpeculativeTypes)
  89. if (auto *STy = dyn_cast<StructType>(Ty))
  90. if (STy->hasName())
  91. STy->setName("");
  92. }
  93. SpeculativeTypes.clear();
  94. SpeculativeDstOpaqueTypes.clear();
  95. }
  96. /// Recursively walk this pair of types, returning true if they are isomorphic,
  97. /// false if they are not.
  98. bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
  99. // Two types with differing kinds are clearly not isomorphic.
  100. if (DstTy->getTypeID() != SrcTy->getTypeID())
  101. return false;
  102. // If we have an entry in the MappedTypes table, then we have our answer.
  103. Type *&Entry = MappedTypes[SrcTy];
  104. if (Entry)
  105. return Entry == DstTy;
  106. // Two identical types are clearly isomorphic. Remember this
  107. // non-speculatively.
  108. if (DstTy == SrcTy) {
  109. Entry = DstTy;
  110. return true;
  111. }
  112. // Okay, we have two types with identical kinds that we haven't seen before.
  113. // If this is an opaque struct type, special case it.
  114. if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
  115. // Mapping an opaque type to any struct, just keep the dest struct.
  116. if (SSTy->isOpaque()) {
  117. Entry = DstTy;
  118. SpeculativeTypes.push_back(SrcTy);
  119. return true;
  120. }
  121. // Mapping a non-opaque source type to an opaque dest. If this is the first
  122. // type that we're mapping onto this destination type then we succeed. Keep
  123. // the dest, but fill it in later. If this is the second (different) type
  124. // that we're trying to map onto the same opaque type then we fail.
  125. if (cast<StructType>(DstTy)->isOpaque()) {
  126. // We can only map one source type onto the opaque destination type.
  127. if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
  128. return false;
  129. SrcDefinitionsToResolve.push_back(SSTy);
  130. SpeculativeTypes.push_back(SrcTy);
  131. SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
  132. Entry = DstTy;
  133. return true;
  134. }
  135. }
  136. // If the number of subtypes disagree between the two types, then we fail.
  137. if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
  138. return false;
  139. // Fail if any of the extra properties (e.g. array size) of the type disagree.
  140. if (isa<IntegerType>(DstTy))
  141. return false; // bitwidth disagrees.
  142. if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
  143. if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
  144. return false;
  145. } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
  146. if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
  147. return false;
  148. } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
  149. StructType *SSTy = cast<StructType>(SrcTy);
  150. if (DSTy->isLiteral() != SSTy->isLiteral() ||
  151. DSTy->isPacked() != SSTy->isPacked())
  152. return false;
  153. } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
  154. if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
  155. return false;
  156. } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
  157. if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
  158. return false;
  159. }
  160. // Otherwise, we speculate that these two types will line up and recursively
  161. // check the subelements.
  162. Entry = DstTy;
  163. SpeculativeTypes.push_back(SrcTy);
  164. for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
  165. if (!areTypesIsomorphic(DstTy->getContainedType(I),
  166. SrcTy->getContainedType(I)))
  167. return false;
  168. // If everything seems to have lined up, then everything is great.
  169. return true;
  170. }
  171. void TypeMapTy::linkDefinedTypeBodies() {
  172. SmallVector<Type *, 16> Elements;
  173. for (StructType *SrcSTy : SrcDefinitionsToResolve) {
  174. StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
  175. assert(DstSTy->isOpaque());
  176. // Map the body of the source type over to a new body for the dest type.
  177. Elements.resize(SrcSTy->getNumElements());
  178. for (unsigned I = 0, E = Elements.size(); I != E; ++I)
  179. Elements[I] = get(SrcSTy->getElementType(I));
  180. DstSTy->setBody(Elements, SrcSTy->isPacked());
  181. DstStructTypesSet.switchToNonOpaque(DstSTy);
  182. }
  183. SrcDefinitionsToResolve.clear();
  184. DstResolvedOpaqueTypes.clear();
  185. }
  186. void TypeMapTy::finishType(StructType *DTy, StructType *STy,
  187. ArrayRef<Type *> ETypes) {
  188. DTy->setBody(ETypes, STy->isPacked());
  189. // Steal STy's name.
  190. if (STy->hasName()) {
  191. SmallString<16> TmpName = STy->getName();
  192. STy->setName("");
  193. DTy->setName(TmpName);
  194. }
  195. DstStructTypesSet.addNonOpaque(DTy);
  196. }
  197. Type *TypeMapTy::get(Type *Ty) {
  198. SmallPtrSet<StructType *, 8> Visited;
  199. return get(Ty, Visited);
  200. }
  201. Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
  202. // If we already have an entry for this type, return it.
  203. Type **Entry = &MappedTypes[Ty];
  204. if (*Entry)
  205. return *Entry;
  206. // These are types that LLVM itself will unique.
  207. bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
  208. if (!IsUniqued) {
  209. #ifndef NDEBUG
  210. for (auto &Pair : MappedTypes) {
  211. assert(!(Pair.first != Ty && Pair.second == Ty) &&
  212. "mapping to a source type");
  213. }
  214. #endif
  215. if (!Visited.insert(cast<StructType>(Ty)).second) {
  216. StructType *DTy = StructType::create(Ty->getContext());
  217. return *Entry = DTy;
  218. }
  219. }
  220. // If this is not a recursive type, then just map all of the elements and
  221. // then rebuild the type from inside out.
  222. SmallVector<Type *, 4> ElementTypes;
  223. // If there are no element types to map, then the type is itself. This is
  224. // true for the anonymous {} struct, things like 'float', integers, etc.
  225. if (Ty->getNumContainedTypes() == 0 && IsUniqued)
  226. return *Entry = Ty;
  227. // Remap all of the elements, keeping track of whether any of them change.
  228. bool AnyChange = false;
  229. ElementTypes.resize(Ty->getNumContainedTypes());
  230. for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
  231. ElementTypes[I] = get(Ty->getContainedType(I), Visited);
  232. AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
  233. }
  234. // If we found our type while recursively processing stuff, just use it.
  235. Entry = &MappedTypes[Ty];
  236. if (*Entry) {
  237. if (auto *DTy = dyn_cast<StructType>(*Entry)) {
  238. if (DTy->isOpaque()) {
  239. auto *STy = cast<StructType>(Ty);
  240. finishType(DTy, STy, ElementTypes);
  241. }
  242. }
  243. return *Entry;
  244. }
  245. // If all of the element types mapped directly over and the type is not
  246. // a named struct, then the type is usable as-is.
  247. if (!AnyChange && IsUniqued)
  248. return *Entry = Ty;
  249. // Otherwise, rebuild a modified type.
  250. switch (Ty->getTypeID()) {
  251. default:
  252. llvm_unreachable("unknown derived type to remap");
  253. case Type::ArrayTyID:
  254. return *Entry = ArrayType::get(ElementTypes[0],
  255. cast<ArrayType>(Ty)->getNumElements());
  256. case Type::ScalableVectorTyID:
  257. case Type::FixedVectorTyID:
  258. return *Entry = VectorType::get(ElementTypes[0],
  259. cast<VectorType>(Ty)->getElementCount());
  260. case Type::PointerTyID:
  261. return *Entry = PointerType::get(ElementTypes[0],
  262. cast<PointerType>(Ty)->getAddressSpace());
  263. case Type::FunctionTyID:
  264. return *Entry = FunctionType::get(ElementTypes[0],
  265. makeArrayRef(ElementTypes).slice(1),
  266. cast<FunctionType>(Ty)->isVarArg());
  267. case Type::StructTyID: {
  268. auto *STy = cast<StructType>(Ty);
  269. bool IsPacked = STy->isPacked();
  270. if (IsUniqued)
  271. return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
  272. // If the type is opaque, we can just use it directly.
  273. if (STy->isOpaque()) {
  274. DstStructTypesSet.addOpaque(STy);
  275. return *Entry = Ty;
  276. }
  277. if (StructType *OldT =
  278. DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
  279. STy->setName("");
  280. return *Entry = OldT;
  281. }
  282. if (!AnyChange) {
  283. DstStructTypesSet.addNonOpaque(STy);
  284. return *Entry = Ty;
  285. }
  286. StructType *DTy = StructType::create(Ty->getContext());
  287. finishType(DTy, STy, ElementTypes);
  288. return *Entry = DTy;
  289. }
  290. }
  291. }
  292. LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
  293. const Twine &Msg)
  294. : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
  295. void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
  296. //===----------------------------------------------------------------------===//
  297. // IRLinker implementation.
  298. //===----------------------------------------------------------------------===//
  299. namespace {
  300. class IRLinker;
  301. /// Creates prototypes for functions that are lazily linked on the fly. This
  302. /// speeds up linking for modules with many/ lazily linked functions of which
  303. /// few get used.
  304. class GlobalValueMaterializer final : public ValueMaterializer {
  305. IRLinker &TheIRLinker;
  306. public:
  307. GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
  308. Value *materialize(Value *V) override;
  309. };
  310. class LocalValueMaterializer final : public ValueMaterializer {
  311. IRLinker &TheIRLinker;
  312. public:
  313. LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
  314. Value *materialize(Value *V) override;
  315. };
  316. /// Type of the Metadata map in \a ValueToValueMapTy.
  317. typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
  318. /// This is responsible for keeping track of the state used for moving data
  319. /// from SrcM to DstM.
  320. class IRLinker {
  321. Module &DstM;
  322. std::unique_ptr<Module> SrcM;
  323. /// See IRMover::move().
  324. std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
  325. TypeMapTy TypeMap;
  326. GlobalValueMaterializer GValMaterializer;
  327. LocalValueMaterializer LValMaterializer;
  328. /// A metadata map that's shared between IRLinker instances.
  329. MDMapT &SharedMDs;
  330. /// Mapping of values from what they used to be in Src, to what they are now
  331. /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
  332. /// due to the use of Value handles which the Linker doesn't actually need,
  333. /// but this allows us to reuse the ValueMapper code.
  334. ValueToValueMapTy ValueMap;
  335. ValueToValueMapTy IndirectSymbolValueMap;
  336. DenseSet<GlobalValue *> ValuesToLink;
  337. std::vector<GlobalValue *> Worklist;
  338. std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
  339. void maybeAdd(GlobalValue *GV) {
  340. if (ValuesToLink.insert(GV).second)
  341. Worklist.push_back(GV);
  342. }
  343. /// Whether we are importing globals for ThinLTO, as opposed to linking the
  344. /// source module. If this flag is set, it means that we can rely on some
  345. /// other object file to define any non-GlobalValue entities defined by the
  346. /// source module. This currently causes us to not link retained types in
  347. /// debug info metadata and module inline asm.
  348. bool IsPerformingImport;
  349. /// Set to true when all global value body linking is complete (including
  350. /// lazy linking). Used to prevent metadata linking from creating new
  351. /// references.
  352. bool DoneLinkingBodies = false;
  353. /// The Error encountered during materialization. We use an Optional here to
  354. /// avoid needing to manage an unconsumed success value.
  355. Optional<Error> FoundError;
  356. void setError(Error E) {
  357. if (E)
  358. FoundError = std::move(E);
  359. }
  360. /// Most of the errors produced by this module are inconvertible StringErrors.
  361. /// This convenience function lets us return one of those more easily.
  362. Error stringErr(const Twine &T) {
  363. return make_error<StringError>(T, inconvertibleErrorCode());
  364. }
  365. /// Entry point for mapping values and alternate context for mapping aliases.
  366. ValueMapper Mapper;
  367. unsigned IndirectSymbolMCID;
  368. /// Handles cloning of a global values from the source module into
  369. /// the destination module, including setting the attributes and visibility.
  370. GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
  371. void emitWarning(const Twine &Message) {
  372. SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
  373. }
  374. /// Given a global in the source module, return the global in the
  375. /// destination module that is being linked to, if any.
  376. GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
  377. // If the source has no name it can't link. If it has local linkage,
  378. // there is no name match-up going on.
  379. if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
  380. return nullptr;
  381. // Otherwise see if we have a match in the destination module's symtab.
  382. GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
  383. if (!DGV)
  384. return nullptr;
  385. // If we found a global with the same name in the dest module, but it has
  386. // internal linkage, we are really not doing any linkage here.
  387. if (DGV->hasLocalLinkage())
  388. return nullptr;
  389. // If we found an intrinsic declaration with mismatching prototypes, we
  390. // probably had a nameclash. Don't use that version.
  391. if (auto *FDGV = dyn_cast<Function>(DGV))
  392. if (FDGV->isIntrinsic())
  393. if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
  394. if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
  395. return nullptr;
  396. // Otherwise, we do in fact link to the destination global.
  397. return DGV;
  398. }
  399. void computeTypeMapping();
  400. Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
  401. const GlobalVariable *SrcGV);
  402. /// Given the GlobaValue \p SGV in the source module, and the matching
  403. /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
  404. /// into the destination module.
  405. ///
  406. /// Note this code may call the client-provided \p AddLazyFor.
  407. bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
  408. Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
  409. bool ForIndirectSymbol);
  410. Error linkModuleFlagsMetadata();
  411. void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
  412. Error linkFunctionBody(Function &Dst, Function &Src);
  413. void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
  414. void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
  415. Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
  416. /// Replace all types in the source AttributeList with the
  417. /// corresponding destination type.
  418. AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
  419. /// Functions that take care of cloning a specific global value type
  420. /// into the destination module.
  421. GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
  422. Function *copyFunctionProto(const Function *SF);
  423. GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
  424. /// Perform "replace all uses with" operations. These work items need to be
  425. /// performed as part of materialization, but we postpone them to happen after
  426. /// materialization is done. The materializer called by ValueMapper is not
  427. /// expected to delete constants, as ValueMapper is holding pointers to some
  428. /// of them, but constant destruction may be indirectly triggered by RAUW.
  429. /// Hence, the need to move this out of the materialization call chain.
  430. void flushRAUWWorklist();
  431. /// When importing for ThinLTO, prevent importing of types listed on
  432. /// the DICompileUnit that we don't need a copy of in the importing
  433. /// module.
  434. void prepareCompileUnitsForImport();
  435. void linkNamedMDNodes();
  436. public:
  437. IRLinker(Module &DstM, MDMapT &SharedMDs,
  438. IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
  439. ArrayRef<GlobalValue *> ValuesToLink,
  440. std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
  441. bool IsPerformingImport)
  442. : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
  443. TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
  444. SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
  445. Mapper(ValueMap, RF_ReuseAndMutateDistinctMDs | RF_IgnoreMissingLocals,
  446. &TypeMap, &GValMaterializer),
  447. IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
  448. IndirectSymbolValueMap, &LValMaterializer)) {
  449. ValueMap.getMDMap() = std::move(SharedMDs);
  450. for (GlobalValue *GV : ValuesToLink)
  451. maybeAdd(GV);
  452. if (IsPerformingImport)
  453. prepareCompileUnitsForImport();
  454. }
  455. ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
  456. Error run();
  457. Value *materialize(Value *V, bool ForIndirectSymbol);
  458. };
  459. }
  460. /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
  461. /// table. This is good for all clients except for us. Go through the trouble
  462. /// to force this back.
  463. static void forceRenaming(GlobalValue *GV, StringRef Name) {
  464. // If the global doesn't force its name or if it already has the right name,
  465. // there is nothing for us to do.
  466. if (GV->hasLocalLinkage() || GV->getName() == Name)
  467. return;
  468. Module *M = GV->getParent();
  469. // If there is a conflict, rename the conflict.
  470. if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
  471. GV->takeName(ConflictGV);
  472. ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
  473. assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
  474. } else {
  475. GV->setName(Name); // Force the name back
  476. }
  477. }
  478. Value *GlobalValueMaterializer::materialize(Value *SGV) {
  479. return TheIRLinker.materialize(SGV, false);
  480. }
  481. Value *LocalValueMaterializer::materialize(Value *SGV) {
  482. return TheIRLinker.materialize(SGV, true);
  483. }
  484. Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
  485. auto *SGV = dyn_cast<GlobalValue>(V);
  486. if (!SGV)
  487. return nullptr;
  488. // When linking a global from other modules than source & dest, skip
  489. // materializing it because it would be mapped later when its containing
  490. // module is linked. Linking it now would potentially pull in many types that
  491. // may not be mapped properly.
  492. if (SGV->getParent() != &DstM && SGV->getParent() != SrcM.get())
  493. return nullptr;
  494. Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
  495. if (!NewProto) {
  496. setError(NewProto.takeError());
  497. return nullptr;
  498. }
  499. if (!*NewProto)
  500. return nullptr;
  501. GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
  502. if (!New)
  503. return *NewProto;
  504. // If we already created the body, just return.
  505. if (auto *F = dyn_cast<Function>(New)) {
  506. if (!F->isDeclaration())
  507. return New;
  508. } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
  509. if (V->hasInitializer() || V->hasAppendingLinkage())
  510. return New;
  511. } else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
  512. if (GA->getAliasee())
  513. return New;
  514. } else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
  515. if (GI->getResolver())
  516. return New;
  517. } else {
  518. llvm_unreachable("Invalid GlobalValue type");
  519. }
  520. // If the global is being linked for an indirect symbol, it may have already
  521. // been scheduled to satisfy a regular symbol. Similarly, a global being linked
  522. // for a regular symbol may have already been scheduled for an indirect
  523. // symbol. Check for these cases by looking in the other value map and
  524. // confirming the same value has been scheduled. If there is an entry in the
  525. // ValueMap but the value is different, it means that the value already had a
  526. // definition in the destination module (linkonce for instance), but we need a
  527. // new definition for the indirect symbol ("New" will be different).
  528. if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
  529. (!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
  530. return New;
  531. if (ForIndirectSymbol || shouldLink(New, *SGV))
  532. setError(linkGlobalValueBody(*New, *SGV));
  533. return New;
  534. }
  535. /// Loop through the global variables in the src module and merge them into the
  536. /// dest module.
  537. GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
  538. // No linking to be performed or linking from the source: simply create an
  539. // identical version of the symbol over in the dest module... the
  540. // initializer will be filled in later by LinkGlobalInits.
  541. GlobalVariable *NewDGV =
  542. new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
  543. SGVar->isConstant(), GlobalValue::ExternalLinkage,
  544. /*init*/ nullptr, SGVar->getName(),
  545. /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
  546. SGVar->getAddressSpace());
  547. NewDGV->setAlignment(SGVar->getAlign());
  548. NewDGV->copyAttributesFrom(SGVar);
  549. return NewDGV;
  550. }
  551. AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
  552. for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
  553. for (int AttrIdx = Attribute::FirstTypeAttr;
  554. AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
  555. Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
  556. if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
  557. if (Type *Ty =
  558. Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
  559. Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
  560. TypeMap.get(Ty));
  561. break;
  562. }
  563. }
  564. }
  565. }
  566. return Attrs;
  567. }
  568. /// Link the function in the source module into the destination module if
  569. /// needed, setting up mapping information.
  570. Function *IRLinker::copyFunctionProto(const Function *SF) {
  571. // If there is no linkage to be performed or we are linking from the source,
  572. // bring SF over.
  573. auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
  574. GlobalValue::ExternalLinkage,
  575. SF->getAddressSpace(), SF->getName(), &DstM);
  576. F->copyAttributesFrom(SF);
  577. F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
  578. return F;
  579. }
  580. /// Set up prototypes for any indirect symbols that come over from the source
  581. /// module.
  582. GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
  583. // If there is no linkage to be performed or we're linking from the source,
  584. // bring over SGA.
  585. auto *Ty = TypeMap.get(SGV->getValueType());
  586. if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
  587. auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
  588. GlobalValue::ExternalLinkage,
  589. SGV->getName(), &DstM);
  590. DGA->copyAttributesFrom(GA);
  591. return DGA;
  592. }
  593. if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
  594. auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
  595. GlobalValue::ExternalLinkage,
  596. SGV->getName(), nullptr, &DstM);
  597. DGI->copyAttributesFrom(GI);
  598. return DGI;
  599. }
  600. llvm_unreachable("Invalid source global value type");
  601. }
  602. GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
  603. bool ForDefinition) {
  604. GlobalValue *NewGV;
  605. if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
  606. NewGV = copyGlobalVariableProto(SGVar);
  607. } else if (auto *SF = dyn_cast<Function>(SGV)) {
  608. NewGV = copyFunctionProto(SF);
  609. } else {
  610. if (ForDefinition)
  611. NewGV = copyIndirectSymbolProto(SGV);
  612. else if (SGV->getValueType()->isFunctionTy())
  613. NewGV =
  614. Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
  615. GlobalValue::ExternalLinkage, SGV->getAddressSpace(),
  616. SGV->getName(), &DstM);
  617. else
  618. NewGV =
  619. new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
  620. /*isConstant*/ false, GlobalValue::ExternalLinkage,
  621. /*init*/ nullptr, SGV->getName(),
  622. /*insertbefore*/ nullptr,
  623. SGV->getThreadLocalMode(), SGV->getAddressSpace());
  624. }
  625. if (ForDefinition)
  626. NewGV->setLinkage(SGV->getLinkage());
  627. else if (SGV->hasExternalWeakLinkage())
  628. NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
  629. if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
  630. // Metadata for global variables and function declarations is copied eagerly.
  631. if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
  632. NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
  633. }
  634. // Remove these copied constants in case this stays a declaration, since
  635. // they point to the source module. If the def is linked the values will
  636. // be mapped in during linkFunctionBody.
  637. if (auto *NewF = dyn_cast<Function>(NewGV)) {
  638. NewF->setPersonalityFn(nullptr);
  639. NewF->setPrefixData(nullptr);
  640. NewF->setPrologueData(nullptr);
  641. }
  642. return NewGV;
  643. }
  644. static StringRef getTypeNamePrefix(StringRef Name) {
  645. size_t DotPos = Name.rfind('.');
  646. return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
  647. !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
  648. ? Name
  649. : Name.substr(0, DotPos);
  650. }
  651. /// Loop over all of the linked values to compute type mappings. For example,
  652. /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
  653. /// types 'Foo' but one got renamed when the module was loaded into the same
  654. /// LLVMContext.
  655. void IRLinker::computeTypeMapping() {
  656. for (GlobalValue &SGV : SrcM->globals()) {
  657. GlobalValue *DGV = getLinkedToGlobal(&SGV);
  658. if (!DGV)
  659. continue;
  660. if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
  661. TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
  662. continue;
  663. }
  664. // Unify the element type of appending arrays.
  665. ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
  666. ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
  667. TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
  668. }
  669. for (GlobalValue &SGV : *SrcM)
  670. if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
  671. if (DGV->getType() == SGV.getType()) {
  672. // If the types of DGV and SGV are the same, it means that DGV is from
  673. // the source module and got added to DstM from a shared metadata. We
  674. // shouldn't map this type to itself in case the type's components get
  675. // remapped to a new type from DstM (for instance, during the loop over
  676. // SrcM->getIdentifiedStructTypes() below).
  677. continue;
  678. }
  679. TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
  680. }
  681. for (GlobalValue &SGV : SrcM->aliases())
  682. if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
  683. TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
  684. // Incorporate types by name, scanning all the types in the source module.
  685. // At this point, the destination module may have a type "%foo = { i32 }" for
  686. // example. When the source module got loaded into the same LLVMContext, if
  687. // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
  688. std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
  689. for (StructType *ST : Types) {
  690. if (!ST->hasName())
  691. continue;
  692. if (TypeMap.DstStructTypesSet.hasType(ST)) {
  693. // This is actually a type from the destination module.
  694. // getIdentifiedStructTypes() can have found it by walking debug info
  695. // metadata nodes, some of which get linked by name when ODR Type Uniquing
  696. // is enabled on the Context, from the source to the destination module.
  697. continue;
  698. }
  699. auto STTypePrefix = getTypeNamePrefix(ST->getName());
  700. if (STTypePrefix.size() == ST->getName().size())
  701. continue;
  702. // Check to see if the destination module has a struct with the prefix name.
  703. StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
  704. if (!DST)
  705. continue;
  706. // Don't use it if this actually came from the source module. They're in
  707. // the same LLVMContext after all. Also don't use it unless the type is
  708. // actually used in the destination module. This can happen in situations
  709. // like this:
  710. //
  711. // Module A Module B
  712. // -------- --------
  713. // %Z = type { %A } %B = type { %C.1 }
  714. // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
  715. // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
  716. // %C = type { i8* } %B.3 = type { %C.1 }
  717. //
  718. // When we link Module B with Module A, the '%B' in Module B is
  719. // used. However, that would then use '%C.1'. But when we process '%C.1',
  720. // we prefer to take the '%C' version. So we are then left with both
  721. // '%C.1' and '%C' being used for the same types. This leads to some
  722. // variables using one type and some using the other.
  723. if (TypeMap.DstStructTypesSet.hasType(DST))
  724. TypeMap.addTypeMapping(DST, ST);
  725. }
  726. // Now that we have discovered all of the type equivalences, get a body for
  727. // any 'opaque' types in the dest module that are now resolved.
  728. TypeMap.linkDefinedTypeBodies();
  729. }
  730. static void getArrayElements(const Constant *C,
  731. SmallVectorImpl<Constant *> &Dest) {
  732. unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
  733. for (unsigned i = 0; i != NumElements; ++i)
  734. Dest.push_back(C->getAggregateElement(i));
  735. }
  736. /// If there were any appending global variables, link them together now.
  737. Expected<Constant *>
  738. IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
  739. const GlobalVariable *SrcGV) {
  740. // Check that both variables have compatible properties.
  741. if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
  742. if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
  743. return stringErr(
  744. "Linking globals named '" + SrcGV->getName() +
  745. "': can only link appending global with another appending "
  746. "global!");
  747. if (DstGV->isConstant() != SrcGV->isConstant())
  748. return stringErr("Appending variables linked with different const'ness!");
  749. if (DstGV->getAlign() != SrcGV->getAlign())
  750. return stringErr(
  751. "Appending variables with different alignment need to be linked!");
  752. if (DstGV->getVisibility() != SrcGV->getVisibility())
  753. return stringErr(
  754. "Appending variables with different visibility need to be linked!");
  755. if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
  756. return stringErr(
  757. "Appending variables with different unnamed_addr need to be linked!");
  758. if (DstGV->getSection() != SrcGV->getSection())
  759. return stringErr(
  760. "Appending variables with different section name need to be linked!");
  761. }
  762. // Do not need to do anything if source is a declaration.
  763. if (SrcGV->isDeclaration())
  764. return DstGV;
  765. Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
  766. ->getElementType();
  767. // FIXME: This upgrade is done during linking to support the C API. Once the
  768. // old form is deprecated, we should move this upgrade to
  769. // llvm::UpgradeGlobalVariable() and simplify the logic here and in
  770. // Mapper::mapAppendingVariable() in ValueMapper.cpp.
  771. StringRef Name = SrcGV->getName();
  772. bool IsNewStructor = false;
  773. bool IsOldStructor = false;
  774. if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
  775. if (cast<StructType>(EltTy)->getNumElements() == 3)
  776. IsNewStructor = true;
  777. else
  778. IsOldStructor = true;
  779. }
  780. PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
  781. if (IsOldStructor) {
  782. auto &ST = *cast<StructType>(EltTy);
  783. Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
  784. EltTy = StructType::get(SrcGV->getContext(), Tys, false);
  785. }
  786. uint64_t DstNumElements = 0;
  787. if (DstGV && !DstGV->isDeclaration()) {
  788. ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
  789. DstNumElements = DstTy->getNumElements();
  790. // Check to see that they two arrays agree on type.
  791. if (EltTy != DstTy->getElementType())
  792. return stringErr("Appending variables with different element types!");
  793. }
  794. SmallVector<Constant *, 16> SrcElements;
  795. getArrayElements(SrcGV->getInitializer(), SrcElements);
  796. if (IsNewStructor) {
  797. erase_if(SrcElements, [this](Constant *E) {
  798. auto *Key =
  799. dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
  800. if (!Key)
  801. return false;
  802. GlobalValue *DGV = getLinkedToGlobal(Key);
  803. return !shouldLink(DGV, *Key);
  804. });
  805. }
  806. uint64_t NewSize = DstNumElements + SrcElements.size();
  807. ArrayType *NewType = ArrayType::get(EltTy, NewSize);
  808. // Create the new global variable.
  809. GlobalVariable *NG = new GlobalVariable(
  810. DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
  811. /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
  812. SrcGV->getAddressSpace());
  813. NG->copyAttributesFrom(SrcGV);
  814. forceRenaming(NG, SrcGV->getName());
  815. Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
  816. Mapper.scheduleMapAppendingVariable(
  817. *NG,
  818. (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
  819. IsOldStructor, SrcElements);
  820. // Replace any uses of the two global variables with uses of the new
  821. // global.
  822. if (DstGV) {
  823. RAUWWorklist.push_back(
  824. std::make_pair(DstGV, ConstantExpr::getBitCast(NG, DstGV->getType())));
  825. }
  826. return Ret;
  827. }
  828. bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
  829. if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
  830. return true;
  831. if (DGV && !DGV->isDeclarationForLinker())
  832. return false;
  833. if (SGV.isDeclaration() || DoneLinkingBodies)
  834. return false;
  835. // Callback to the client to give a chance to lazily add the Global to the
  836. // list of value to link.
  837. bool LazilyAdded = false;
  838. AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
  839. maybeAdd(&GV);
  840. LazilyAdded = true;
  841. });
  842. return LazilyAdded;
  843. }
  844. Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
  845. bool ForIndirectSymbol) {
  846. GlobalValue *DGV = getLinkedToGlobal(SGV);
  847. bool ShouldLink = shouldLink(DGV, *SGV);
  848. // just missing from map
  849. if (ShouldLink) {
  850. auto I = ValueMap.find(SGV);
  851. if (I != ValueMap.end())
  852. return cast<Constant>(I->second);
  853. I = IndirectSymbolValueMap.find(SGV);
  854. if (I != IndirectSymbolValueMap.end())
  855. return cast<Constant>(I->second);
  856. }
  857. if (!ShouldLink && ForIndirectSymbol)
  858. DGV = nullptr;
  859. // Handle the ultra special appending linkage case first.
  860. if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
  861. return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
  862. cast<GlobalVariable>(SGV));
  863. bool NeedsRenaming = false;
  864. GlobalValue *NewGV;
  865. if (DGV && !ShouldLink) {
  866. NewGV = DGV;
  867. } else {
  868. // If we are done linking global value bodies (i.e. we are performing
  869. // metadata linking), don't link in the global value due to this
  870. // reference, simply map it to null.
  871. if (DoneLinkingBodies)
  872. return nullptr;
  873. NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
  874. if (ShouldLink || !ForIndirectSymbol)
  875. NeedsRenaming = true;
  876. }
  877. // Overloaded intrinsics have overloaded types names as part of their
  878. // names. If we renamed overloaded types we should rename the intrinsic
  879. // as well.
  880. if (Function *F = dyn_cast<Function>(NewGV))
  881. if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
  882. NewGV->eraseFromParent();
  883. NewGV = Remangled.getValue();
  884. NeedsRenaming = false;
  885. }
  886. if (NeedsRenaming)
  887. forceRenaming(NewGV, SGV->getName());
  888. if (ShouldLink || ForIndirectSymbol) {
  889. if (const Comdat *SC = SGV->getComdat()) {
  890. if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
  891. Comdat *DC = DstM.getOrInsertComdat(SC->getName());
  892. DC->setSelectionKind(SC->getSelectionKind());
  893. GO->setComdat(DC);
  894. }
  895. }
  896. }
  897. if (!ShouldLink && ForIndirectSymbol)
  898. NewGV->setLinkage(GlobalValue::InternalLinkage);
  899. Constant *C = NewGV;
  900. // Only create a bitcast if necessary. In particular, with
  901. // DebugTypeODRUniquing we may reach metadata in the destination module
  902. // containing a GV from the source module, in which case SGV will be
  903. // the same as DGV and NewGV, and TypeMap.get() will assert since it
  904. // assumes it is being invoked on a type in the source module.
  905. if (DGV && NewGV != SGV) {
  906. C = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  907. NewGV, TypeMap.get(SGV->getType()));
  908. }
  909. if (DGV && NewGV != DGV) {
  910. // Schedule "replace all uses with" to happen after materializing is
  911. // done. It is not safe to do it now, since ValueMapper may be holding
  912. // pointers to constants that will get deleted if RAUW runs.
  913. RAUWWorklist.push_back(std::make_pair(
  914. DGV,
  915. ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV, DGV->getType())));
  916. }
  917. return C;
  918. }
  919. /// Update the initializers in the Dest module now that all globals that may be
  920. /// referenced are in Dest.
  921. void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
  922. // Figure out what the initializer looks like in the dest module.
  923. Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
  924. }
  925. /// Copy the source function over into the dest function and fix up references
  926. /// to values. At this point we know that Dest is an external function, and
  927. /// that Src is not.
  928. Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
  929. assert(Dst.isDeclaration() && !Src.isDeclaration());
  930. // Materialize if needed.
  931. if (Error Err = Src.materialize())
  932. return Err;
  933. // Link in the operands without remapping.
  934. if (Src.hasPrefixData())
  935. Dst.setPrefixData(Src.getPrefixData());
  936. if (Src.hasPrologueData())
  937. Dst.setPrologueData(Src.getPrologueData());
  938. if (Src.hasPersonalityFn())
  939. Dst.setPersonalityFn(Src.getPersonalityFn());
  940. // Copy over the metadata attachments without remapping.
  941. Dst.copyMetadata(&Src, 0);
  942. // Steal arguments and splice the body of Src into Dst.
  943. Dst.stealArgumentListFrom(Src);
  944. Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
  945. // Everything has been moved over. Remap it.
  946. Mapper.scheduleRemapFunction(Dst);
  947. return Error::success();
  948. }
  949. void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
  950. Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
  951. }
  952. void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
  953. Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
  954. }
  955. Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
  956. if (auto *F = dyn_cast<Function>(&Src))
  957. return linkFunctionBody(cast<Function>(Dst), *F);
  958. if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
  959. linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
  960. return Error::success();
  961. }
  962. if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
  963. linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
  964. return Error::success();
  965. }
  966. linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
  967. return Error::success();
  968. }
  969. void IRLinker::flushRAUWWorklist() {
  970. for (const auto &Elem : RAUWWorklist) {
  971. GlobalValue *Old;
  972. Value *New;
  973. std::tie(Old, New) = Elem;
  974. Old->replaceAllUsesWith(New);
  975. Old->eraseFromParent();
  976. }
  977. RAUWWorklist.clear();
  978. }
  979. void IRLinker::prepareCompileUnitsForImport() {
  980. NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
  981. if (!SrcCompileUnits)
  982. return;
  983. // When importing for ThinLTO, prevent importing of types listed on
  984. // the DICompileUnit that we don't need a copy of in the importing
  985. // module. They will be emitted by the originating module.
  986. for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
  987. auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
  988. assert(CU && "Expected valid compile unit");
  989. // Enums, macros, and retained types don't need to be listed on the
  990. // imported DICompileUnit. This means they will only be imported
  991. // if reached from the mapped IR.
  992. CU->replaceEnumTypes(nullptr);
  993. CU->replaceMacros(nullptr);
  994. CU->replaceRetainedTypes(nullptr);
  995. // The original definition (or at least its debug info - if the variable is
  996. // internalized and optimized away) will remain in the source module, so
  997. // there's no need to import them.
  998. // If LLVM ever does more advanced optimizations on global variables
  999. // (removing/localizing write operations, for instance) that can track
  1000. // through debug info, this decision may need to be revisited - but do so
  1001. // with care when it comes to debug info size. Emitting small CUs containing
  1002. // only a few imported entities into every destination module may be very
  1003. // size inefficient.
  1004. CU->replaceGlobalVariables(nullptr);
  1005. // Imported entities only need to be mapped in if they have local
  1006. // scope, as those might correspond to an imported entity inside a
  1007. // function being imported (any locally scoped imported entities that
  1008. // don't end up referenced by an imported function will not be emitted
  1009. // into the object). Imported entities not in a local scope
  1010. // (e.g. on the namespace) only need to be emitted by the originating
  1011. // module. Create a list of the locally scoped imported entities, and
  1012. // replace the source CUs imported entity list with the new list, so
  1013. // only those are mapped in.
  1014. // FIXME: Locally-scoped imported entities could be moved to the
  1015. // functions they are local to instead of listing them on the CU, and
  1016. // we would naturally only link in those needed by function importing.
  1017. SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
  1018. bool ReplaceImportedEntities = false;
  1019. for (auto *IE : CU->getImportedEntities()) {
  1020. DIScope *Scope = IE->getScope();
  1021. assert(Scope && "Invalid Scope encoding!");
  1022. if (isa<DILocalScope>(Scope))
  1023. AllImportedModules.emplace_back(IE);
  1024. else
  1025. ReplaceImportedEntities = true;
  1026. }
  1027. if (ReplaceImportedEntities) {
  1028. if (!AllImportedModules.empty())
  1029. CU->replaceImportedEntities(MDTuple::get(
  1030. CU->getContext(),
  1031. SmallVector<Metadata *, 16>(AllImportedModules.begin(),
  1032. AllImportedModules.end())));
  1033. else
  1034. // If there were no local scope imported entities, we can map
  1035. // the whole list to nullptr.
  1036. CU->replaceImportedEntities(nullptr);
  1037. }
  1038. }
  1039. }
  1040. /// Insert all of the named MDNodes in Src into the Dest module.
  1041. void IRLinker::linkNamedMDNodes() {
  1042. const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
  1043. for (const NamedMDNode &NMD : SrcM->named_metadata()) {
  1044. // Don't link module flags here. Do them separately.
  1045. if (&NMD == SrcModFlags)
  1046. continue;
  1047. // Don't import pseudo probe descriptors here for thinLTO. They will be
  1048. // emitted by the originating module.
  1049. if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName)
  1050. continue;
  1051. NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
  1052. // Add Src elements into Dest node.
  1053. for (const MDNode *Op : NMD.operands())
  1054. DestNMD->addOperand(Mapper.mapMDNode(*Op));
  1055. }
  1056. }
  1057. /// Merge the linker flags in Src into the Dest module.
  1058. Error IRLinker::linkModuleFlagsMetadata() {
  1059. // If the source module has no module flags, we are done.
  1060. const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
  1061. if (!SrcModFlags)
  1062. return Error::success();
  1063. // If the destination module doesn't have module flags yet, then just copy
  1064. // over the source module's flags.
  1065. NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
  1066. if (DstModFlags->getNumOperands() == 0) {
  1067. for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
  1068. DstModFlags->addOperand(SrcModFlags->getOperand(I));
  1069. return Error::success();
  1070. }
  1071. // First build a map of the existing module flags and requirements.
  1072. DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
  1073. SmallSetVector<MDNode *, 16> Requirements;
  1074. for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
  1075. MDNode *Op = DstModFlags->getOperand(I);
  1076. ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
  1077. MDString *ID = cast<MDString>(Op->getOperand(1));
  1078. if (Behavior->getZExtValue() == Module::Require) {
  1079. Requirements.insert(cast<MDNode>(Op->getOperand(2)));
  1080. } else {
  1081. Flags[ID] = std::make_pair(Op, I);
  1082. }
  1083. }
  1084. // Merge in the flags from the source module, and also collect its set of
  1085. // requirements.
  1086. for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
  1087. MDNode *SrcOp = SrcModFlags->getOperand(I);
  1088. ConstantInt *SrcBehavior =
  1089. mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
  1090. MDString *ID = cast<MDString>(SrcOp->getOperand(1));
  1091. MDNode *DstOp;
  1092. unsigned DstIndex;
  1093. std::tie(DstOp, DstIndex) = Flags.lookup(ID);
  1094. unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
  1095. // If this is a requirement, add it and continue.
  1096. if (SrcBehaviorValue == Module::Require) {
  1097. // If the destination module does not already have this requirement, add
  1098. // it.
  1099. if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
  1100. DstModFlags->addOperand(SrcOp);
  1101. }
  1102. continue;
  1103. }
  1104. // If there is no existing flag with this ID, just add it.
  1105. if (!DstOp) {
  1106. Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
  1107. DstModFlags->addOperand(SrcOp);
  1108. continue;
  1109. }
  1110. // Otherwise, perform a merge.
  1111. ConstantInt *DstBehavior =
  1112. mdconst::extract<ConstantInt>(DstOp->getOperand(0));
  1113. unsigned DstBehaviorValue = DstBehavior->getZExtValue();
  1114. auto overrideDstValue = [&]() {
  1115. DstModFlags->setOperand(DstIndex, SrcOp);
  1116. Flags[ID].first = SrcOp;
  1117. };
  1118. // If either flag has override behavior, handle it first.
  1119. if (DstBehaviorValue == Module::Override) {
  1120. // Diagnose inconsistent flags which both have override behavior.
  1121. if (SrcBehaviorValue == Module::Override &&
  1122. SrcOp->getOperand(2) != DstOp->getOperand(2))
  1123. return stringErr("linking module flags '" + ID->getString() +
  1124. "': IDs have conflicting override values in '" +
  1125. SrcM->getModuleIdentifier() + "' and '" +
  1126. DstM.getModuleIdentifier() + "'");
  1127. continue;
  1128. } else if (SrcBehaviorValue == Module::Override) {
  1129. // Update the destination flag to that of the source.
  1130. overrideDstValue();
  1131. continue;
  1132. }
  1133. // Diagnose inconsistent merge behavior types.
  1134. if (SrcBehaviorValue != DstBehaviorValue) {
  1135. bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
  1136. DstBehaviorValue == Module::Warning) ||
  1137. (DstBehaviorValue == Module::Max &&
  1138. SrcBehaviorValue == Module::Warning);
  1139. if (!MaxAndWarn)
  1140. return stringErr("linking module flags '" + ID->getString() +
  1141. "': IDs have conflicting behaviors in '" +
  1142. SrcM->getModuleIdentifier() + "' and '" +
  1143. DstM.getModuleIdentifier() + "'");
  1144. }
  1145. auto replaceDstValue = [&](MDNode *New) {
  1146. Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
  1147. MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
  1148. DstModFlags->setOperand(DstIndex, Flag);
  1149. Flags[ID].first = Flag;
  1150. };
  1151. // Emit a warning if the values differ and either source or destination
  1152. // request Warning behavior.
  1153. if ((DstBehaviorValue == Module::Warning ||
  1154. SrcBehaviorValue == Module::Warning) &&
  1155. SrcOp->getOperand(2) != DstOp->getOperand(2)) {
  1156. std::string Str;
  1157. raw_string_ostream(Str)
  1158. << "linking module flags '" << ID->getString()
  1159. << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
  1160. << "' from " << SrcM->getModuleIdentifier() << " with '"
  1161. << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
  1162. << ')';
  1163. emitWarning(Str);
  1164. }
  1165. // Choose the maximum if either source or destination request Max behavior.
  1166. if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
  1167. ConstantInt *DstValue =
  1168. mdconst::extract<ConstantInt>(DstOp->getOperand(2));
  1169. ConstantInt *SrcValue =
  1170. mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
  1171. // The resulting flag should have a Max behavior, and contain the maximum
  1172. // value from between the source and destination values.
  1173. Metadata *FlagOps[] = {
  1174. (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
  1175. (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
  1176. ->getOperand(2)};
  1177. MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
  1178. DstModFlags->setOperand(DstIndex, Flag);
  1179. Flags[ID].first = Flag;
  1180. continue;
  1181. }
  1182. // Perform the merge for standard behavior types.
  1183. switch (SrcBehaviorValue) {
  1184. case Module::Require:
  1185. case Module::Override:
  1186. llvm_unreachable("not possible");
  1187. case Module::Error: {
  1188. // Emit an error if the values differ.
  1189. if (SrcOp->getOperand(2) != DstOp->getOperand(2))
  1190. return stringErr("linking module flags '" + ID->getString() +
  1191. "': IDs have conflicting values in '" +
  1192. SrcM->getModuleIdentifier() + "' and '" +
  1193. DstM.getModuleIdentifier() + "'");
  1194. continue;
  1195. }
  1196. case Module::Warning: {
  1197. break;
  1198. }
  1199. case Module::Max: {
  1200. break;
  1201. }
  1202. case Module::Append: {
  1203. MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
  1204. MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
  1205. SmallVector<Metadata *, 8> MDs;
  1206. MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
  1207. MDs.append(DstValue->op_begin(), DstValue->op_end());
  1208. MDs.append(SrcValue->op_begin(), SrcValue->op_end());
  1209. replaceDstValue(MDNode::get(DstM.getContext(), MDs));
  1210. break;
  1211. }
  1212. case Module::AppendUnique: {
  1213. SmallSetVector<Metadata *, 16> Elts;
  1214. MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
  1215. MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
  1216. Elts.insert(DstValue->op_begin(), DstValue->op_end());
  1217. Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
  1218. replaceDstValue(MDNode::get(DstM.getContext(),
  1219. makeArrayRef(Elts.begin(), Elts.end())));
  1220. break;
  1221. }
  1222. }
  1223. }
  1224. // Check all of the requirements.
  1225. for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
  1226. MDNode *Requirement = Requirements[I];
  1227. MDString *Flag = cast<MDString>(Requirement->getOperand(0));
  1228. Metadata *ReqValue = Requirement->getOperand(1);
  1229. MDNode *Op = Flags[Flag].first;
  1230. if (!Op || Op->getOperand(2) != ReqValue)
  1231. return stringErr("linking module flags '" + Flag->getString() +
  1232. "': does not have the required value");
  1233. }
  1234. return Error::success();
  1235. }
  1236. /// Return InlineAsm adjusted with target-specific directives if required.
  1237. /// For ARM and Thumb, we have to add directives to select the appropriate ISA
  1238. /// to support mixing module-level inline assembly from ARM and Thumb modules.
  1239. static std::string adjustInlineAsm(const std::string &InlineAsm,
  1240. const Triple &Triple) {
  1241. if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
  1242. return ".text\n.balign 2\n.thumb\n" + InlineAsm;
  1243. if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
  1244. return ".text\n.balign 4\n.arm\n" + InlineAsm;
  1245. return InlineAsm;
  1246. }
  1247. Error IRLinker::run() {
  1248. // Ensure metadata materialized before value mapping.
  1249. if (SrcM->getMaterializer())
  1250. if (Error Err = SrcM->getMaterializer()->materializeMetadata())
  1251. return Err;
  1252. // Inherit the target data from the source module if the destination module
  1253. // doesn't have one already.
  1254. if (DstM.getDataLayout().isDefault())
  1255. DstM.setDataLayout(SrcM->getDataLayout());
  1256. // Copy the target triple from the source to dest if the dest's is empty.
  1257. if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
  1258. DstM.setTargetTriple(SrcM->getTargetTriple());
  1259. Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
  1260. // During CUDA compilation we have to link with the bitcode supplied with
  1261. // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
  1262. // the layout that is different from the one used by LLVM/clang (it does not
  1263. // include i128). Issuing a warning is not very helpful as there's not much
  1264. // the user can do about it.
  1265. bool EnableDLWarning = true;
  1266. bool EnableTripleWarning = true;
  1267. if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
  1268. std::string ModuleId = SrcM->getModuleIdentifier();
  1269. StringRef FileName = llvm::sys::path::filename(ModuleId);
  1270. bool SrcIsLibDevice =
  1271. FileName.startswith("libdevice") && FileName.endswith(".10.bc");
  1272. bool SrcHasLibDeviceDL =
  1273. (SrcM->getDataLayoutStr().empty() ||
  1274. SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
  1275. // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
  1276. // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
  1277. // all NVPTX variants.
  1278. bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
  1279. SrcTriple.getOSName() == "gpulibs") ||
  1280. (SrcTriple.getVendorName() == "unknown" &&
  1281. SrcTriple.getOSName() == "unknown");
  1282. EnableTripleWarning = !(SrcIsLibDevice && SrcHasLibDeviceTriple);
  1283. EnableDLWarning = !(SrcIsLibDevice && SrcHasLibDeviceDL);
  1284. }
  1285. if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
  1286. emitWarning("Linking two modules of different data layouts: '" +
  1287. SrcM->getModuleIdentifier() + "' is '" +
  1288. SrcM->getDataLayoutStr() + "' whereas '" +
  1289. DstM.getModuleIdentifier() + "' is '" +
  1290. DstM.getDataLayoutStr() + "'\n");
  1291. }
  1292. if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
  1293. !SrcTriple.isCompatibleWith(DstTriple))
  1294. emitWarning("Linking two modules of different target triples: '" +
  1295. SrcM->getModuleIdentifier() + "' is '" +
  1296. SrcM->getTargetTriple() + "' whereas '" +
  1297. DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
  1298. "'\n");
  1299. DstM.setTargetTriple(SrcTriple.merge(DstTriple));
  1300. // Loop over all of the linked values to compute type mappings.
  1301. computeTypeMapping();
  1302. std::reverse(Worklist.begin(), Worklist.end());
  1303. while (!Worklist.empty()) {
  1304. GlobalValue *GV = Worklist.back();
  1305. Worklist.pop_back();
  1306. // Already mapped.
  1307. if (ValueMap.find(GV) != ValueMap.end() ||
  1308. IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
  1309. continue;
  1310. assert(!GV->isDeclaration());
  1311. Mapper.mapValue(*GV);
  1312. if (FoundError)
  1313. return std::move(*FoundError);
  1314. flushRAUWWorklist();
  1315. }
  1316. // Note that we are done linking global value bodies. This prevents
  1317. // metadata linking from creating new references.
  1318. DoneLinkingBodies = true;
  1319. Mapper.addFlags(RF_NullMapMissingGlobalValues);
  1320. // Remap all of the named MDNodes in Src into the DstM module. We do this
  1321. // after linking GlobalValues so that MDNodes that reference GlobalValues
  1322. // are properly remapped.
  1323. linkNamedMDNodes();
  1324. if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
  1325. // Append the module inline asm string.
  1326. DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
  1327. SrcTriple));
  1328. } else if (IsPerformingImport) {
  1329. // Import any symver directives for symbols in DstM.
  1330. ModuleSymbolTable::CollectAsmSymvers(*SrcM,
  1331. [&](StringRef Name, StringRef Alias) {
  1332. if (DstM.getNamedValue(Name)) {
  1333. SmallString<256> S(".symver ");
  1334. S += Name;
  1335. S += ", ";
  1336. S += Alias;
  1337. DstM.appendModuleInlineAsm(S);
  1338. }
  1339. });
  1340. }
  1341. // Reorder the globals just added to the destination module to match their
  1342. // original order in the source module.
  1343. Module::GlobalListType &Globals = DstM.getGlobalList();
  1344. for (GlobalVariable &GV : SrcM->globals()) {
  1345. if (GV.hasAppendingLinkage())
  1346. continue;
  1347. Value *NewValue = Mapper.mapValue(GV);
  1348. if (NewValue) {
  1349. auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
  1350. if (NewGV)
  1351. Globals.splice(Globals.end(), Globals, NewGV->getIterator());
  1352. }
  1353. }
  1354. // Merge the module flags into the DstM module.
  1355. return linkModuleFlagsMetadata();
  1356. }
  1357. IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
  1358. : ETypes(E), IsPacked(P) {}
  1359. IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
  1360. : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
  1361. bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
  1362. return IsPacked == That.IsPacked && ETypes == That.ETypes;
  1363. }
  1364. bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
  1365. return !this->operator==(That);
  1366. }
  1367. StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
  1368. return DenseMapInfo<StructType *>::getEmptyKey();
  1369. }
  1370. StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
  1371. return DenseMapInfo<StructType *>::getTombstoneKey();
  1372. }
  1373. unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
  1374. return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
  1375. Key.IsPacked);
  1376. }
  1377. unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
  1378. return getHashValue(KeyTy(ST));
  1379. }
  1380. bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
  1381. const StructType *RHS) {
  1382. if (RHS == getEmptyKey() || RHS == getTombstoneKey())
  1383. return false;
  1384. return LHS == KeyTy(RHS);
  1385. }
  1386. bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
  1387. const StructType *RHS) {
  1388. if (RHS == getEmptyKey() || RHS == getTombstoneKey())
  1389. return LHS == RHS;
  1390. return KeyTy(LHS) == KeyTy(RHS);
  1391. }
  1392. void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
  1393. assert(!Ty->isOpaque());
  1394. NonOpaqueStructTypes.insert(Ty);
  1395. }
  1396. void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
  1397. assert(!Ty->isOpaque());
  1398. NonOpaqueStructTypes.insert(Ty);
  1399. bool Removed = OpaqueStructTypes.erase(Ty);
  1400. (void)Removed;
  1401. assert(Removed);
  1402. }
  1403. void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
  1404. assert(Ty->isOpaque());
  1405. OpaqueStructTypes.insert(Ty);
  1406. }
  1407. StructType *
  1408. IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
  1409. bool IsPacked) {
  1410. IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
  1411. auto I = NonOpaqueStructTypes.find_as(Key);
  1412. return I == NonOpaqueStructTypes.end() ? nullptr : *I;
  1413. }
  1414. bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
  1415. if (Ty->isOpaque())
  1416. return OpaqueStructTypes.count(Ty);
  1417. auto I = NonOpaqueStructTypes.find(Ty);
  1418. return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
  1419. }
  1420. IRMover::IRMover(Module &M) : Composite(M) {
  1421. TypeFinder StructTypes;
  1422. StructTypes.run(M, /* OnlyNamed */ false);
  1423. for (StructType *Ty : StructTypes) {
  1424. if (Ty->isOpaque())
  1425. IdentifiedStructTypes.addOpaque(Ty);
  1426. else
  1427. IdentifiedStructTypes.addNonOpaque(Ty);
  1428. }
  1429. // Self-map metadatas in the destination module. This is needed when
  1430. // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
  1431. // destination module may be reached from the source module.
  1432. for (auto *MD : StructTypes.getVisitedMetadata()) {
  1433. SharedMDs[MD].reset(const_cast<MDNode *>(MD));
  1434. }
  1435. }
  1436. Error IRMover::move(
  1437. std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
  1438. std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
  1439. bool IsPerformingImport) {
  1440. IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
  1441. std::move(Src), ValuesToLink, std::move(AddLazyFor),
  1442. IsPerformingImport);
  1443. Error E = TheIRLinker.run();
  1444. Composite.dropTriviallyDeadConstantArrays();
  1445. return E;
  1446. }