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