Bug Summary

File:llvm/lib/Transforms/IPO/LowerTypeTests.cpp
Warning:line 1532, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LowerTypeTests.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/IPO -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/IPO -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
1//===- LowerTypeTests.cpp - type metadata lowering pass -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass lowers type metadata and calls to the llvm.type.test intrinsic.
10// It also ensures that globals are properly laid out for the
11// llvm.icall.branch.funnel intrinsic.
12// See http://llvm.org/docs/TypeMetadata.html for more information.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/IPO/LowerTypeTests.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/EquivalenceClasses.h"
21#include "llvm/ADT/PointerUnion.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/TinyPtrVector.h"
27#include "llvm/ADT/Triple.h"
28#include "llvm/Analysis/TypeMetadataUtils.h"
29#include "llvm/Analysis/ValueTracking.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalObject.h"
39#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/GlobalVariable.h"
41#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/InlineAsm.h"
43#include "llvm/IR/Instruction.h"
44#include "llvm/IR/Instructions.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/Metadata.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/ModuleSummaryIndex.h"
50#include "llvm/IR/ModuleSummaryIndexYAML.h"
51#include "llvm/IR/Operator.h"
52#include "llvm/IR/PassManager.h"
53#include "llvm/IR/Type.h"
54#include "llvm/IR/Use.h"
55#include "llvm/IR/User.h"
56#include "llvm/IR/Value.h"
57#include "llvm/InitializePasses.h"
58#include "llvm/Pass.h"
59#include "llvm/Support/Allocator.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Support/Error.h"
64#include "llvm/Support/ErrorHandling.h"
65#include "llvm/Support/FileSystem.h"
66#include "llvm/Support/MathExtras.h"
67#include "llvm/Support/MemoryBuffer.h"
68#include "llvm/Support/TrailingObjects.h"
69#include "llvm/Support/YAMLTraits.h"
70#include "llvm/Support/raw_ostream.h"
71#include "llvm/Transforms/IPO.h"
72#include "llvm/Transforms/Utils/BasicBlockUtils.h"
73#include "llvm/Transforms/Utils/ModuleUtils.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
84using namespace llvm;
85using namespace lowertypetests;
86
87#define DEBUG_TYPE"lowertypetests" "lowertypetests"
88
89STATISTIC(ByteArraySizeBits, "Byte array size in bits")static llvm::Statistic ByteArraySizeBits = {"lowertypetests",
"ByteArraySizeBits", "Byte array size in bits"}
;
90STATISTIC(ByteArraySizeBytes, "Byte array size in bytes")static llvm::Statistic ByteArraySizeBytes = {"lowertypetests"
, "ByteArraySizeBytes", "Byte array size in bytes"}
;
91STATISTIC(NumByteArraysCreated, "Number of byte arrays created")static llvm::Statistic NumByteArraysCreated = {"lowertypetests"
, "NumByteArraysCreated", "Number of byte arrays created"}
;
92STATISTIC(NumTypeTestCallsLowered, "Number of type test calls lowered")static llvm::Statistic NumTypeTestCallsLowered = {"lowertypetests"
, "NumTypeTestCallsLowered", "Number of type test calls lowered"
}
;
93STATISTIC(NumTypeIdDisjointSets, "Number of disjoint sets of type identifiers")static llvm::Statistic NumTypeIdDisjointSets = {"lowertypetests"
, "NumTypeIdDisjointSets", "Number of disjoint sets of type identifiers"
}
;
94
95static cl::opt<bool> AvoidReuse(
96 "lowertypetests-avoid-reuse",
97 cl::desc("Try to avoid reuse of byte array addresses using aliases"),
98 cl::Hidden, cl::init(true));
99
100static cl::opt<PassSummaryAction> ClSummaryAction(
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")llvm::cl::OptionEnumValue { "none", int(PassSummaryAction::None
), "Do nothing" }
,
104 clEnumValN(PassSummaryAction::Import, "import",llvm::cl::OptionEnumValue { "import", int(PassSummaryAction::
Import), "Import typeid resolutions from summary and globals"
}
105 "Import typeid resolutions from summary and globals")llvm::cl::OptionEnumValue { "import", int(PassSummaryAction::
Import), "Import typeid resolutions from summary and globals"
}
,
106 clEnumValN(PassSummaryAction::Export, "export",llvm::cl::OptionEnumValue { "export", int(PassSummaryAction::
Export), "Export typeid resolutions to summary and globals" }
107 "Export typeid resolutions to summary and globals")llvm::cl::OptionEnumValue { "export", int(PassSummaryAction::
Export), "Export typeid resolutions to summary and globals" }
),
108 cl::Hidden);
109
110static cl::opt<std::string> ClReadSummary(
111 "lowertypetests-read-summary",
112 cl::desc("Read summary from given YAML file before running pass"),
113 cl::Hidden);
114
115static cl::opt<std::string> ClWriteSummary(
116 "lowertypetests-write-summary",
117 cl::desc("Write summary to given YAML file after running pass"),
118 cl::Hidden);
119
120bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
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
134void BitSetInfo::print(raw_ostream &OS) const {
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
149BitSetInfo BitSetBuilder::build() {
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)
169 BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
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
182void 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
211void 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
234bool lowertypetests::isJumpTableCanonical(Function *F) {
235 if (F->isDeclarationForLinker())
236 return false;
237 auto *CI = mdconst::extract_or_null<ConstantInt>(
238 F->getParent()->getModuleFlag("CFI Canonical Jump Tables"));
239 if (!CI || CI->getZExtValue() != 0)
240 return true;
241 return F->hasFnAttribute("cfi-canonical-jump-table");
242}
243
244namespace {
245
246struct ByteArrayInfo {
247 std::set<uint64_t> Bits;
248 uint64_t BitSize;
249 GlobalVariable *ByteArray;
250 GlobalVariable *MaskGlobal;
251 uint8_t *MaskPtr = nullptr;
252};
253
254/// A POD-like structure that we use to store a global reference together with
255/// its metadata types. In this pass we frequently need to query the set of
256/// metadata types referenced by a global, which at the IR level is an expensive
257/// operation involving a map lookup; this data structure helps to reduce the
258/// number of times we need to do this lookup.
259class GlobalTypeMember final : TrailingObjects<GlobalTypeMember, MDNode *> {
260 friend TrailingObjects;
261
262 GlobalObject *GO;
263 size_t NTypes;
264
265 // For functions: true if the jump table is canonical. This essentially means
266 // whether the canonical address (i.e. the symbol table entry) of the function
267 // is provided by the local jump table. This is normally the same as whether
268 // the function is defined locally, but if canonical jump tables are disabled
269 // by the user then the jump table never provides a canonical definition.
270 bool IsJumpTableCanonical;
271
272 // For functions: true if this function is either defined or used in a thinlto
273 // module and its jumptable entry needs to be exported to thinlto backends.
274 bool IsExported;
275
276 size_t numTrailingObjects(OverloadToken<MDNode *>) const { return NTypes; }
277
278public:
279 static GlobalTypeMember *create(BumpPtrAllocator &Alloc, GlobalObject *GO,
280 bool IsJumpTableCanonical, bool IsExported,
281 ArrayRef<MDNode *> Types) {
282 auto *GTM = static_cast<GlobalTypeMember *>(Alloc.Allocate(
283 totalSizeToAlloc<MDNode *>(Types.size()), alignof(GlobalTypeMember)));
284 GTM->GO = GO;
285 GTM->NTypes = Types.size();
286 GTM->IsJumpTableCanonical = IsJumpTableCanonical;
287 GTM->IsExported = IsExported;
288 std::uninitialized_copy(Types.begin(), Types.end(),
289 GTM->getTrailingObjects<MDNode *>());
290 return GTM;
291 }
292
293 GlobalObject *getGlobal() const {
294 return GO;
295 }
296
297 bool isJumpTableCanonical() const {
298 return IsJumpTableCanonical;
299 }
300
301 bool isExported() const {
302 return IsExported;
303 }
304
305 ArrayRef<MDNode *> types() const {
306 return makeArrayRef(getTrailingObjects<MDNode *>(), NTypes);
307 }
308};
309
310struct ICallBranchFunnel final
311 : TrailingObjects<ICallBranchFunnel, GlobalTypeMember *> {
312 static ICallBranchFunnel *create(BumpPtrAllocator &Alloc, CallInst *CI,
313 ArrayRef<GlobalTypeMember *> Targets,
314 unsigned UniqueId) {
315 auto *Call = static_cast<ICallBranchFunnel *>(
316 Alloc.Allocate(totalSizeToAlloc<GlobalTypeMember *>(Targets.size()),
317 alignof(ICallBranchFunnel)));
318 Call->CI = CI;
319 Call->UniqueId = UniqueId;
320 Call->NTargets = Targets.size();
321 std::uninitialized_copy(Targets.begin(), Targets.end(),
322 Call->getTrailingObjects<GlobalTypeMember *>());
323 return Call;
324 }
325
326 CallInst *CI;
327 ArrayRef<GlobalTypeMember *> targets() const {
328 return makeArrayRef(getTrailingObjects<GlobalTypeMember *>(), NTargets);
329 }
330
331 unsigned UniqueId;
332
333private:
334 size_t NTargets;
335};
336
337struct ScopedSaveAliaseesAndUsed {
338 Module &M;
339 SmallPtrSet<GlobalValue *, 16> Used, CompilerUsed;
340 std::vector<std::pair<GlobalIndirectSymbol *, Function *>> FunctionAliases;
341
342 ScopedSaveAliaseesAndUsed(Module &M) : M(M) {
343 // The users of this class want to replace all function references except
344 // for aliases and llvm.used/llvm.compiler.used with references to a jump
345 // table. We avoid replacing aliases in order to avoid introducing a double
346 // indirection (or an alias pointing to a declaration in ThinLTO mode), and
347 // we avoid replacing llvm.used/llvm.compiler.used because these global
348 // variables describe properties of the global, not the jump table (besides,
349 // offseted references to the jump table in llvm.used are invalid).
350 // Unfortunately, LLVM doesn't have a "RAUW except for these (possibly
351 // indirect) users", so what we do is save the list of globals referenced by
352 // llvm.used/llvm.compiler.used and aliases, erase the used lists, let RAUW
353 // replace the aliasees and then set them back to their original values at
354 // the end.
355 if (GlobalVariable *GV = collectUsedGlobalVariables(M, Used, false))
356 GV->eraseFromParent();
357 if (GlobalVariable *GV = collectUsedGlobalVariables(M, CompilerUsed, true))
358 GV->eraseFromParent();
359
360 for (auto &GIS : concat<GlobalIndirectSymbol>(M.aliases(), M.ifuncs())) {
361 // FIXME: This should look past all aliases not just interposable ones,
362 // see discussion on D65118.
363 if (auto *F =
364 dyn_cast<Function>(GIS.getIndirectSymbol()->stripPointerCasts()))
365 FunctionAliases.push_back({&GIS, F});
366 }
367 }
368
369 ~ScopedSaveAliaseesAndUsed() {
370 appendToUsed(M, std::vector<GlobalValue *>(Used.begin(), Used.end()));
371 appendToCompilerUsed(M, std::vector<GlobalValue *>(CompilerUsed.begin(),
372 CompilerUsed.end()));
373
374 for (auto P : FunctionAliases)
375 P.first->setIndirectSymbol(
376 ConstantExpr::getBitCast(P.second, P.first->getType()));
377 }
378};
379
380class LowerTypeTestsModule {
381 Module &M;
382
383 ModuleSummaryIndex *ExportSummary;
384 const ModuleSummaryIndex *ImportSummary;
385 // Set when the client has invoked this to simply drop all type test assume
386 // sequences.
387 bool DropTypeTests;
388
389 Triple::ArchType Arch;
390 Triple::OSType OS;
391 Triple::ObjectFormatType ObjectFormat;
392
393 IntegerType *Int1Ty = Type::getInt1Ty(M.getContext());
394 IntegerType *Int8Ty = Type::getInt8Ty(M.getContext());
395 PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
396 ArrayType *Int8Arr0Ty = ArrayType::get(Type::getInt8Ty(M.getContext()), 0);
397 IntegerType *Int32Ty = Type::getInt32Ty(M.getContext());
398 PointerType *Int32PtrTy = PointerType::getUnqual(Int32Ty);
399 IntegerType *Int64Ty = Type::getInt64Ty(M.getContext());
400 IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext(), 0);
401
402 // Indirect function call index assignment counter for WebAssembly
403 uint64_t IndirectIndex = 1;
404
405 // Mapping from type identifiers to the call sites that test them, as well as
406 // whether the type identifier needs to be exported to ThinLTO backends as
407 // part of the regular LTO phase of the ThinLTO pipeline (see exportTypeId).
408 struct TypeIdUserInfo {
409 std::vector<CallInst *> CallSites;
410 bool IsExported = false;
411 };
412 DenseMap<Metadata *, TypeIdUserInfo> TypeIdUsers;
413
414 /// This structure describes how to lower type tests for a particular type
415 /// identifier. It is either built directly from the global analysis (during
416 /// regular LTO or the regular LTO phase of ThinLTO), or indirectly using type
417 /// identifier summaries and external symbol references (in ThinLTO backends).
418 struct TypeIdLowering {
419 TypeTestResolution::Kind TheKind = TypeTestResolution::Unsat;
420
421 /// All except Unsat: the start address within the combined global.
422 Constant *OffsetedGlobal;
423
424 /// ByteArray, Inline, AllOnes: log2 of the required global alignment
425 /// relative to the start address.
426 Constant *AlignLog2;
427
428 /// ByteArray, Inline, AllOnes: one less than the size of the memory region
429 /// covering members of this type identifier as a multiple of 2^AlignLog2.
430 Constant *SizeM1;
431
432 /// ByteArray: the byte array to test the address against.
433 Constant *TheByteArray;
434
435 /// ByteArray: the bit mask to apply to bytes loaded from the byte array.
436 Constant *BitMask;
437
438 /// Inline: the bit mask to test the address against.
439 Constant *InlineBits;
440 };
441
442 std::vector<ByteArrayInfo> ByteArrayInfos;
443
444 Function *WeakInitializerFn = nullptr;
445
446 bool shouldExportConstantsAsAbsoluteSymbols();
447 uint8_t *exportTypeId(StringRef TypeId, const TypeIdLowering &TIL);
448 TypeIdLowering importTypeId(StringRef TypeId);
449 void importTypeTest(CallInst *CI);
450 void importFunction(Function *F, bool isJumpTableCanonical,
451 std::vector<GlobalAlias *> &AliasesToErase);
452
453 BitSetInfo
454 buildBitSet(Metadata *TypeId,
455 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
456 ByteArrayInfo *createByteArray(BitSetInfo &BSI);
457 void allocateByteArrays();
458 Value *createBitSetTest(IRBuilder<> &B, const TypeIdLowering &TIL,
459 Value *BitOffset);
460 void lowerTypeTestCalls(
461 ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
462 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
463 Value *lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
464 const TypeIdLowering &TIL);
465
466 void buildBitSetsFromGlobalVariables(ArrayRef<Metadata *> TypeIds,
467 ArrayRef<GlobalTypeMember *> Globals);
468 unsigned getJumpTableEntrySize();
469 Type *getJumpTableEntryType();
470 void createJumpTableEntry(raw_ostream &AsmOS, raw_ostream &ConstraintOS,
471 Triple::ArchType JumpTableArch,
472 SmallVectorImpl<Value *> &AsmArgs, Function *Dest);
473 void verifyTypeMDNode(GlobalObject *GO, MDNode *Type);
474 void buildBitSetsFromFunctions(ArrayRef<Metadata *> TypeIds,
475 ArrayRef<GlobalTypeMember *> Functions);
476 void buildBitSetsFromFunctionsNative(ArrayRef<Metadata *> TypeIds,
477 ArrayRef<GlobalTypeMember *> Functions);
478 void buildBitSetsFromFunctionsWASM(ArrayRef<Metadata *> TypeIds,
479 ArrayRef<GlobalTypeMember *> Functions);
480 void
481 buildBitSetsFromDisjointSet(ArrayRef<Metadata *> TypeIds,
482 ArrayRef<GlobalTypeMember *> Globals,
483 ArrayRef<ICallBranchFunnel *> ICallBranchFunnels);
484
485 void replaceWeakDeclarationWithJumpTablePtr(Function *F, Constant *JT,
486 bool IsJumpTableCanonical);
487 void moveInitializerToModuleConstructor(GlobalVariable *GV);
488 void findGlobalVariableUsersOf(Constant *C,
489 SmallSetVector<GlobalVariable *, 8> &Out);
490
491 void createJumpTable(Function *F, ArrayRef<GlobalTypeMember *> Functions);
492
493 /// replaceCfiUses - Go through the uses list for this definition
494 /// and make each use point to "V" instead of "this" when the use is outside
495 /// the block. 'This's use list is expected to have at least one element.
496 /// Unlike replaceAllUsesWith this function skips blockaddr and direct call
497 /// uses.
498 void replaceCfiUses(Function *Old, Value *New, bool IsJumpTableCanonical);
499
500 /// replaceDirectCalls - Go through the uses list for this definition and
501 /// replace each use, which is a direct function call.
502 void replaceDirectCalls(Value *Old, Value *New);
503
504public:
505 LowerTypeTestsModule(Module &M, ModuleSummaryIndex *ExportSummary,
506 const ModuleSummaryIndex *ImportSummary,
507 bool DropTypeTests);
508
509 bool lower();
510
511 // Lower the module using the action and summary passed as command line
512 // arguments. For testing purposes only.
513 static bool runForTesting(Module &M);
514};
515
516struct LowerTypeTests : public ModulePass {
517 static char ID;
518
519 bool UseCommandLine = false;
520
521 ModuleSummaryIndex *ExportSummary;
522 const ModuleSummaryIndex *ImportSummary;
523 bool DropTypeTests;
524
525 LowerTypeTests() : ModulePass(ID), UseCommandLine(true) {
526 initializeLowerTypeTestsPass(*PassRegistry::getPassRegistry());
527 }
528
529 LowerTypeTests(ModuleSummaryIndex *ExportSummary,
530 const ModuleSummaryIndex *ImportSummary, bool DropTypeTests)
531 : ModulePass(ID), ExportSummary(ExportSummary),
532 ImportSummary(ImportSummary), DropTypeTests(DropTypeTests) {
533 initializeLowerTypeTestsPass(*PassRegistry::getPassRegistry());
534 }
535
536 bool runOnModule(Module &M) override {
537 if (UseCommandLine)
538 return LowerTypeTestsModule::runForTesting(M);
539 return LowerTypeTestsModule(M, ExportSummary, ImportSummary, DropTypeTests)
540 .lower();
541 }
542};
543
544} // end anonymous namespace
545
546char LowerTypeTests::ID = 0;
547
548INITIALIZE_PASS(LowerTypeTests, "lowertypetests", "Lower type metadata", false,static void *initializeLowerTypeTestsPassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Lower type metadata"
, "lowertypetests", &LowerTypeTests::ID, PassInfo::NormalCtor_t
(callDefaultCtor<LowerTypeTests>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeLowerTypeTestsPassFlag; void llvm::initializeLowerTypeTestsPass
(PassRegistry &Registry) { llvm::call_once(InitializeLowerTypeTestsPassFlag
, initializeLowerTypeTestsPassOnce, std::ref(Registry)); }
549 false)static void *initializeLowerTypeTestsPassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Lower type metadata"
, "lowertypetests", &LowerTypeTests::ID, PassInfo::NormalCtor_t
(callDefaultCtor<LowerTypeTests>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeLowerTypeTestsPassFlag; void llvm::initializeLowerTypeTestsPass
(PassRegistry &Registry) { llvm::call_once(InitializeLowerTypeTestsPassFlag
, initializeLowerTypeTestsPassOnce, std::ref(Registry)); }
550
551ModulePass *
552llvm::createLowerTypeTestsPass(ModuleSummaryIndex *ExportSummary,
553 const ModuleSummaryIndex *ImportSummary,
554 bool DropTypeTests) {
555 return new LowerTypeTests(ExportSummary, ImportSummary, DropTypeTests);
556}
557
558/// Build a bit set for TypeId using the object layouts in
559/// GlobalLayout.
560BitSetInfo LowerTypeTestsModule::buildBitSet(
561 Metadata *TypeId,
562 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
563 BitSetBuilder BSB;
564
565 // Compute the byte offset of each address associated with this type
566 // identifier.
567 for (auto &GlobalAndOffset : GlobalLayout) {
568 for (MDNode *Type : GlobalAndOffset.first->types()) {
569 if (Type->getOperand(1) != TypeId)
570 continue;
571 uint64_t Offset =
572 cast<ConstantInt>(
573 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
574 ->getZExtValue();
575 BSB.addOffset(GlobalAndOffset.second + Offset);
576 }
577 }
578
579 return BSB.build();
580}
581
582/// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
583/// Bits. This pattern matches to the bt instruction on x86.
584static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
585 Value *BitOffset) {
586 auto BitsType = cast<IntegerType>(Bits->getType());
587 unsigned BitWidth = BitsType->getBitWidth();
588
589 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
590 Value *BitIndex =
591 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
592 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
593 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
594 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
595}
596
597ByteArrayInfo *LowerTypeTestsModule::createByteArray(BitSetInfo &BSI) {
598 // Create globals to stand in for byte arrays and masks. These never actually
599 // get initialized, we RAUW and erase them later in allocateByteArrays() once
600 // we know the offset and mask to use.
601 auto ByteArrayGlobal = new GlobalVariable(
602 M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
603 auto MaskGlobal = new GlobalVariable(M, Int8Ty, /*isConstant=*/true,
604 GlobalValue::PrivateLinkage, nullptr);
605
606 ByteArrayInfos.emplace_back();
607 ByteArrayInfo *BAI = &ByteArrayInfos.back();
608
609 BAI->Bits = BSI.Bits;
610 BAI->BitSize = BSI.BitSize;
611 BAI->ByteArray = ByteArrayGlobal;
612 BAI->MaskGlobal = MaskGlobal;
613 return BAI;
614}
615
616void LowerTypeTestsModule::allocateByteArrays() {
617 llvm::stable_sort(ByteArrayInfos,
618 [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
619 return BAI1.BitSize > BAI2.BitSize;
620 });
621
622 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
623
624 ByteArrayBuilder BAB;
625 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
626 ByteArrayInfo *BAI = &ByteArrayInfos[I];
627
628 uint8_t Mask;
629 BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
630
631 BAI->MaskGlobal->replaceAllUsesWith(
632 ConstantExpr::getIntToPtr(ConstantInt::get(Int8Ty, Mask), Int8PtrTy));
633 BAI->MaskGlobal->eraseFromParent();
634 if (BAI->MaskPtr)
635 *BAI->MaskPtr = Mask;
636 }
637
638 Constant *ByteArrayConst = ConstantDataArray::get(M.getContext(), BAB.Bytes);
639 auto ByteArray =
640 new GlobalVariable(M, ByteArrayConst->getType(), /*isConstant=*/true,
641 GlobalValue::PrivateLinkage, ByteArrayConst);
642
643 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
644 ByteArrayInfo *BAI = &ByteArrayInfos[I];
645
646 Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
647 ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
648 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
649 ByteArrayConst->getType(), ByteArray, Idxs);
650
651 // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
652 // that the pc-relative displacement is folded into the lea instead of the
653 // test instruction getting another displacement.
654 GlobalAlias *Alias = GlobalAlias::create(
655 Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, &M);
656 BAI->ByteArray->replaceAllUsesWith(Alias);
657 BAI->ByteArray->eraseFromParent();
658 }
659
660 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
661 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
662 BAB.BitAllocs[6] + BAB.BitAllocs[7];
663 ByteArraySizeBytes = BAB.Bytes.size();
664}
665
666/// Build a test that bit BitOffset is set in the type identifier that was
667/// lowered to TIL, which must be either an Inline or a ByteArray.
668Value *LowerTypeTestsModule::createBitSetTest(IRBuilder<> &B,
669 const TypeIdLowering &TIL,
670 Value *BitOffset) {
671 if (TIL.TheKind == TypeTestResolution::Inline) {
672 // If the bit set is sufficiently small, we can avoid a load by bit testing
673 // a constant.
674 return createMaskedBitTest(B, TIL.InlineBits, BitOffset);
675 } else {
676 Constant *ByteArray = TIL.TheByteArray;
677 if (AvoidReuse && !ImportSummary) {
678 // Each use of the byte array uses a different alias. This makes the
679 // backend less likely to reuse previously computed byte array addresses,
680 // improving the security of the CFI mechanism based on this pass.
681 // This won't work when importing because TheByteArray is external.
682 ByteArray = GlobalAlias::create(Int8Ty, 0, GlobalValue::PrivateLinkage,
683 "bits_use", ByteArray, &M);
684 }
685
686 Value *ByteAddr = B.CreateGEP(Int8Ty, ByteArray, BitOffset);
687 Value *Byte = B.CreateLoad(Int8Ty, ByteAddr);
688
689 Value *ByteAndMask =
690 B.CreateAnd(Byte, ConstantExpr::getPtrToInt(TIL.BitMask, Int8Ty));
691 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
692 }
693}
694
695static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL,
696 Value *V, uint64_t COffset) {
697 if (auto GV = dyn_cast<GlobalObject>(V)) {
698 SmallVector<MDNode *, 2> Types;
699 GV->getMetadata(LLVMContext::MD_type, Types);
700 for (MDNode *Type : Types) {
701 if (Type->getOperand(1) != TypeId)
702 continue;
703 uint64_t Offset =
704 cast<ConstantInt>(
705 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
706 ->getZExtValue();
707 if (COffset == Offset)
708 return true;
709 }
710 return false;
711 }
712
713 if (auto GEP = dyn_cast<GEPOperator>(V)) {
714 APInt APOffset(DL.getPointerSizeInBits(0), 0);
715 bool Result = GEP->accumulateConstantOffset(DL, APOffset);
716 if (!Result)
717 return false;
718 COffset += APOffset.getZExtValue();
719 return isKnownTypeIdMember(TypeId, DL, GEP->getPointerOperand(), COffset);
720 }
721
722 if (auto Op = dyn_cast<Operator>(V)) {
723 if (Op->getOpcode() == Instruction::BitCast)
724 return isKnownTypeIdMember(TypeId, DL, Op->getOperand(0), COffset);
725
726 if (Op->getOpcode() == Instruction::Select)
727 return isKnownTypeIdMember(TypeId, DL, Op->getOperand(1), COffset) &&
728 isKnownTypeIdMember(TypeId, DL, Op->getOperand(2), COffset);
729 }
730
731 return false;
732}
733
734/// Lower a llvm.type.test call to its implementation. Returns the value to
735/// replace the call with.
736Value *LowerTypeTestsModule::lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
737 const TypeIdLowering &TIL) {
738 if (TIL.TheKind == TypeTestResolution::Unsat)
739 return ConstantInt::getFalse(M.getContext());
740
741 Value *Ptr = CI->getArgOperand(0);
742 const DataLayout &DL = M.getDataLayout();
743 if (isKnownTypeIdMember(TypeId, DL, Ptr, 0))
744 return ConstantInt::getTrue(M.getContext());
745
746 BasicBlock *InitialBB = CI->getParent();
747
748 IRBuilder<> B(CI);
749
750 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
751
752 Constant *OffsetedGlobalAsInt =
753 ConstantExpr::getPtrToInt(TIL.OffsetedGlobal, IntPtrTy);
754 if (TIL.TheKind == TypeTestResolution::Single)
755 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
756
757 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
758
759 // We need to check that the offset both falls within our range and is
760 // suitably aligned. We can check both properties at the same time by
761 // performing a right rotate by log2(alignment) followed by an integer
762 // comparison against the bitset size. The rotate will move the lower
763 // order bits that need to be zero into the higher order bits of the
764 // result, causing the comparison to fail if they are nonzero. The rotate
765 // also conveniently gives us a bit offset to use during the load from
766 // the bitset.
767 Value *OffsetSHR =
768 B.CreateLShr(PtrOffset, ConstantExpr::getZExt(TIL.AlignLog2, IntPtrTy));
769 Value *OffsetSHL = B.CreateShl(
770 PtrOffset, ConstantExpr::getZExt(
771 ConstantExpr::getSub(
772 ConstantInt::get(Int8Ty, DL.getPointerSizeInBits(0)),
773 TIL.AlignLog2),
774 IntPtrTy));
775 Value *BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
776
777 Value *OffsetInRange = B.CreateICmpULE(BitOffset, TIL.SizeM1);
778
779 // If the bit set is all ones, testing against it is unnecessary.
780 if (TIL.TheKind == TypeTestResolution::AllOnes)
781 return OffsetInRange;
782
783 // See if the intrinsic is used in the following common pattern:
784 // br(llvm.type.test(...), thenbb, elsebb)
785 // where nothing happens between the type test and the br.
786 // If so, create slightly simpler IR.
787 if (CI->hasOneUse())
788 if (auto *Br = dyn_cast<BranchInst>(*CI->user_begin()))
789 if (CI->getNextNode() == Br) {
790 BasicBlock *Then = InitialBB->splitBasicBlock(CI->getIterator());
791 BasicBlock *Else = Br->getSuccessor(1);
792 BranchInst *NewBr = BranchInst::Create(Then, Else, OffsetInRange);
793 NewBr->setMetadata(LLVMContext::MD_prof,
794 Br->getMetadata(LLVMContext::MD_prof));
795 ReplaceInstWithInst(InitialBB->getTerminator(), NewBr);
796
797 // Update phis in Else resulting from InitialBB being split
798 for (auto &Phi : Else->phis())
799 Phi.addIncoming(Phi.getIncomingValueForBlock(Then), InitialBB);
800
801 IRBuilder<> ThenB(CI);
802 return createBitSetTest(ThenB, TIL, BitOffset);
803 }
804
805 IRBuilder<> ThenB(SplitBlockAndInsertIfThen(OffsetInRange, CI, false));
806
807 // Now that we know that the offset is in range and aligned, load the
808 // appropriate bit from the bitset.
809 Value *Bit = createBitSetTest(ThenB, TIL, BitOffset);
810
811 // The value we want is 0 if we came directly from the initial block
812 // (having failed the range or alignment checks), or the loaded bit if
813 // we came from the block in which we loaded it.
814 B.SetInsertPoint(CI);
815 PHINode *P = B.CreatePHI(Int1Ty, 2);
816 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
817 P->addIncoming(Bit, ThenB.GetInsertBlock());
818 return P;
819}
820
821/// Given a disjoint set of type identifiers and globals, lay out the globals,
822/// build the bit sets and lower the llvm.type.test calls.
823void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
824 ArrayRef<Metadata *> TypeIds, ArrayRef<GlobalTypeMember *> Globals) {
825 // Build a new global with the combined contents of the referenced globals.
826 // This global is a struct whose even-indexed elements contain the original
827 // contents of the referenced globals and whose odd-indexed elements contain
828 // any padding required to align the next element to the next power of 2 plus
829 // any additional padding required to meet its alignment requirements.
830 std::vector<Constant *> GlobalInits;
831 const DataLayout &DL = M.getDataLayout();
832 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
833 Align MaxAlign;
834 uint64_t CurOffset = 0;
835 uint64_t DesiredPadding = 0;
836 for (GlobalTypeMember *G : Globals) {
837 auto *GV = cast<GlobalVariable>(G->getGlobal());
838 MaybeAlign Alignment(GV->getAlignment());
839 if (!Alignment)
840 Alignment = Align(DL.getABITypeAlignment(GV->getValueType()));
841 MaxAlign = std::max(MaxAlign, *Alignment);
842 uint64_t GVOffset = alignTo(CurOffset + DesiredPadding, *Alignment);
843 GlobalLayout[G] = GVOffset;
844 if (GVOffset != 0) {
845 uint64_t Padding = GVOffset - CurOffset;
846 GlobalInits.push_back(
847 ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
848 }
849
850 GlobalInits.push_back(GV->getInitializer());
851 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
852 CurOffset = GVOffset + InitSize;
853
854 // Compute the amount of padding that we'd like for the next element.
855 DesiredPadding = NextPowerOf2(InitSize - 1) - InitSize;
856
857 // Experiments of different caps with Chromium on both x64 and ARM64
858 // have shown that the 32-byte cap generates the smallest binary on
859 // both platforms while different caps yield similar performance.
860 // (see https://lists.llvm.org/pipermail/llvm-dev/2018-July/124694.html)
861 if (DesiredPadding > 32)
862 DesiredPadding = alignTo(InitSize, 32) - InitSize;
863 }
864
865 Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
866 auto *CombinedGlobal =
867 new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
868 GlobalValue::PrivateLinkage, NewInit);
869 CombinedGlobal->setAlignment(MaxAlign);
870
871 StructType *NewTy = cast<StructType>(NewInit->getType());
872 lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
873
874 // Build aliases pointing to offsets into the combined global for each
875 // global from which we built the combined global, and replace references
876 // to the original globals with references to the aliases.
877 for (unsigned I = 0; I != Globals.size(); ++I) {
878 GlobalVariable *GV = cast<GlobalVariable>(Globals[I]->getGlobal());
879
880 // Multiply by 2 to account for padding elements.
881 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
882 ConstantInt::get(Int32Ty, I * 2)};
883 Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
884 NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
885 assert(GV->getType()->getAddressSpace() == 0)((GV->getType()->getAddressSpace() == 0) ? static_cast<
void> (0) : __assert_fail ("GV->getType()->getAddressSpace() == 0"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 885, __PRETTY_FUNCTION__))
;
886 GlobalAlias *GAlias =
887 GlobalAlias::create(NewTy->getElementType(I * 2), 0, GV->getLinkage(),
888 "", CombinedGlobalElemPtr, &M);
889 GAlias->setVisibility(GV->getVisibility());
890 GAlias->takeName(GV);
891 GV->replaceAllUsesWith(GAlias);
892 GV->eraseFromParent();
893 }
894}
895
896bool LowerTypeTestsModule::shouldExportConstantsAsAbsoluteSymbols() {
897 return (Arch == Triple::x86 || Arch == Triple::x86_64) &&
898 ObjectFormat == Triple::ELF;
899}
900
901/// Export the given type identifier so that ThinLTO backends may import it.
902/// Type identifiers are exported by adding coarse-grained information about how
903/// to test the type identifier to the summary, and creating symbols in the
904/// object file (aliases and absolute symbols) containing fine-grained
905/// information about the type identifier.
906///
907/// Returns a pointer to the location in which to store the bitmask, if
908/// applicable.
909uint8_t *LowerTypeTestsModule::exportTypeId(StringRef TypeId,
910 const TypeIdLowering &TIL) {
911 TypeTestResolution &TTRes =
912 ExportSummary->getOrInsertTypeIdSummary(TypeId).TTRes;
913 TTRes.TheKind = TIL.TheKind;
914
915 auto ExportGlobal = [&](StringRef Name, Constant *C) {
916 GlobalAlias *GA =
917 GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
918 "__typeid_" + TypeId + "_" + Name, C, &M);
919 GA->setVisibility(GlobalValue::HiddenVisibility);
920 };
921
922 auto ExportConstant = [&](StringRef Name, uint64_t &Storage, Constant *C) {
923 if (shouldExportConstantsAsAbsoluteSymbols())
924 ExportGlobal(Name, ConstantExpr::getIntToPtr(C, Int8PtrTy));
925 else
926 Storage = cast<ConstantInt>(C)->getZExtValue();
927 };
928
929 if (TIL.TheKind != TypeTestResolution::Unsat)
930 ExportGlobal("global_addr", TIL.OffsetedGlobal);
931
932 if (TIL.TheKind == TypeTestResolution::ByteArray ||
933 TIL.TheKind == TypeTestResolution::Inline ||
934 TIL.TheKind == TypeTestResolution::AllOnes) {
935 ExportConstant("align", TTRes.AlignLog2, TIL.AlignLog2);
936 ExportConstant("size_m1", TTRes.SizeM1, TIL.SizeM1);
937
938 uint64_t BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
939 if (TIL.TheKind == TypeTestResolution::Inline)
940 TTRes.SizeM1BitWidth = (BitSize <= 32) ? 5 : 6;
941 else
942 TTRes.SizeM1BitWidth = (BitSize <= 128) ? 7 : 32;
943 }
944
945 if (TIL.TheKind == TypeTestResolution::ByteArray) {
946 ExportGlobal("byte_array", TIL.TheByteArray);
947 if (shouldExportConstantsAsAbsoluteSymbols())
948 ExportGlobal("bit_mask", TIL.BitMask);
949 else
950 return &TTRes.BitMask;
951 }
952
953 if (TIL.TheKind == TypeTestResolution::Inline)
954 ExportConstant("inline_bits", TTRes.InlineBits, TIL.InlineBits);
955
956 return nullptr;
957}
958
959LowerTypeTestsModule::TypeIdLowering
960LowerTypeTestsModule::importTypeId(StringRef TypeId) {
961 const TypeIdSummary *TidSummary = ImportSummary->getTypeIdSummary(TypeId);
962 if (!TidSummary)
963 return {}; // Unsat: no globals match this type id.
964 const TypeTestResolution &TTRes = TidSummary->TTRes;
965
966 TypeIdLowering TIL;
967 TIL.TheKind = TTRes.TheKind;
968
969 auto ImportGlobal = [&](StringRef Name) {
970 // Give the global a type of length 0 so that it is not assumed not to alias
971 // with any other global.
972 Constant *C = M.getOrInsertGlobal(("__typeid_" + TypeId + "_" + Name).str(),
973 Int8Arr0Ty);
974 if (auto *GV = dyn_cast<GlobalVariable>(C))
975 GV->setVisibility(GlobalValue::HiddenVisibility);
976 C = ConstantExpr::getBitCast(C, Int8PtrTy);
977 return C;
978 };
979
980 auto ImportConstant = [&](StringRef Name, uint64_t Const, unsigned AbsWidth,
981 Type *Ty) {
982 if (!shouldExportConstantsAsAbsoluteSymbols()) {
983 Constant *C =
984 ConstantInt::get(isa<IntegerType>(Ty) ? Ty : Int64Ty, Const);
985 if (!isa<IntegerType>(Ty))
986 C = ConstantExpr::getIntToPtr(C, Ty);
987 return C;
988 }
989
990 Constant *C = ImportGlobal(Name);
991 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
992 if (isa<IntegerType>(Ty))
993 C = ConstantExpr::getPtrToInt(C, Ty);
994 if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
995 return C;
996
997 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
998 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
999 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1000 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1001 MDNode::get(M.getContext(), {MinC, MaxC}));
1002 };
1003 if (AbsWidth == IntPtrTy->getBitWidth())
1004 SetAbsRange(~0ull, ~0ull); // Full set.
1005 else
1006 SetAbsRange(0, 1ull << AbsWidth);
1007 return C;
1008 };
1009
1010 if (TIL.TheKind != TypeTestResolution::Unsat)
1011 TIL.OffsetedGlobal = ImportGlobal("global_addr");
1012
1013 if (TIL.TheKind == TypeTestResolution::ByteArray ||
1014 TIL.TheKind == TypeTestResolution::Inline ||
1015 TIL.TheKind == TypeTestResolution::AllOnes) {
1016 TIL.AlignLog2 = ImportConstant("align", TTRes.AlignLog2, 8, Int8Ty);
1017 TIL.SizeM1 =
1018 ImportConstant("size_m1", TTRes.SizeM1, TTRes.SizeM1BitWidth, IntPtrTy);
1019 }
1020
1021 if (TIL.TheKind == TypeTestResolution::ByteArray) {
1022 TIL.TheByteArray = ImportGlobal("byte_array");
1023 TIL.BitMask = ImportConstant("bit_mask", TTRes.BitMask, 8, Int8PtrTy);
1024 }
1025
1026 if (TIL.TheKind == TypeTestResolution::Inline)
1027 TIL.InlineBits = ImportConstant(
1028 "inline_bits", TTRes.InlineBits, 1 << TTRes.SizeM1BitWidth,
1029 TTRes.SizeM1BitWidth <= 5 ? Int32Ty : Int64Ty);
1030
1031 return TIL;
1032}
1033
1034void LowerTypeTestsModule::importTypeTest(CallInst *CI) {
1035 auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
1036 if (!TypeIdMDVal)
1037 report_fatal_error("Second argument of llvm.type.test must be metadata");
1038
1039 auto TypeIdStr = dyn_cast<MDString>(TypeIdMDVal->getMetadata());
1040 if (!TypeIdStr)
1041 report_fatal_error(
1042 "Second argument of llvm.type.test must be a metadata string");
1043
1044 TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
1045 Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
1046 CI->replaceAllUsesWith(Lowered);
1047 CI->eraseFromParent();
1048}
1049
1050// ThinLTO backend: the function F has a jump table entry; update this module
1051// accordingly. isJumpTableCanonical describes the type of the jump table entry.
1052void LowerTypeTestsModule::importFunction(
1053 Function *F, bool isJumpTableCanonical,
1054 std::vector<GlobalAlias *> &AliasesToErase) {
1055 assert(F->getType()->getAddressSpace() == 0)((F->getType()->getAddressSpace() == 0) ? static_cast<
void> (0) : __assert_fail ("F->getType()->getAddressSpace() == 0"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 1055, __PRETTY_FUNCTION__))
;
1056
1057 GlobalValue::VisibilityTypes Visibility = F->getVisibility();
1058 std::string Name = std::string(F->getName());
1059
1060 if (F->isDeclarationForLinker() && isJumpTableCanonical) {
1061 // Non-dso_local functions may be overriden at run time,
1062 // don't short curcuit them
1063 if (F->isDSOLocal()) {
1064 Function *RealF = Function::Create(F->getFunctionType(),
1065 GlobalValue::ExternalLinkage,
1066 F->getAddressSpace(),
1067 Name + ".cfi", &M);
1068 RealF->setVisibility(GlobalVariable::HiddenVisibility);
1069 replaceDirectCalls(F, RealF);
1070 }
1071 return;
1072 }
1073
1074 Function *FDecl;
1075 if (!isJumpTableCanonical) {
1076 // Either a declaration of an external function or a reference to a locally
1077 // defined jump table.
1078 FDecl = Function::Create(F->getFunctionType(), GlobalValue::ExternalLinkage,
1079 F->getAddressSpace(), Name + ".cfi_jt", &M);
1080 FDecl->setVisibility(GlobalValue::HiddenVisibility);
1081 } else {
1082 F->setName(Name + ".cfi");
1083 F->setLinkage(GlobalValue::ExternalLinkage);
1084 FDecl = Function::Create(F->getFunctionType(), GlobalValue::ExternalLinkage,
1085 F->getAddressSpace(), Name, &M);
1086 FDecl->setVisibility(Visibility);
1087 Visibility = GlobalValue::HiddenVisibility;
1088
1089 // Delete aliases pointing to this function, they'll be re-created in the
1090 // merged output. Don't do it yet though because ScopedSaveAliaseesAndUsed
1091 // will want to reset the aliasees first.
1092 for (auto &U : F->uses()) {
1093 if (auto *A = dyn_cast<GlobalAlias>(U.getUser())) {
1094 Function *AliasDecl = Function::Create(
1095 F->getFunctionType(), GlobalValue::ExternalLinkage,
1096 F->getAddressSpace(), "", &M);
1097 AliasDecl->takeName(A);
1098 A->replaceAllUsesWith(AliasDecl);
1099 AliasesToErase.push_back(A);
1100 }
1101 }
1102 }
1103
1104 if (F->hasExternalWeakLinkage())
1105 replaceWeakDeclarationWithJumpTablePtr(F, FDecl, isJumpTableCanonical);
1106 else
1107 replaceCfiUses(F, FDecl, isJumpTableCanonical);
1108
1109 // Set visibility late because it's used in replaceCfiUses() to determine
1110 // whether uses need to to be replaced.
1111 F->setVisibility(Visibility);
1112}
1113
1114void LowerTypeTestsModule::lowerTypeTestCalls(
1115 ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
1116 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
1117 CombinedGlobalAddr = ConstantExpr::getBitCast(CombinedGlobalAddr, Int8PtrTy);
1118
1119 // For each type identifier in this disjoint set...
1120 for (Metadata *TypeId : TypeIds) {
1121 // Build the bitset.
1122 BitSetInfo BSI = buildBitSet(TypeId, GlobalLayout);
1123 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
1124 if (auto MDS = dyn_cast<MDString>(TypeId))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
1125 dbgs() << MDS->getString() << ": ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
1126 elsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
1127 dbgs() << "<unnamed>: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
1128 BSI.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
1129 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lowertypetests")) { { if (auto MDS = dyn_cast<MDString>
(TypeId)) dbgs() << MDS->getString() << ": "; else
dbgs() << "<unnamed>: "; BSI.print(dbgs()); }; }
} while (false)
;
1130
1131 ByteArrayInfo *BAI = nullptr;
1132 TypeIdLowering TIL;
1133 TIL.OffsetedGlobal = ConstantExpr::getGetElementPtr(
1134 Int8Ty, CombinedGlobalAddr, ConstantInt::get(IntPtrTy, BSI.ByteOffset)),
1135 TIL.AlignLog2 = ConstantInt::get(Int8Ty, BSI.AlignLog2);
1136 TIL.SizeM1 = ConstantInt::get(IntPtrTy, BSI.BitSize - 1);
1137 if (BSI.isAllOnes()) {
1138 TIL.TheKind = (BSI.BitSize == 1) ? TypeTestResolution::Single
1139 : TypeTestResolution::AllOnes;
1140 } else if (BSI.BitSize <= 64) {
1141 TIL.TheKind = TypeTestResolution::Inline;
1142 uint64_t InlineBits = 0;
1143 for (auto Bit : BSI.Bits)
1144 InlineBits |= uint64_t(1) << Bit;
1145 if (InlineBits == 0)
1146 TIL.TheKind = TypeTestResolution::Unsat;
1147 else
1148 TIL.InlineBits = ConstantInt::get(
1149 (BSI.BitSize <= 32) ? Int32Ty : Int64Ty, InlineBits);
1150 } else {
1151 TIL.TheKind = TypeTestResolution::ByteArray;
1152 ++NumByteArraysCreated;
1153 BAI = createByteArray(BSI);
1154 TIL.TheByteArray = BAI->ByteArray;
1155 TIL.BitMask = BAI->MaskGlobal;
1156 }
1157
1158 TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
1159
1160 if (TIUI.IsExported) {
1161 uint8_t *MaskPtr = exportTypeId(cast<MDString>(TypeId)->getString(), TIL);
1162 if (BAI)
1163 BAI->MaskPtr = MaskPtr;
1164 }
1165
1166 // Lower each call to llvm.type.test for this type identifier.
1167 for (CallInst *CI : TIUI.CallSites) {
1168 ++NumTypeTestCallsLowered;
1169 Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
1170 CI->replaceAllUsesWith(Lowered);
1171 CI->eraseFromParent();
1172 }
1173 }
1174}
1175
1176void LowerTypeTestsModule::verifyTypeMDNode(GlobalObject *GO, MDNode *Type) {
1177 if (Type->getNumOperands() != 2)
1178 report_fatal_error("All operands of type metadata must have 2 elements");
1179
1180 if (GO->isThreadLocal())
1181 report_fatal_error("Bit set element may not be thread-local");
1182 if (isa<GlobalVariable>(GO) && GO->hasSection())
1183 report_fatal_error(
1184 "A member of a type identifier may not have an explicit section");
1185
1186 // FIXME: We previously checked that global var member of a type identifier
1187 // must be a definition, but the IR linker may leave type metadata on
1188 // declarations. We should restore this check after fixing PR31759.
1189
1190 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Type->getOperand(0));
1191 if (!OffsetConstMD)
1192 report_fatal_error("Type offset must be a constant");
1193 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
1194 if (!OffsetInt)
1195 report_fatal_error("Type offset must be an integer constant");
1196}
1197
1198static const unsigned kX86JumpTableEntrySize = 8;
1199static const unsigned kARMJumpTableEntrySize = 4;
1200
1201unsigned LowerTypeTestsModule::getJumpTableEntrySize() {
1202 switch (Arch) {
1203 case Triple::x86:
1204 case Triple::x86_64:
1205 return kX86JumpTableEntrySize;
1206 case Triple::arm:
1207 case Triple::thumb:
1208 case Triple::aarch64:
1209 return kARMJumpTableEntrySize;
1210 default:
1211 report_fatal_error("Unsupported architecture for jump tables");
1212 }
1213}
1214
1215// Create a jump table entry for the target. This consists of an instruction
1216// sequence containing a relative branch to Dest. Appends inline asm text,
1217// constraints and arguments to AsmOS, ConstraintOS and AsmArgs.
1218void LowerTypeTestsModule::createJumpTableEntry(
1219 raw_ostream &AsmOS, raw_ostream &ConstraintOS,
1220 Triple::ArchType JumpTableArch, SmallVectorImpl<Value *> &AsmArgs,
1221 Function *Dest) {
1222 unsigned ArgIndex = AsmArgs.size();
1223
1224 if (JumpTableArch == Triple::x86 || JumpTableArch == Triple::x86_64) {
1225 AsmOS << "jmp ${" << ArgIndex << ":c}@plt\n";
1226 AsmOS << "int3\nint3\nint3\n";
1227 } else if (JumpTableArch == Triple::arm || JumpTableArch == Triple::aarch64) {
1228 AsmOS << "b $" << ArgIndex << "\n";
1229 } else if (JumpTableArch == Triple::thumb) {
1230 AsmOS << "b.w $" << ArgIndex << "\n";
1231 } else {
1232 report_fatal_error("Unsupported architecture for jump tables");
1233 }
1234
1235 ConstraintOS << (ArgIndex > 0 ? ",s" : "s");
1236 AsmArgs.push_back(Dest);
1237}
1238
1239Type *LowerTypeTestsModule::getJumpTableEntryType() {
1240 return ArrayType::get(Int8Ty, getJumpTableEntrySize());
1241}
1242
1243/// Given a disjoint set of type identifiers and functions, build the bit sets
1244/// and lower the llvm.type.test calls, architecture dependently.
1245void LowerTypeTestsModule::buildBitSetsFromFunctions(
1246 ArrayRef<Metadata *> TypeIds, ArrayRef<GlobalTypeMember *> Functions) {
1247 if (Arch == Triple::x86 || Arch == Triple::x86_64 || Arch == Triple::arm ||
25
Assuming field 'Arch' is not equal to x86
26
Assuming field 'Arch' is not equal to x86_64
27
Assuming field 'Arch' is not equal to arm
30
Taking true branch
1248 Arch == Triple::thumb || Arch == Triple::aarch64)
28
Assuming field 'Arch' is not equal to thumb
29
Assuming field 'Arch' is equal to aarch64
1249 buildBitSetsFromFunctionsNative(TypeIds, Functions);
31
Calling 'LowerTypeTestsModule::buildBitSetsFromFunctionsNative'
1250 else if (Arch == Triple::wasm32 || Arch == Triple::wasm64)
1251 buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1252 else
1253 report_fatal_error("Unsupported architecture for jump tables");
1254}
1255
1256void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1257 GlobalVariable *GV) {
1258 if (WeakInitializerFn == nullptr) {
1259 WeakInitializerFn = Function::Create(
1260 FunctionType::get(Type::getVoidTy(M.getContext()),
1261 /* IsVarArg */ false),
1262 GlobalValue::InternalLinkage,
1263 M.getDataLayout().getProgramAddressSpace(),
1264 "__cfi_global_var_init", &M);
1265 BasicBlock *BB =
1266 BasicBlock::Create(M.getContext(), "entry", WeakInitializerFn);
1267 ReturnInst::Create(M.getContext(), BB);
1268 WeakInitializerFn->setSection(
1269 ObjectFormat == Triple::MachO
1270 ? "__TEXT,__StaticInit,regular,pure_instructions"
1271 : ".text.startup");
1272 // This code is equivalent to relocation application, and should run at the
1273 // earliest possible time (i.e. with the highest priority).
1274 appendToGlobalCtors(M, WeakInitializerFn, /* Priority */ 0);
1275 }
1276
1277 IRBuilder<> IRB(WeakInitializerFn->getEntryBlock().getTerminator());
1278 GV->setConstant(false);
1279 IRB.CreateAlignedStore(GV->getInitializer(), GV, GV->getAlign());
1280 GV->setInitializer(Constant::getNullValue(GV->getValueType()));
1281}
1282
1283void LowerTypeTestsModule::findGlobalVariableUsersOf(
1284 Constant *C, SmallSetVector<GlobalVariable *, 8> &Out) {
1285 for (auto *U : C->users()){
1286 if (auto *GV = dyn_cast<GlobalVariable>(U))
1287 Out.insert(GV);
1288 else if (auto *C2 = dyn_cast<Constant>(U))
1289 findGlobalVariableUsersOf(C2, Out);
1290 }
1291}
1292
1293// Replace all uses of F with (F ? JT : 0).
1294void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1295 Function *F, Constant *JT, bool IsJumpTableCanonical) {
1296 // The target expression can not appear in a constant initializer on most
1297 // (all?) targets. Switch to a runtime initializer.
1298 SmallSetVector<GlobalVariable *, 8> GlobalVarUsers;
1299 findGlobalVariableUsersOf(F, GlobalVarUsers);
1300 for (auto GV : GlobalVarUsers)
1301 moveInitializerToModuleConstructor(GV);
1302
1303 // Can not RAUW F with an expression that uses F. Replace with a temporary
1304 // placeholder first.
1305 Function *PlaceholderFn =
1306 Function::Create(cast<FunctionType>(F->getValueType()),
1307 GlobalValue::ExternalWeakLinkage,
1308 F->getAddressSpace(), "", &M);
1309 replaceCfiUses(F, PlaceholderFn, IsJumpTableCanonical);
1310
1311 Constant *Target = ConstantExpr::getSelect(
1312 ConstantExpr::getICmp(CmpInst::ICMP_NE, F,
1313 Constant::getNullValue(F->getType())),
1314 JT, Constant::getNullValue(F->getType()));
1315 PlaceholderFn->replaceAllUsesWith(Target);
1316 PlaceholderFn->eraseFromParent();
1317}
1318
1319static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch) {
1320 Attribute TFAttr = F->getFnAttribute("target-features");
1321 if (!TFAttr.hasAttribute(Attribute::None)) {
1322 SmallVector<StringRef, 6> Features;
1323 TFAttr.getValueAsString().split(Features, ',');
1324 for (StringRef Feature : Features) {
1325 if (Feature == "-thumb-mode")
1326 return false;
1327 else if (Feature == "+thumb-mode")
1328 return true;
1329 }
1330 }
1331
1332 return ModuleArch == Triple::thumb;
1333}
1334
1335// Each jump table must be either ARM or Thumb as a whole for the bit-test math
1336// to work. Pick one that matches the majority of members to minimize interop
1337// veneers inserted by the linker.
1338static Triple::ArchType
1339selectJumpTableArmEncoding(ArrayRef<GlobalTypeMember *> Functions,
1340 Triple::ArchType ModuleArch) {
1341 if (ModuleArch != Triple::arm && ModuleArch != Triple::thumb)
1342 return ModuleArch;
1343
1344 unsigned ArmCount = 0, ThumbCount = 0;
1345 for (const auto GTM : Functions) {
1346 if (!GTM->isJumpTableCanonical()) {
1347 // PLT stubs are always ARM.
1348 // FIXME: This is the wrong heuristic for non-canonical jump tables.
1349 ++ArmCount;
1350 continue;
1351 }
1352
1353 Function *F = cast<Function>(GTM->getGlobal());
1354 ++(isThumbFunction(F, ModuleArch) ? ThumbCount : ArmCount);
1355 }
1356
1357 return ArmCount > ThumbCount ? Triple::arm : Triple::thumb;
1358}
1359
1360void LowerTypeTestsModule::createJumpTable(
1361 Function *F, ArrayRef<GlobalTypeMember *> Functions) {
1362 std::string AsmStr, ConstraintStr;
1363 raw_string_ostream AsmOS(AsmStr), ConstraintOS(ConstraintStr);
1364 SmallVector<Value *, 16> AsmArgs;
1365 AsmArgs.reserve(Functions.size() * 2);
1366
1367 Triple::ArchType JumpTableArch = selectJumpTableArmEncoding(Functions, Arch);
1368
1369 for (unsigned I = 0; I != Functions.size(); ++I)
1370 createJumpTableEntry(AsmOS, ConstraintOS, JumpTableArch, AsmArgs,
1371 cast<Function>(Functions[I]->getGlobal()));
1372
1373 // Align the whole table by entry size.
1374 F->setAlignment(Align(getJumpTableEntrySize()));
1375 // Skip prologue.
1376 // Disabled on win32 due to https://llvm.org/bugs/show_bug.cgi?id=28641#c3.
1377 // Luckily, this function does not get any prologue even without the
1378 // attribute.
1379 if (OS != Triple::Win32)
1380 F->addFnAttr(Attribute::Naked);
1381 if (JumpTableArch == Triple::arm)
1382 F->addFnAttr("target-features", "-thumb-mode");
1383 if (JumpTableArch == Triple::thumb) {
1384 F->addFnAttr("target-features", "+thumb-mode");
1385 // Thumb jump table assembly needs Thumb2. The following attribute is added
1386 // by Clang for -march=armv7.
1387 F->addFnAttr("target-cpu", "cortex-a8");
1388 }
1389 // Make sure we don't emit .eh_frame for this function.
1390 F->addFnAttr(Attribute::NoUnwind);
1391
1392 BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", F);
1393 IRBuilder<> IRB(BB);
1394
1395 SmallVector<Type *, 16> ArgTypes;
1396 ArgTypes.reserve(AsmArgs.size());
1397 for (const auto &Arg : AsmArgs)
1398 ArgTypes.push_back(Arg->getType());
1399 InlineAsm *JumpTableAsm =
1400 InlineAsm::get(FunctionType::get(IRB.getVoidTy(), ArgTypes, false),
1401 AsmOS.str(), ConstraintOS.str(),
1402 /*hasSideEffects=*/true);
1403
1404 IRB.CreateCall(JumpTableAsm, AsmArgs);
1405 IRB.CreateUnreachable();
1406}
1407
1408/// Given a disjoint set of type identifiers and functions, build a jump table
1409/// for the functions, build the bit sets and lower the llvm.type.test calls.
1410void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
1411 ArrayRef<Metadata *> TypeIds, ArrayRef<GlobalTypeMember *> Functions) {
1412 // Unlike the global bitset builder, the function bitset builder cannot
1413 // re-arrange functions in a particular order and base its calculations on the
1414 // layout of the functions' entry points, as we have no idea how large a
1415 // particular function will end up being (the size could even depend on what
1416 // this pass does!) Instead, we build a jump table, which is a block of code
1417 // consisting of one branch instruction for each of the functions in the bit
1418 // set that branches to the target function, and redirect any taken function
1419 // addresses to the corresponding jump table entry. In the object file's
1420 // symbol table, the symbols for the target functions also refer to the jump
1421 // table entries, so that addresses taken outside the module will pass any
1422 // verification done inside the module.
1423 //
1424 // In more concrete terms, suppose we have three functions f, g, h which are
1425 // of the same type, and a function foo that returns their addresses:
1426 //
1427 // f:
1428 // mov 0, %eax
1429 // ret
1430 //
1431 // g:
1432 // mov 1, %eax
1433 // ret
1434 //
1435 // h:
1436 // mov 2, %eax
1437 // ret
1438 //
1439 // foo:
1440 // mov f, %eax
1441 // mov g, %edx
1442 // mov h, %ecx
1443 // ret
1444 //
1445 // We output the jump table as module-level inline asm string. The end result
1446 // will (conceptually) look like this:
1447 //
1448 // f = .cfi.jumptable
1449 // g = .cfi.jumptable + 4
1450 // h = .cfi.jumptable + 8
1451 // .cfi.jumptable:
1452 // jmp f.cfi ; 5 bytes
1453 // int3 ; 1 byte
1454 // int3 ; 1 byte
1455 // int3 ; 1 byte
1456 // jmp g.cfi ; 5 bytes
1457 // int3 ; 1 byte
1458 // int3 ; 1 byte
1459 // int3 ; 1 byte
1460 // jmp h.cfi ; 5 bytes
1461 // int3 ; 1 byte
1462 // int3 ; 1 byte
1463 // int3 ; 1 byte
1464 //
1465 // f.cfi:
1466 // mov 0, %eax
1467 // ret
1468 //
1469 // g.cfi:
1470 // mov 1, %eax
1471 // ret
1472 //
1473 // h.cfi:
1474 // mov 2, %eax
1475 // ret
1476 //
1477 // foo:
1478 // mov f, %eax
1479 // mov g, %edx
1480 // mov h, %ecx
1481 // ret
1482 //
1483 // Because the addresses of f, g, h are evenly spaced at a power of 2, in the
1484 // normal case the check can be carried out using the same kind of simple
1485 // arithmetic that we normally use for globals.
1486
1487 // FIXME: find a better way to represent the jumptable in the IR.
1488 assert(!Functions.empty())((!Functions.empty()) ? static_cast<void> (0) : __assert_fail
("!Functions.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 1488, __PRETTY_FUNCTION__))
;
32
Assuming the condition is true
33
'?' condition is true
1489
1490 // Build a simple layout based on the regular layout of jump tables.
1491 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
1492 unsigned EntrySize = getJumpTableEntrySize();
1493 for (unsigned I = 0; I != Functions.size(); ++I)
34
Assuming the condition is false
35
Loop condition is false. Execution continues on line 1497
1494 GlobalLayout[Functions[I]] = I * EntrySize;
1495
1496 Function *JumpTableFn =
1497 Function::Create(FunctionType::get(Type::getVoidTy(M.getContext()),
1498 /* IsVarArg */ false),
1499 GlobalValue::PrivateLinkage,
1500 M.getDataLayout().getProgramAddressSpace(),
1501 ".cfi.jumptable", &M);
1502 ArrayType *JumpTableType =
1503 ArrayType::get(getJumpTableEntryType(), Functions.size());
1504 auto JumpTable =
1505 ConstantExpr::getPointerCast(JumpTableFn, JumpTableType->getPointerTo(0));
1506
1507 lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
1508
1509 {
1510 ScopedSaveAliaseesAndUsed S(M);
1511
1512 // Build aliases pointing to offsets into the jump table, and replace
1513 // references to the original functions with references to the aliases.
1514 for (unsigned I = 0; I != Functions.size(); ++I) {
36
Assuming the condition is true
37
Loop condition is true. Entering loop body
1515 Function *F = cast<Function>(Functions[I]->getGlobal());
38
The object is a 'Function'
1516 bool IsJumpTableCanonical = Functions[I]->isJumpTableCanonical();
1517
1518 Constant *CombinedGlobalElemPtr = ConstantExpr::getBitCast(
1519 ConstantExpr::getInBoundsGetElementPtr(
1520 JumpTableType, JumpTable,
1521 ArrayRef<Constant *>{ConstantInt::get(IntPtrTy, 0),
1522 ConstantInt::get(IntPtrTy, I)}),
1523 F->getType());
1524 if (Functions[I]->isExported()) {
39
Assuming the condition is true
40
Taking true branch
1525 if (IsJumpTableCanonical) {
41
Assuming 'IsJumpTableCanonical' is false
42
Taking false branch
1526 ExportSummary->cfiFunctionDefs().insert(std::string(F->getName()));
1527 } else {
1528 GlobalAlias *JtAlias = GlobalAlias::create(
1529 F->getValueType(), 0, GlobalValue::ExternalLinkage,
1530 F->getName() + ".cfi_jt", CombinedGlobalElemPtr, &M);
1531 JtAlias->setVisibility(GlobalValue::HiddenVisibility);
1532 ExportSummary->cfiFunctionDecls().insert(std::string(F->getName()));
43
Called C++ object pointer is null
1533 }
1534 }
1535 if (!IsJumpTableCanonical) {
1536 if (F->hasExternalWeakLinkage())
1537 replaceWeakDeclarationWithJumpTablePtr(F, CombinedGlobalElemPtr,
1538 IsJumpTableCanonical);
1539 else
1540 replaceCfiUses(F, CombinedGlobalElemPtr, IsJumpTableCanonical);
1541 } else {
1542 assert(F->getType()->getAddressSpace() == 0)((F->getType()->getAddressSpace() == 0) ? static_cast<
void> (0) : __assert_fail ("F->getType()->getAddressSpace() == 0"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 1542, __PRETTY_FUNCTION__))
;
1543
1544 GlobalAlias *FAlias =
1545 GlobalAlias::create(F->getValueType(), 0, F->getLinkage(), "",
1546 CombinedGlobalElemPtr, &M);
1547 FAlias->setVisibility(F->getVisibility());
1548 FAlias->takeName(F);
1549 if (FAlias->hasName())
1550 F->setName(FAlias->getName() + ".cfi");
1551 replaceCfiUses(F, FAlias, IsJumpTableCanonical);
1552 if (!F->hasLocalLinkage())
1553 F->setVisibility(GlobalVariable::HiddenVisibility);
1554 }
1555 }
1556 }
1557
1558 createJumpTable(JumpTableFn, Functions);
1559}
1560
1561/// Assign a dummy layout using an incrementing counter, tag each function
1562/// with its index represented as metadata, and lower each type test to an
1563/// integer range comparison. During generation of the indirect function call
1564/// table in the backend, it will assign the given indexes.
1565/// Note: Dynamic linking is not supported, as the WebAssembly ABI has not yet
1566/// been finalized.
1567void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
1568 ArrayRef<Metadata *> TypeIds, ArrayRef<GlobalTypeMember *> Functions) {
1569 assert(!Functions.empty())((!Functions.empty()) ? static_cast<void> (0) : __assert_fail
("!Functions.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 1569, __PRETTY_FUNCTION__))
;
1570
1571 // Build consecutive monotonic integer ranges for each call target set
1572 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
1573
1574 for (GlobalTypeMember *GTM : Functions) {
1575 Function *F = cast<Function>(GTM->getGlobal());
1576
1577 // Skip functions that are not address taken, to avoid bloating the table
1578 if (!F->hasAddressTaken())
1579 continue;
1580
1581 // Store metadata with the index for each function
1582 MDNode *MD = MDNode::get(F->getContext(),
1583 ArrayRef<Metadata *>(ConstantAsMetadata::get(
1584 ConstantInt::get(Int64Ty, IndirectIndex))));
1585 F->setMetadata("wasm.index", MD);
1586
1587 // Assign the counter value
1588 GlobalLayout[GTM] = IndirectIndex++;
1589 }
1590
1591 // The indirect function table index space starts at zero, so pass a NULL
1592 // pointer as the subtracted "jump table" offset.
1593 lowerTypeTestCalls(TypeIds, ConstantPointerNull::get(Int32PtrTy),
1594 GlobalLayout);
1595}
1596
1597void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
1598 ArrayRef<Metadata *> TypeIds, ArrayRef<GlobalTypeMember *> Globals,
1599 ArrayRef<ICallBranchFunnel *> ICallBranchFunnels) {
1600 DenseMap<Metadata *, uint64_t> TypeIdIndices;
1601 for (unsigned I = 0; I != TypeIds.size(); ++I)
17
Assuming the condition is false
18
Loop condition is false. Execution continues on line 1606
1602 TypeIdIndices[TypeIds[I]] = I;
1603
1604 // For each type identifier, build a set of indices that refer to members of
1605 // the type identifier.
1606 std::vector<std::set<uint64_t>> TypeMembers(TypeIds.size());
1607 unsigned GlobalIndex = 0;
1608 DenseMap<GlobalTypeMember *, uint64_t> GlobalIndices;
1609 for (GlobalTypeMember *GTM : Globals) {
19
Assuming '__begin1' is equal to '__end1'
1610 for (MDNode *Type : GTM->types()) {
1611 // Type = { offset, type identifier }
1612 auto I = TypeIdIndices.find(Type->getOperand(1));
1613 if (I != TypeIdIndices.end())
1614 TypeMembers[I->second].insert(GlobalIndex);
1615 }
1616 GlobalIndices[GTM] = GlobalIndex;
1617 GlobalIndex++;
1618 }
1619
1620 for (ICallBranchFunnel *JT : ICallBranchFunnels) {
20
Assuming '__begin1' is equal to '__end1'
1621 TypeMembers.emplace_back();
1622 std::set<uint64_t> &TMSet = TypeMembers.back();
1623 for (GlobalTypeMember *T : JT->targets())
1624 TMSet.insert(GlobalIndices[T]);
1625 }
1626
1627 // Order the sets of indices by size. The GlobalLayoutBuilder works best
1628 // when given small index sets first.
1629 llvm::stable_sort(TypeMembers, [](const std::set<uint64_t> &O1,
1630 const std::set<uint64_t> &O2) {
1631 return O1.size() < O2.size();
1632 });
1633
1634 // Create a GlobalLayoutBuilder and provide it with index sets as layout
1635 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments as
1636 // close together as possible.
1637 GlobalLayoutBuilder GLB(Globals.size());
1638 for (auto &&MemSet : TypeMembers)
1639 GLB.addFragment(MemSet);
1640
1641 // Build a vector of globals with the computed layout.
1642 bool IsGlobalSet =
1643 Globals.empty() || isa<GlobalVariable>(Globals[0]->getGlobal());
21
Assuming the condition is false
22
Assuming the object is not a 'GlobalVariable'
1644 std::vector<GlobalTypeMember *> OrderedGTMs(Globals.size());
1645 auto OGTMI = OrderedGTMs.begin();
1646 for (auto &&F : GLB.Fragments) {
1647 for (auto &&Offset : F) {
1648 if (IsGlobalSet != isa<GlobalVariable>(Globals[Offset]->getGlobal()))
1649 report_fatal_error("Type identifier may not contain both global "
1650 "variables and functions");
1651 *OGTMI++ = Globals[Offset];
1652 }
1653 }
1654
1655 // Build the bitsets from this disjoint set.
1656 if (IsGlobalSet
22.1
'IsGlobalSet' is false
)
23
Taking false branch
1657 buildBitSetsFromGlobalVariables(TypeIds, OrderedGTMs);
1658 else
1659 buildBitSetsFromFunctions(TypeIds, OrderedGTMs);
24
Calling 'LowerTypeTestsModule::buildBitSetsFromFunctions'
1660}
1661
1662/// Lower all type tests in this module.
1663LowerTypeTestsModule::LowerTypeTestsModule(
1664 Module &M, ModuleSummaryIndex *ExportSummary,
1665 const ModuleSummaryIndex *ImportSummary, bool DropTypeTests)
1666 : M(M), ExportSummary(ExportSummary), ImportSummary(ImportSummary),
1667 DropTypeTests(DropTypeTests) {
1668 assert(!(ExportSummary && ImportSummary))((!(ExportSummary && ImportSummary)) ? static_cast<
void> (0) : __assert_fail ("!(ExportSummary && ImportSummary)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 1668, __PRETTY_FUNCTION__))
;
1669 Triple TargetTriple(M.getTargetTriple());
1670 Arch = TargetTriple.getArch();
1671 OS = TargetTriple.getOS();
1672 ObjectFormat = TargetTriple.getObjectFormat();
1673}
1674
1675bool LowerTypeTestsModule::runForTesting(Module &M) {
1676 ModuleSummaryIndex Summary(/*HaveGVs=*/false);
1677
1678 // Handle the command-line summary arguments. This code is for testing
1679 // purposes only, so we handle errors directly.
1680 if (!ClReadSummary.empty()) {
1681 ExitOnError ExitOnErr("-lowertypetests-read-summary: " + ClReadSummary +
1682 ": ");
1683 auto ReadSummaryFile =
1684 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
1685
1686 yaml::Input In(ReadSummaryFile->getBuffer());
1687 In >> Summary;
1688 ExitOnErr(errorCodeToError(In.error()));
1689 }
1690
1691 bool Changed =
1692 LowerTypeTestsModule(
1693 M, ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
1694 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr,
1695 /*DropTypeTests*/ false)
1696 .lower();
1697
1698 if (!ClWriteSummary.empty()) {
1699 ExitOnError ExitOnErr("-lowertypetests-write-summary: " + ClWriteSummary +
1700 ": ");
1701 std::error_code EC;
1702 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_Text);
1703 ExitOnErr(errorCodeToError(EC));
1704
1705 yaml::Output Out(OS);
1706 Out << Summary;
1707 }
1708
1709 return Changed;
1710}
1711
1712static bool isDirectCall(Use& U) {
1713 auto *Usr = dyn_cast<CallInst>(U.getUser());
1714 if (Usr) {
1715 CallSite CS(Usr);
1716 if (CS.isCallee(&U))
1717 return true;
1718 }
1719 return false;
1720}
1721
1722void LowerTypeTestsModule::replaceCfiUses(Function *Old, Value *New,
1723 bool IsJumpTableCanonical) {
1724 SmallSetVector<Constant *, 4> Constants;
1725 auto UI = Old->use_begin(), E = Old->use_end();
1726 for (; UI != E;) {
1727 Use &U = *UI;
1728 ++UI;
1729
1730 // Skip block addresses
1731 if (isa<BlockAddress>(U.getUser()))
1732 continue;
1733
1734 // Skip direct calls to externally defined or non-dso_local functions
1735 if (isDirectCall(U) && (Old->isDSOLocal() || !IsJumpTableCanonical))
1736 continue;
1737
1738 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
1739 // constant because they are uniqued.
1740 if (auto *C = dyn_cast<Constant>(U.getUser())) {
1741 if (!isa<GlobalValue>(C)) {
1742 // Save unique users to avoid processing operand replacement
1743 // more than once.
1744 Constants.insert(C);
1745 continue;
1746 }
1747 }
1748
1749 U.set(New);
1750 }
1751
1752 // Process operand replacement of saved constants.
1753 for (auto *C : Constants)
1754 C->handleOperandChange(Old, New);
1755}
1756
1757void LowerTypeTestsModule::replaceDirectCalls(Value *Old, Value *New) {
1758 Old->replaceUsesWithIf(New, [](Use &U) { return isDirectCall(U); });
1759}
1760
1761bool LowerTypeTestsModule::lower() {
1762 Function *TypeTestFunc =
1763 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1764
1765 if (DropTypeTests && TypeTestFunc) {
1
Assuming field 'DropTypeTests' is false
1766 for (auto UI = TypeTestFunc->use_begin(), UE = TypeTestFunc->use_end();
1767 UI != UE;) {
1768 auto *CI = cast<CallInst>((*UI++).getUser());
1769 // Find and erase llvm.assume intrinsics for this llvm.type.test call.
1770 for (auto CIU = CI->use_begin(), CIUE = CI->use_end(); CIU != CIUE;) {
1771 if (auto *AssumeCI = dyn_cast<CallInst>((*CIU++).getUser())) {
1772 Function *F = AssumeCI->getCalledFunction();
1773 if (F && F->getIntrinsicID() == Intrinsic::assume)
1774 AssumeCI->eraseFromParent();
1775 }
1776 }
1777 CI->eraseFromParent();
1778 }
1779
1780 // We have deleted the type intrinsics, so we no longer have enough
1781 // information to reason about the liveness of virtual function pointers
1782 // in GlobalDCE.
1783 for (GlobalVariable &GV : M.globals())
1784 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
1785
1786 return true;
1787 }
1788
1789 // If only some of the modules were split, we cannot correctly perform
1790 // this transformation. We already checked for the presense of type tests
1791 // with partially split modules during the thin link, and would have emitted
1792 // an error if any were found, so here we can simply return.
1793 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
2
Assuming field 'ExportSummary' is null
1794 (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
3
Assuming field 'ImportSummary' is null
1795 return false;
1796
1797 Function *ICallBranchFunnelFunc =
1798 M.getFunction(Intrinsic::getName(Intrinsic::icall_branch_funnel));
1799 if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
4
Assuming 'TypeTestFunc' is non-null
1800 (!ICallBranchFunnelFunc || ICallBranchFunnelFunc->use_empty()) &&
1801 !ExportSummary && !ImportSummary)
1802 return false;
1803
1804 if (ImportSummary
4.1
Field 'ImportSummary' is null
) {
5
Taking false branch
1805 if (TypeTestFunc) {
1806 for (auto UI = TypeTestFunc->use_begin(), UE = TypeTestFunc->use_end();
1807 UI != UE;) {
1808 auto *CI = cast<CallInst>((*UI++).getUser());
1809 importTypeTest(CI);
1810 }
1811 }
1812
1813 if (ICallBranchFunnelFunc && !ICallBranchFunnelFunc->use_empty())
1814 report_fatal_error(
1815 "unexpected call to llvm.icall.branch.funnel during import phase");
1816
1817 SmallVector<Function *, 8> Defs;
1818 SmallVector<Function *, 8> Decls;
1819 for (auto &F : M) {
1820 // CFI functions are either external, or promoted. A local function may
1821 // have the same name, but it's not the one we are looking for.
1822 if (F.hasLocalLinkage())
1823 continue;
1824 if (ImportSummary->cfiFunctionDefs().count(std::string(F.getName())))
1825 Defs.push_back(&F);
1826 else if (ImportSummary->cfiFunctionDecls().count(
1827 std::string(F.getName())))
1828 Decls.push_back(&F);
1829 }
1830
1831 std::vector<GlobalAlias *> AliasesToErase;
1832 {
1833 ScopedSaveAliaseesAndUsed S(M);
1834 for (auto F : Defs)
1835 importFunction(F, /*isJumpTableCanonical*/ true, AliasesToErase);
1836 for (auto F : Decls)
1837 importFunction(F, /*isJumpTableCanonical*/ false, AliasesToErase);
1838 }
1839 for (GlobalAlias *GA : AliasesToErase)
1840 GA->eraseFromParent();
1841
1842 return true;
1843 }
1844
1845 // Equivalence class set containing type identifiers and the globals that
1846 // reference them. This is used to partition the set of type identifiers in
1847 // the module into disjoint sets.
1848 using GlobalClassesTy = EquivalenceClasses<
1849 PointerUnion<GlobalTypeMember *, Metadata *, ICallBranchFunnel *>>;
1850 GlobalClassesTy GlobalClasses;
1851
1852 // Verify the type metadata and build a few data structures to let us
1853 // efficiently enumerate the type identifiers associated with a global:
1854 // a list of GlobalTypeMembers (a GlobalObject stored alongside a vector
1855 // of associated type metadata) and a mapping from type identifiers to their
1856 // list of GlobalTypeMembers and last observed index in the list of globals.
1857 // The indices will be used later to deterministically order the list of type
1858 // identifiers.
1859 BumpPtrAllocator Alloc;
1860 struct TIInfo {
1861 unsigned UniqueId;
1862 std::vector<GlobalTypeMember *> RefGlobals;
1863 };
1864 DenseMap<Metadata *, TIInfo> TypeIdInfo;
1865 unsigned CurUniqueId = 0;
1866 SmallVector<MDNode *, 2> Types;
1867
1868 // Cross-DSO CFI emits jumptable entries for exported functions as well as
1869 // address taken functions in case they are address taken in other modules.
1870 const bool CrossDsoCfi = M.getModuleFlag("Cross-DSO CFI") != nullptr;
6
Assuming the condition is false
1871
1872 struct ExportedFunctionInfo {
1873 CfiFunctionLinkage Linkage;
1874 MDNode *FuncMD; // {name, linkage, type[, type...]}
1875 };
1876 DenseMap<StringRef, ExportedFunctionInfo> ExportedFunctions;
1877 if (ExportSummary
6.1
Field 'ExportSummary' is null
) {
7
Taking false branch
1878 // A set of all functions that are address taken by a live global object.
1879 DenseSet<GlobalValue::GUID> AddressTaken;
1880 for (auto &I : *ExportSummary)
1881 for (auto &GVS : I.second.SummaryList)
1882 if (GVS->isLive())
1883 for (auto &Ref : GVS->refs())
1884 AddressTaken.insert(Ref.getGUID());
1885
1886 NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions");
1887 if (CfiFunctionsMD) {
1888 for (auto FuncMD : CfiFunctionsMD->operands()) {
1889 assert(FuncMD->getNumOperands() >= 2)((FuncMD->getNumOperands() >= 2) ? static_cast<void>
(0) : __assert_fail ("FuncMD->getNumOperands() >= 2", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 1889, __PRETTY_FUNCTION__))
;
1890 StringRef FunctionName =
1891 cast<MDString>(FuncMD->getOperand(0))->getString();
1892 CfiFunctionLinkage Linkage = static_cast<CfiFunctionLinkage>(
1893 cast<ConstantAsMetadata>(FuncMD->getOperand(1))
1894 ->getValue()
1895 ->getUniqueInteger()
1896 .getZExtValue());
1897 const GlobalValue::GUID GUID = GlobalValue::getGUID(
1898 GlobalValue::dropLLVMManglingEscape(FunctionName));
1899 // Do not emit jumptable entries for functions that are not-live and
1900 // have no live references (and are not exported with cross-DSO CFI.)
1901 if (!ExportSummary->isGUIDLive(GUID))
1902 continue;
1903 if (!AddressTaken.count(GUID)) {
1904 if (!CrossDsoCfi || Linkage != CFL_Definition)
1905 continue;
1906
1907 bool Exported = false;
1908 if (auto VI = ExportSummary->getValueInfo(GUID))
1909 for (auto &GVS : VI.getSummaryList())
1910 if (GVS->isLive() && !GlobalValue::isLocalLinkage(GVS->linkage()))
1911 Exported = true;
1912
1913 if (!Exported)
1914 continue;
1915 }
1916 auto P = ExportedFunctions.insert({FunctionName, {Linkage, FuncMD}});
1917 if (!P.second && P.first->second.Linkage != CFL_Definition)
1918 P.first->second = {Linkage, FuncMD};
1919 }
1920
1921 for (const auto &P : ExportedFunctions) {
1922 StringRef FunctionName = P.first;
1923 CfiFunctionLinkage Linkage = P.second.Linkage;
1924 MDNode *FuncMD = P.second.FuncMD;
1925 Function *F = M.getFunction(FunctionName);
1926 if (F && F->hasLocalLinkage()) {
1927 // Locally defined function that happens to have the same name as a
1928 // function defined in a ThinLTO module. Rename it to move it out of
1929 // the way of the external reference that we're about to create.
1930 // Note that setName will find a unique name for the function, so even
1931 // if there is an existing function with the suffix there won't be a
1932 // name collision.
1933 F->setName(F->getName() + ".1");
1934 F = nullptr;
1935 }
1936
1937 if (!F)
1938 F = Function::Create(
1939 FunctionType::get(Type::getVoidTy(M.getContext()), false),
1940 GlobalVariable::ExternalLinkage,
1941 M.getDataLayout().getProgramAddressSpace(), FunctionName, &M);
1942
1943 // If the function is available_externally, remove its definition so
1944 // that it is handled the same way as a declaration. Later we will try
1945 // to create an alias using this function's linkage, which will fail if
1946 // the linkage is available_externally. This will also result in us
1947 // following the code path below to replace the type metadata.
1948 if (F->hasAvailableExternallyLinkage()) {
1949 F->setLinkage(GlobalValue::ExternalLinkage);
1950 F->deleteBody();
1951 F->setComdat(nullptr);
1952 F->clearMetadata();
1953 }
1954
1955 // Update the linkage for extern_weak declarations when a definition
1956 // exists.
1957 if (Linkage == CFL_Definition && F->hasExternalWeakLinkage())
1958 F->setLinkage(GlobalValue::ExternalLinkage);
1959
1960 // If the function in the full LTO module is a declaration, replace its
1961 // type metadata with the type metadata we found in cfi.functions. That
1962 // metadata is presumed to be more accurate than the metadata attached
1963 // to the declaration.
1964 if (F->isDeclaration()) {
1965 if (Linkage == CFL_WeakDeclaration)
1966 F->setLinkage(GlobalValue::ExternalWeakLinkage);
1967
1968 F->eraseMetadata(LLVMContext::MD_type);
1969 for (unsigned I = 2; I < FuncMD->getNumOperands(); ++I)
1970 F->addMetadata(LLVMContext::MD_type,
1971 *cast<MDNode>(FuncMD->getOperand(I).get()));
1972 }
1973 }
1974 }
1975 }
1976
1977 DenseMap<GlobalObject *, GlobalTypeMember *> GlobalTypeMembers;
1978 for (GlobalObject &GO : M.global_objects()) {
1979 if (isa<GlobalVariable>(GO) && GO.isDeclarationForLinker())
1980 continue;
1981
1982 Types.clear();
1983 GO.getMetadata(LLVMContext::MD_type, Types);
1984
1985 bool IsJumpTableCanonical = false;
1986 bool IsExported = false;
1987 if (Function *F = dyn_cast<Function>(&GO)) {
1988 IsJumpTableCanonical = isJumpTableCanonical(F);
1989 if (ExportedFunctions.count(F->getName())) {
1990 IsJumpTableCanonical |=
1991 ExportedFunctions[F->getName()].Linkage == CFL_Definition;
1992 IsExported = true;
1993 // TODO: The logic here checks only that the function is address taken,
1994 // not that the address takers are live. This can be updated to check
1995 // their liveness and emit fewer jumptable entries once monolithic LTO
1996 // builds also emit summaries.
1997 } else if (!F->hasAddressTaken()) {
1998 if (!CrossDsoCfi || !IsJumpTableCanonical || F->hasLocalLinkage())
1999 continue;
2000 }
2001 }
2002
2003 auto *GTM = GlobalTypeMember::create(Alloc, &GO, IsJumpTableCanonical,
2004 IsExported, Types);
2005 GlobalTypeMembers[&GO] = GTM;
2006 for (MDNode *Type : Types) {
2007 verifyTypeMDNode(&GO, Type);
2008 auto &Info = TypeIdInfo[Type->getOperand(1)];
2009 Info.UniqueId = ++CurUniqueId;
2010 Info.RefGlobals.push_back(GTM);
2011 }
2012 }
2013
2014 auto AddTypeIdUse = [&](Metadata *TypeId) -> TypeIdUserInfo & {
2015 // Add the call site to the list of call sites for this type identifier. We
2016 // also use TypeIdUsers to keep track of whether we have seen this type
2017 // identifier before. If we have, we don't need to re-add the referenced
2018 // globals to the equivalence class.
2019 auto Ins = TypeIdUsers.insert({TypeId, {}});
2020 if (Ins.second) {
2021 // Add the type identifier to the equivalence class.
2022 GlobalClassesTy::iterator GCI = GlobalClasses.insert(TypeId);
2023 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
2024
2025 // Add the referenced globals to the type identifier's equivalence class.
2026 for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
2027 CurSet = GlobalClasses.unionSets(
2028 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
2029 }
2030
2031 return Ins.first->second;
2032 };
2033
2034 if (TypeTestFunc
7.1
'TypeTestFunc' is non-null
) {
8
Taking true branch
2035 for (const Use &U : TypeTestFunc->uses()) {
2036 auto CI = cast<CallInst>(U.getUser());
2037
2038 auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
2039 if (!TypeIdMDVal)
2040 report_fatal_error("Second argument of llvm.type.test must be metadata");
2041 auto TypeId = TypeIdMDVal->getMetadata();
2042 AddTypeIdUse(TypeId).CallSites.push_back(CI);
2043 }
2044 }
2045
2046 if (ICallBranchFunnelFunc) {
9
Assuming 'ICallBranchFunnelFunc' is null
10
Taking false branch
2047 for (const Use &U : ICallBranchFunnelFunc->uses()) {
2048 if (Arch != Triple::x86_64)
2049 report_fatal_error(
2050 "llvm.icall.branch.funnel not supported on this target");
2051
2052 auto CI = cast<CallInst>(U.getUser());
2053
2054 std::vector<GlobalTypeMember *> Targets;
2055 if (CI->getNumArgOperands() % 2 != 1)
2056 report_fatal_error("number of arguments should be odd");
2057
2058 GlobalClassesTy::member_iterator CurSet;
2059 for (unsigned I = 1; I != CI->getNumArgOperands(); I += 2) {
2060 int64_t Offset;
2061 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
2062 CI->getOperand(I), Offset, M.getDataLayout()));
2063 if (!Base)
2064 report_fatal_error(
2065 "Expected branch funnel operand to be global value");
2066
2067 GlobalTypeMember *GTM = GlobalTypeMembers[Base];
2068 Targets.push_back(GTM);
2069 GlobalClassesTy::member_iterator NewSet =
2070 GlobalClasses.findLeader(GlobalClasses.insert(GTM));
2071 if (I == 1)
2072 CurSet = NewSet;
2073 else
2074 CurSet = GlobalClasses.unionSets(CurSet, NewSet);
2075 }
2076
2077 GlobalClasses.unionSets(
2078 CurSet, GlobalClasses.findLeader(
2079 GlobalClasses.insert(ICallBranchFunnel::create(
2080 Alloc, CI, Targets, ++CurUniqueId))));
2081 }
2082 }
2083
2084 if (ExportSummary
10.1
Field 'ExportSummary' is null
) {
11
Taking false branch
2085 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2086 for (auto &P : TypeIdInfo) {
2087 if (auto *TypeId = dyn_cast<MDString>(P.first))
2088 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
2089 TypeId);
2090 }
2091
2092 for (auto &P : *ExportSummary) {
2093 for (auto &S : P.second.SummaryList) {
2094 if (!ExportSummary->isGlobalValueLive(S.get()))
2095 continue;
2096 if (auto *FS = dyn_cast<FunctionSummary>(S->getBaseObject()))
2097 for (GlobalValue::GUID G : FS->type_tests())
2098 for (Metadata *MD : MetadataByGUID[G])
2099 AddTypeIdUse(MD).IsExported = true;
2100 }
2101 }
2102 }
2103
2104 if (GlobalClasses.empty())
12
Assuming the condition is false
13
Taking false branch
2105 return false;
2106
2107 // Build a list of disjoint sets ordered by their maximum global index for
2108 // determinism.
2109 std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
2110 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
14
Loop condition is false. Execution continues on line 2127
2111 E = GlobalClasses.end();
2112 I != E; ++I) {
2113 if (!I->isLeader())
2114 continue;
2115 ++NumTypeIdDisjointSets;
2116
2117 unsigned MaxUniqueId = 0;
2118 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
2119 MI != GlobalClasses.member_end(); ++MI) {
2120 if (auto *MD = MI->dyn_cast<Metadata *>())
2121 MaxUniqueId = std::max(MaxUniqueId, TypeIdInfo[MD].UniqueId);
2122 else if (auto *BF = MI->dyn_cast<ICallBranchFunnel *>())
2123 MaxUniqueId = std::max(MaxUniqueId, BF->UniqueId);
2124 }
2125 Sets.emplace_back(I, MaxUniqueId);
2126 }
2127 llvm::sort(Sets,
2128 [](const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
2129 const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
2130 return S1.second < S2.second;
2131 });
2132
2133 // For each disjoint set we found...
2134 for (const auto &S : Sets) {
2135 // Build the list of type identifiers in this disjoint set.
2136 std::vector<Metadata *> TypeIds;
2137 std::vector<GlobalTypeMember *> Globals;
2138 std::vector<ICallBranchFunnel *> ICallBranchFunnels;
2139 for (GlobalClassesTy::member_iterator MI =
15
Loop condition is false. Execution continues on line 2152
2140 GlobalClasses.member_begin(S.first);
2141 MI != GlobalClasses.member_end(); ++MI) {
2142 if (MI->is<Metadata *>())
2143 TypeIds.push_back(MI->get<Metadata *>());
2144 else if (MI->is<GlobalTypeMember *>())
2145 Globals.push_back(MI->get<GlobalTypeMember *>());
2146 else
2147 ICallBranchFunnels.push_back(MI->get<ICallBranchFunnel *>());
2148 }
2149
2150 // Order type identifiers by unique ID for determinism. This ordering is
2151 // stable as there is a one-to-one mapping between metadata and unique IDs.
2152 llvm::sort(TypeIds, [&](Metadata *M1, Metadata *M2) {
2153 return TypeIdInfo[M1].UniqueId < TypeIdInfo[M2].UniqueId;
2154 });
2155
2156 // Same for the branch funnels.
2157 llvm::sort(ICallBranchFunnels,
2158 [&](ICallBranchFunnel *F1, ICallBranchFunnel *F2) {
2159 return F1->UniqueId < F2->UniqueId;
2160 });
2161
2162 // Build bitsets for this disjoint set.
2163 buildBitSetsFromDisjointSet(TypeIds, Globals, ICallBranchFunnels);
16
Calling 'LowerTypeTestsModule::buildBitSetsFromDisjointSet'
2164 }
2165
2166 allocateByteArrays();
2167
2168 // Parse alias data to replace stand-in function declarations for aliases
2169 // with an alias to the intended target.
2170 if (ExportSummary) {
2171 if (NamedMDNode *AliasesMD = M.getNamedMetadata("aliases")) {
2172 for (auto AliasMD : AliasesMD->operands()) {
2173 assert(AliasMD->getNumOperands() >= 4)((AliasMD->getNumOperands() >= 4) ? static_cast<void
> (0) : __assert_fail ("AliasMD->getNumOperands() >= 4"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 2173, __PRETTY_FUNCTION__))
;
2174 StringRef AliasName =
2175 cast<MDString>(AliasMD->getOperand(0))->getString();
2176 StringRef Aliasee = cast<MDString>(AliasMD->getOperand(1))->getString();
2177
2178 if (!ExportedFunctions.count(Aliasee) ||
2179 ExportedFunctions[Aliasee].Linkage != CFL_Definition ||
2180 !M.getNamedAlias(Aliasee))
2181 continue;
2182
2183 GlobalValue::VisibilityTypes Visibility =
2184 static_cast<GlobalValue::VisibilityTypes>(
2185 cast<ConstantAsMetadata>(AliasMD->getOperand(2))
2186 ->getValue()
2187 ->getUniqueInteger()
2188 .getZExtValue());
2189 bool Weak =
2190 static_cast<bool>(cast<ConstantAsMetadata>(AliasMD->getOperand(3))
2191 ->getValue()
2192 ->getUniqueInteger()
2193 .getZExtValue());
2194
2195 auto *Alias = GlobalAlias::create("", M.getNamedAlias(Aliasee));
2196 Alias->setVisibility(Visibility);
2197 if (Weak)
2198 Alias->setLinkage(GlobalValue::WeakAnyLinkage);
2199
2200 if (auto *F = M.getFunction(AliasName)) {
2201 Alias->takeName(F);
2202 F->replaceAllUsesWith(Alias);
2203 F->eraseFromParent();
2204 } else {
2205 Alias->setName(AliasName);
2206 }
2207 }
2208 }
2209 }
2210
2211 // Emit .symver directives for exported functions, if they exist.
2212 if (ExportSummary) {
2213 if (NamedMDNode *SymversMD = M.getNamedMetadata("symvers")) {
2214 for (auto Symver : SymversMD->operands()) {
2215 assert(Symver->getNumOperands() >= 2)((Symver->getNumOperands() >= 2) ? static_cast<void>
(0) : __assert_fail ("Symver->getNumOperands() >= 2", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/IPO/LowerTypeTests.cpp"
, 2215, __PRETTY_FUNCTION__))
;
2216 StringRef SymbolName =
2217 cast<MDString>(Symver->getOperand(0))->getString();
2218 StringRef Alias = cast<MDString>(Symver->getOperand(1))->getString();
2219
2220 if (!ExportedFunctions.count(SymbolName))
2221 continue;
2222
2223 M.appendModuleInlineAsm(
2224 (llvm::Twine(".symver ") + SymbolName + ", " + Alias).str());
2225 }
2226 }
2227 }
2228
2229 return true;
2230}
2231
2232PreservedAnalyses LowerTypeTestsPass::run(Module &M,
2233 ModuleAnalysisManager &AM) {
2234 bool Changed =
2235 LowerTypeTestsModule(M, ExportSummary, ImportSummary, DropTypeTests)
2236 .lower();
2237 if (!Changed)
2238 return PreservedAnalyses::all();
2239 return PreservedAnalyses::none();
2240}