IRMover.cpp 68 KB

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