LLVM  7.0.0svn
LowerTypeTests.cpp
Go to the documentation of this file.
1 //===- LowerTypeTests.cpp - type metadata lowering pass -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers type metadata and calls to the llvm.type.test intrinsic.
11 // It also ensures that globals are properly laid out for the
12 // llvm.icall.branch.funnel intrinsic.
13 // See http://llvm.org/docs/TypeMetadata.html for more information.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/PointerUnion.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/TinyPtrVector.h"
28 #include "llvm/ADT/Triple.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalObject.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/LLVMContext.h"
48 #include "llvm/IR/Metadata.h"
49 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Operator.h"
53 #include "llvm/IR/PassManager.h"
54 #include "llvm/IR/Type.h"
55 #include "llvm/IR/Use.h"
56 #include "llvm/IR/User.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/Allocator.h"
60 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/Error.h"
71 #include "llvm/Transforms/IPO.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstdint>
77 #include <memory>
78 #include <set>
79 #include <string>
80 #include <system_error>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 using namespace lowertypetests;
86 
87 #define DEBUG_TYPE "lowertypetests"
88 
89 STATISTIC(ByteArraySizeBits, "Byte array size in bits");
90 STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
91 STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
92 STATISTIC(NumTypeTestCallsLowered, "Number of type test calls lowered");
93 STATISTIC(NumTypeIdDisjointSets, "Number of disjoint sets of type identifiers");
94 
96  "lowertypetests-avoid-reuse",
97  cl::desc("Try to avoid reuse of byte array addresses using aliases"),
98  cl::Hidden, cl::init(true));
99 
101  "lowertypetests-summary-action",
102  cl::desc("What to do with the summary when running this pass"),
103  cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
105  "Import typeid resolutions from summary and globals"),
107  "Export typeid resolutions to summary and globals")),
108  cl::Hidden);
109 
111  "lowertypetests-read-summary",
112  cl::desc("Read summary from given YAML file before running pass"),
113  cl::Hidden);
114 
116  "lowertypetests-write-summary",
117  cl::desc("Write summary to given YAML file after running pass"),
118  cl::Hidden);
119 
121  if (Offset < ByteOffset)
122  return false;
123 
124  if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
125  return false;
126 
127  uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
128  if (BitOffset >= BitSize)
129  return false;
130 
131  return Bits.count(BitOffset);
132 }
133 
135  OS << "offset " << ByteOffset << " size " << BitSize << " align "
136  << (1 << AlignLog2);
137 
138  if (isAllOnes()) {
139  OS << " all-ones\n";
140  return;
141  }
142 
143  OS << " { ";
144  for (uint64_t B : Bits)
145  OS << B << ' ';
146  OS << "}\n";
147 }
148 
150  if (Min > Max)
151  Min = 0;
152 
153  // Normalize each offset against the minimum observed offset, and compute
154  // the bitwise OR of each of the offsets. The number of trailing zeros
155  // in the mask gives us the log2 of the alignment of all offsets, which
156  // allows us to compress the bitset by only storing one bit per aligned
157  // address.
158  uint64_t Mask = 0;
159  for (uint64_t &Offset : Offsets) {
160  Offset -= Min;
161  Mask |= Offset;
162  }
163 
164  BitSetInfo BSI;
165  BSI.ByteOffset = Min;
166 
167  BSI.AlignLog2 = 0;
168  if (Mask != 0)
170 
171  // Build the compressed bitset while normalizing the offsets against the
172  // computed alignment.
173  BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
174  for (uint64_t Offset : Offsets) {
175  Offset >>= BSI.AlignLog2;
176  BSI.Bits.insert(Offset);
177  }
178 
179  return BSI;
180 }
181 
182 void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
183  // Create a new fragment to hold the layout for F.
184  Fragments.emplace_back();
185  std::vector<uint64_t> &Fragment = Fragments.back();
186  uint64_t FragmentIndex = Fragments.size() - 1;
187 
188  for (auto ObjIndex : F) {
189  uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
190  if (OldFragmentIndex == 0) {
191  // We haven't seen this object index before, so just add it to the current
192  // fragment.
193  Fragment.push_back(ObjIndex);
194  } else {
195  // This index belongs to an existing fragment. Copy the elements of the
196  // old fragment into this one and clear the old fragment. We don't update
197  // the fragment map just yet, this ensures that any further references to
198  // indices from the old fragment in this fragment do not insert any more
199  // indices.
200  std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
201  Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
202  OldFragment.clear();
203  }
204  }
205 
206  // Update the fragment map to point our object indices to this fragment.
207  for (uint64_t ObjIndex : Fragment)
208  FragmentMap[ObjIndex] = FragmentIndex;
209 }
210 
211 void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
212  uint64_t BitSize, uint64_t &AllocByteOffset,
213  uint8_t &AllocMask) {
214  // Find the smallest current allocation.
215  unsigned Bit = 0;
216  for (unsigned I = 1; I != BitsPerByte; ++I)
217  if (BitAllocs[I] < BitAllocs[Bit])
218  Bit = I;
219 
220  AllocByteOffset = BitAllocs[Bit];
221 
222  // Add our size to it.
223  unsigned ReqSize = AllocByteOffset + BitSize;
224  BitAllocs[Bit] = ReqSize;
225  if (Bytes.size() < ReqSize)
226  Bytes.resize(ReqSize);
227 
228  // Set our bits.
229  AllocMask = 1 << Bit;
230  for (uint64_t B : Bits)
231  Bytes[AllocByteOffset + B] |= AllocMask;
232 }
233 
234 namespace {
235 
236 struct ByteArrayInfo {
237  std::set<uint64_t> Bits;
238  uint64_t BitSize;
239  GlobalVariable *ByteArray;
240  GlobalVariable *MaskGlobal;
241  uint8_t *MaskPtr = nullptr;
242 };
243 
244 /// A POD-like structure that we use to store a global reference together with
245 /// its metadata types. In this pass we frequently need to query the set of
246 /// metadata types referenced by a global, which at the IR level is an expensive
247 /// operation involving a map lookup; this data structure helps to reduce the
248 /// number of times we need to do this lookup.
249 class GlobalTypeMember final : TrailingObjects<GlobalTypeMember, MDNode *> {
250  friend TrailingObjects;
251 
252  GlobalObject *GO;
253  size_t NTypes;
254 
255  // For functions: true if this is a definition (either in the merged module or
256  // in one of the thinlto modules).
257  bool IsDefinition;
258 
259  // For functions: true if this function is either defined or used in a thinlto
260  // module and its jumptable entry needs to be exported to thinlto backends.
261  bool IsExported;
262 
263  size_t numTrailingObjects(OverloadToken<MDNode *>) const { return NTypes; }
264 
265 public:
266  static GlobalTypeMember *create(BumpPtrAllocator &Alloc, GlobalObject *GO,
267  bool IsDefinition, bool IsExported,
268  ArrayRef<MDNode *> Types) {
269  auto *GTM = static_cast<GlobalTypeMember *>(Alloc.Allocate(
270  totalSizeToAlloc<MDNode *>(Types.size()), alignof(GlobalTypeMember)));
271  GTM->GO = GO;
272  GTM->NTypes = Types.size();
273  GTM->IsDefinition = IsDefinition;
274  GTM->IsExported = IsExported;
275  std::uninitialized_copy(Types.begin(), Types.end(),
276  GTM->getTrailingObjects<MDNode *>());
277  return GTM;
278  }
279 
280  GlobalObject *getGlobal() const {
281  return GO;
282  }
283 
284  bool isDefinition() const {
285  return IsDefinition;
286  }
287 
288  bool isExported() const {
289  return IsExported;
290  }
291 
292  ArrayRef<MDNode *> types() const {
293  return makeArrayRef(getTrailingObjects<MDNode *>(), NTypes);
294  }
295 };
296 
297 struct ICallBranchFunnel final
298  : TrailingObjects<ICallBranchFunnel, GlobalTypeMember *> {
299  static ICallBranchFunnel *create(BumpPtrAllocator &Alloc, CallInst *CI,
301  unsigned UniqueId) {
302  auto *Call = static_cast<ICallBranchFunnel *>(
303  Alloc.Allocate(totalSizeToAlloc<GlobalTypeMember *>(Targets.size()),
304  alignof(ICallBranchFunnel)));
305  Call->CI = CI;
306  Call->UniqueId = UniqueId;
307  Call->NTargets = Targets.size();
308  std::uninitialized_copy(Targets.begin(), Targets.end(),
309  Call->getTrailingObjects<GlobalTypeMember *>());
310  return Call;
311  }
312 
313  CallInst *CI;
314  ArrayRef<GlobalTypeMember *> targets() const {
315  return makeArrayRef(getTrailingObjects<GlobalTypeMember *>(), NTargets);
316  }
317 
318  unsigned UniqueId;
319 
320 private:
321  size_t NTargets;
322 };
323 
324 class LowerTypeTestsModule {
325  Module &M;
326 
327  ModuleSummaryIndex *ExportSummary;
328  const ModuleSummaryIndex *ImportSummary;
329 
330  Triple::ArchType Arch;
331  Triple::OSType OS;
332  Triple::ObjectFormatType ObjectFormat;
333 
334  IntegerType *Int1Ty = Type::getInt1Ty(M.getContext());
335  IntegerType *Int8Ty = Type::getInt8Ty(M.getContext());
336  PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
337  ArrayType *Int8Arr0Ty = ArrayType::get(Type::getInt8Ty(M.getContext()), 0);
339  PointerType *Int32PtrTy = PointerType::getUnqual(Int32Ty);
340  IntegerType *Int64Ty = Type::getInt64Ty(M.getContext());
341  IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext(), 0);
342 
343  // Indirect function call index assignment counter for WebAssembly
344  uint64_t IndirectIndex = 1;
345 
346  // Mapping from type identifiers to the call sites that test them, as well as
347  // whether the type identifier needs to be exported to ThinLTO backends as
348  // part of the regular LTO phase of the ThinLTO pipeline (see exportTypeId).
349  struct TypeIdUserInfo {
350  std::vector<CallInst *> CallSites;
351  bool IsExported = false;
352  };
354 
355  /// This structure describes how to lower type tests for a particular type
356  /// identifier. It is either built directly from the global analysis (during
357  /// regular LTO or the regular LTO phase of ThinLTO), or indirectly using type
358  /// identifier summaries and external symbol references (in ThinLTO backends).
359  struct TypeIdLowering {
361 
362  /// All except Unsat: the start address within the combined global.
363  Constant *OffsetedGlobal;
364 
365  /// ByteArray, Inline, AllOnes: log2 of the required global alignment
366  /// relative to the start address.
368 
369  /// ByteArray, Inline, AllOnes: one less than the size of the memory region
370  /// covering members of this type identifier as a multiple of 2^AlignLog2.
371  Constant *SizeM1;
372 
373  /// ByteArray: the byte array to test the address against.
374  Constant *TheByteArray;
375 
376  /// ByteArray: the bit mask to apply to bytes loaded from the byte array.
377  Constant *BitMask;
378 
379  /// Inline: the bit mask to test the address against.
380  Constant *InlineBits;
381  };
382 
383  std::vector<ByteArrayInfo> ByteArrayInfos;
384 
385  Function *WeakInitializerFn = nullptr;
386 
387  bool shouldExportConstantsAsAbsoluteSymbols();
388  uint8_t *exportTypeId(StringRef TypeId, const TypeIdLowering &TIL);
389  TypeIdLowering importTypeId(StringRef TypeId);
390  void importTypeTest(CallInst *CI);
391  void importFunction(Function *F, bool isDefinition);
392 
393  BitSetInfo
394  buildBitSet(Metadata *TypeId,
395  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
396  ByteArrayInfo *createByteArray(BitSetInfo &BSI);
397  void allocateByteArrays();
398  Value *createBitSetTest(IRBuilder<> &B, const TypeIdLowering &TIL,
399  Value *BitOffset);
400  void lowerTypeTestCalls(
401  ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
402  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
403  Value *lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
404  const TypeIdLowering &TIL);
405 
406  void buildBitSetsFromGlobalVariables(ArrayRef<Metadata *> TypeIds,
408  unsigned getJumpTableEntrySize();
409  Type *getJumpTableEntryType();
410  void createJumpTableEntry(raw_ostream &AsmOS, raw_ostream &ConstraintOS,
411  Triple::ArchType JumpTableArch,
412  SmallVectorImpl<Value *> &AsmArgs, Function *Dest);
413  void verifyTypeMDNode(GlobalObject *GO, MDNode *Type);
414  void buildBitSetsFromFunctions(ArrayRef<Metadata *> TypeIds,
415  ArrayRef<GlobalTypeMember *> Functions);
416  void buildBitSetsFromFunctionsNative(ArrayRef<Metadata *> TypeIds,
417  ArrayRef<GlobalTypeMember *> Functions);
418  void buildBitSetsFromFunctionsWASM(ArrayRef<Metadata *> TypeIds,
419  ArrayRef<GlobalTypeMember *> Functions);
420  void
421  buildBitSetsFromDisjointSet(ArrayRef<Metadata *> TypeIds,
423  ArrayRef<ICallBranchFunnel *> ICallBranchFunnels);
424 
425  void replaceWeakDeclarationWithJumpTablePtr(Function *F, Constant *JT, bool IsDefinition);
426  void moveInitializerToModuleConstructor(GlobalVariable *GV);
427  void findGlobalVariableUsersOf(Constant *C,
429 
430  void createJumpTable(Function *F, ArrayRef<GlobalTypeMember *> Functions);
431 
432  /// replaceCfiUses - Go through the uses list for this definition
433  /// and make each use point to "V" instead of "this" when the use is outside
434  /// the block. 'This's use list is expected to have at least one element.
435  /// Unlike replaceAllUsesWith this function skips blockaddr and direct call
436  /// uses.
437  void replaceCfiUses(Function *Old, Value *New, bool IsDefinition);
438 
439  /// replaceDirectCalls - Go through the uses list for this definition and
440  /// replace each use, which is a direct function call.
441  void replaceDirectCalls(Value *Old, Value *New);
442 
443 public:
444  LowerTypeTestsModule(Module &M, ModuleSummaryIndex *ExportSummary,
445  const ModuleSummaryIndex *ImportSummary);
446 
447  bool lower();
448 
449  // Lower the module using the action and summary passed as command line
450  // arguments. For testing purposes only.
451  static bool runForTesting(Module &M);
452 };
453 
454 struct LowerTypeTests : public ModulePass {
455  static char ID;
456 
457  bool UseCommandLine = false;
458 
459  ModuleSummaryIndex *ExportSummary;
460  const ModuleSummaryIndex *ImportSummary;
461 
462  LowerTypeTests() : ModulePass(ID), UseCommandLine(true) {
464  }
465 
466  LowerTypeTests(ModuleSummaryIndex *ExportSummary,
467  const ModuleSummaryIndex *ImportSummary)
468  : ModulePass(ID), ExportSummary(ExportSummary),
469  ImportSummary(ImportSummary) {
471  }
472 
473  bool runOnModule(Module &M) override {
474  if (UseCommandLine)
475  return LowerTypeTestsModule::runForTesting(M);
476  return LowerTypeTestsModule(M, ExportSummary, ImportSummary).lower();
477  }
478 };
479 
480 } // end anonymous namespace
481 
482 char LowerTypeTests::ID = 0;
483 
484 INITIALIZE_PASS(LowerTypeTests, "lowertypetests", "Lower type metadata", false,
485  false)
486 
487 ModulePass *
489  const ModuleSummaryIndex *ImportSummary) {
490  return new LowerTypeTests(ExportSummary, ImportSummary);
491 }
492 
493 /// Build a bit set for TypeId using the object layouts in
494 /// GlobalLayout.
495 BitSetInfo LowerTypeTestsModule::buildBitSet(
496  Metadata *TypeId,
497  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
498  BitSetBuilder BSB;
499 
500  // Compute the byte offset of each address associated with this type
501  // identifier.
502  for (auto &GlobalAndOffset : GlobalLayout) {
503  for (MDNode *Type : GlobalAndOffset.first->types()) {
504  if (Type->getOperand(1) != TypeId)
505  continue;
506  uint64_t Offset =
507  cast<ConstantInt>(
508  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
509  ->getZExtValue();
510  BSB.addOffset(GlobalAndOffset.second + Offset);
511  }
512  }
513 
514  return BSB.build();
515 }
516 
517 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
518 /// Bits. This pattern matches to the bt instruction on x86.
520  Value *BitOffset) {
521  auto BitsType = cast<IntegerType>(Bits->getType());
522  unsigned BitWidth = BitsType->getBitWidth();
523 
524  BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
525  Value *BitIndex =
526  B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
527  Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
528  Value *MaskedBits = B.CreateAnd(Bits, BitMask);
529  return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
530 }
531 
532 ByteArrayInfo *LowerTypeTestsModule::createByteArray(BitSetInfo &BSI) {
533  // Create globals to stand in for byte arrays and masks. These never actually
534  // get initialized, we RAUW and erase them later in allocateByteArrays() once
535  // we know the offset and mask to use.
536  auto ByteArrayGlobal = new GlobalVariable(
537  M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
538  auto MaskGlobal = new GlobalVariable(M, Int8Ty, /*isConstant=*/true,
539  GlobalValue::PrivateLinkage, nullptr);
540 
541  ByteArrayInfos.emplace_back();
542  ByteArrayInfo *BAI = &ByteArrayInfos.back();
543 
544  BAI->Bits = BSI.Bits;
545  BAI->BitSize = BSI.BitSize;
546  BAI->ByteArray = ByteArrayGlobal;
547  BAI->MaskGlobal = MaskGlobal;
548  return BAI;
549 }
550 
551 void LowerTypeTestsModule::allocateByteArrays() {
552  std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
553  [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
554  return BAI1.BitSize > BAI2.BitSize;
555  });
556 
557  std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
558 
559  ByteArrayBuilder BAB;
560  for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
561  ByteArrayInfo *BAI = &ByteArrayInfos[I];
562 
563  uint8_t Mask;
564  BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
565 
566  BAI->MaskGlobal->replaceAllUsesWith(
567  ConstantExpr::getIntToPtr(ConstantInt::get(Int8Ty, Mask), Int8PtrTy));
568  BAI->MaskGlobal->eraseFromParent();
569  if (BAI->MaskPtr)
570  *BAI->MaskPtr = Mask;
571  }
572 
573  Constant *ByteArrayConst = ConstantDataArray::get(M.getContext(), BAB.Bytes);
574  auto ByteArray =
575  new GlobalVariable(M, ByteArrayConst->getType(), /*isConstant=*/true,
576  GlobalValue::PrivateLinkage, ByteArrayConst);
577 
578  for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
579  ByteArrayInfo *BAI = &ByteArrayInfos[I];
580 
581  Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
582  ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
584  ByteArrayConst->getType(), ByteArray, Idxs);
585 
586  // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
587  // that the pc-relative displacement is folded into the lea instead of the
588  // test instruction getting another displacement.
590  Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, &M);
591  BAI->ByteArray->replaceAllUsesWith(Alias);
592  BAI->ByteArray->eraseFromParent();
593  }
594 
595  ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
596  BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
597  BAB.BitAllocs[6] + BAB.BitAllocs[7];
598  ByteArraySizeBytes = BAB.Bytes.size();
599 }
600 
601 /// Build a test that bit BitOffset is set in the type identifier that was
602 /// lowered to TIL, which must be either an Inline or a ByteArray.
603 Value *LowerTypeTestsModule::createBitSetTest(IRBuilder<> &B,
604  const TypeIdLowering &TIL,
605  Value *BitOffset) {
606  if (TIL.TheKind == TypeTestResolution::Inline) {
607  // If the bit set is sufficiently small, we can avoid a load by bit testing
608  // a constant.
609  return createMaskedBitTest(B, TIL.InlineBits, BitOffset);
610  } else {
611  Constant *ByteArray = TIL.TheByteArray;
612  if (AvoidReuse && !ImportSummary) {
613  // Each use of the byte array uses a different alias. This makes the
614  // backend less likely to reuse previously computed byte array addresses,
615  // improving the security of the CFI mechanism based on this pass.
616  // This won't work when importing because TheByteArray is external.
617  ByteArray = GlobalAlias::create(Int8Ty, 0, GlobalValue::PrivateLinkage,
618  "bits_use", ByteArray, &M);
619  }
620 
621  Value *ByteAddr = B.CreateGEP(Int8Ty, ByteArray, BitOffset);
622  Value *Byte = B.CreateLoad(ByteAddr);
623 
624  Value *ByteAndMask =
625  B.CreateAnd(Byte, ConstantExpr::getPtrToInt(TIL.BitMask, Int8Ty));
626  return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
627  }
628 }
629 
630 static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL,
631  Value *V, uint64_t COffset) {
632  if (auto GV = dyn_cast<GlobalObject>(V)) {
634  GV->getMetadata(LLVMContext::MD_type, Types);
635  for (MDNode *Type : Types) {
636  if (Type->getOperand(1) != TypeId)
637  continue;
638  uint64_t Offset =
639  cast<ConstantInt>(
640  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
641  ->getZExtValue();
642  if (COffset == Offset)
643  return true;
644  }
645  return false;
646  }
647 
648  if (auto GEP = dyn_cast<GEPOperator>(V)) {
649  APInt APOffset(DL.getPointerSizeInBits(0), 0);
650  bool Result = GEP->accumulateConstantOffset(DL, APOffset);
651  if (!Result)
652  return false;
653  COffset += APOffset.getZExtValue();
654  return isKnownTypeIdMember(TypeId, DL, GEP->getPointerOperand(), COffset);
655  }
656 
657  if (auto Op = dyn_cast<Operator>(V)) {
658  if (Op->getOpcode() == Instruction::BitCast)
659  return isKnownTypeIdMember(TypeId, DL, Op->getOperand(0), COffset);
660 
661  if (Op->getOpcode() == Instruction::Select)
662  return isKnownTypeIdMember(TypeId, DL, Op->getOperand(1), COffset) &&
663  isKnownTypeIdMember(TypeId, DL, Op->getOperand(2), COffset);
664  }
665 
666  return false;
667 }
668 
669 /// Lower a llvm.type.test call to its implementation. Returns the value to
670 /// replace the call with.
671 Value *LowerTypeTestsModule::lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
672  const TypeIdLowering &TIL) {
673  if (TIL.TheKind == TypeTestResolution::Unsat)
674  return ConstantInt::getFalse(M.getContext());
675 
676  Value *Ptr = CI->getArgOperand(0);
677  const DataLayout &DL = M.getDataLayout();
678  if (isKnownTypeIdMember(TypeId, DL, Ptr, 0))
679  return ConstantInt::getTrue(M.getContext());
680 
681  BasicBlock *InitialBB = CI->getParent();
682 
683  IRBuilder<> B(CI);
684 
685  Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
686 
687  Constant *OffsetedGlobalAsInt =
688  ConstantExpr::getPtrToInt(TIL.OffsetedGlobal, IntPtrTy);
689  if (TIL.TheKind == TypeTestResolution::Single)
690  return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
691 
692  Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
693 
694  // We need to check that the offset both falls within our range and is
695  // suitably aligned. We can check both properties at the same time by
696  // performing a right rotate by log2(alignment) followed by an integer
697  // comparison against the bitset size. The rotate will move the lower
698  // order bits that need to be zero into the higher order bits of the
699  // result, causing the comparison to fail if they are nonzero. The rotate
700  // also conveniently gives us a bit offset to use during the load from
701  // the bitset.
702  Value *OffsetSHR =
703  B.CreateLShr(PtrOffset, ConstantExpr::getZExt(TIL.AlignLog2, IntPtrTy));
704  Value *OffsetSHL = B.CreateShl(
705  PtrOffset, ConstantExpr::getZExt(
707  ConstantInt::get(Int8Ty, DL.getPointerSizeInBits(0)),
708  TIL.AlignLog2),
709  IntPtrTy));
710  Value *BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
711 
712  Value *OffsetInRange = B.CreateICmpULE(BitOffset, TIL.SizeM1);
713 
714  // If the bit set is all ones, testing against it is unnecessary.
715  if (TIL.TheKind == TypeTestResolution::AllOnes)
716  return OffsetInRange;
717 
718  // See if the intrinsic is used in the following common pattern:
719  // br(llvm.type.test(...), thenbb, elsebb)
720  // where nothing happens between the type test and the br.
721  // If so, create slightly simpler IR.
722  if (CI->hasOneUse())
723  if (auto *Br = dyn_cast<BranchInst>(*CI->user_begin()))
724  if (CI->getNextNode() == Br) {
725  BasicBlock *Then = InitialBB->splitBasicBlock(CI->getIterator());
726  BasicBlock *Else = Br->getSuccessor(1);
727  BranchInst *NewBr = BranchInst::Create(Then, Else, OffsetInRange);
729  Br->getMetadata(LLVMContext::MD_prof));
730  ReplaceInstWithInst(InitialBB->getTerminator(), NewBr);
731 
732  // Update phis in Else resulting from InitialBB being split
733  for (auto &Phi : Else->phis())
734  Phi.addIncoming(Phi.getIncomingValueForBlock(Then), InitialBB);
735 
736  IRBuilder<> ThenB(CI);
737  return createBitSetTest(ThenB, TIL, BitOffset);
738  }
739 
740  IRBuilder<> ThenB(SplitBlockAndInsertIfThen(OffsetInRange, CI, false));
741 
742  // Now that we know that the offset is in range and aligned, load the
743  // appropriate bit from the bitset.
744  Value *Bit = createBitSetTest(ThenB, TIL, BitOffset);
745 
746  // The value we want is 0 if we came directly from the initial block
747  // (having failed the range or alignment checks), or the loaded bit if
748  // we came from the block in which we loaded it.
749  B.SetInsertPoint(CI);
750  PHINode *P = B.CreatePHI(Int1Ty, 2);
751  P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
752  P->addIncoming(Bit, ThenB.GetInsertBlock());
753  return P;
754 }
755 
756 /// Given a disjoint set of type identifiers and globals, lay out the globals,
757 /// build the bit sets and lower the llvm.type.test calls.
758 void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
760  // Build a new global with the combined contents of the referenced globals.
761  // This global is a struct whose even-indexed elements contain the original
762  // contents of the referenced globals and whose odd-indexed elements contain
763  // any padding required to align the next element to the next power of 2.
764  std::vector<Constant *> GlobalInits;
765  const DataLayout &DL = M.getDataLayout();
766  for (GlobalTypeMember *G : Globals) {
767  GlobalVariable *GV = cast<GlobalVariable>(G->getGlobal());
768  GlobalInits.push_back(GV->getInitializer());
769  uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
770 
771  // Compute the amount of padding required.
772  uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
773 
774  // Cap at 128 was found experimentally to have a good data/instruction
775  // overhead tradeoff.
776  if (Padding > 128)
777  Padding = alignTo(InitSize, 128) - InitSize;
778 
779  GlobalInits.push_back(
780  ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
781  }
782  if (!GlobalInits.empty())
783  GlobalInits.pop_back();
784  Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
785  auto *CombinedGlobal =
786  new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
787  GlobalValue::PrivateLinkage, NewInit);
788 
789  StructType *NewTy = cast<StructType>(NewInit->getType());
790  const StructLayout *CombinedGlobalLayout = DL.getStructLayout(NewTy);
791 
792  // Compute the offsets of the original globals within the new global.
794  for (unsigned I = 0; I != Globals.size(); ++I)
795  // Multiply by 2 to account for padding elements.
796  GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
797 
798  lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
799 
800  // Build aliases pointing to offsets into the combined global for each
801  // global from which we built the combined global, and replace references
802  // to the original globals with references to the aliases.
803  for (unsigned I = 0; I != Globals.size(); ++I) {
804  GlobalVariable *GV = cast<GlobalVariable>(Globals[I]->getGlobal());
805 
806  // Multiply by 2 to account for padding elements.
807  Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
808  ConstantInt::get(Int32Ty, I * 2)};
809  Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
810  NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
811  assert(GV->getType()->getAddressSpace() == 0);
812  GlobalAlias *GAlias =
813  GlobalAlias::create(NewTy->getElementType(I * 2), 0, GV->getLinkage(),
814  "", CombinedGlobalElemPtr, &M);
815  GAlias->setVisibility(GV->getVisibility());
816  GAlias->takeName(GV);
817  GV->replaceAllUsesWith(GAlias);
818  GV->eraseFromParent();
819  }
820 }
821 
822 bool LowerTypeTestsModule::shouldExportConstantsAsAbsoluteSymbols() {
823  return (Arch == Triple::x86 || Arch == Triple::x86_64) &&
824  ObjectFormat == Triple::ELF;
825 }
826 
827 /// Export the given type identifier so that ThinLTO backends may import it.
828 /// Type identifiers are exported by adding coarse-grained information about how
829 /// to test the type identifier to the summary, and creating symbols in the
830 /// object file (aliases and absolute symbols) containing fine-grained
831 /// information about the type identifier.
832 ///
833 /// Returns a pointer to the location in which to store the bitmask, if
834 /// applicable.
835 uint8_t *LowerTypeTestsModule::exportTypeId(StringRef TypeId,
836  const TypeIdLowering &TIL) {
837  TypeTestResolution &TTRes =
838  ExportSummary->getOrInsertTypeIdSummary(TypeId).TTRes;
839  TTRes.TheKind = TIL.TheKind;
840 
841  auto ExportGlobal = [&](StringRef Name, Constant *C) {
842  GlobalAlias *GA =
844  "__typeid_" + TypeId + "_" + Name, C, &M);
846  };
847 
848  auto ExportConstant = [&](StringRef Name, uint64_t &Storage, Constant *C) {
849  if (shouldExportConstantsAsAbsoluteSymbols())
850  ExportGlobal(Name, ConstantExpr::getIntToPtr(C, Int8PtrTy));
851  else
852  Storage = cast<ConstantInt>(C)->getZExtValue();
853  };
854 
855  if (TIL.TheKind != TypeTestResolution::Unsat)
856  ExportGlobal("global_addr", TIL.OffsetedGlobal);
857 
858  if (TIL.TheKind == TypeTestResolution::ByteArray ||
859  TIL.TheKind == TypeTestResolution::Inline ||
860  TIL.TheKind == TypeTestResolution::AllOnes) {
861  ExportConstant("align", TTRes.AlignLog2, TIL.AlignLog2);
862  ExportConstant("size_m1", TTRes.SizeM1, TIL.SizeM1);
863 
864  uint64_t BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
865  if (TIL.TheKind == TypeTestResolution::Inline)
866  TTRes.SizeM1BitWidth = (BitSize <= 32) ? 5 : 6;
867  else
868  TTRes.SizeM1BitWidth = (BitSize <= 128) ? 7 : 32;
869  }
870 
871  if (TIL.TheKind == TypeTestResolution::ByteArray) {
872  ExportGlobal("byte_array", TIL.TheByteArray);
873  if (shouldExportConstantsAsAbsoluteSymbols())
874  ExportGlobal("bit_mask", TIL.BitMask);
875  else
876  return &TTRes.BitMask;
877  }
878 
879  if (TIL.TheKind == TypeTestResolution::Inline)
880  ExportConstant("inline_bits", TTRes.InlineBits, TIL.InlineBits);
881 
882  return nullptr;
883 }
884 
885 LowerTypeTestsModule::TypeIdLowering
886 LowerTypeTestsModule::importTypeId(StringRef TypeId) {
887  const TypeIdSummary *TidSummary = ImportSummary->getTypeIdSummary(TypeId);
888  if (!TidSummary)
889  return {}; // Unsat: no globals match this type id.
890  const TypeTestResolution &TTRes = TidSummary->TTRes;
891 
892  TypeIdLowering TIL;
893  TIL.TheKind = TTRes.TheKind;
894 
895  auto ImportGlobal = [&](StringRef Name) {
896  // Give the global a type of length 0 so that it is not assumed not to alias
897  // with any other global.
898  Constant *C = M.getOrInsertGlobal(("__typeid_" + TypeId + "_" + Name).str(),
899  Int8Arr0Ty);
900  if (auto *GV = dyn_cast<GlobalVariable>(C))
901  GV->setVisibility(GlobalValue::HiddenVisibility);
902  C = ConstantExpr::getBitCast(C, Int8PtrTy);
903  return C;
904  };
905 
906  auto ImportConstant = [&](StringRef Name, uint64_t Const, unsigned AbsWidth,
907  Type *Ty) {
908  if (!shouldExportConstantsAsAbsoluteSymbols()) {
909  Constant *C =
910  ConstantInt::get(isa<IntegerType>(Ty) ? Ty : Int64Ty, Const);
911  if (!isa<IntegerType>(Ty))
912  C = ConstantExpr::getIntToPtr(C, Ty);
913  return C;
914  }
915 
916  Constant *C = ImportGlobal(Name);
917  auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
918  if (isa<IntegerType>(Ty))
919  C = ConstantExpr::getPtrToInt(C, Ty);
920  if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
921  return C;
922 
923  auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
924  auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
925  auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
926  GV->setMetadata(LLVMContext::MD_absolute_symbol,
927  MDNode::get(M.getContext(), {MinC, MaxC}));
928  };
929  if (AbsWidth == IntPtrTy->getBitWidth())
930  SetAbsRange(~0ull, ~0ull); // Full set.
931  else
932  SetAbsRange(0, 1ull << AbsWidth);
933  return C;
934  };
935 
936  if (TIL.TheKind != TypeTestResolution::Unsat)
937  TIL.OffsetedGlobal = ImportGlobal("global_addr");
938 
939  if (TIL.TheKind == TypeTestResolution::ByteArray ||
940  TIL.TheKind == TypeTestResolution::Inline ||
941  TIL.TheKind == TypeTestResolution::AllOnes) {
942  TIL.AlignLog2 = ImportConstant("align", TTRes.AlignLog2, 8, Int8Ty);
943  TIL.SizeM1 =
944  ImportConstant("size_m1", TTRes.SizeM1, TTRes.SizeM1BitWidth, IntPtrTy);
945  }
946 
947  if (TIL.TheKind == TypeTestResolution::ByteArray) {
948  TIL.TheByteArray = ImportGlobal("byte_array");
949  TIL.BitMask = ImportConstant("bit_mask", TTRes.BitMask, 8, Int8PtrTy);
950  }
951 
952  if (TIL.TheKind == TypeTestResolution::Inline)
953  TIL.InlineBits = ImportConstant(
954  "inline_bits", TTRes.InlineBits, 1 << TTRes.SizeM1BitWidth,
955  TTRes.SizeM1BitWidth <= 5 ? Int32Ty : Int64Ty);
956 
957  return TIL;
958 }
959 
960 void LowerTypeTestsModule::importTypeTest(CallInst *CI) {
961  auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
962  if (!TypeIdMDVal)
963  report_fatal_error("Second argument of llvm.type.test must be metadata");
964 
965  auto TypeIdStr = dyn_cast<MDString>(TypeIdMDVal->getMetadata());
966  if (!TypeIdStr)
968  "Second argument of llvm.type.test must be a metadata string");
969 
970  TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
971  Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
972  CI->replaceAllUsesWith(Lowered);
973  CI->eraseFromParent();
974 }
975 
976 // ThinLTO backend: the function F has a jump table entry; update this module
977 // accordingly. isDefinition describes the type of the jump table entry.
978 void LowerTypeTestsModule::importFunction(Function *F, bool isDefinition) {
979  assert(F->getType()->getAddressSpace() == 0);
980 
982  std::string Name = F->getName();
983 
984  if (F->isDeclarationForLinker() && isDefinition) {
985  // Non-dso_local functions may be overriden at run time,
986  // don't short curcuit them
987  if (F->isDSOLocal()) {
990  Name + ".cfi", &M);
992  replaceDirectCalls(F, RealF);
993  }
994  return;
995  }
996 
997  Function *FDecl;
998  if (F->isDeclarationForLinker() && !isDefinition) {
999  // Declaration of an external function.
1001  Name + ".cfi_jt", &M);
1003  } else if (isDefinition) {
1004  F->setName(Name + ".cfi");
1007  Name, &M);
1008  FDecl->setVisibility(Visibility);
1009  Visibility = GlobalValue::HiddenVisibility;
1010 
1011  // Delete aliases pointing to this function, they'll be re-created in the
1012  // merged output
1014  for (auto &U : F->uses()) {
1015  if (auto *A = dyn_cast<GlobalAlias>(U.getUser())) {
1016  Function *AliasDecl = Function::Create(
1018  AliasDecl->takeName(A);
1019  A->replaceAllUsesWith(AliasDecl);
1020  ToErase.push_back(A);
1021  }
1022  }
1023  for (auto *A : ToErase)
1024  A->eraseFromParent();
1025  } else {
1026  // Function definition without type metadata, where some other translation
1027  // unit contained a declaration with type metadata. This normally happens
1028  // during mixed CFI + non-CFI compilation. We do nothing with the function
1029  // so that it is treated the same way as a function defined outside of the
1030  // LTO unit.
1031  return;
1032  }
1033 
1034  if (F->isWeakForLinker())
1035  replaceWeakDeclarationWithJumpTablePtr(F, FDecl, isDefinition);
1036  else
1037  replaceCfiUses(F, FDecl, isDefinition);
1038 
1039  // Set visibility late because it's used in replaceCfiUses() to determine
1040  // whether uses need to to be replaced.
1041  F->setVisibility(Visibility);
1042 }
1043 
1044 void LowerTypeTestsModule::lowerTypeTestCalls(
1045  ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
1046  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
1047  CombinedGlobalAddr = ConstantExpr::getBitCast(CombinedGlobalAddr, Int8PtrTy);
1048 
1049  // For each type identifier in this disjoint set...
1050  for (Metadata *TypeId : TypeIds) {
1051  // Build the bitset.
1052  BitSetInfo BSI = buildBitSet(TypeId, GlobalLayout);
1053  LLVM_DEBUG({
1054  if (auto MDS = dyn_cast<MDString>(TypeId))
1055  dbgs() << MDS->getString() << ": ";
1056  else
1057  dbgs() << "<unnamed>: ";
1058  BSI.print(dbgs());
1059  });
1060 
1061  ByteArrayInfo *BAI = nullptr;
1062  TypeIdLowering TIL;
1063  TIL.OffsetedGlobal = ConstantExpr::getGetElementPtr(
1064  Int8Ty, CombinedGlobalAddr, ConstantInt::get(IntPtrTy, BSI.ByteOffset)),
1065  TIL.AlignLog2 = ConstantInt::get(Int8Ty, BSI.AlignLog2);
1066  TIL.SizeM1 = ConstantInt::get(IntPtrTy, BSI.BitSize - 1);
1067  if (BSI.isAllOnes()) {
1068  TIL.TheKind = (BSI.BitSize == 1) ? TypeTestResolution::Single
1070  } else if (BSI.BitSize <= 64) {
1071  TIL.TheKind = TypeTestResolution::Inline;
1072  uint64_t InlineBits = 0;
1073  for (auto Bit : BSI.Bits)
1074  InlineBits |= uint64_t(1) << Bit;
1075  if (InlineBits == 0)
1076  TIL.TheKind = TypeTestResolution::Unsat;
1077  else
1078  TIL.InlineBits = ConstantInt::get(
1079  (BSI.BitSize <= 32) ? Int32Ty : Int64Ty, InlineBits);
1080  } else {
1081  TIL.TheKind = TypeTestResolution::ByteArray;
1082  ++NumByteArraysCreated;
1083  BAI = createByteArray(BSI);
1084  TIL.TheByteArray = BAI->ByteArray;
1085  TIL.BitMask = BAI->MaskGlobal;
1086  }
1087 
1088  TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
1089 
1090  if (TIUI.IsExported) {
1091  uint8_t *MaskPtr = exportTypeId(cast<MDString>(TypeId)->getString(), TIL);
1092  if (BAI)
1093  BAI->MaskPtr = MaskPtr;
1094  }
1095 
1096  // Lower each call to llvm.type.test for this type identifier.
1097  for (CallInst *CI : TIUI.CallSites) {
1098  ++NumTypeTestCallsLowered;
1099  Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
1100  CI->replaceAllUsesWith(Lowered);
1101  CI->eraseFromParent();
1102  }
1103  }
1104 }
1105 
1106 void LowerTypeTestsModule::verifyTypeMDNode(GlobalObject *GO, MDNode *Type) {
1107  if (Type->getNumOperands() != 2)
1108  report_fatal_error("All operands of type metadata must have 2 elements");
1109 
1110  if (GO->isThreadLocal())
1111  report_fatal_error("Bit set element may not be thread-local");
1112  if (isa<GlobalVariable>(GO) && GO->hasSection())
1114  "A member of a type identifier may not have an explicit section");
1115 
1116  // FIXME: We previously checked that global var member of a type identifier
1117  // must be a definition, but the IR linker may leave type metadata on
1118  // declarations. We should restore this check after fixing PR31759.
1119 
1120  auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Type->getOperand(0));
1121  if (!OffsetConstMD)
1122  report_fatal_error("Type offset must be a constant");
1123  auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
1124  if (!OffsetInt)
1125  report_fatal_error("Type offset must be an integer constant");
1126 }
1127 
1128 static const unsigned kX86JumpTableEntrySize = 8;
1129 static const unsigned kARMJumpTableEntrySize = 4;
1130 
1131 unsigned LowerTypeTestsModule::getJumpTableEntrySize() {
1132  switch (Arch) {
1133  case Triple::x86:
1134  case Triple::x86_64:
1135  return kX86JumpTableEntrySize;
1136  case Triple::arm:
1137  case Triple::thumb:
1138  case Triple::aarch64:
1139  return kARMJumpTableEntrySize;
1140  default:
1141  report_fatal_error("Unsupported architecture for jump tables");
1142  }
1143 }
1144 
1145 // Create a jump table entry for the target. This consists of an instruction
1146 // sequence containing a relative branch to Dest. Appends inline asm text,
1147 // constraints and arguments to AsmOS, ConstraintOS and AsmArgs.
1148 void LowerTypeTestsModule::createJumpTableEntry(
1149  raw_ostream &AsmOS, raw_ostream &ConstraintOS,
1150  Triple::ArchType JumpTableArch, SmallVectorImpl<Value *> &AsmArgs,
1151  Function *Dest) {
1152  unsigned ArgIndex = AsmArgs.size();
1153 
1154  if (JumpTableArch == Triple::x86 || JumpTableArch == Triple::x86_64) {
1155  AsmOS << "jmp ${" << ArgIndex << ":c}@plt\n";
1156  AsmOS << "int3\nint3\nint3\n";
1157  } else if (JumpTableArch == Triple::arm || JumpTableArch == Triple::aarch64) {
1158  AsmOS << "b $" << ArgIndex << "\n";
1159  } else if (JumpTableArch == Triple::thumb) {
1160  AsmOS << "b.w $" << ArgIndex << "\n";
1161  } else {
1162  report_fatal_error("Unsupported architecture for jump tables");
1163  }
1164 
1165  ConstraintOS << (ArgIndex > 0 ? ",s" : "s");
1166  AsmArgs.push_back(Dest);
1167 }
1168 
1169 Type *LowerTypeTestsModule::getJumpTableEntryType() {
1170  return ArrayType::get(Int8Ty, getJumpTableEntrySize());
1171 }
1172 
1173 /// Given a disjoint set of type identifiers and functions, build the bit sets
1174 /// and lower the llvm.type.test calls, architecture dependently.
1175 void LowerTypeTestsModule::buildBitSetsFromFunctions(
1177  if (Arch == Triple::x86 || Arch == Triple::x86_64 || Arch == Triple::arm ||
1178  Arch == Triple::thumb || Arch == Triple::aarch64)
1179  buildBitSetsFromFunctionsNative(TypeIds, Functions);
1180  else if (Arch == Triple::wasm32 || Arch == Triple::wasm64)
1181  buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1182  else
1183  report_fatal_error("Unsupported architecture for jump tables");
1184 }
1185 
1186 void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1187  GlobalVariable *GV) {
1188  if (WeakInitializerFn == nullptr) {
1189  WeakInitializerFn = Function::Create(
1190  FunctionType::get(Type::getVoidTy(M.getContext()),
1191  /* IsVarArg */ false),
1192  GlobalValue::InternalLinkage, "__cfi_global_var_init", &M);
1193  BasicBlock *BB =
1194  BasicBlock::Create(M.getContext(), "entry", WeakInitializerFn);
1195  ReturnInst::Create(M.getContext(), BB);
1196  WeakInitializerFn->setSection(
1197  ObjectFormat == Triple::MachO
1198  ? "__TEXT,__StaticInit,regular,pure_instructions"
1199  : ".text.startup");
1200  // This code is equivalent to relocation application, and should run at the
1201  // earliest possible time (i.e. with the highest priority).
1202  appendToGlobalCtors(M, WeakInitializerFn, /* Priority */ 0);
1203  }
1204 
1205  IRBuilder<> IRB(WeakInitializerFn->getEntryBlock().getTerminator());
1206  GV->setConstant(false);
1207  IRB.CreateAlignedStore(GV->getInitializer(), GV, GV->getAlignment());
1209 }
1210 
1211 void LowerTypeTestsModule::findGlobalVariableUsersOf(
1213  for (auto *U : C->users()){
1214  if (auto *GV = dyn_cast<GlobalVariable>(U))
1215  Out.insert(GV);
1216  else if (auto *C2 = dyn_cast<Constant>(U))
1217  findGlobalVariableUsersOf(C2, Out);
1218  }
1219 }
1220 
1221 // Replace all uses of F with (F ? JT : 0).
1222 void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1223  Function *F, Constant *JT, bool IsDefinition) {
1224  // The target expression can not appear in a constant initializer on most
1225  // (all?) targets. Switch to a runtime initializer.
1226  SmallSetVector<GlobalVariable *, 8> GlobalVarUsers;
1227  findGlobalVariableUsersOf(F, GlobalVarUsers);
1228  for (auto GV : GlobalVarUsers)
1229  moveInitializerToModuleConstructor(GV);
1230 
1231  // Can not RAUW F with an expression that uses F. Replace with a temporary
1232  // placeholder first.
1233  Function *PlaceholderFn =
1234  Function::Create(cast<FunctionType>(F->getValueType()),
1236  replaceCfiUses(F, PlaceholderFn, IsDefinition);
1237 
1242  PlaceholderFn->replaceAllUsesWith(Target);
1243  PlaceholderFn->eraseFromParent();
1244 }
1245 
1246 static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch) {
1247  Attribute TFAttr = F->getFnAttribute("target-features");
1248  if (!TFAttr.hasAttribute(Attribute::None)) {
1250  TFAttr.getValueAsString().split(Features, ',');
1251  for (StringRef Feature : Features) {
1252  if (Feature == "-thumb-mode")
1253  return false;
1254  else if (Feature == "+thumb-mode")
1255  return true;
1256  }
1257  }
1258 
1259  return ModuleArch == Triple::thumb;
1260 }
1261 
1262 // Each jump table must be either ARM or Thumb as a whole for the bit-test math
1263 // to work. Pick one that matches the majority of members to minimize interop
1264 // veneers inserted by the linker.
1265 static Triple::ArchType
1267  Triple::ArchType ModuleArch) {
1268  if (ModuleArch != Triple::arm && ModuleArch != Triple::thumb)
1269  return ModuleArch;
1270 
1271  unsigned ArmCount = 0, ThumbCount = 0;
1272  for (const auto GTM : Functions) {
1273  if (!GTM->isDefinition()) {
1274  // PLT stubs are always ARM.
1275  ++ArmCount;
1276  continue;
1277  }
1278 
1279  Function *F = cast<Function>(GTM->getGlobal());
1280  ++(isThumbFunction(F, ModuleArch) ? ThumbCount : ArmCount);
1281  }
1282 
1283  return ArmCount > ThumbCount ? Triple::arm : Triple::thumb;
1284 }
1285 
1286 void LowerTypeTestsModule::createJumpTable(
1287  Function *F, ArrayRef<GlobalTypeMember *> Functions) {
1288  std::string AsmStr, ConstraintStr;
1289  raw_string_ostream AsmOS(AsmStr), ConstraintOS(ConstraintStr);
1290  SmallVector<Value *, 16> AsmArgs;
1291  AsmArgs.reserve(Functions.size() * 2);
1292 
1293  Triple::ArchType JumpTableArch = selectJumpTableArmEncoding(Functions, Arch);
1294 
1295  for (unsigned I = 0; I != Functions.size(); ++I)
1296  createJumpTableEntry(AsmOS, ConstraintOS, JumpTableArch, AsmArgs,
1297  cast<Function>(Functions[I]->getGlobal()));
1298 
1299  // Align the whole table by entry size.
1300  F->setAlignment(getJumpTableEntrySize());
1301  // Skip prologue.
1302  // Disabled on win32 due to https://llvm.org/bugs/show_bug.cgi?id=28641#c3.
1303  // Luckily, this function does not get any prologue even without the
1304  // attribute.
1305  if (OS != Triple::Win32)
1306  F->addFnAttr(Attribute::Naked);
1307  if (JumpTableArch == Triple::arm)
1308  F->addFnAttr("target-features", "-thumb-mode");
1309  if (JumpTableArch == Triple::thumb) {
1310  F->addFnAttr("target-features", "+thumb-mode");
1311  // Thumb jump table assembly needs Thumb2. The following attribute is added
1312  // by Clang for -march=armv7.
1313  F->addFnAttr("target-cpu", "cortex-a8");
1314  }
1315  // Make sure we don't emit .eh_frame for this function.
1316  F->addFnAttr(Attribute::NoUnwind);
1317 
1318  BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", F);
1319  IRBuilder<> IRB(BB);
1320 
1321  SmallVector<Type *, 16> ArgTypes;
1322  ArgTypes.reserve(AsmArgs.size());
1323  for (const auto &Arg : AsmArgs)
1324  ArgTypes.push_back(Arg->getType());
1325  InlineAsm *JumpTableAsm =
1326  InlineAsm::get(FunctionType::get(IRB.getVoidTy(), ArgTypes, false),
1327  AsmOS.str(), ConstraintOS.str(),
1328  /*hasSideEffects=*/true);
1329 
1330  IRB.CreateCall(JumpTableAsm, AsmArgs);
1331  IRB.CreateUnreachable();
1332 }
1333 
1334 /// Given a disjoint set of type identifiers and functions, build a jump table
1335 /// for the functions, build the bit sets and lower the llvm.type.test calls.
1336 void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
1338  // Unlike the global bitset builder, the function bitset builder cannot
1339  // re-arrange functions in a particular order and base its calculations on the
1340  // layout of the functions' entry points, as we have no idea how large a
1341  // particular function will end up being (the size could even depend on what
1342  // this pass does!) Instead, we build a jump table, which is a block of code
1343  // consisting of one branch instruction for each of the functions in the bit
1344  // set that branches to the target function, and redirect any taken function
1345  // addresses to the corresponding jump table entry. In the object file's
1346  // symbol table, the symbols for the target functions also refer to the jump
1347  // table entries, so that addresses taken outside the module will pass any
1348  // verification done inside the module.
1349  //
1350  // In more concrete terms, suppose we have three functions f, g, h which are
1351  // of the same type, and a function foo that returns their addresses:
1352  //
1353  // f:
1354  // mov 0, %eax
1355  // ret
1356  //
1357  // g:
1358  // mov 1, %eax
1359  // ret
1360  //
1361  // h:
1362  // mov 2, %eax
1363  // ret
1364  //
1365  // foo:
1366  // mov f, %eax
1367  // mov g, %edx
1368  // mov h, %ecx
1369  // ret
1370  //
1371  // We output the jump table as module-level inline asm string. The end result
1372  // will (conceptually) look like this:
1373  //
1374  // f = .cfi.jumptable
1375  // g = .cfi.jumptable + 4
1376  // h = .cfi.jumptable + 8
1377  // .cfi.jumptable:
1378  // jmp f.cfi ; 5 bytes
1379  // int3 ; 1 byte
1380  // int3 ; 1 byte
1381  // int3 ; 1 byte
1382  // jmp g.cfi ; 5 bytes
1383  // int3 ; 1 byte
1384  // int3 ; 1 byte
1385  // int3 ; 1 byte
1386  // jmp h.cfi ; 5 bytes
1387  // int3 ; 1 byte
1388  // int3 ; 1 byte
1389  // int3 ; 1 byte
1390  //
1391  // f.cfi:
1392  // mov 0, %eax
1393  // ret
1394  //
1395  // g.cfi:
1396  // mov 1, %eax
1397  // ret
1398  //
1399  // h.cfi:
1400  // mov 2, %eax
1401  // ret
1402  //
1403  // foo:
1404  // mov f, %eax
1405  // mov g, %edx
1406  // mov h, %ecx
1407  // ret
1408  //
1409  // Because the addresses of f, g, h are evenly spaced at a power of 2, in the
1410  // normal case the check can be carried out using the same kind of simple
1411  // arithmetic that we normally use for globals.
1412 
1413  // FIXME: find a better way to represent the jumptable in the IR.
1414  assert(!Functions.empty());
1415 
1416  // Build a simple layout based on the regular layout of jump tables.
1418  unsigned EntrySize = getJumpTableEntrySize();
1419  for (unsigned I = 0; I != Functions.size(); ++I)
1420  GlobalLayout[Functions[I]] = I * EntrySize;
1421 
1422  Function *JumpTableFn =
1424  /* IsVarArg */ false),
1425  GlobalValue::PrivateLinkage, ".cfi.jumptable", &M);
1427  ArrayType::get(getJumpTableEntryType(), Functions.size());
1428  auto JumpTable =
1429  ConstantExpr::getPointerCast(JumpTableFn, JumpTableType->getPointerTo(0));
1430 
1431  lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
1432 
1433  // Build aliases pointing to offsets into the jump table, and replace
1434  // references to the original functions with references to the aliases.
1435  for (unsigned I = 0; I != Functions.size(); ++I) {
1436  Function *F = cast<Function>(Functions[I]->getGlobal());
1437  bool IsDefinition = Functions[I]->isDefinition();
1438 
1439  Constant *CombinedGlobalElemPtr = ConstantExpr::getBitCast(
1441  JumpTableType, JumpTable,
1443  ConstantInt::get(IntPtrTy, I)}),
1444  F->getType());
1445  if (Functions[I]->isExported()) {
1446  if (IsDefinition) {
1447  ExportSummary->cfiFunctionDefs().insert(F->getName());
1448  } else {
1449  GlobalAlias *JtAlias = GlobalAlias::create(
1451  F->getName() + ".cfi_jt", CombinedGlobalElemPtr, &M);
1453  ExportSummary->cfiFunctionDecls().insert(F->getName());
1454  }
1455  }
1456  if (!IsDefinition) {
1457  if (F->isWeakForLinker())
1458  replaceWeakDeclarationWithJumpTablePtr(F, CombinedGlobalElemPtr, IsDefinition);
1459  else
1460  replaceCfiUses(F, CombinedGlobalElemPtr, IsDefinition);
1461  } else {
1462  assert(F->getType()->getAddressSpace() == 0);
1463 
1464  GlobalAlias *FAlias = GlobalAlias::create(
1465  F->getValueType(), 0, F->getLinkage(), "", CombinedGlobalElemPtr, &M);
1466  FAlias->setVisibility(F->getVisibility());
1467  FAlias->takeName(F);
1468  if (FAlias->hasName())
1469  F->setName(FAlias->getName() + ".cfi");
1470  replaceCfiUses(F, FAlias, IsDefinition);
1471  if (!F->hasLocalLinkage())
1473  }
1474  }
1475 
1476  createJumpTable(JumpTableFn, Functions);
1477 }
1478 
1479 /// Assign a dummy layout using an incrementing counter, tag each function
1480 /// with its index represented as metadata, and lower each type test to an
1481 /// integer range comparison. During generation of the indirect function call
1482 /// table in the backend, it will assign the given indexes.
1483 /// Note: Dynamic linking is not supported, as the WebAssembly ABI has not yet
1484 /// been finalized.
1485 void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
1487  assert(!Functions.empty());
1488 
1489  // Build consecutive monotonic integer ranges for each call target set
1491 
1492  for (GlobalTypeMember *GTM : Functions) {
1493  Function *F = cast<Function>(GTM->getGlobal());
1494 
1495  // Skip functions that are not address taken, to avoid bloating the table
1496  if (!F->hasAddressTaken())
1497  continue;
1498 
1499  // Store metadata with the index for each function
1500  MDNode *MD = MDNode::get(F->getContext(),
1502  ConstantInt::get(Int64Ty, IndirectIndex))));
1503  F->setMetadata("wasm.index", MD);
1504 
1505  // Assign the counter value
1506  GlobalLayout[GTM] = IndirectIndex++;
1507  }
1508 
1509  // The indirect function table index space starts at zero, so pass a NULL
1510  // pointer as the subtracted "jump table" offset.
1511  lowerTypeTestCalls(TypeIds, ConstantPointerNull::get(Int32PtrTy),
1512  GlobalLayout);
1513 }
1514 
1515 void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
1517  ArrayRef<ICallBranchFunnel *> ICallBranchFunnels) {
1518  DenseMap<Metadata *, uint64_t> TypeIdIndices;
1519  for (unsigned I = 0; I != TypeIds.size(); ++I)
1520  TypeIdIndices[TypeIds[I]] = I;
1521 
1522  // For each type identifier, build a set of indices that refer to members of
1523  // the type identifier.
1524  std::vector<std::set<uint64_t>> TypeMembers(TypeIds.size());
1525  unsigned GlobalIndex = 0;
1527  for (GlobalTypeMember *GTM : Globals) {
1528  for (MDNode *Type : GTM->types()) {
1529  // Type = { offset, type identifier }
1530  auto I = TypeIdIndices.find(Type->getOperand(1));
1531  if (I != TypeIdIndices.end())
1532  TypeMembers[I->second].insert(GlobalIndex);
1533  }
1534  GlobalIndices[GTM] = GlobalIndex;
1535  GlobalIndex++;
1536  }
1537 
1538  for (ICallBranchFunnel *JT : ICallBranchFunnels) {
1539  TypeMembers.emplace_back();
1540  std::set<uint64_t> &TMSet = TypeMembers.back();
1541  for (GlobalTypeMember *T : JT->targets())
1542  TMSet.insert(GlobalIndices[T]);
1543  }
1544 
1545  // Order the sets of indices by size. The GlobalLayoutBuilder works best
1546  // when given small index sets first.
1547  std::stable_sort(
1548  TypeMembers.begin(), TypeMembers.end(),
1549  [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
1550  return O1.size() < O2.size();
1551  });
1552 
1553  // Create a GlobalLayoutBuilder and provide it with index sets as layout
1554  // fragments. The GlobalLayoutBuilder tries to lay out members of fragments as
1555  // close together as possible.
1556  GlobalLayoutBuilder GLB(Globals.size());
1557  for (auto &&MemSet : TypeMembers)
1558  GLB.addFragment(MemSet);
1559 
1560  // Build a vector of globals with the computed layout.
1561  bool IsGlobalSet =
1562  Globals.empty() || isa<GlobalVariable>(Globals[0]->getGlobal());
1563  std::vector<GlobalTypeMember *> OrderedGTMs(Globals.size());
1564  auto OGTMI = OrderedGTMs.begin();
1565  for (auto &&F : GLB.Fragments) {
1566  for (auto &&Offset : F) {
1567  if (IsGlobalSet != isa<GlobalVariable>(Globals[Offset]->getGlobal()))
1568  report_fatal_error("Type identifier may not contain both global "
1569  "variables and functions");
1570  *OGTMI++ = Globals[Offset];
1571  }
1572  }
1573 
1574  // Build the bitsets from this disjoint set.
1575  if (IsGlobalSet)
1576  buildBitSetsFromGlobalVariables(TypeIds, OrderedGTMs);
1577  else
1578  buildBitSetsFromFunctions(TypeIds, OrderedGTMs);
1579 }
1580 
1581 /// Lower all type tests in this module.
1582 LowerTypeTestsModule::LowerTypeTestsModule(
1583  Module &M, ModuleSummaryIndex *ExportSummary,
1584  const ModuleSummaryIndex *ImportSummary)
1585  : M(M), ExportSummary(ExportSummary), ImportSummary(ImportSummary) {
1586  assert(!(ExportSummary && ImportSummary));
1587  Triple TargetTriple(M.getTargetTriple());
1588  Arch = TargetTriple.getArch();
1589  OS = TargetTriple.getOS();
1590  ObjectFormat = TargetTriple.getObjectFormat();
1591 }
1592 
1593 bool LowerTypeTestsModule::runForTesting(Module &M) {
1594  ModuleSummaryIndex Summary(/*HaveGVs=*/false);
1595 
1596  // Handle the command-line summary arguments. This code is for testing
1597  // purposes only, so we handle errors directly.
1598  if (!ClReadSummary.empty()) {
1599  ExitOnError ExitOnErr("-lowertypetests-read-summary: " + ClReadSummary +
1600  ": ");
1601  auto ReadSummaryFile =
1603 
1604  yaml::Input In(ReadSummaryFile->getBuffer());
1605  In >> Summary;
1606  ExitOnErr(errorCodeToError(In.error()));
1607  }
1608 
1609  bool Changed =
1610  LowerTypeTestsModule(
1611  M, ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
1612  ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
1613  .lower();
1614 
1615  if (!ClWriteSummary.empty()) {
1616  ExitOnError ExitOnErr("-lowertypetests-write-summary: " + ClWriteSummary +
1617  ": ");
1618  std::error_code EC;
1620  ExitOnErr(errorCodeToError(EC));
1621 
1622  yaml::Output Out(OS);
1623  Out << Summary;
1624  }
1625 
1626  return Changed;
1627 }
1628 
1629 static bool isDirectCall(Use& U) {
1630  auto *Usr = dyn_cast<CallInst>(U.getUser());
1631  if (Usr) {
1632  CallSite CS(Usr);
1633  if (CS.isCallee(&U))
1634  return true;
1635  }
1636  return false;
1637 }
1638 
1639 void LowerTypeTestsModule::replaceCfiUses(Function *Old, Value *New, bool IsDefinition) {
1641  auto UI = Old->use_begin(), E = Old->use_end();
1642  for (; UI != E;) {
1643  Use &U = *UI;
1644  ++UI;
1645 
1646  // Skip block addresses
1647  if (isa<BlockAddress>(U.getUser()))
1648  continue;
1649 
1650  // Skip direct calls to externally defined or non-dso_local functions
1651  if (isDirectCall(U) && (Old->isDSOLocal() || !IsDefinition))
1652  continue;
1653 
1654  // Must handle Constants specially, we cannot call replaceUsesOfWith on a
1655  // constant because they are uniqued.
1656  if (auto *C = dyn_cast<Constant>(U.getUser())) {
1657  if (!isa<GlobalValue>(C)) {
1658  // Save unique users to avoid processing operand replacement
1659  // more than once.
1660  Constants.insert(C);
1661  continue;
1662  }
1663  }
1664 
1665  U.set(New);
1666  }
1667 
1668  // Process operand replacement of saved constants.
1669  for (auto *C : Constants)
1670  C->handleOperandChange(Old, New);
1671 }
1672 
1673 void LowerTypeTestsModule::replaceDirectCalls(Value *Old, Value *New) {
1674  auto UI = Old->use_begin(), E = Old->use_end();
1675  for (; UI != E;) {
1676  Use &U = *UI;
1677  ++UI;
1678 
1679  if (!isDirectCall(U))
1680  continue;
1681 
1682  U.set(New);
1683  }
1684 }
1685 
1686 bool LowerTypeTestsModule::lower() {
1687  Function *TypeTestFunc =
1688  M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1689  Function *ICallBranchFunnelFunc =
1690  M.getFunction(Intrinsic::getName(Intrinsic::icall_branch_funnel));
1691  if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
1692  (!ICallBranchFunnelFunc || ICallBranchFunnelFunc->use_empty()) &&
1693  !ExportSummary && !ImportSummary)
1694  return false;
1695 
1696  if (ImportSummary) {
1697  if (TypeTestFunc) {
1698  for (auto UI = TypeTestFunc->use_begin(), UE = TypeTestFunc->use_end();
1699  UI != UE;) {
1700  auto *CI = cast<CallInst>((*UI++).getUser());
1701  importTypeTest(CI);
1702  }
1703  }
1704 
1705  if (ICallBranchFunnelFunc && !ICallBranchFunnelFunc->use_empty())
1707  "unexpected call to llvm.icall.branch.funnel during import phase");
1708 
1711  for (auto &F : M) {
1712  // CFI functions are either external, or promoted. A local function may
1713  // have the same name, but it's not the one we are looking for.
1714  if (F.hasLocalLinkage())
1715  continue;
1716  if (ImportSummary->cfiFunctionDefs().count(F.getName()))
1717  Defs.push_back(&F);
1718  else if (ImportSummary->cfiFunctionDecls().count(F.getName()))
1719  Decls.push_back(&F);
1720  }
1721 
1722  for (auto F : Defs)
1723  importFunction(F, /*isDefinition*/ true);
1724  for (auto F : Decls)
1725  importFunction(F, /*isDefinition*/ false);
1726 
1727  return true;
1728  }
1729 
1730  // Equivalence class set containing type identifiers and the globals that
1731  // reference them. This is used to partition the set of type identifiers in
1732  // the module into disjoint sets.
1733  using GlobalClassesTy = EquivalenceClasses<
1735  GlobalClassesTy GlobalClasses;
1736 
1737  // Verify the type metadata and build a few data structures to let us
1738  // efficiently enumerate the type identifiers associated with a global:
1739  // a list of GlobalTypeMembers (a GlobalObject stored alongside a vector
1740  // of associated type metadata) and a mapping from type identifiers to their
1741  // list of GlobalTypeMembers and last observed index in the list of globals.
1742  // The indices will be used later to deterministically order the list of type
1743  // identifiers.
1744  BumpPtrAllocator Alloc;
1745  struct TIInfo {
1746  unsigned UniqueId;
1747  std::vector<GlobalTypeMember *> RefGlobals;
1748  };
1749  DenseMap<Metadata *, TIInfo> TypeIdInfo;
1750  unsigned CurUniqueId = 0;
1752 
1753  struct ExportedFunctionInfo {
1754  CfiFunctionLinkage Linkage;
1755  MDNode *FuncMD; // {name, linkage, type[, type...]}
1756  };
1758  if (ExportSummary) {
1759  NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions");
1760  if (CfiFunctionsMD) {
1761  for (auto FuncMD : CfiFunctionsMD->operands()) {
1762  assert(FuncMD->getNumOperands() >= 2);
1763  StringRef FunctionName =
1764  cast<MDString>(FuncMD->getOperand(0))->getString();
1765  if (!ExportSummary->isGUIDLive(GlobalValue::getGUID(
1766  GlobalValue::dropLLVMManglingEscape(FunctionName))))
1767  continue;
1768  CfiFunctionLinkage Linkage = static_cast<CfiFunctionLinkage>(
1769  cast<ConstantAsMetadata>(FuncMD->getOperand(1))
1770  ->getValue()
1771  ->getUniqueInteger()
1772  .getZExtValue());
1773  auto P = ExportedFunctions.insert({FunctionName, {Linkage, FuncMD}});
1774  if (!P.second && P.first->second.Linkage != CFL_Definition)
1775  P.first->second = {Linkage, FuncMD};
1776  }
1777 
1778  for (const auto &P : ExportedFunctions) {
1779  StringRef FunctionName = P.first;
1780  CfiFunctionLinkage Linkage = P.second.Linkage;
1781  MDNode *FuncMD = P.second.FuncMD;
1782  Function *F = M.getFunction(FunctionName);
1783  if (!F)
1784  F = Function::Create(
1786  GlobalVariable::ExternalLinkage, FunctionName, &M);
1787 
1788  // If the function is available_externally, remove its definition so
1789  // that it is handled the same way as a declaration. Later we will try
1790  // to create an alias using this function's linkage, which will fail if
1791  // the linkage is available_externally. This will also result in us
1792  // following the code path below to replace the type metadata.
1793  if (F->hasAvailableExternallyLinkage()) {
1795  F->deleteBody();
1796  F->setComdat(nullptr);
1797  F->clearMetadata();
1798  }
1799 
1800  // Update the linkage for extern_weak declarations when a definition
1801  // exists.
1802  if (Linkage == CFL_Definition && F->hasExternalWeakLinkage())
1804 
1805  // If the function in the full LTO module is a declaration, replace its
1806  // type metadata with the type metadata we found in cfi.functions. That
1807  // metadata is presumed to be more accurate than the metadata attached
1808  // to the declaration.
1809  if (F->isDeclaration()) {
1810  if (Linkage == CFL_WeakDeclaration)
1812 
1814  for (unsigned I = 2; I < FuncMD->getNumOperands(); ++I)
1816  *cast<MDNode>(FuncMD->getOperand(I).get()));
1817  }
1818  }
1819  }
1820  }
1821 
1823  for (GlobalObject &GO : M.global_objects()) {
1824  if (isa<GlobalVariable>(GO) && GO.isDeclarationForLinker())
1825  continue;
1826 
1827  Types.clear();
1828  GO.getMetadata(LLVMContext::MD_type, Types);
1829 
1830  bool IsDefinition = !GO.isDeclarationForLinker();
1831  bool IsExported = false;
1832  if (isa<Function>(GO) && ExportedFunctions.count(GO.getName())) {
1833  IsDefinition |= ExportedFunctions[GO.getName()].Linkage == CFL_Definition;
1834  IsExported = true;
1835  }
1836 
1837  auto *GTM =
1838  GlobalTypeMember::create(Alloc, &GO, IsDefinition, IsExported, Types);
1839  GlobalTypeMembers[&GO] = GTM;
1840  for (MDNode *Type : Types) {
1841  verifyTypeMDNode(&GO, Type);
1842  auto &Info = TypeIdInfo[Type->getOperand(1)];
1843  Info.UniqueId = ++CurUniqueId;
1844  Info.RefGlobals.push_back(GTM);
1845  }
1846  }
1847 
1848  auto AddTypeIdUse = [&](Metadata *TypeId) -> TypeIdUserInfo & {
1849  // Add the call site to the list of call sites for this type identifier. We
1850  // also use TypeIdUsers to keep track of whether we have seen this type
1851  // identifier before. If we have, we don't need to re-add the referenced
1852  // globals to the equivalence class.
1853  auto Ins = TypeIdUsers.insert({TypeId, {}});
1854  if (Ins.second) {
1855  // Add the type identifier to the equivalence class.
1856  GlobalClassesTy::iterator GCI = GlobalClasses.insert(TypeId);
1857  GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
1858 
1859  // Add the referenced globals to the type identifier's equivalence class.
1860  for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
1861  CurSet = GlobalClasses.unionSets(
1862  CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
1863  }
1864 
1865  return Ins.first->second;
1866  };
1867 
1868  if (TypeTestFunc) {
1869  for (const Use &U : TypeTestFunc->uses()) {
1870  auto CI = cast<CallInst>(U.getUser());
1871 
1872  auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
1873  if (!TypeIdMDVal)
1874  report_fatal_error("Second argument of llvm.type.test must be metadata");
1875  auto TypeId = TypeIdMDVal->getMetadata();
1876  AddTypeIdUse(TypeId).CallSites.push_back(CI);
1877  }
1878  }
1879 
1880  if (ICallBranchFunnelFunc) {
1881  for (const Use &U : ICallBranchFunnelFunc->uses()) {
1882  if (Arch != Triple::x86_64)
1884  "llvm.icall.branch.funnel not supported on this target");
1885 
1886  auto CI = cast<CallInst>(U.getUser());
1887 
1888  std::vector<GlobalTypeMember *> Targets;
1889  if (CI->getNumArgOperands() % 2 != 1)
1890  report_fatal_error("number of arguments should be odd");
1891 
1892  GlobalClassesTy::member_iterator CurSet;
1893  for (unsigned I = 1; I != CI->getNumArgOperands(); I += 2) {
1894  int64_t Offset;
1896  CI->getOperand(I), Offset, M.getDataLayout()));
1897  if (!Base)
1899  "Expected branch funnel operand to be global value");
1900 
1901  GlobalTypeMember *GTM = GlobalTypeMembers[Base];
1902  Targets.push_back(GTM);
1903  GlobalClassesTy::member_iterator NewSet =
1904  GlobalClasses.findLeader(GlobalClasses.insert(GTM));
1905  if (I == 1)
1906  CurSet = NewSet;
1907  else
1908  CurSet = GlobalClasses.unionSets(CurSet, NewSet);
1909  }
1910 
1911  GlobalClasses.unionSets(
1912  CurSet, GlobalClasses.findLeader(
1913  GlobalClasses.insert(ICallBranchFunnel::create(
1914  Alloc, CI, Targets, ++CurUniqueId))));
1915  }
1916  }
1917 
1918  if (ExportSummary) {
1920  for (auto &P : TypeIdInfo) {
1921  if (auto *TypeId = dyn_cast<MDString>(P.first))
1922  MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1923  TypeId);
1924  }
1925 
1926  for (auto &P : *ExportSummary) {
1927  for (auto &S : P.second.SummaryList) {
1928  if (!ExportSummary->isGlobalValueLive(S.get()))
1929  continue;
1930  if (auto *FS = dyn_cast<FunctionSummary>(S->getBaseObject()))
1931  for (GlobalValue::GUID G : FS->type_tests())
1932  for (Metadata *MD : MetadataByGUID[G])
1933  AddTypeIdUse(MD).IsExported = true;
1934  }
1935  }
1936  }
1937 
1938  if (GlobalClasses.empty())
1939  return false;
1940 
1941  // Build a list of disjoint sets ordered by their maximum global index for
1942  // determinism.
1943  std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
1944  for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
1945  E = GlobalClasses.end();
1946  I != E; ++I) {
1947  if (!I->isLeader())
1948  continue;
1949  ++NumTypeIdDisjointSets;
1950 
1951  unsigned MaxUniqueId = 0;
1952  for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
1953  MI != GlobalClasses.member_end(); ++MI) {
1954  if (auto *MD = MI->dyn_cast<Metadata *>())
1955  MaxUniqueId = std::max(MaxUniqueId, TypeIdInfo[MD].UniqueId);
1956  else if (auto *BF = MI->dyn_cast<ICallBranchFunnel *>())
1957  MaxUniqueId = std::max(MaxUniqueId, BF->UniqueId);
1958  }
1959  Sets.emplace_back(I, MaxUniqueId);
1960  }
1961  llvm::sort(Sets.begin(), Sets.end(),
1962  [](const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
1963  const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
1964  return S1.second < S2.second;
1965  });
1966 
1967  // For each disjoint set we found...
1968  for (const auto &S : Sets) {
1969  // Build the list of type identifiers in this disjoint set.
1970  std::vector<Metadata *> TypeIds;
1971  std::vector<GlobalTypeMember *> Globals;
1972  std::vector<ICallBranchFunnel *> ICallBranchFunnels;
1973  for (GlobalClassesTy::member_iterator MI =
1974  GlobalClasses.member_begin(S.first);
1975  MI != GlobalClasses.member_end(); ++MI) {
1976  if (MI->is<Metadata *>())
1977  TypeIds.push_back(MI->get<Metadata *>());
1978  else if (MI->is<GlobalTypeMember *>())
1979  Globals.push_back(MI->get<GlobalTypeMember *>());
1980  else
1981  ICallBranchFunnels.push_back(MI->get<ICallBranchFunnel *>());
1982  }
1983 
1984  // Order type identifiers by unique ID for determinism. This ordering is
1985  // stable as there is a one-to-one mapping between metadata and unique IDs.
1986  llvm::sort(TypeIds.begin(), TypeIds.end(), [&](Metadata *M1, Metadata *M2) {
1987  return TypeIdInfo[M1].UniqueId < TypeIdInfo[M2].UniqueId;
1988  });
1989 
1990  // Same for the branch funnels.
1991  llvm::sort(ICallBranchFunnels.begin(), ICallBranchFunnels.end(),
1992  [&](ICallBranchFunnel *F1, ICallBranchFunnel *F2) {
1993  return F1->UniqueId < F2->UniqueId;
1994  });
1995 
1996  // Build bitsets for this disjoint set.
1997  buildBitSetsFromDisjointSet(TypeIds, Globals, ICallBranchFunnels);
1998  }
1999 
2000  allocateByteArrays();
2001 
2002  // Parse alias data to replace stand-in function declarations for aliases
2003  // with an alias to the intended target.
2004  if (ExportSummary) {
2005  if (NamedMDNode *AliasesMD = M.getNamedMetadata("aliases")) {
2006  for (auto AliasMD : AliasesMD->operands()) {
2007  assert(AliasMD->getNumOperands() >= 4);
2008  StringRef AliasName =
2009  cast<MDString>(AliasMD->getOperand(0))->getString();
2010  StringRef Aliasee = cast<MDString>(AliasMD->getOperand(1))->getString();
2011 
2012  if (!ExportedFunctions.count(Aliasee) ||
2013  ExportedFunctions[Aliasee].Linkage != CFL_Definition ||
2014  !M.getNamedAlias(Aliasee))
2015  continue;
2016 
2018  static_cast<GlobalValue::VisibilityTypes>(
2019  cast<ConstantAsMetadata>(AliasMD->getOperand(2))
2020  ->getValue()
2021  ->getUniqueInteger()
2022  .getZExtValue());
2023  bool Weak =
2024  static_cast<bool>(cast<ConstantAsMetadata>(AliasMD->getOperand(3))
2025  ->getValue()
2026  ->getUniqueInteger()
2027  .getZExtValue());
2028 
2029  auto *Alias = GlobalAlias::create("", M.getNamedAlias(Aliasee));
2030  Alias->setVisibility(Visibility);
2031  if (Weak)
2032  Alias->setLinkage(GlobalValue::WeakAnyLinkage);
2033 
2034  if (auto *F = M.getFunction(AliasName)) {
2035  Alias->takeName(F);
2036  F->replaceAllUsesWith(Alias);
2037  F->eraseFromParent();
2038  } else {
2039  Alias->setName(AliasName);
2040  }
2041  }
2042  }
2043  }
2044 
2045  // Emit .symver directives for exported functions, if they exist.
2046  if (ExportSummary) {
2047  if (NamedMDNode *SymversMD = M.getNamedMetadata("symvers")) {
2048  for (auto Symver : SymversMD->operands()) {
2049  assert(Symver->getNumOperands() >= 2);
2051  cast<MDString>(Symver->getOperand(0))->getString();
2052  StringRef Alias = cast<MDString>(Symver->getOperand(1))->getString();
2053 
2054  if (!ExportedFunctions.count(SymbolName))
2055  continue;
2056 
2058  (llvm::Twine(".symver ") + SymbolName + ", " + Alias).str());
2059  }
2060  }
2061  }
2062 
2063  return true;
2064 }
2065 
2067  ModuleAnalysisManager &AM) {
2068  bool Changed = LowerTypeTestsModule(M, /*ExportSummary=*/nullptr,
2069  /*ImportSummary=*/nullptr)
2070  .lower();
2071  if (!Changed)
2072  return PreservedAnalyses::all();
2073  return PreservedAnalyses::none();
2074 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:238
bool isDeclarationForLinker() const
Definition: GlobalValue.h:523
uint64_t CallInst * C
This class implements a layout algorithm for globals referenced by bit sets that tries to keep member...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
unsigned getAlignment() const
Definition: GlobalObject.h:59
use_iterator use_end()
Definition: Value.h:346
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:574
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:238
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
iterator_range< use_iterator > uses()
Definition: Value.h:354
This class is used to build a byte array containing overlapping bit sets.
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:173
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1740
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1566
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:492
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
static cl::opt< bool > AvoidReuse("lowertypetests-avoid-reuse", cl::desc("Try to avoid reuse of byte array addresses using aliases"), cl::Hidden, cl::init(true))
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1138
iterator begin() const
Definition: ArrayRef.h:137
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:137
Unsatisfiable type (i.e. no global has this type metadata)
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:588
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1299
void allocate(const std::set< uint64_t > &Bits, uint64_t BitSize, uint64_t &AllocByteOffset, uint8_t &AllocMask)
Allocate BitSize bits in the byte array where Bits contains the bits to set.
Helper for check-and-exit error handling.
Definition: Error.h:1120
void print(raw_ostream &OS) const
This class represents a function call, abstracting a target machine&#39;s calling convention.
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:422
This file contains the declarations for metadata subclasses.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1727
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:936
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:360
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:862
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
ELFYAML::ELF_STV Visibility
Definition: ELFYAML.cpp:769
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:436
Hexagon Common GEP
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2188
Kind
Specifies which kind of type check we should emit for this byte array.
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1756
This defines the Use class.
void reserve(size_type N)
Definition: SmallVector.h:377
void setAlignment(unsigned Align)
Definition: Globals.cpp:111
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
TypeTestResolution TTRes
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:258
Export information to summary.
iterator_range< global_object_iterator > global_objects()
Definition: Module.h:641
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL, Value *V, uint64_t COffset)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:191
GlobalAlias * getNamedAlias(StringRef Name) const
Return the global alias in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:231
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:521
A tuple of MDNodes.
Definition: Metadata.h:1323
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:612
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
void initializeLowerTypeTestsPass(PassRegistry &)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:358
bool isDSOLocal() const
Definition: GlobalValue.h:279
Class to represent struct types.
Definition: DerivedTypes.h:201
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:242
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
static const unsigned kX86JumpTableEntrySize
The returned value is undefined.
Definition: MathExtras.h:38
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:731
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1444
This file contains the simple types necessary to represent the attributes associated with functions a...
No attributes have been set.
Definition: Attributes.h:72
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:295
This file implements a class to represent arbitrary precision integral constant values and operations...
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1632
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Definition: Use.cpp:41
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:283
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:121
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset...
Class to represent array types.
Definition: DerivedTypes.h:369
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:63
void setComdat(Comdat *C)
Definition: GlobalObject.h:103
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:1916
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:242
INITIALIZE_PASS(LowerTypeTests, "lowertypetests", "Lower type metadata", false, false) ModulePass *llvm
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:979
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:439
bool containsGlobalOffset(uint64_t Offset) const
static bool isDirectCall(Use &U)
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:301
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:408
static cl::opt< PassSummaryAction > ClSummaryAction("lowertypetests-summary-action", cl::desc("What to do with the summary when running this pass"), cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), clEnumValN(PassSummaryAction::Import, "import", "Import typeid resolutions from summary and globals"), clEnumValN(PassSummaryAction::Export, "export", "Export typeid resolutions to summary and globals")), cl::Hidden)
iterator_range< op_iterator > operands()
Definition: Metadata.h:1415
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:127
Class to represent pointers.
Definition: DerivedTypes.h:467
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1130
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:369
Value * getOperand(unsigned i_nocapture) const
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1740
ExternalWeak linkage description.
Definition: GlobalValue.h:58
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool&#39; fo...
Definition: IRBuilder.h:1305
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:742
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1164
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
Definition: Attributes.cpp:202
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1368
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0&#39;s from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:112
static Triple::ArchType selectJumpTableArmEncoding(ArrayRef< GlobalTypeMember *> Functions, Triple::ArchType ModuleArch)
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:232
void set(Value *Val)
Definition: Value.h:670
Import information from summary.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
Conditional or Unconditional Branch instruction.
static ManagedStatic< std::map< const Function *, ExFunc > > ExportedFunctions
void deleteBody()
deleteBody - This method deletes the body of the function, and converts the linkage to external...
Definition: Function.h:595
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:630
This file contains the declarations for the subclasses of Constant, which represent the different fla...
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:214
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Globals.cpp:354
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition: Error.h:1082
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
Single element (last example in "Short Inline Bit Vectors")
ModulePass * createLowerTypeTestsPass(ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
This pass lowers type metadata and the llvm.type.test intrinsic to bitsets.
See the file comment for details on the usage of the TrailingObjects type.
bool isGUIDLive(GlobalValue::GUID GUID) const
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
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:101
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1736
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:1992
self_iterator getIterator()
Definition: ilist_node.h:82
Class to represent integer types.
Definition: DerivedTypes.h:40
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:172
void setConstant(bool Val)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:193
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:632
const Constant * stripPointerCasts() const
Definition: Constant.h:169
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:493
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1226
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:859
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1866
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1374
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1554
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:482
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:82
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:727
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1394
iterator end() const
Definition: ArrayRef.h:138
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:611
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:84
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:567
void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
Definition: Constants.cpp:2729
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:444
enum llvm::TypeTestResolution::Kind TheKind
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:150
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
Definition: APInt.h:69
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:471
iterator_range< user_iterator > users()
Definition: Value.h:399
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:500
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1051
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1434
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:605
amdgpu Simplify well known AMD library false Value Value * Arg
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
std::set< std::string > & cfiFunctionDefs()
use_iterator use_begin()
Definition: Value.h:338
Test a byte array (first example)
A pointer union of three pointer types.
Definition: PointerUnion.h:229
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:366
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
unsigned getNumArgOperands() const
Return the number of call arguments.
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:195
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1165
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1714
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
Definition: Module.h:286
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:568
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
Type * getValueType() const
Definition: GlobalValue.h:275
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:320
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Function.cpp:209
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:401
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
Inlined bit vector ("Short Inline Bit Vectors")
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:141
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1112
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1619
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:201
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition: Function.cpp:1234
static cl::opt< std::string > ClReadSummary("lowertypetests-read-summary", cl::desc("Read summary from given YAML file before running pass"), cl::Hidden)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
user_iterator user_begin()
Definition: Value.h:375
static Value * createMaskedBitTest(IRBuilder<> &B, Value *Bits, Value *BitOffset)
Build a test that bit BitOffset mod sizeof(Bits)*8 is set in Bits.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
ObjectFormatType
Definition: Triple.h:209
void addFragment(const std::set< uint64_t > &F)
Add F to the layout while trying to keep its indices contiguous.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:477
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:73
const FeatureBitset Features
This header defines support for implementing classes that have some trailing object (or arrays of obj...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:317
Metadata * get() const
Definition: Metadata.h:720
static Constant * getAnon(ArrayRef< Constant *> V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition: Constants.h:465
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1072
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:699
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
static const unsigned kARMJumpTableEntrySize
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:216
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:246
IRTranslator LLVM IR MI
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:412
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
Definition: Metadata.cpp:1405
This header defines various interfaces for pass management in LLVM.
static cl::opt< std::string > ClWriteSummary("lowertypetests-write-summary", cl::desc("Write summary to given YAML file after running pass"), cl::Hidden)
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
#define LLVM_DEBUG(X)
Definition: Debug.h:119
Root of the metadata hierarchy.
Definition: Metadata.h:58
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
bool use_empty() const
Definition: Value.h:322
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:418
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
IntegerType * Int32Ty
const BasicBlock * getParent() const
Definition: Instruction.h:67
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand&#39;s Use.
Definition: CallSite.h:143