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