Bug Summary

File:llvm/lib/Bitcode/Reader/BitcodeReader.cpp
Warning:line 3545, column 5
Value stored to 'OpNum' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BitcodeReader.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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Bitcode/Reader -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Bitcode/Reader -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-14-033624-32907-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Bitcode/BitcodeReader.h"
10#include "MetadataLoader.h"
11#include "ValueList.h"
12#include "llvm/ADT/APFloat.h"
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Triple.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Bitcode/BitcodeCommon.h"
24#include "llvm/Bitcode/LLVMBitCodes.h"
25#include "llvm/Bitstream/BitstreamReader.h"
26#include "llvm/Config/llvm-config.h"
27#include "llvm/IR/Argument.h"
28#include "llvm/IR/Attributes.h"
29#include "llvm/IR/AutoUpgrade.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CallingConv.h"
32#include "llvm/IR/Comdat.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DebugInfoMetadata.h"
38#include "llvm/IR/DebugLoc.h"
39#include "llvm/IR/DerivedTypes.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/GVMaterializer.h"
42#include "llvm/IR/GlobalAlias.h"
43#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalIndirectSymbol.h"
45#include "llvm/IR/GlobalObject.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/GlobalVariable.h"
48#include "llvm/IR/InlineAsm.h"
49#include "llvm/IR/InstIterator.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Intrinsics.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/ModuleSummaryIndex.h"
58#include "llvm/IR/Operator.h"
59#include "llvm/IR/Type.h"
60#include "llvm/IR/Value.h"
61#include "llvm/IR/Verifier.h"
62#include "llvm/Support/AtomicOrdering.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/Error.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/ErrorOr.h"
70#include "llvm/Support/ManagedStatic.h"
71#include "llvm/Support/MathExtras.h"
72#include "llvm/Support/MemoryBuffer.h"
73#include "llvm/Support/raw_ostream.h"
74#include <algorithm>
75#include <cassert>
76#include <cstddef>
77#include <cstdint>
78#include <deque>
79#include <map>
80#include <memory>
81#include <set>
82#include <string>
83#include <system_error>
84#include <tuple>
85#include <utility>
86#include <vector>
87
88using namespace llvm;
89
90static cl::opt<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden,
92 cl::desc(
93 "Print the global id for each value when reading the module summary"));
94
95namespace {
96
97enum {
98 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99};
100
101} // end anonymous namespace
102
103static Error error(const Twine &Message) {
104 return make_error<StringError>(
105 Message, make_error_code(BitcodeError::CorruptedBitcode));
106}
107
108static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
109 if (!Stream.canSkipToPos(4))
110 return createStringError(std::errc::illegal_byte_sequence,
111 "file too small to contain bitcode header");
112 for (unsigned C : {'B', 'C'})
113 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
114 if (Res.get() != C)
115 return createStringError(std::errc::illegal_byte_sequence,
116 "file doesn't start with bitcode header");
117 } else
118 return Res.takeError();
119 for (unsigned C : {0x0, 0xC, 0xE, 0xD})
120 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
121 if (Res.get() != C)
122 return createStringError(std::errc::illegal_byte_sequence,
123 "file doesn't start with bitcode header");
124 } else
125 return Res.takeError();
126 return Error::success();
127}
128
129static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
130 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
131 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
132
133 if (Buffer.getBufferSize() & 3)
134 return error("Invalid bitcode signature");
135
136 // If we have a wrapper header, parse it and ignore the non-bc file contents.
137 // The magic number is 0x0B17C0DE stored in little endian.
138 if (isBitcodeWrapper(BufPtr, BufEnd))
139 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
140 return error("Invalid bitcode wrapper header");
141
142 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
143 if (Error Err = hasInvalidBitcodeHeader(Stream))
144 return std::move(Err);
145
146 return std::move(Stream);
147}
148
149/// Convert a string from a record into an std::string, return true on failure.
150template <typename StrTy>
151static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
152 StrTy &Result) {
153 if (Idx > Record.size())
154 return true;
155
156 Result.append(Record.begin() + Idx, Record.end());
157 return false;
158}
159
160// Strip all the TBAA attachment for the module.
161static void stripTBAA(Module *M) {
162 for (auto &F : *M) {
163 if (F.isMaterializable())
164 continue;
165 for (auto &I : instructions(F))
166 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
167 }
168}
169
170/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
171/// "epoch" encoded in the bitcode, and return the producer name if any.
172static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
173 if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
174 return std::move(Err);
175
176 // Read all the records.
177 SmallVector<uint64_t, 64> Record;
178
179 std::string ProducerIdentification;
180
181 while (true) {
182 BitstreamEntry Entry;
183 if (Expected<BitstreamEntry> Res = Stream.advance())
184 Entry = Res.get();
185 else
186 return Res.takeError();
187
188 switch (Entry.Kind) {
189 default:
190 case BitstreamEntry::Error:
191 return error("Malformed block");
192 case BitstreamEntry::EndBlock:
193 return ProducerIdentification;
194 case BitstreamEntry::Record:
195 // The interesting case.
196 break;
197 }
198
199 // Read a record.
200 Record.clear();
201 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
202 if (!MaybeBitCode)
203 return MaybeBitCode.takeError();
204 switch (MaybeBitCode.get()) {
205 default: // Default behavior: reject
206 return error("Invalid value");
207 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
208 convertToString(Record, 0, ProducerIdentification);
209 break;
210 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
211 unsigned epoch = (unsigned)Record[0];
212 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
213 return error(
214 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
215 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
216 }
217 }
218 }
219 }
220}
221
222static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
223 // We expect a number of well-defined blocks, though we don't necessarily
224 // need to understand them all.
225 while (true) {
226 if (Stream.AtEndOfStream())
227 return "";
228
229 BitstreamEntry Entry;
230 if (Expected<BitstreamEntry> Res = Stream.advance())
231 Entry = std::move(Res.get());
232 else
233 return Res.takeError();
234
235 switch (Entry.Kind) {
236 case BitstreamEntry::EndBlock:
237 case BitstreamEntry::Error:
238 return error("Malformed block");
239
240 case BitstreamEntry::SubBlock:
241 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
242 return readIdentificationBlock(Stream);
243
244 // Ignore other sub-blocks.
245 if (Error Err = Stream.SkipBlock())
246 return std::move(Err);
247 continue;
248 case BitstreamEntry::Record:
249 if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
250 continue;
251 else
252 return Skipped.takeError();
253 }
254 }
255}
256
257static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
258 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
259 return std::move(Err);
260
261 SmallVector<uint64_t, 64> Record;
262 // Read all the records for this module.
263
264 while (true) {
265 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
266 if (!MaybeEntry)
267 return MaybeEntry.takeError();
268 BitstreamEntry Entry = MaybeEntry.get();
269
270 switch (Entry.Kind) {
271 case BitstreamEntry::SubBlock: // Handled for us already.
272 case BitstreamEntry::Error:
273 return error("Malformed block");
274 case BitstreamEntry::EndBlock:
275 return false;
276 case BitstreamEntry::Record:
277 // The interesting case.
278 break;
279 }
280
281 // Read a record.
282 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
283 if (!MaybeRecord)
284 return MaybeRecord.takeError();
285 switch (MaybeRecord.get()) {
286 default:
287 break; // Default behavior, ignore unknown content.
288 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
289 std::string S;
290 if (convertToString(Record, 0, S))
291 return error("Invalid record");
292 // Check for the i386 and other (x86_64, ARM) conventions
293 if (S.find("__DATA,__objc_catlist") != std::string::npos ||
294 S.find("__OBJC,__category") != std::string::npos)
295 return true;
296 break;
297 }
298 }
299 Record.clear();
300 }
301 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 301)
;
302}
303
304static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
305 // We expect a number of well-defined blocks, though we don't necessarily
306 // need to understand them all.
307 while (true) {
308 BitstreamEntry Entry;
309 if (Expected<BitstreamEntry> Res = Stream.advance())
310 Entry = std::move(Res.get());
311 else
312 return Res.takeError();
313
314 switch (Entry.Kind) {
315 case BitstreamEntry::Error:
316 return error("Malformed block");
317 case BitstreamEntry::EndBlock:
318 return false;
319
320 case BitstreamEntry::SubBlock:
321 if (Entry.ID == bitc::MODULE_BLOCK_ID)
322 return hasObjCCategoryInModule(Stream);
323
324 // Ignore other sub-blocks.
325 if (Error Err = Stream.SkipBlock())
326 return std::move(Err);
327 continue;
328
329 case BitstreamEntry::Record:
330 if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
331 continue;
332 else
333 return Skipped.takeError();
334 }
335 }
336}
337
338static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
339 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
340 return std::move(Err);
341
342 SmallVector<uint64_t, 64> Record;
343
344 std::string Triple;
345
346 // Read all the records for this module.
347 while (true) {
348 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
349 if (!MaybeEntry)
350 return MaybeEntry.takeError();
351 BitstreamEntry Entry = MaybeEntry.get();
352
353 switch (Entry.Kind) {
354 case BitstreamEntry::SubBlock: // Handled for us already.
355 case BitstreamEntry::Error:
356 return error("Malformed block");
357 case BitstreamEntry::EndBlock:
358 return Triple;
359 case BitstreamEntry::Record:
360 // The interesting case.
361 break;
362 }
363
364 // Read a record.
365 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
366 if (!MaybeRecord)
367 return MaybeRecord.takeError();
368 switch (MaybeRecord.get()) {
369 default: break; // Default behavior, ignore unknown content.
370 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
371 std::string S;
372 if (convertToString(Record, 0, S))
373 return error("Invalid record");
374 Triple = S;
375 break;
376 }
377 }
378 Record.clear();
379 }
380 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 380)
;
381}
382
383static Expected<std::string> readTriple(BitstreamCursor &Stream) {
384 // We expect a number of well-defined blocks, though we don't necessarily
385 // need to understand them all.
386 while (true) {
387 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
388 if (!MaybeEntry)
389 return MaybeEntry.takeError();
390 BitstreamEntry Entry = MaybeEntry.get();
391
392 switch (Entry.Kind) {
393 case BitstreamEntry::Error:
394 return error("Malformed block");
395 case BitstreamEntry::EndBlock:
396 return "";
397
398 case BitstreamEntry::SubBlock:
399 if (Entry.ID == bitc::MODULE_BLOCK_ID)
400 return readModuleTriple(Stream);
401
402 // Ignore other sub-blocks.
403 if (Error Err = Stream.SkipBlock())
404 return std::move(Err);
405 continue;
406
407 case BitstreamEntry::Record:
408 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
409 continue;
410 else
411 return Skipped.takeError();
412 }
413 }
414}
415
416namespace {
417
418class BitcodeReaderBase {
419protected:
420 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
421 : Stream(std::move(Stream)), Strtab(Strtab) {
422 this->Stream.setBlockInfo(&BlockInfo);
423 }
424
425 BitstreamBlockInfo BlockInfo;
426 BitstreamCursor Stream;
427 StringRef Strtab;
428
429 /// In version 2 of the bitcode we store names of global values and comdats in
430 /// a string table rather than in the VST.
431 bool UseStrtab = false;
432
433 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
434
435 /// If this module uses a string table, pop the reference to the string table
436 /// and return the referenced string and the rest of the record. Otherwise
437 /// just return the record itself.
438 std::pair<StringRef, ArrayRef<uint64_t>>
439 readNameFromStrtab(ArrayRef<uint64_t> Record);
440
441 bool readBlockInfo();
442
443 // Contains an arbitrary and optional string identifying the bitcode producer
444 std::string ProducerIdentification;
445
446 Error error(const Twine &Message);
447};
448
449} // end anonymous namespace
450
451Error BitcodeReaderBase::error(const Twine &Message) {
452 std::string FullMsg = Message.str();
453 if (!ProducerIdentification.empty())
454 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
455 LLVM_VERSION_STRING"13.0.0" "')";
456 return ::error(FullMsg);
457}
458
459Expected<unsigned>
460BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
461 if (Record.empty())
462 return error("Invalid record");
463 unsigned ModuleVersion = Record[0];
464 if (ModuleVersion > 2)
465 return error("Invalid value");
466 UseStrtab = ModuleVersion >= 2;
467 return ModuleVersion;
468}
469
470std::pair<StringRef, ArrayRef<uint64_t>>
471BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
472 if (!UseStrtab)
473 return {"", Record};
474 // Invalid reference. Let the caller complain about the record being empty.
475 if (Record[0] + Record[1] > Strtab.size())
476 return {"", {}};
477 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
478}
479
480namespace {
481
482class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
483 LLVMContext &Context;
484 Module *TheModule = nullptr;
485 // Next offset to start scanning for lazy parsing of function bodies.
486 uint64_t NextUnreadBit = 0;
487 // Last function offset found in the VST.
488 uint64_t LastFunctionBlockBit = 0;
489 bool SeenValueSymbolTable = false;
490 uint64_t VSTOffset = 0;
491
492 std::vector<std::string> SectionTable;
493 std::vector<std::string> GCTable;
494
495 std::vector<Type*> TypeList;
496 DenseMap<Function *, FunctionType *> FunctionTypes;
497 BitcodeReaderValueList ValueList;
498 Optional<MetadataLoader> MDLoader;
499 std::vector<Comdat *> ComdatList;
500 SmallVector<Instruction *, 64> InstructionList;
501
502 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
503 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
504 std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
505 std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
506 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
507
508 /// The set of attributes by index. Index zero in the file is for null, and
509 /// is thus not represented here. As such all indices are off by one.
510 std::vector<AttributeList> MAttributes;
511
512 /// The set of attribute groups.
513 std::map<unsigned, AttributeList> MAttributeGroups;
514
515 /// While parsing a function body, this is a list of the basic blocks for the
516 /// function.
517 std::vector<BasicBlock*> FunctionBBs;
518
519 // When reading the module header, this list is populated with functions that
520 // have bodies later in the file.
521 std::vector<Function*> FunctionsWithBodies;
522
523 // When intrinsic functions are encountered which require upgrading they are
524 // stored here with their replacement function.
525 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
526 UpdatedIntrinsicMap UpgradedIntrinsics;
527 // Intrinsics which were remangled because of types rename
528 UpdatedIntrinsicMap RemangledIntrinsics;
529
530 // Several operations happen after the module header has been read, but
531 // before function bodies are processed. This keeps track of whether
532 // we've done this yet.
533 bool SeenFirstFunctionBody = false;
534
535 /// When function bodies are initially scanned, this map contains info about
536 /// where to find deferred function body in the stream.
537 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
538
539 /// When Metadata block is initially scanned when parsing the module, we may
540 /// choose to defer parsing of the metadata. This vector contains info about
541 /// which Metadata blocks are deferred.
542 std::vector<uint64_t> DeferredMetadataInfo;
543
544 /// These are basic blocks forward-referenced by block addresses. They are
545 /// inserted lazily into functions when they're loaded. The basic block ID is
546 /// its index into the vector.
547 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
548 std::deque<Function *> BasicBlockFwdRefQueue;
549
550 /// Indicates that we are using a new encoding for instruction operands where
551 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
552 /// instruction number, for a more compact encoding. Some instruction
553 /// operands are not relative to the instruction ID: basic block numbers, and
554 /// types. Once the old style function blocks have been phased out, we would
555 /// not need this flag.
556 bool UseRelativeIDs = false;
557
558 /// True if all functions will be materialized, negating the need to process
559 /// (e.g.) blockaddress forward references.
560 bool WillMaterializeAllForwardRefs = false;
561
562 bool StripDebugInfo = false;
563 TBAAVerifier TBAAVerifyHelper;
564
565 std::vector<std::string> BundleTags;
566 SmallVector<SyncScope::ID, 8> SSIDs;
567
568public:
569 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
570 StringRef ProducerIdentification, LLVMContext &Context);
571
572 Error materializeForwardReferencedFunctions();
573
574 Error materialize(GlobalValue *GV) override;
575 Error materializeModule() override;
576 std::vector<StructType *> getIdentifiedStructTypes() const override;
577
578 /// Main interface to parsing a bitcode buffer.
579 /// \returns true if an error occurred.
580 Error parseBitcodeInto(
581 Module *M, bool ShouldLazyLoadMetadata = false, bool IsImporting = false,
582 DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
583
584 static uint64_t decodeSignRotatedValue(uint64_t V);
585
586 /// Materialize any deferred Metadata block.
587 Error materializeMetadata() override;
588
589 void setStripDebugInfo() override;
590
591private:
592 std::vector<StructType *> IdentifiedStructTypes;
593 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
594 StructType *createIdentifiedStructType(LLVMContext &Context);
595
596 /// Map all pointer types within \param Ty to the opaque pointer
597 /// type in the same address space if opaque pointers are being
598 /// used, otherwise nop. This converts a bitcode-reader internal
599 /// type into one suitable for use in a Value.
600 Type *flattenPointerTypes(Type *Ty) {
601 return Ty;
602 }
603
604 /// Given a fully structured pointer type (i.e. not opaque), return
605 /// the flattened form of its element, suitable for use in a Value.
606 Type *getPointerElementFlatType(Type *Ty) {
607 return flattenPointerTypes(cast<PointerType>(Ty)->getElementType());
608 }
609
610 /// Given a fully structured pointer type, get its element type in
611 /// both fully structured form, and flattened form suitable for use
612 /// in a Value.
613 std::pair<Type *, Type *> getPointerElementTypes(Type *FullTy) {
614 Type *ElTy = cast<PointerType>(FullTy)->getElementType();
615 return std::make_pair(ElTy, flattenPointerTypes(ElTy));
616 }
617
618 /// Return the flattened type (suitable for use in a Value)
619 /// specified by the given \param ID .
620 Type *getTypeByID(unsigned ID) {
621 return flattenPointerTypes(getFullyStructuredTypeByID(ID));
622 }
623
624 /// Return the fully structured (bitcode-reader internal) type
625 /// corresponding to the given \param ID .
626 Type *getFullyStructuredTypeByID(unsigned ID);
627
628 Value *getFnValueByID(unsigned ID, Type *Ty, Type **FullTy = nullptr) {
629 if (Ty && Ty->isMetadataTy())
630 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
631 return ValueList.getValueFwdRef(ID, Ty, FullTy);
632 }
633
634 Metadata *getFnMetadataByID(unsigned ID) {
635 return MDLoader->getMetadataFwdRefOrLoad(ID);
636 }
637
638 BasicBlock *getBasicBlock(unsigned ID) const {
639 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
640 return FunctionBBs[ID];
641 }
642
643 AttributeList getAttributes(unsigned i) const {
644 if (i-1 < MAttributes.size())
645 return MAttributes[i-1];
646 return AttributeList();
647 }
648
649 /// Read a value/type pair out of the specified record from slot 'Slot'.
650 /// Increment Slot past the number of slots used in the record. Return true on
651 /// failure.
652 bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
653 unsigned InstNum, Value *&ResVal,
654 Type **FullTy = nullptr) {
655 if (Slot == Record.size()) return true;
656 unsigned ValNo = (unsigned)Record[Slot++];
657 // Adjust the ValNo, if it was encoded relative to the InstNum.
658 if (UseRelativeIDs)
659 ValNo = InstNum - ValNo;
660 if (ValNo < InstNum) {
661 // If this is not a forward reference, just return the value we already
662 // have.
663 ResVal = getFnValueByID(ValNo, nullptr, FullTy);
664 return ResVal == nullptr;
665 }
666 if (Slot == Record.size())
667 return true;
668
669 unsigned TypeNo = (unsigned)Record[Slot++];
670 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
671 if (FullTy)
672 *FullTy = getFullyStructuredTypeByID(TypeNo);
673 return ResVal == nullptr;
674 }
675
676 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
677 /// past the number of slots used by the value in the record. Return true if
678 /// there is an error.
679 bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
680 unsigned InstNum, Type *Ty, Value *&ResVal) {
681 if (getValue(Record, Slot, InstNum, Ty, ResVal))
682 return true;
683 // All values currently take a single record slot.
684 ++Slot;
685 return false;
686 }
687
688 /// Like popValue, but does not increment the Slot number.
689 bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
690 unsigned InstNum, Type *Ty, Value *&ResVal) {
691 ResVal = getValue(Record, Slot, InstNum, Ty);
692 return ResVal == nullptr;
693 }
694
695 /// Version of getValue that returns ResVal directly, or 0 if there is an
696 /// error.
697 Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
698 unsigned InstNum, Type *Ty) {
699 if (Slot == Record.size()) return nullptr;
700 unsigned ValNo = (unsigned)Record[Slot];
701 // Adjust the ValNo, if it was encoded relative to the InstNum.
702 if (UseRelativeIDs)
703 ValNo = InstNum - ValNo;
704 return getFnValueByID(ValNo, Ty);
705 }
706
707 /// Like getValue, but decodes signed VBRs.
708 Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
709 unsigned InstNum, Type *Ty) {
710 if (Slot == Record.size()) return nullptr;
711 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
712 // Adjust the ValNo, if it was encoded relative to the InstNum.
713 if (UseRelativeIDs)
714 ValNo = InstNum - ValNo;
715 return getFnValueByID(ValNo, Ty);
716 }
717
718 /// Upgrades old-style typeless byval or sret attributes by adding the
719 /// corresponding argument's pointee type.
720 void propagateByValSRetTypes(CallBase *CB, ArrayRef<Type *> ArgsFullTys);
721
722 /// Converts alignment exponent (i.e. power of two (or zero)) to the
723 /// corresponding alignment to use. If alignment is too large, returns
724 /// a corresponding error code.
725 Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
726 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
727 Error parseModule(
728 uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
729 DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
730
731 Error parseComdatRecord(ArrayRef<uint64_t> Record);
732 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
733 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
734 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
735 ArrayRef<uint64_t> Record);
736
737 Error parseAttributeBlock();
738 Error parseAttributeGroupBlock();
739 Error parseTypeTable();
740 Error parseTypeTableBody();
741 Error parseOperandBundleTags();
742 Error parseSyncScopeNames();
743
744 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
745 unsigned NameIndex, Triple &TT);
746 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
747 ArrayRef<uint64_t> Record);
748 Error parseValueSymbolTable(uint64_t Offset = 0);
749 Error parseGlobalValueSymbolTable();
750 Error parseConstants();
751 Error rememberAndSkipFunctionBodies();
752 Error rememberAndSkipFunctionBody();
753 /// Save the positions of the Metadata blocks and skip parsing the blocks.
754 Error rememberAndSkipMetadata();
755 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
756 Error parseFunctionBody(Function *F);
757 Error globalCleanup();
758 Error resolveGlobalAndIndirectSymbolInits();
759 Error parseUseLists();
760 Error findFunctionInStream(
761 Function *F,
762 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
763
764 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
765};
766
767/// Class to manage reading and parsing function summary index bitcode
768/// files/sections.
769class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
770 /// The module index built during parsing.
771 ModuleSummaryIndex &TheIndex;
772
773 /// Indicates whether we have encountered a global value summary section
774 /// yet during parsing.
775 bool SeenGlobalValSummary = false;
776
777 /// Indicates whether we have already parsed the VST, used for error checking.
778 bool SeenValueSymbolTable = false;
779
780 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
781 /// Used to enable on-demand parsing of the VST.
782 uint64_t VSTOffset = 0;
783
784 // Map to save ValueId to ValueInfo association that was recorded in the
785 // ValueSymbolTable. It is used after the VST is parsed to convert
786 // call graph edges read from the function summary from referencing
787 // callees by their ValueId to using the ValueInfo instead, which is how
788 // they are recorded in the summary index being built.
789 // We save a GUID which refers to the same global as the ValueInfo, but
790 // ignoring the linkage, i.e. for values other than local linkage they are
791 // identical.
792 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
793 ValueIdToValueInfoMap;
794
795 /// Map populated during module path string table parsing, from the
796 /// module ID to a string reference owned by the index's module
797 /// path string table, used to correlate with combined index
798 /// summary records.
799 DenseMap<uint64_t, StringRef> ModuleIdMap;
800
801 /// Original source file name recorded in a bitcode record.
802 std::string SourceFileName;
803
804 /// The string identifier given to this module by the client, normally the
805 /// path to the bitcode file.
806 StringRef ModulePath;
807
808 /// For per-module summary indexes, the unique numerical identifier given to
809 /// this module by the client.
810 unsigned ModuleId;
811
812public:
813 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
814 ModuleSummaryIndex &TheIndex,
815 StringRef ModulePath, unsigned ModuleId);
816
817 Error parseModule();
818
819private:
820 void setValueGUID(uint64_t ValueID, StringRef ValueName,
821 GlobalValue::LinkageTypes Linkage,
822 StringRef SourceFileName);
823 Error parseValueSymbolTable(
824 uint64_t Offset,
825 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
826 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
827 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
828 bool IsOldProfileFormat,
829 bool HasProfile,
830 bool HasRelBF);
831 Error parseEntireSummary(unsigned ID);
832 Error parseModuleStringTable();
833 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
834 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
835 TypeIdCompatibleVtableInfo &TypeId);
836 std::vector<FunctionSummary::ParamAccess>
837 parseParamAccesses(ArrayRef<uint64_t> Record);
838
839 std::pair<ValueInfo, GlobalValue::GUID>
840 getValueInfoFromValueId(unsigned ValueId);
841
842 void addThisModule();
843 ModuleSummaryIndex::ModuleInfo *getThisModule();
844};
845
846} // end anonymous namespace
847
848std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
849 Error Err) {
850 if (Err) {
851 std::error_code EC;
852 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
853 EC = EIB.convertToErrorCode();
854 Ctx.emitError(EIB.message());
855 });
856 return EC;
857 }
858 return std::error_code();
859}
860
861BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
862 StringRef ProducerIdentification,
863 LLVMContext &Context)
864 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
865 ValueList(Context, Stream.SizeInBytes()) {
866 this->ProducerIdentification = std::string(ProducerIdentification);
867}
868
869Error BitcodeReader::materializeForwardReferencedFunctions() {
870 if (WillMaterializeAllForwardRefs)
871 return Error::success();
872
873 // Prevent recursion.
874 WillMaterializeAllForwardRefs = true;
875
876 while (!BasicBlockFwdRefQueue.empty()) {
877 Function *F = BasicBlockFwdRefQueue.front();
878 BasicBlockFwdRefQueue.pop_front();
879 assert(F && "Expected valid function")(static_cast <bool> (F && "Expected valid function"
) ? void (0) : __assert_fail ("F && \"Expected valid function\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 879, __extension__ __PRETTY_FUNCTION__))
;
880 if (!BasicBlockFwdRefs.count(F))
881 // Already materialized.
882 continue;
883
884 // Check for a function that isn't materializable to prevent an infinite
885 // loop. When parsing a blockaddress stored in a global variable, there
886 // isn't a trivial way to check if a function will have a body without a
887 // linear search through FunctionsWithBodies, so just check it here.
888 if (!F->isMaterializable())
889 return error("Never resolved function from blockaddress");
890
891 // Try to materialize F.
892 if (Error Err = materialize(F))
893 return Err;
894 }
895 assert(BasicBlockFwdRefs.empty() && "Function missing from queue")(static_cast <bool> (BasicBlockFwdRefs.empty() &&
"Function missing from queue") ? void (0) : __assert_fail ("BasicBlockFwdRefs.empty() && \"Function missing from queue\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 895, __extension__ __PRETTY_FUNCTION__))
;
896
897 // Reset state.
898 WillMaterializeAllForwardRefs = false;
899 return Error::success();
900}
901
902//===----------------------------------------------------------------------===//
903// Helper functions to implement forward reference resolution, etc.
904//===----------------------------------------------------------------------===//
905
906static bool hasImplicitComdat(size_t Val) {
907 switch (Val) {
908 default:
909 return false;
910 case 1: // Old WeakAnyLinkage
911 case 4: // Old LinkOnceAnyLinkage
912 case 10: // Old WeakODRLinkage
913 case 11: // Old LinkOnceODRLinkage
914 return true;
915 }
916}
917
918static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
919 switch (Val) {
920 default: // Map unknown/new linkages to external
921 case 0:
922 return GlobalValue::ExternalLinkage;
923 case 2:
924 return GlobalValue::AppendingLinkage;
925 case 3:
926 return GlobalValue::InternalLinkage;
927 case 5:
928 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
929 case 6:
930 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
931 case 7:
932 return GlobalValue::ExternalWeakLinkage;
933 case 8:
934 return GlobalValue::CommonLinkage;
935 case 9:
936 return GlobalValue::PrivateLinkage;
937 case 12:
938 return GlobalValue::AvailableExternallyLinkage;
939 case 13:
940 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
941 case 14:
942 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
943 case 15:
944 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
945 case 1: // Old value with implicit comdat.
946 case 16:
947 return GlobalValue::WeakAnyLinkage;
948 case 10: // Old value with implicit comdat.
949 case 17:
950 return GlobalValue::WeakODRLinkage;
951 case 4: // Old value with implicit comdat.
952 case 18:
953 return GlobalValue::LinkOnceAnyLinkage;
954 case 11: // Old value with implicit comdat.
955 case 19:
956 return GlobalValue::LinkOnceODRLinkage;
957 }
958}
959
960static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
961 FunctionSummary::FFlags Flags;
962 Flags.ReadNone = RawFlags & 0x1;
963 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
964 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
965 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
966 Flags.NoInline = (RawFlags >> 4) & 0x1;
967 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
968 return Flags;
969}
970
971// Decode the flags for GlobalValue in the summary. The bits for each attribute:
972//
973// linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
974// visibility: [8, 10).
975static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
976 uint64_t Version) {
977 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
978 // like getDecodedLinkage() above. Any future change to the linkage enum and
979 // to getDecodedLinkage() will need to be taken into account here as above.
980 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
981 auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
982 RawFlags = RawFlags >> 4;
983 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
984 // The Live flag wasn't introduced until version 3. For dead stripping
985 // to work correctly on earlier versions, we must conservatively treat all
986 // values as live.
987 bool Live = (RawFlags & 0x2) || Version < 3;
988 bool Local = (RawFlags & 0x4);
989 bool AutoHide = (RawFlags & 0x8);
990
991 return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
992 Live, Local, AutoHide);
993}
994
995// Decode the flags for GlobalVariable in the summary
996static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
997 return GlobalVarSummary::GVarFlags(
998 (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
999 (RawFlags & 0x4) ? true : false,
1000 (GlobalObject::VCallVisibility)(RawFlags >> 3));
1001}
1002
1003static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
1004 switch (Val) {
1005 default: // Map unknown visibilities to default.
1006 case 0: return GlobalValue::DefaultVisibility;
1007 case 1: return GlobalValue::HiddenVisibility;
1008 case 2: return GlobalValue::ProtectedVisibility;
1009 }
1010}
1011
1012static GlobalValue::DLLStorageClassTypes
1013getDecodedDLLStorageClass(unsigned Val) {
1014 switch (Val) {
1015 default: // Map unknown values to default.
1016 case 0: return GlobalValue::DefaultStorageClass;
1017 case 1: return GlobalValue::DLLImportStorageClass;
1018 case 2: return GlobalValue::DLLExportStorageClass;
1019 }
1020}
1021
1022static bool getDecodedDSOLocal(unsigned Val) {
1023 switch(Val) {
1024 default: // Map unknown values to preemptable.
1025 case 0: return false;
1026 case 1: return true;
1027 }
1028}
1029
1030static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1031 switch (Val) {
1032 case 0: return GlobalVariable::NotThreadLocal;
1033 default: // Map unknown non-zero value to general dynamic.
1034 case 1: return GlobalVariable::GeneralDynamicTLSModel;
1035 case 2: return GlobalVariable::LocalDynamicTLSModel;
1036 case 3: return GlobalVariable::InitialExecTLSModel;
1037 case 4: return GlobalVariable::LocalExecTLSModel;
1038 }
1039}
1040
1041static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1042 switch (Val) {
1043 default: // Map unknown to UnnamedAddr::None.
1044 case 0: return GlobalVariable::UnnamedAddr::None;
1045 case 1: return GlobalVariable::UnnamedAddr::Global;
1046 case 2: return GlobalVariable::UnnamedAddr::Local;
1047 }
1048}
1049
1050static int getDecodedCastOpcode(unsigned Val) {
1051 switch (Val) {
1052 default: return -1;
1053 case bitc::CAST_TRUNC : return Instruction::Trunc;
1054 case bitc::CAST_ZEXT : return Instruction::ZExt;
1055 case bitc::CAST_SEXT : return Instruction::SExt;
1056 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
1057 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
1058 case bitc::CAST_UITOFP : return Instruction::UIToFP;
1059 case bitc::CAST_SITOFP : return Instruction::SIToFP;
1060 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1061 case bitc::CAST_FPEXT : return Instruction::FPExt;
1062 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1063 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1064 case bitc::CAST_BITCAST : return Instruction::BitCast;
1065 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1066 }
1067}
1068
1069static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1070 bool IsFP = Ty->isFPOrFPVectorTy();
1071 // UnOps are only valid for int/fp or vector of int/fp types
1072 if (!IsFP && !Ty->isIntOrIntVectorTy())
1073 return -1;
1074
1075 switch (Val) {
1076 default:
1077 return -1;
1078 case bitc::UNOP_FNEG:
1079 return IsFP ? Instruction::FNeg : -1;
1080 }
1081}
1082
1083static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1084 bool IsFP = Ty->isFPOrFPVectorTy();
1085 // BinOps are only valid for int/fp or vector of int/fp types
1086 if (!IsFP && !Ty->isIntOrIntVectorTy())
1087 return -1;
1088
1089 switch (Val) {
1090 default:
1091 return -1;
1092 case bitc::BINOP_ADD:
1093 return IsFP ? Instruction::FAdd : Instruction::Add;
1094 case bitc::BINOP_SUB:
1095 return IsFP ? Instruction::FSub : Instruction::Sub;
1096 case bitc::BINOP_MUL:
1097 return IsFP ? Instruction::FMul : Instruction::Mul;
1098 case bitc::BINOP_UDIV:
1099 return IsFP ? -1 : Instruction::UDiv;
1100 case bitc::BINOP_SDIV:
1101 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1102 case bitc::BINOP_UREM:
1103 return IsFP ? -1 : Instruction::URem;
1104 case bitc::BINOP_SREM:
1105 return IsFP ? Instruction::FRem : Instruction::SRem;
1106 case bitc::BINOP_SHL:
1107 return IsFP ? -1 : Instruction::Shl;
1108 case bitc::BINOP_LSHR:
1109 return IsFP ? -1 : Instruction::LShr;
1110 case bitc::BINOP_ASHR:
1111 return IsFP ? -1 : Instruction::AShr;
1112 case bitc::BINOP_AND:
1113 return IsFP ? -1 : Instruction::And;
1114 case bitc::BINOP_OR:
1115 return IsFP ? -1 : Instruction::Or;
1116 case bitc::BINOP_XOR:
1117 return IsFP ? -1 : Instruction::Xor;
1118 }
1119}
1120
1121static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1122 switch (Val) {
1123 default: return AtomicRMWInst::BAD_BINOP;
1124 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1125 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1126 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1127 case bitc::RMW_AND: return AtomicRMWInst::And;
1128 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1129 case bitc::RMW_OR: return AtomicRMWInst::Or;
1130 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1131 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1132 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1133 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1134 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1135 case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1136 case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1137 }
1138}
1139
1140static AtomicOrdering getDecodedOrdering(unsigned Val) {
1141 switch (Val) {
1142 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1143 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1144 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1145 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1146 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1147 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1148 default: // Map unknown orderings to sequentially-consistent.
1149 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1150 }
1151}
1152
1153static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1154 switch (Val) {
1155 default: // Map unknown selection kinds to any.
1156 case bitc::COMDAT_SELECTION_KIND_ANY:
1157 return Comdat::Any;
1158 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1159 return Comdat::ExactMatch;
1160 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1161 return Comdat::Largest;
1162 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1163 return Comdat::NoDuplicates;
1164 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1165 return Comdat::SameSize;
1166 }
1167}
1168
1169static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1170 FastMathFlags FMF;
1171 if (0 != (Val & bitc::UnsafeAlgebra))
1172 FMF.setFast();
1173 if (0 != (Val & bitc::AllowReassoc))
1174 FMF.setAllowReassoc();
1175 if (0 != (Val & bitc::NoNaNs))
1176 FMF.setNoNaNs();
1177 if (0 != (Val & bitc::NoInfs))
1178 FMF.setNoInfs();
1179 if (0 != (Val & bitc::NoSignedZeros))
1180 FMF.setNoSignedZeros();
1181 if (0 != (Val & bitc::AllowReciprocal))
1182 FMF.setAllowReciprocal();
1183 if (0 != (Val & bitc::AllowContract))
1184 FMF.setAllowContract(true);
1185 if (0 != (Val & bitc::ApproxFunc))
1186 FMF.setApproxFunc();
1187 return FMF;
1188}
1189
1190static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1191 switch (Val) {
1192 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1193 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1194 }
1195}
1196
1197Type *BitcodeReader::getFullyStructuredTypeByID(unsigned ID) {
1198 // The type table size is always specified correctly.
1199 if (ID >= TypeList.size())
1200 return nullptr;
1201
1202 if (Type *Ty = TypeList[ID])
1203 return Ty;
1204
1205 // If we have a forward reference, the only possible case is when it is to a
1206 // named struct. Just create a placeholder for now.
1207 return TypeList[ID] = createIdentifiedStructType(Context);
1208}
1209
1210StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1211 StringRef Name) {
1212 auto *Ret = StructType::create(Context, Name);
1213 IdentifiedStructTypes.push_back(Ret);
1214 return Ret;
1215}
1216
1217StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1218 auto *Ret = StructType::create(Context);
1219 IdentifiedStructTypes.push_back(Ret);
1220 return Ret;
1221}
1222
1223//===----------------------------------------------------------------------===//
1224// Functions for parsing blocks from the bitcode file
1225//===----------------------------------------------------------------------===//
1226
1227static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1228 switch (Val) {
1229 case Attribute::EndAttrKinds:
1230 case Attribute::EmptyKey:
1231 case Attribute::TombstoneKey:
1232 llvm_unreachable("Synthetic enumerators which should never get here")::llvm::llvm_unreachable_internal("Synthetic enumerators which should never get here"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1232)
;
1233
1234 case Attribute::None: return 0;
1235 case Attribute::ZExt: return 1 << 0;
1236 case Attribute::SExt: return 1 << 1;
1237 case Attribute::NoReturn: return 1 << 2;
1238 case Attribute::InReg: return 1 << 3;
1239 case Attribute::StructRet: return 1 << 4;
1240 case Attribute::NoUnwind: return 1 << 5;
1241 case Attribute::NoAlias: return 1 << 6;
1242 case Attribute::ByVal: return 1 << 7;
1243 case Attribute::Nest: return 1 << 8;
1244 case Attribute::ReadNone: return 1 << 9;
1245 case Attribute::ReadOnly: return 1 << 10;
1246 case Attribute::NoInline: return 1 << 11;
1247 case Attribute::AlwaysInline: return 1 << 12;
1248 case Attribute::OptimizeForSize: return 1 << 13;
1249 case Attribute::StackProtect: return 1 << 14;
1250 case Attribute::StackProtectReq: return 1 << 15;
1251 case Attribute::Alignment: return 31 << 16;
1252 case Attribute::NoCapture: return 1 << 21;
1253 case Attribute::NoRedZone: return 1 << 22;
1254 case Attribute::NoImplicitFloat: return 1 << 23;
1255 case Attribute::Naked: return 1 << 24;
1256 case Attribute::InlineHint: return 1 << 25;
1257 case Attribute::StackAlignment: return 7 << 26;
1258 case Attribute::ReturnsTwice: return 1 << 29;
1259 case Attribute::UWTable: return 1 << 30;
1260 case Attribute::NonLazyBind: return 1U << 31;
1261 case Attribute::SanitizeAddress: return 1ULL << 32;
1262 case Attribute::MinSize: return 1ULL << 33;
1263 case Attribute::NoDuplicate: return 1ULL << 34;
1264 case Attribute::StackProtectStrong: return 1ULL << 35;
1265 case Attribute::SanitizeThread: return 1ULL << 36;
1266 case Attribute::SanitizeMemory: return 1ULL << 37;
1267 case Attribute::NoBuiltin: return 1ULL << 38;
1268 case Attribute::Returned: return 1ULL << 39;
1269 case Attribute::Cold: return 1ULL << 40;
1270 case Attribute::Builtin: return 1ULL << 41;
1271 case Attribute::OptimizeNone: return 1ULL << 42;
1272 case Attribute::InAlloca: return 1ULL << 43;
1273 case Attribute::NonNull: return 1ULL << 44;
1274 case Attribute::JumpTable: return 1ULL << 45;
1275 case Attribute::Convergent: return 1ULL << 46;
1276 case Attribute::SafeStack: return 1ULL << 47;
1277 case Attribute::NoRecurse: return 1ULL << 48;
1278 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1279 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1280 case Attribute::SwiftSelf: return 1ULL << 51;
1281 case Attribute::SwiftError: return 1ULL << 52;
1282 case Attribute::WriteOnly: return 1ULL << 53;
1283 case Attribute::Speculatable: return 1ULL << 54;
1284 case Attribute::StrictFP: return 1ULL << 55;
1285 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1286 case Attribute::NoCfCheck: return 1ULL << 57;
1287 case Attribute::OptForFuzzing: return 1ULL << 58;
1288 case Attribute::ShadowCallStack: return 1ULL << 59;
1289 case Attribute::SpeculativeLoadHardening:
1290 return 1ULL << 60;
1291 case Attribute::ImmArg:
1292 return 1ULL << 61;
1293 case Attribute::WillReturn:
1294 return 1ULL << 62;
1295 case Attribute::NoFree:
1296 return 1ULL << 63;
1297 default:
1298 // Other attributes are not supported in the raw format,
1299 // as we ran out of space.
1300 return 0;
1301 }
1302 llvm_unreachable("Unsupported attribute type")::llvm::llvm_unreachable_internal("Unsupported attribute type"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1302)
;
1303}
1304
1305static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1306 if (!Val) return;
1307
1308 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1309 I = Attribute::AttrKind(I + 1)) {
1310 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1311 if (I == Attribute::Alignment)
1312 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1313 else if (I == Attribute::StackAlignment)
1314 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1315 else
1316 B.addAttribute(I);
1317 }
1318 }
1319}
1320
1321/// This fills an AttrBuilder object with the LLVM attributes that have
1322/// been decoded from the given integer. This function must stay in sync with
1323/// 'encodeLLVMAttributesForBitcode'.
1324static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1325 uint64_t EncodedAttrs) {
1326 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1327 // the bits above 31 down by 11 bits.
1328 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1329 assert((!Alignment || isPowerOf2_32(Alignment)) &&(static_cast <bool> ((!Alignment || isPowerOf2_32(Alignment
)) && "Alignment must be a power of two.") ? void (0)
: __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1330, __extension__ __PRETTY_FUNCTION__))
1330 "Alignment must be a power of two.")(static_cast <bool> ((!Alignment || isPowerOf2_32(Alignment
)) && "Alignment must be a power of two.") ? void (0)
: __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1330, __extension__ __PRETTY_FUNCTION__))
;
1331
1332 if (Alignment)
1333 B.addAlignmentAttr(Alignment);
1334 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1335 (EncodedAttrs & 0xffff));
1336}
1337
1338Error BitcodeReader::parseAttributeBlock() {
1339 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1340 return Err;
1341
1342 if (!MAttributes.empty())
1343 return error("Invalid multiple blocks");
1344
1345 SmallVector<uint64_t, 64> Record;
1346
1347 SmallVector<AttributeList, 8> Attrs;
1348
1349 // Read all the records.
1350 while (true) {
1351 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1352 if (!MaybeEntry)
1353 return MaybeEntry.takeError();
1354 BitstreamEntry Entry = MaybeEntry.get();
1355
1356 switch (Entry.Kind) {
1357 case BitstreamEntry::SubBlock: // Handled for us already.
1358 case BitstreamEntry::Error:
1359 return error("Malformed block");
1360 case BitstreamEntry::EndBlock:
1361 return Error::success();
1362 case BitstreamEntry::Record:
1363 // The interesting case.
1364 break;
1365 }
1366
1367 // Read a record.
1368 Record.clear();
1369 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1370 if (!MaybeRecord)
1371 return MaybeRecord.takeError();
1372 switch (MaybeRecord.get()) {
1373 default: // Default behavior: ignore.
1374 break;
1375 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1376 // Deprecated, but still needed to read old bitcode files.
1377 if (Record.size() & 1)
1378 return error("Invalid record");
1379
1380 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1381 AttrBuilder B;
1382 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1383 Attrs.push_back(AttributeList::get(Context, Record[i], B));
1384 }
1385
1386 MAttributes.push_back(AttributeList::get(Context, Attrs));
1387 Attrs.clear();
1388 break;
1389 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1390 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1391 Attrs.push_back(MAttributeGroups[Record[i]]);
1392
1393 MAttributes.push_back(AttributeList::get(Context, Attrs));
1394 Attrs.clear();
1395 break;
1396 }
1397 }
1398}
1399
1400// Returns Attribute::None on unrecognized codes.
1401static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1402 switch (Code) {
1403 default:
1404 return Attribute::None;
1405 case bitc::ATTR_KIND_ALIGNMENT:
1406 return Attribute::Alignment;
1407 case bitc::ATTR_KIND_ALWAYS_INLINE:
1408 return Attribute::AlwaysInline;
1409 case bitc::ATTR_KIND_ARGMEMONLY:
1410 return Attribute::ArgMemOnly;
1411 case bitc::ATTR_KIND_BUILTIN:
1412 return Attribute::Builtin;
1413 case bitc::ATTR_KIND_BY_VAL:
1414 return Attribute::ByVal;
1415 case bitc::ATTR_KIND_IN_ALLOCA:
1416 return Attribute::InAlloca;
1417 case bitc::ATTR_KIND_COLD:
1418 return Attribute::Cold;
1419 case bitc::ATTR_KIND_CONVERGENT:
1420 return Attribute::Convergent;
1421 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1422 return Attribute::InaccessibleMemOnly;
1423 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1424 return Attribute::InaccessibleMemOrArgMemOnly;
1425 case bitc::ATTR_KIND_INLINE_HINT:
1426 return Attribute::InlineHint;
1427 case bitc::ATTR_KIND_IN_REG:
1428 return Attribute::InReg;
1429 case bitc::ATTR_KIND_JUMP_TABLE:
1430 return Attribute::JumpTable;
1431 case bitc::ATTR_KIND_MIN_SIZE:
1432 return Attribute::MinSize;
1433 case bitc::ATTR_KIND_NAKED:
1434 return Attribute::Naked;
1435 case bitc::ATTR_KIND_NEST:
1436 return Attribute::Nest;
1437 case bitc::ATTR_KIND_NO_ALIAS:
1438 return Attribute::NoAlias;
1439 case bitc::ATTR_KIND_NO_BUILTIN:
1440 return Attribute::NoBuiltin;
1441 case bitc::ATTR_KIND_NO_CALLBACK:
1442 return Attribute::NoCallback;
1443 case bitc::ATTR_KIND_NO_CAPTURE:
1444 return Attribute::NoCapture;
1445 case bitc::ATTR_KIND_NO_DUPLICATE:
1446 return Attribute::NoDuplicate;
1447 case bitc::ATTR_KIND_NOFREE:
1448 return Attribute::NoFree;
1449 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1450 return Attribute::NoImplicitFloat;
1451 case bitc::ATTR_KIND_NO_INLINE:
1452 return Attribute::NoInline;
1453 case bitc::ATTR_KIND_NO_RECURSE:
1454 return Attribute::NoRecurse;
1455 case bitc::ATTR_KIND_NO_MERGE:
1456 return Attribute::NoMerge;
1457 case bitc::ATTR_KIND_NON_LAZY_BIND:
1458 return Attribute::NonLazyBind;
1459 case bitc::ATTR_KIND_NON_NULL:
1460 return Attribute::NonNull;
1461 case bitc::ATTR_KIND_DEREFERENCEABLE:
1462 return Attribute::Dereferenceable;
1463 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1464 return Attribute::DereferenceableOrNull;
1465 case bitc::ATTR_KIND_ALLOC_SIZE:
1466 return Attribute::AllocSize;
1467 case bitc::ATTR_KIND_NO_RED_ZONE:
1468 return Attribute::NoRedZone;
1469 case bitc::ATTR_KIND_NO_RETURN:
1470 return Attribute::NoReturn;
1471 case bitc::ATTR_KIND_NOSYNC:
1472 return Attribute::NoSync;
1473 case bitc::ATTR_KIND_NOCF_CHECK:
1474 return Attribute::NoCfCheck;
1475 case bitc::ATTR_KIND_NO_UNWIND:
1476 return Attribute::NoUnwind;
1477 case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
1478 return Attribute::NoSanitizeCoverage;
1479 case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
1480 return Attribute::NullPointerIsValid;
1481 case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1482 return Attribute::OptForFuzzing;
1483 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1484 return Attribute::OptimizeForSize;
1485 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1486 return Attribute::OptimizeNone;
1487 case bitc::ATTR_KIND_READ_NONE:
1488 return Attribute::ReadNone;
1489 case bitc::ATTR_KIND_READ_ONLY:
1490 return Attribute::ReadOnly;
1491 case bitc::ATTR_KIND_RETURNED:
1492 return Attribute::Returned;
1493 case bitc::ATTR_KIND_RETURNS_TWICE:
1494 return Attribute::ReturnsTwice;
1495 case bitc::ATTR_KIND_S_EXT:
1496 return Attribute::SExt;
1497 case bitc::ATTR_KIND_SPECULATABLE:
1498 return Attribute::Speculatable;
1499 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1500 return Attribute::StackAlignment;
1501 case bitc::ATTR_KIND_STACK_PROTECT:
1502 return Attribute::StackProtect;
1503 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1504 return Attribute::StackProtectReq;
1505 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1506 return Attribute::StackProtectStrong;
1507 case bitc::ATTR_KIND_SAFESTACK:
1508 return Attribute::SafeStack;
1509 case bitc::ATTR_KIND_SHADOWCALLSTACK:
1510 return Attribute::ShadowCallStack;
1511 case bitc::ATTR_KIND_STRICT_FP:
1512 return Attribute::StrictFP;
1513 case bitc::ATTR_KIND_STRUCT_RET:
1514 return Attribute::StructRet;
1515 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1516 return Attribute::SanitizeAddress;
1517 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1518 return Attribute::SanitizeHWAddress;
1519 case bitc::ATTR_KIND_SANITIZE_THREAD:
1520 return Attribute::SanitizeThread;
1521 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1522 return Attribute::SanitizeMemory;
1523 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1524 return Attribute::SpeculativeLoadHardening;
1525 case bitc::ATTR_KIND_SWIFT_ERROR:
1526 return Attribute::SwiftError;
1527 case bitc::ATTR_KIND_SWIFT_SELF:
1528 return Attribute::SwiftSelf;
1529 case bitc::ATTR_KIND_SWIFT_ASYNC:
1530 return Attribute::SwiftAsync;
1531 case bitc::ATTR_KIND_UW_TABLE:
1532 return Attribute::UWTable;
1533 case bitc::ATTR_KIND_VSCALE_RANGE:
1534 return Attribute::VScaleRange;
1535 case bitc::ATTR_KIND_WILLRETURN:
1536 return Attribute::WillReturn;
1537 case bitc::ATTR_KIND_WRITEONLY:
1538 return Attribute::WriteOnly;
1539 case bitc::ATTR_KIND_Z_EXT:
1540 return Attribute::ZExt;
1541 case bitc::ATTR_KIND_IMMARG:
1542 return Attribute::ImmArg;
1543 case bitc::ATTR_KIND_SANITIZE_MEMTAG:
1544 return Attribute::SanitizeMemTag;
1545 case bitc::ATTR_KIND_PREALLOCATED:
1546 return Attribute::Preallocated;
1547 case bitc::ATTR_KIND_NOUNDEF:
1548 return Attribute::NoUndef;
1549 case bitc::ATTR_KIND_BYREF:
1550 return Attribute::ByRef;
1551 case bitc::ATTR_KIND_MUSTPROGRESS:
1552 return Attribute::MustProgress;
1553 case bitc::ATTR_KIND_HOT:
1554 return Attribute::Hot;
1555 }
1556}
1557
1558Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1559 MaybeAlign &Alignment) {
1560 // Note: Alignment in bitcode files is incremented by 1, so that zero
1561 // can be used for default alignment.
1562 if (Exponent > Value::MaxAlignmentExponent + 1)
1563 return error("Invalid alignment value");
1564 Alignment = decodeMaybeAlign(Exponent);
1565 return Error::success();
1566}
1567
1568Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1569 *Kind = getAttrFromCode(Code);
1570 if (*Kind == Attribute::None)
1571 return error("Unknown attribute kind (" + Twine(Code) + ")");
1572 return Error::success();
1573}
1574
1575Error BitcodeReader::parseAttributeGroupBlock() {
1576 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1577 return Err;
1578
1579 if (!MAttributeGroups.empty())
1580 return error("Invalid multiple blocks");
1581
1582 SmallVector<uint64_t, 64> Record;
1583
1584 // Read all the records.
1585 while (true) {
1586 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1587 if (!MaybeEntry)
1588 return MaybeEntry.takeError();
1589 BitstreamEntry Entry = MaybeEntry.get();
1590
1591 switch (Entry.Kind) {
1592 case BitstreamEntry::SubBlock: // Handled for us already.
1593 case BitstreamEntry::Error:
1594 return error("Malformed block");
1595 case BitstreamEntry::EndBlock:
1596 return Error::success();
1597 case BitstreamEntry::Record:
1598 // The interesting case.
1599 break;
1600 }
1601
1602 // Read a record.
1603 Record.clear();
1604 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1605 if (!MaybeRecord)
1606 return MaybeRecord.takeError();
1607 switch (MaybeRecord.get()) {
1608 default: // Default behavior: ignore.
1609 break;
1610 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1611 if (Record.size() < 3)
1612 return error("Invalid record");
1613
1614 uint64_t GrpID = Record[0];
1615 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1616
1617 AttrBuilder B;
1618 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1619 if (Record[i] == 0) { // Enum attribute
1620 Attribute::AttrKind Kind;
1621 if (Error Err = parseAttrKind(Record[++i], &Kind))
1622 return Err;
1623
1624 // Upgrade old-style byval attribute to one with a type, even if it's
1625 // nullptr. We will have to insert the real type when we associate
1626 // this AttributeList with a function.
1627 if (Kind == Attribute::ByVal)
1628 B.addByValAttr(nullptr);
1629 else if (Kind == Attribute::StructRet)
1630 B.addStructRetAttr(nullptr);
1631 else if (Kind == Attribute::InAlloca)
1632 B.addInAllocaAttr(nullptr);
1633
1634 B.addAttribute(Kind);
1635 } else if (Record[i] == 1) { // Integer attribute
1636 Attribute::AttrKind Kind;
1637 if (Error Err = parseAttrKind(Record[++i], &Kind))
1638 return Err;
1639 if (Kind == Attribute::Alignment)
1640 B.addAlignmentAttr(Record[++i]);
1641 else if (Kind == Attribute::StackAlignment)
1642 B.addStackAlignmentAttr(Record[++i]);
1643 else if (Kind == Attribute::Dereferenceable)
1644 B.addDereferenceableAttr(Record[++i]);
1645 else if (Kind == Attribute::DereferenceableOrNull)
1646 B.addDereferenceableOrNullAttr(Record[++i]);
1647 else if (Kind == Attribute::AllocSize)
1648 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1649 else if (Kind == Attribute::VScaleRange)
1650 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
1651 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
1652 bool HasValue = (Record[i++] == 4);
1653 SmallString<64> KindStr;
1654 SmallString<64> ValStr;
1655
1656 while (Record[i] != 0 && i != e)
1657 KindStr += Record[i++];
1658 assert(Record[i] == 0 && "Kind string not null terminated")(static_cast <bool> (Record[i] == 0 && "Kind string not null terminated"
) ? void (0) : __assert_fail ("Record[i] == 0 && \"Kind string not null terminated\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1658, __extension__ __PRETTY_FUNCTION__))
;
1659
1660 if (HasValue) {
1661 // Has a value associated with it.
1662 ++i; // Skip the '0' that terminates the "kind" string.
1663 while (Record[i] != 0 && i != e)
1664 ValStr += Record[i++];
1665 assert(Record[i] == 0 && "Value string not null terminated")(static_cast <bool> (Record[i] == 0 && "Value string not null terminated"
) ? void (0) : __assert_fail ("Record[i] == 0 && \"Value string not null terminated\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1665, __extension__ __PRETTY_FUNCTION__))
;
1666 }
1667
1668 B.addAttribute(KindStr.str(), ValStr.str());
1669 } else {
1670 assert((Record[i] == 5 || Record[i] == 6) &&(static_cast <bool> ((Record[i] == 5 || Record[i] == 6)
&& "Invalid attribute group entry") ? void (0) : __assert_fail
("(Record[i] == 5 || Record[i] == 6) && \"Invalid attribute group entry\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1671, __extension__ __PRETTY_FUNCTION__))
1671 "Invalid attribute group entry")(static_cast <bool> ((Record[i] == 5 || Record[i] == 6)
&& "Invalid attribute group entry") ? void (0) : __assert_fail
("(Record[i] == 5 || Record[i] == 6) && \"Invalid attribute group entry\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1671, __extension__ __PRETTY_FUNCTION__))
;
1672 bool HasType = Record[i] == 6;
1673 Attribute::AttrKind Kind;
1674 if (Error Err = parseAttrKind(Record[++i], &Kind))
1675 return Err;
1676 if (Kind == Attribute::ByVal) {
1677 B.addByValAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1678 } else if (Kind == Attribute::StructRet) {
1679 B.addStructRetAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1680 } else if (Kind == Attribute::ByRef) {
1681 B.addByRefAttr(getTypeByID(Record[++i]));
1682 } else if (Kind == Attribute::Preallocated) {
1683 B.addPreallocatedAttr(getTypeByID(Record[++i]));
1684 } else if (Kind == Attribute::InAlloca) {
1685 B.addInAllocaAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1686 }
1687 }
1688 }
1689
1690 UpgradeAttributes(B);
1691 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1692 break;
1693 }
1694 }
1695 }
1696}
1697
1698Error BitcodeReader::parseTypeTable() {
1699 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1700 return Err;
1701
1702 return parseTypeTableBody();
1703}
1704
1705Error BitcodeReader::parseTypeTableBody() {
1706 if (!TypeList.empty())
1707 return error("Invalid multiple blocks");
1708
1709 SmallVector<uint64_t, 64> Record;
1710 unsigned NumRecords = 0;
1711
1712 SmallString<64> TypeName;
1713
1714 // Read all the records for this type table.
1715 while (true) {
1716 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1717 if (!MaybeEntry)
1718 return MaybeEntry.takeError();
1719 BitstreamEntry Entry = MaybeEntry.get();
1720
1721 switch (Entry.Kind) {
1722 case BitstreamEntry::SubBlock: // Handled for us already.
1723 case BitstreamEntry::Error:
1724 return error("Malformed block");
1725 case BitstreamEntry::EndBlock:
1726 if (NumRecords != TypeList.size())
1727 return error("Malformed block");
1728 return Error::success();
1729 case BitstreamEntry::Record:
1730 // The interesting case.
1731 break;
1732 }
1733
1734 // Read a record.
1735 Record.clear();
1736 Type *ResultTy = nullptr;
1737 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1738 if (!MaybeRecord)
1739 return MaybeRecord.takeError();
1740 switch (MaybeRecord.get()) {
1741 default:
1742 return error("Invalid value");
1743 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1744 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1745 // type list. This allows us to reserve space.
1746 if (Record.empty())
1747 return error("Invalid record");
1748 TypeList.resize(Record[0]);
1749 continue;
1750 case bitc::TYPE_CODE_VOID: // VOID
1751 ResultTy = Type::getVoidTy(Context);
1752 break;
1753 case bitc::TYPE_CODE_HALF: // HALF
1754 ResultTy = Type::getHalfTy(Context);
1755 break;
1756 case bitc::TYPE_CODE_BFLOAT: // BFLOAT
1757 ResultTy = Type::getBFloatTy(Context);
1758 break;
1759 case bitc::TYPE_CODE_FLOAT: // FLOAT
1760 ResultTy = Type::getFloatTy(Context);
1761 break;
1762 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1763 ResultTy = Type::getDoubleTy(Context);
1764 break;
1765 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1766 ResultTy = Type::getX86_FP80Ty(Context);
1767 break;
1768 case bitc::TYPE_CODE_FP128: // FP128
1769 ResultTy = Type::getFP128Ty(Context);
1770 break;
1771 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1772 ResultTy = Type::getPPC_FP128Ty(Context);
1773 break;
1774 case bitc::TYPE_CODE_LABEL: // LABEL
1775 ResultTy = Type::getLabelTy(Context);
1776 break;
1777 case bitc::TYPE_CODE_METADATA: // METADATA
1778 ResultTy = Type::getMetadataTy(Context);
1779 break;
1780 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1781 ResultTy = Type::getX86_MMXTy(Context);
1782 break;
1783 case bitc::TYPE_CODE_X86_AMX: // X86_AMX
1784 ResultTy = Type::getX86_AMXTy(Context);
1785 break;
1786 case bitc::TYPE_CODE_TOKEN: // TOKEN
1787 ResultTy = Type::getTokenTy(Context);
1788 break;
1789 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1790 if (Record.empty())
1791 return error("Invalid record");
1792
1793 uint64_t NumBits = Record[0];
1794 if (NumBits < IntegerType::MIN_INT_BITS ||
1795 NumBits > IntegerType::MAX_INT_BITS)
1796 return error("Bitwidth for integer type out of range");
1797 ResultTy = IntegerType::get(Context, NumBits);
1798 break;
1799 }
1800 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1801 // [pointee type, address space]
1802 if (Record.empty())
1803 return error("Invalid record");
1804 unsigned AddressSpace = 0;
1805 if (Record.size() == 2)
1806 AddressSpace = Record[1];
1807 ResultTy = getTypeByID(Record[0]);
1808 if (!ResultTy ||
1809 !PointerType::isValidElementType(ResultTy))
1810 return error("Invalid type");
1811 ResultTy = PointerType::get(ResultTy, AddressSpace);
1812 break;
1813 }
1814 case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
1815 if (Record.size() != 1)
1816 return error("Invalid record");
1817 unsigned AddressSpace = Record[0];
1818 ResultTy = PointerType::get(Context, AddressSpace);
1819 break;
1820 }
1821 case bitc::TYPE_CODE_FUNCTION_OLD: {
1822 // Deprecated, but still needed to read old bitcode files.
1823 // FUNCTION: [vararg, attrid, retty, paramty x N]
1824 if (Record.size() < 3)
1825 return error("Invalid record");
1826 SmallVector<Type*, 8> ArgTys;
1827 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1828 if (Type *T = getTypeByID(Record[i]))
1829 ArgTys.push_back(T);
1830 else
1831 break;
1832 }
1833
1834 ResultTy = getTypeByID(Record[2]);
1835 if (!ResultTy || ArgTys.size() < Record.size()-3)
1836 return error("Invalid type");
1837
1838 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1839 break;
1840 }
1841 case bitc::TYPE_CODE_FUNCTION: {
1842 // FUNCTION: [vararg, retty, paramty x N]
1843 if (Record.size() < 2)
1844 return error("Invalid record");
1845 SmallVector<Type*, 8> ArgTys;
1846 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1847 if (Type *T = getTypeByID(Record[i])) {
1848 if (!FunctionType::isValidArgumentType(T))
1849 return error("Invalid function argument type");
1850 ArgTys.push_back(T);
1851 }
1852 else
1853 break;
1854 }
1855
1856 ResultTy = getTypeByID(Record[1]);
1857 if (!ResultTy || ArgTys.size() < Record.size()-2)
1858 return error("Invalid type");
1859
1860 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1861 break;
1862 }
1863 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1864 if (Record.empty())
1865 return error("Invalid record");
1866 SmallVector<Type*, 8> EltTys;
1867 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1868 if (Type *T = getTypeByID(Record[i]))
1869 EltTys.push_back(T);
1870 else
1871 break;
1872 }
1873 if (EltTys.size() != Record.size()-1)
1874 return error("Invalid type");
1875 ResultTy = StructType::get(Context, EltTys, Record[0]);
1876 break;
1877 }
1878 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1879 if (convertToString(Record, 0, TypeName))
1880 return error("Invalid record");
1881 continue;
1882
1883 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1884 if (Record.empty())
1885 return error("Invalid record");
1886
1887 if (NumRecords >= TypeList.size())
1888 return error("Invalid TYPE table");
1889
1890 // Check to see if this was forward referenced, if so fill in the temp.
1891 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1892 if (Res) {
1893 Res->setName(TypeName);
1894 TypeList[NumRecords] = nullptr;
1895 } else // Otherwise, create a new struct.
1896 Res = createIdentifiedStructType(Context, TypeName);
1897 TypeName.clear();
1898
1899 SmallVector<Type*, 8> EltTys;
1900 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1901 if (Type *T = getTypeByID(Record[i]))
1902 EltTys.push_back(T);
1903 else
1904 break;
1905 }
1906 if (EltTys.size() != Record.size()-1)
1907 return error("Invalid record");
1908 Res->setBody(EltTys, Record[0]);
1909 ResultTy = Res;
1910 break;
1911 }
1912 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1913 if (Record.size() != 1)
1914 return error("Invalid record");
1915
1916 if (NumRecords >= TypeList.size())
1917 return error("Invalid TYPE table");
1918
1919 // Check to see if this was forward referenced, if so fill in the temp.
1920 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1921 if (Res) {
1922 Res->setName(TypeName);
1923 TypeList[NumRecords] = nullptr;
1924 } else // Otherwise, create a new struct with no body.
1925 Res = createIdentifiedStructType(Context, TypeName);
1926 TypeName.clear();
1927 ResultTy = Res;
1928 break;
1929 }
1930 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1931 if (Record.size() < 2)
1932 return error("Invalid record");
1933 ResultTy = getTypeByID(Record[1]);
1934 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1935 return error("Invalid type");
1936 ResultTy = ArrayType::get(ResultTy, Record[0]);
1937 break;
1938 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
1939 // [numelts, eltty, scalable]
1940 if (Record.size() < 2)
1941 return error("Invalid record");
1942 if (Record[0] == 0)
1943 return error("Invalid vector length");
1944 ResultTy = getTypeByID(Record[1]);
1945 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1946 return error("Invalid type");
1947 bool Scalable = Record.size() > 2 ? Record[2] : false;
1948 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
1949 break;
1950 }
1951
1952 if (NumRecords >= TypeList.size())
1953 return error("Invalid TYPE table");
1954 if (TypeList[NumRecords])
1955 return error(
1956 "Invalid TYPE table: Only named structs can be forward referenced");
1957 assert(ResultTy && "Didn't read a type?")(static_cast <bool> (ResultTy && "Didn't read a type?"
) ? void (0) : __assert_fail ("ResultTy && \"Didn't read a type?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 1957, __extension__ __PRETTY_FUNCTION__))
;
1958 TypeList[NumRecords++] = ResultTy;
1959 }
1960}
1961
1962Error BitcodeReader::parseOperandBundleTags() {
1963 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1964 return Err;
1965
1966 if (!BundleTags.empty())
1967 return error("Invalid multiple blocks");
1968
1969 SmallVector<uint64_t, 64> Record;
1970
1971 while (true) {
1972 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1973 if (!MaybeEntry)
1974 return MaybeEntry.takeError();
1975 BitstreamEntry Entry = MaybeEntry.get();
1976
1977 switch (Entry.Kind) {
1978 case BitstreamEntry::SubBlock: // Handled for us already.
1979 case BitstreamEntry::Error:
1980 return error("Malformed block");
1981 case BitstreamEntry::EndBlock:
1982 return Error::success();
1983 case BitstreamEntry::Record:
1984 // The interesting case.
1985 break;
1986 }
1987
1988 // Tags are implicitly mapped to integers by their order.
1989
1990 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1991 if (!MaybeRecord)
1992 return MaybeRecord.takeError();
1993 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
1994 return error("Invalid record");
1995
1996 // OPERAND_BUNDLE_TAG: [strchr x N]
1997 BundleTags.emplace_back();
1998 if (convertToString(Record, 0, BundleTags.back()))
1999 return error("Invalid record");
2000 Record.clear();
2001 }
2002}
2003
2004Error BitcodeReader::parseSyncScopeNames() {
2005 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2006 return Err;
2007
2008 if (!SSIDs.empty())
2009 return error("Invalid multiple synchronization scope names blocks");
2010
2011 SmallVector<uint64_t, 64> Record;
2012 while (true) {
2013 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2014 if (!MaybeEntry)
2015 return MaybeEntry.takeError();
2016 BitstreamEntry Entry = MaybeEntry.get();
2017
2018 switch (Entry.Kind) {
2019 case BitstreamEntry::SubBlock: // Handled for us already.
2020 case BitstreamEntry::Error:
2021 return error("Malformed block");
2022 case BitstreamEntry::EndBlock:
2023 if (SSIDs.empty())
2024 return error("Invalid empty synchronization scope names block");
2025 return Error::success();
2026 case BitstreamEntry::Record:
2027 // The interesting case.
2028 break;
2029 }
2030
2031 // Synchronization scope names are implicitly mapped to synchronization
2032 // scope IDs by their order.
2033
2034 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2035 if (!MaybeRecord)
2036 return MaybeRecord.takeError();
2037 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2038 return error("Invalid record");
2039
2040 SmallString<16> SSN;
2041 if (convertToString(Record, 0, SSN))
2042 return error("Invalid record");
2043
2044 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2045 Record.clear();
2046 }
2047}
2048
2049/// Associate a value with its name from the given index in the provided record.
2050Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2051 unsigned NameIndex, Triple &TT) {
2052 SmallString<128> ValueName;
2053 if (convertToString(Record, NameIndex, ValueName))
2054 return error("Invalid record");
2055 unsigned ValueID = Record[0];
2056 if (ValueID >= ValueList.size() || !ValueList[ValueID])
2057 return error("Invalid record");
2058 Value *V = ValueList[ValueID];
2059
2060 StringRef NameStr(ValueName.data(), ValueName.size());
2061 if (NameStr.find_first_of(0) != StringRef::npos)
2062 return error("Invalid value name");
2063 V->setName(NameStr);
2064 auto *GO = dyn_cast<GlobalObject>(V);
2065 if (GO) {
2066 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
2067 if (TT.supportsCOMDAT())
2068 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2069 else
2070 GO->setComdat(nullptr);
2071 }
2072 }
2073 return V;
2074}
2075
2076/// Helper to note and return the current location, and jump to the given
2077/// offset.
2078static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2079 BitstreamCursor &Stream) {
2080 // Save the current parsing location so we can jump back at the end
2081 // of the VST read.
2082 uint64_t CurrentBit = Stream.GetCurrentBitNo();
2083 if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2084 return std::move(JumpFailed);
2085 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2086 if (!MaybeEntry)
2087 return MaybeEntry.takeError();
2088 assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock)(static_cast <bool> (MaybeEntry.get().Kind == BitstreamEntry
::SubBlock) ? void (0) : __assert_fail ("MaybeEntry.get().Kind == BitstreamEntry::SubBlock"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2088, __extension__ __PRETTY_FUNCTION__))
;
2089 assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID)(static_cast <bool> (MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID
) ? void (0) : __assert_fail ("MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2089, __extension__ __PRETTY_FUNCTION__))
;
2090 return CurrentBit;
2091}
2092
2093void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2094 Function *F,
2095 ArrayRef<uint64_t> Record) {
2096 // Note that we subtract 1 here because the offset is relative to one word
2097 // before the start of the identification or module block, which was
2098 // historically always the start of the regular bitcode header.
2099 uint64_t FuncWordOffset = Record[1] - 1;
2100 uint64_t FuncBitOffset = FuncWordOffset * 32;
2101 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2102 // Set the LastFunctionBlockBit to point to the last function block.
2103 // Later when parsing is resumed after function materialization,
2104 // we can simply skip that last function block.
2105 if (FuncBitOffset > LastFunctionBlockBit)
2106 LastFunctionBlockBit = FuncBitOffset;
2107}
2108
2109/// Read a new-style GlobalValue symbol table.
2110Error BitcodeReader::parseGlobalValueSymbolTable() {
2111 unsigned FuncBitcodeOffsetDelta =
2112 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2113
2114 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2115 return Err;
2116
2117 SmallVector<uint64_t, 64> Record;
2118 while (true) {
2119 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2120 if (!MaybeEntry)
2121 return MaybeEntry.takeError();
2122 BitstreamEntry Entry = MaybeEntry.get();
2123
2124 switch (Entry.Kind) {
2125 case BitstreamEntry::SubBlock:
2126 case BitstreamEntry::Error:
2127 return error("Malformed block");
2128 case BitstreamEntry::EndBlock:
2129 return Error::success();
2130 case BitstreamEntry::Record:
2131 break;
2132 }
2133
2134 Record.clear();
2135 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2136 if (!MaybeRecord)
2137 return MaybeRecord.takeError();
2138 switch (MaybeRecord.get()) {
2139 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
2140 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2141 cast<Function>(ValueList[Record[0]]), Record);
2142 break;
2143 }
2144 }
2145}
2146
2147/// Parse the value symbol table at either the current parsing location or
2148/// at the given bit offset if provided.
2149Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2150 uint64_t CurrentBit;
2151 // Pass in the Offset to distinguish between calling for the module-level
2152 // VST (where we want to jump to the VST offset) and the function-level
2153 // VST (where we don't).
2154 if (Offset > 0) {
2155 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2156 if (!MaybeCurrentBit)
2157 return MaybeCurrentBit.takeError();
2158 CurrentBit = MaybeCurrentBit.get();
2159 // If this module uses a string table, read this as a module-level VST.
2160 if (UseStrtab) {
2161 if (Error Err = parseGlobalValueSymbolTable())
2162 return Err;
2163 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2164 return JumpFailed;
2165 return Error::success();
2166 }
2167 // Otherwise, the VST will be in a similar format to a function-level VST,
2168 // and will contain symbol names.
2169 }
2170
2171 // Compute the delta between the bitcode indices in the VST (the word offset
2172 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2173 // expected by the lazy reader. The reader's EnterSubBlock expects to have
2174 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2175 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2176 // just before entering the VST subblock because: 1) the EnterSubBlock
2177 // changes the AbbrevID width; 2) the VST block is nested within the same
2178 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2179 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2180 // jump to the FUNCTION_BLOCK using this offset later, we don't want
2181 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2182 unsigned FuncBitcodeOffsetDelta =
2183 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2184
2185 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2186 return Err;
2187
2188 SmallVector<uint64_t, 64> Record;
2189
2190 Triple TT(TheModule->getTargetTriple());
2191
2192 // Read all the records for this value table.
2193 SmallString<128> ValueName;
2194
2195 while (true) {
2196 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2197 if (!MaybeEntry)
2198 return MaybeEntry.takeError();
2199 BitstreamEntry Entry = MaybeEntry.get();
2200
2201 switch (Entry.Kind) {
2202 case BitstreamEntry::SubBlock: // Handled for us already.
2203 case BitstreamEntry::Error:
2204 return error("Malformed block");
2205 case BitstreamEntry::EndBlock:
2206 if (Offset > 0)
2207 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2208 return JumpFailed;
2209 return Error::success();
2210 case BitstreamEntry::Record:
2211 // The interesting case.
2212 break;
2213 }
2214
2215 // Read a record.
2216 Record.clear();
2217 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2218 if (!MaybeRecord)
2219 return MaybeRecord.takeError();
2220 switch (MaybeRecord.get()) {
2221 default: // Default behavior: unknown type.
2222 break;
2223 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2224 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2225 if (Error Err = ValOrErr.takeError())
2226 return Err;
2227 ValOrErr.get();
2228 break;
2229 }
2230 case bitc::VST_CODE_FNENTRY: {
2231 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2232 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2233 if (Error Err = ValOrErr.takeError())
2234 return Err;
2235 Value *V = ValOrErr.get();
2236
2237 // Ignore function offsets emitted for aliases of functions in older
2238 // versions of LLVM.
2239 if (auto *F = dyn_cast<Function>(V))
2240 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2241 break;
2242 }
2243 case bitc::VST_CODE_BBENTRY: {
2244 if (convertToString(Record, 1, ValueName))
2245 return error("Invalid record");
2246 BasicBlock *BB = getBasicBlock(Record[0]);
2247 if (!BB)
2248 return error("Invalid record");
2249
2250 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2251 ValueName.clear();
2252 break;
2253 }
2254 }
2255 }
2256}
2257
2258/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2259/// encoding.
2260uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2261 if ((V & 1) == 0)
2262 return V >> 1;
2263 if (V != 1)
2264 return -(V >> 1);
2265 // There is no such thing as -0 with integers. "-0" really means MININT.
2266 return 1ULL << 63;
2267}
2268
2269/// Resolve all of the initializers for global values and aliases that we can.
2270Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2271 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2272 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2273 IndirectSymbolInitWorklist;
2274 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2275 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2276 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2277
2278 GlobalInitWorklist.swap(GlobalInits);
2279 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2280 FunctionPrefixWorklist.swap(FunctionPrefixes);
2281 FunctionPrologueWorklist.swap(FunctionPrologues);
2282 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2283
2284 while (!GlobalInitWorklist.empty()) {
2285 unsigned ValID = GlobalInitWorklist.back().second;
2286 if (ValID >= ValueList.size()) {
2287 // Not ready to resolve this yet, it requires something later in the file.
2288 GlobalInits.push_back(GlobalInitWorklist.back());
2289 } else {
2290 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2291 GlobalInitWorklist.back().first->setInitializer(C);
2292 else
2293 return error("Expected a constant");
2294 }
2295 GlobalInitWorklist.pop_back();
2296 }
2297
2298 while (!IndirectSymbolInitWorklist.empty()) {
2299 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2300 if (ValID >= ValueList.size()) {
2301 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2302 } else {
2303 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2304 if (!C)
2305 return error("Expected a constant");
2306 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2307 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2308 return error("Alias and aliasee types don't match");
2309 GIS->setIndirectSymbol(C);
2310 }
2311 IndirectSymbolInitWorklist.pop_back();
2312 }
2313
2314 while (!FunctionPrefixWorklist.empty()) {
2315 unsigned ValID = FunctionPrefixWorklist.back().second;
2316 if (ValID >= ValueList.size()) {
2317 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2318 } else {
2319 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2320 FunctionPrefixWorklist.back().first->setPrefixData(C);
2321 else
2322 return error("Expected a constant");
2323 }
2324 FunctionPrefixWorklist.pop_back();
2325 }
2326
2327 while (!FunctionPrologueWorklist.empty()) {
2328 unsigned ValID = FunctionPrologueWorklist.back().second;
2329 if (ValID >= ValueList.size()) {
2330 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2331 } else {
2332 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2333 FunctionPrologueWorklist.back().first->setPrologueData(C);
2334 else
2335 return error("Expected a constant");
2336 }
2337 FunctionPrologueWorklist.pop_back();
2338 }
2339
2340 while (!FunctionPersonalityFnWorklist.empty()) {
2341 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2342 if (ValID >= ValueList.size()) {
2343 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2344 } else {
2345 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2346 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2347 else
2348 return error("Expected a constant");
2349 }
2350 FunctionPersonalityFnWorklist.pop_back();
2351 }
2352
2353 return Error::success();
2354}
2355
2356APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2357 SmallVector<uint64_t, 8> Words(Vals.size());
2358 transform(Vals, Words.begin(),
2359 BitcodeReader::decodeSignRotatedValue);
2360
2361 return APInt(TypeBits, Words);
2362}
2363
2364Error BitcodeReader::parseConstants() {
2365 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2366 return Err;
2367
2368 SmallVector<uint64_t, 64> Record;
2369
2370 // Read all the records for this value table.
2371 Type *CurTy = Type::getInt32Ty(Context);
2372 Type *CurFullTy = Type::getInt32Ty(Context);
2373 unsigned NextCstNo = ValueList.size();
2374
2375 struct DelayedShufTy {
2376 VectorType *OpTy;
2377 VectorType *RTy;
2378 Type *CurFullTy;
2379 uint64_t Op0Idx;
2380 uint64_t Op1Idx;
2381 uint64_t Op2Idx;
2382 unsigned CstNo;
2383 };
2384 std::vector<DelayedShufTy> DelayedShuffles;
2385 while (true) {
2386 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2387 if (!MaybeEntry)
2388 return MaybeEntry.takeError();
2389 BitstreamEntry Entry = MaybeEntry.get();
2390
2391 switch (Entry.Kind) {
2392 case BitstreamEntry::SubBlock: // Handled for us already.
2393 case BitstreamEntry::Error:
2394 return error("Malformed block");
2395 case BitstreamEntry::EndBlock:
2396 // Once all the constants have been read, go through and resolve forward
2397 // references.
2398 //
2399 // We have to treat shuffles specially because they don't have three
2400 // operands anymore. We need to convert the shuffle mask into an array,
2401 // and we can't convert a forward reference.
2402 for (auto &DelayedShuffle : DelayedShuffles) {
2403 VectorType *OpTy = DelayedShuffle.OpTy;
2404 VectorType *RTy = DelayedShuffle.RTy;
2405 uint64_t Op0Idx = DelayedShuffle.Op0Idx;
2406 uint64_t Op1Idx = DelayedShuffle.Op1Idx;
2407 uint64_t Op2Idx = DelayedShuffle.Op2Idx;
2408 uint64_t CstNo = DelayedShuffle.CstNo;
2409 Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy);
2410 Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
2411 Type *ShufTy =
2412 VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());
2413 Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy);
2414 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2415 return error("Invalid shufflevector operands");
2416 SmallVector<int, 16> Mask;
2417 ShuffleVectorInst::getShuffleMask(Op2, Mask);
2418 Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);
2419 ValueList.assignValue(V, CstNo, DelayedShuffle.CurFullTy);
2420 }
2421
2422 if (NextCstNo != ValueList.size())
2423 return error("Invalid constant reference");
2424
2425 ValueList.resolveConstantForwardRefs();
2426 return Error::success();
2427 case BitstreamEntry::Record:
2428 // The interesting case.
2429 break;
2430 }
2431
2432 // Read a record.
2433 Record.clear();
2434 Type *VoidType = Type::getVoidTy(Context);
2435 Value *V = nullptr;
2436 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2437 if (!MaybeBitCode)
2438 return MaybeBitCode.takeError();
2439 switch (unsigned BitCode = MaybeBitCode.get()) {
2440 default: // Default behavior: unknown constant
2441 case bitc::CST_CODE_UNDEF: // UNDEF
2442 V = UndefValue::get(CurTy);
2443 break;
2444 case bitc::CST_CODE_POISON: // POISON
2445 V = PoisonValue::get(CurTy);
2446 break;
2447 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2448 if (Record.empty())
2449 return error("Invalid record");
2450 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2451 return error("Invalid record");
2452 if (TypeList[Record[0]] == VoidType)
2453 return error("Invalid constant type");
2454 CurFullTy = TypeList[Record[0]];
2455 CurTy = flattenPointerTypes(CurFullTy);
2456 continue; // Skip the ValueList manipulation.
2457 case bitc::CST_CODE_NULL: // NULL
2458 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
2459 return error("Invalid type for a constant null value");
2460 V = Constant::getNullValue(CurTy);
2461 break;
2462 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2463 if (!CurTy->isIntegerTy() || Record.empty())
2464 return error("Invalid record");
2465 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2466 break;
2467 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2468 if (!CurTy->isIntegerTy() || Record.empty())
2469 return error("Invalid record");
2470
2471 APInt VInt =
2472 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2473 V = ConstantInt::get(Context, VInt);
2474
2475 break;
2476 }
2477 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2478 if (Record.empty())
2479 return error("Invalid record");
2480 if (CurTy->isHalfTy())
2481 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2482 APInt(16, (uint16_t)Record[0])));
2483 else if (CurTy->isBFloatTy())
2484 V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
2485 APInt(16, (uint32_t)Record[0])));
2486 else if (CurTy->isFloatTy())
2487 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2488 APInt(32, (uint32_t)Record[0])));
2489 else if (CurTy->isDoubleTy())
2490 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2491 APInt(64, Record[0])));
2492 else if (CurTy->isX86_FP80Ty()) {
2493 // Bits are not stored the same way as a normal i80 APInt, compensate.
2494 uint64_t Rearrange[2];
2495 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2496 Rearrange[1] = Record[0] >> 48;
2497 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2498 APInt(80, Rearrange)));
2499 } else if (CurTy->isFP128Ty())
2500 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2501 APInt(128, Record)));
2502 else if (CurTy->isPPC_FP128Ty())
2503 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2504 APInt(128, Record)));
2505 else
2506 V = UndefValue::get(CurTy);
2507 break;
2508 }
2509
2510 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2511 if (Record.empty())
2512 return error("Invalid record");
2513
2514 unsigned Size = Record.size();
2515 SmallVector<Constant*, 16> Elts;
2516
2517 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2518 for (unsigned i = 0; i != Size; ++i)
2519 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2520 STy->getElementType(i)));
2521 V = ConstantStruct::get(STy, Elts);
2522 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2523 Type *EltTy = ATy->getElementType();
2524 for (unsigned i = 0; i != Size; ++i)
2525 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2526 V = ConstantArray::get(ATy, Elts);
2527 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2528 Type *EltTy = VTy->getElementType();
2529 for (unsigned i = 0; i != Size; ++i)
2530 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2531 V = ConstantVector::get(Elts);
2532 } else {
2533 V = UndefValue::get(CurTy);
2534 }
2535 break;
2536 }
2537 case bitc::CST_CODE_STRING: // STRING: [values]
2538 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2539 if (Record.empty())
2540 return error("Invalid record");
2541
2542 SmallString<16> Elts(Record.begin(), Record.end());
2543 V = ConstantDataArray::getString(Context, Elts,
2544 BitCode == bitc::CST_CODE_CSTRING);
2545 break;
2546 }
2547 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2548 if (Record.empty())
2549 return error("Invalid record");
2550
2551 Type *EltTy;
2552 if (auto *Array = dyn_cast<ArrayType>(CurTy))
2553 EltTy = Array->getElementType();
2554 else
2555 EltTy = cast<VectorType>(CurTy)->getElementType();
2556 if (EltTy->isIntegerTy(8)) {
2557 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2558 if (isa<VectorType>(CurTy))
2559 V = ConstantDataVector::get(Context, Elts);
2560 else
2561 V = ConstantDataArray::get(Context, Elts);
2562 } else if (EltTy->isIntegerTy(16)) {
2563 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2564 if (isa<VectorType>(CurTy))
2565 V = ConstantDataVector::get(Context, Elts);
2566 else
2567 V = ConstantDataArray::get(Context, Elts);
2568 } else if (EltTy->isIntegerTy(32)) {
2569 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2570 if (isa<VectorType>(CurTy))
2571 V = ConstantDataVector::get(Context, Elts);
2572 else
2573 V = ConstantDataArray::get(Context, Elts);
2574 } else if (EltTy->isIntegerTy(64)) {
2575 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2576 if (isa<VectorType>(CurTy))
2577 V = ConstantDataVector::get(Context, Elts);
2578 else
2579 V = ConstantDataArray::get(Context, Elts);
2580 } else if (EltTy->isHalfTy()) {
2581 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2582 if (isa<VectorType>(CurTy))
2583 V = ConstantDataVector::getFP(EltTy, Elts);
2584 else
2585 V = ConstantDataArray::getFP(EltTy, Elts);
2586 } else if (EltTy->isBFloatTy()) {
2587 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2588 if (isa<VectorType>(CurTy))
2589 V = ConstantDataVector::getFP(EltTy, Elts);
2590 else
2591 V = ConstantDataArray::getFP(EltTy, Elts);
2592 } else if (EltTy->isFloatTy()) {
2593 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2594 if (isa<VectorType>(CurTy))
2595 V = ConstantDataVector::getFP(EltTy, Elts);
2596 else
2597 V = ConstantDataArray::getFP(EltTy, Elts);
2598 } else if (EltTy->isDoubleTy()) {
2599 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2600 if (isa<VectorType>(CurTy))
2601 V = ConstantDataVector::getFP(EltTy, Elts);
2602 else
2603 V = ConstantDataArray::getFP(EltTy, Elts);
2604 } else {
2605 return error("Invalid type for value");
2606 }
2607 break;
2608 }
2609 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
2610 if (Record.size() < 2)
2611 return error("Invalid record");
2612 int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2613 if (Opc < 0) {
2614 V = UndefValue::get(CurTy); // Unknown unop.
2615 } else {
2616 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2617 unsigned Flags = 0;
2618 V = ConstantExpr::get(Opc, LHS, Flags);
2619 }
2620 break;
2621 }
2622 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2623 if (Record.size() < 3)
2624 return error("Invalid record");
2625 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2626 if (Opc < 0) {
2627 V = UndefValue::get(CurTy); // Unknown binop.
2628 } else {
2629 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2630 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2631 unsigned Flags = 0;
2632 if (Record.size() >= 4) {
2633 if (Opc == Instruction::Add ||
2634 Opc == Instruction::Sub ||
2635 Opc == Instruction::Mul ||
2636 Opc == Instruction::Shl) {
2637 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2638 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2639 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2640 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2641 } else if (Opc == Instruction::SDiv ||
2642 Opc == Instruction::UDiv ||
2643 Opc == Instruction::LShr ||
2644 Opc == Instruction::AShr) {
2645 if (Record[3] & (1 << bitc::PEO_EXACT))
2646 Flags |= SDivOperator::IsExact;
2647 }
2648 }
2649 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2650 }
2651 break;
2652 }
2653 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2654 if (Record.size() < 3)
2655 return error("Invalid record");
2656 int Opc = getDecodedCastOpcode(Record[0]);
2657 if (Opc < 0) {
2658 V = UndefValue::get(CurTy); // Unknown cast.
2659 } else {
2660 Type *OpTy = getTypeByID(Record[1]);
2661 if (!OpTy)
2662 return error("Invalid record");
2663 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2664 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2665 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2666 }
2667 break;
2668 }
2669 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2670 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2671 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2672 // operands]
2673 unsigned OpNum = 0;
2674 Type *PointeeType = nullptr;
2675 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2676 Record.size() % 2)
2677 PointeeType = getTypeByID(Record[OpNum++]);
2678
2679 bool InBounds = false;
2680 Optional<unsigned> InRangeIndex;
2681 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2682 uint64_t Op = Record[OpNum++];
2683 InBounds = Op & 1;
2684 InRangeIndex = Op >> 1;
2685 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2686 InBounds = true;
2687
2688 SmallVector<Constant*, 16> Elts;
2689 Type *Elt0FullTy = nullptr;
2690 while (OpNum != Record.size()) {
2691 if (!Elt0FullTy)
2692 Elt0FullTy = getFullyStructuredTypeByID(Record[OpNum]);
2693 Type *ElTy = getTypeByID(Record[OpNum++]);
2694 if (!ElTy)
2695 return error("Invalid record");
2696 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2697 }
2698
2699 if (Elts.size() < 1)
2700 return error("Invalid gep with no operands");
2701
2702 Type *ImplicitPointeeType =
2703 getPointerElementFlatType(Elt0FullTy->getScalarType());
2704 if (!PointeeType)
2705 PointeeType = ImplicitPointeeType;
2706 else if (PointeeType != ImplicitPointeeType)
2707 return error("Explicit gep operator type does not match pointee type "
2708 "of pointer operand");
2709
2710 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2711 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2712 InBounds, InRangeIndex);
2713 break;
2714 }
2715 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2716 if (Record.size() < 3)
2717 return error("Invalid record");
2718
2719 Type *SelectorTy = Type::getInt1Ty(Context);
2720
2721 // The selector might be an i1, an <n x i1>, or a <vscale x n x i1>
2722 // Get the type from the ValueList before getting a forward ref.
2723 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2724 if (Value *V = ValueList[Record[0]])
2725 if (SelectorTy != V->getType())
2726 SelectorTy = VectorType::get(SelectorTy,
2727 VTy->getElementCount());
2728
2729 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2730 SelectorTy),
2731 ValueList.getConstantFwdRef(Record[1],CurTy),
2732 ValueList.getConstantFwdRef(Record[2],CurTy));
2733 break;
2734 }
2735 case bitc::CST_CODE_CE_EXTRACTELT
2736 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2737 if (Record.size() < 3)
2738 return error("Invalid record");
2739 VectorType *OpTy =
2740 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2741 if (!OpTy)
2742 return error("Invalid record");
2743 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2744 Constant *Op1 = nullptr;
2745 if (Record.size() == 4) {
2746 Type *IdxTy = getTypeByID(Record[2]);
2747 if (!IdxTy)
2748 return error("Invalid record");
2749 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2750 } else {
2751 // Deprecated, but still needed to read old bitcode files.
2752 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2753 }
2754 if (!Op1)
2755 return error("Invalid record");
2756 V = ConstantExpr::getExtractElement(Op0, Op1);
2757 break;
2758 }
2759 case bitc::CST_CODE_CE_INSERTELT
2760 : { // CE_INSERTELT: [opval, opval, opty, opval]
2761 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2762 if (Record.size() < 3 || !OpTy)
2763 return error("Invalid record");
2764 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2765 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2766 OpTy->getElementType());
2767 Constant *Op2 = nullptr;
2768 if (Record.size() == 4) {
2769 Type *IdxTy = getTypeByID(Record[2]);
2770 if (!IdxTy)
2771 return error("Invalid record");
2772 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2773 } else {
2774 // Deprecated, but still needed to read old bitcode files.
2775 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2776 }
2777 if (!Op2)
2778 return error("Invalid record");
2779 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2780 break;
2781 }
2782 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2783 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2784 if (Record.size() < 3 || !OpTy)
2785 return error("Invalid record");
2786 DelayedShuffles.push_back(
2787 {OpTy, OpTy, CurFullTy, Record[0], Record[1], Record[2], NextCstNo});
2788 ++NextCstNo;
2789 continue;
2790 }
2791 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2792 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2793 VectorType *OpTy =
2794 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2795 if (Record.size() < 4 || !RTy || !OpTy)
2796 return error("Invalid record");
2797 DelayedShuffles.push_back(
2798 {OpTy, RTy, CurFullTy, Record[1], Record[2], Record[3], NextCstNo});
2799 ++NextCstNo;
2800 continue;
2801 }
2802 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2803 if (Record.size() < 4)
2804 return error("Invalid record");
2805 Type *OpTy = getTypeByID(Record[0]);
2806 if (!OpTy)
2807 return error("Invalid record");
2808 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2809 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2810
2811 if (OpTy->isFPOrFPVectorTy())
2812 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2813 else
2814 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2815 break;
2816 }
2817 // This maintains backward compatibility, pre-asm dialect keywords.
2818 // Deprecated, but still needed to read old bitcode files.
2819 case bitc::CST_CODE_INLINEASM_OLD: {
2820 if (Record.size() < 2)
2821 return error("Invalid record");
2822 std::string AsmStr, ConstrStr;
2823 bool HasSideEffects = Record[0] & 1;
2824 bool IsAlignStack = Record[0] >> 1;
2825 unsigned AsmStrSize = Record[1];
2826 if (2+AsmStrSize >= Record.size())
2827 return error("Invalid record");
2828 unsigned ConstStrSize = Record[2+AsmStrSize];
2829 if (3+AsmStrSize+ConstStrSize > Record.size())
2830 return error("Invalid record");
2831
2832 for (unsigned i = 0; i != AsmStrSize; ++i)
2833 AsmStr += (char)Record[2+i];
2834 for (unsigned i = 0; i != ConstStrSize; ++i)
2835 ConstrStr += (char)Record[3+AsmStrSize+i];
2836 UpgradeInlineAsmString(&AsmStr);
2837 V = InlineAsm::get(
2838 cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2839 ConstrStr, HasSideEffects, IsAlignStack);
2840 break;
2841 }
2842 // This version adds support for the asm dialect keywords (e.g.,
2843 // inteldialect).
2844 case bitc::CST_CODE_INLINEASM_OLD2: {
2845 if (Record.size() < 2)
2846 return error("Invalid record");
2847 std::string AsmStr, ConstrStr;
2848 bool HasSideEffects = Record[0] & 1;
2849 bool IsAlignStack = (Record[0] >> 1) & 1;
2850 unsigned AsmDialect = Record[0] >> 2;
2851 unsigned AsmStrSize = Record[1];
2852 if (2+AsmStrSize >= Record.size())
2853 return error("Invalid record");
2854 unsigned ConstStrSize = Record[2+AsmStrSize];
2855 if (3+AsmStrSize+ConstStrSize > Record.size())
2856 return error("Invalid record");
2857
2858 for (unsigned i = 0; i != AsmStrSize; ++i)
2859 AsmStr += (char)Record[2+i];
2860 for (unsigned i = 0; i != ConstStrSize; ++i)
2861 ConstrStr += (char)Record[3+AsmStrSize+i];
2862 UpgradeInlineAsmString(&AsmStr);
2863 V = InlineAsm::get(
2864 cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2865 ConstrStr, HasSideEffects, IsAlignStack,
2866 InlineAsm::AsmDialect(AsmDialect));
2867 break;
2868 }
2869 // This version adds support for the unwind keyword.
2870 case bitc::CST_CODE_INLINEASM: {
2871 if (Record.size() < 2)
2872 return error("Invalid record");
2873 std::string AsmStr, ConstrStr;
2874 bool HasSideEffects = Record[0] & 1;
2875 bool IsAlignStack = (Record[0] >> 1) & 1;
2876 unsigned AsmDialect = (Record[0] >> 2) & 1;
2877 bool CanThrow = (Record[0] >> 3) & 1;
2878 unsigned AsmStrSize = Record[1];
2879 if (2 + AsmStrSize >= Record.size())
2880 return error("Invalid record");
2881 unsigned ConstStrSize = Record[2 + AsmStrSize];
2882 if (3 + AsmStrSize + ConstStrSize > Record.size())
2883 return error("Invalid record");
2884
2885 for (unsigned i = 0; i != AsmStrSize; ++i)
2886 AsmStr += (char)Record[2 + i];
2887 for (unsigned i = 0; i != ConstStrSize; ++i)
2888 ConstrStr += (char)Record[3 + AsmStrSize + i];
2889 UpgradeInlineAsmString(&AsmStr);
2890 V = InlineAsm::get(
2891 cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2892 ConstrStr, HasSideEffects, IsAlignStack,
2893 InlineAsm::AsmDialect(AsmDialect), CanThrow);
2894 break;
2895 }
2896 case bitc::CST_CODE_BLOCKADDRESS:{
2897 if (Record.size() < 3)
2898 return error("Invalid record");
2899 Type *FnTy = getTypeByID(Record[0]);
2900 if (!FnTy)
2901 return error("Invalid record");
2902 Function *Fn =
2903 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2904 if (!Fn)
2905 return error("Invalid record");
2906
2907 // If the function is already parsed we can insert the block address right
2908 // away.
2909 BasicBlock *BB;
2910 unsigned BBID = Record[2];
2911 if (!BBID)
2912 // Invalid reference to entry block.
2913 return error("Invalid ID");
2914 if (!Fn->empty()) {
2915 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2916 for (size_t I = 0, E = BBID; I != E; ++I) {
2917 if (BBI == BBE)
2918 return error("Invalid ID");
2919 ++BBI;
2920 }
2921 BB = &*BBI;
2922 } else {
2923 // Otherwise insert a placeholder and remember it so it can be inserted
2924 // when the function is parsed.
2925 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2926 if (FwdBBs.empty())
2927 BasicBlockFwdRefQueue.push_back(Fn);
2928 if (FwdBBs.size() < BBID + 1)
2929 FwdBBs.resize(BBID + 1);
2930 if (!FwdBBs[BBID])
2931 FwdBBs[BBID] = BasicBlock::Create(Context);
2932 BB = FwdBBs[BBID];
2933 }
2934 V = BlockAddress::get(Fn, BB);
2935 break;
2936 }
2937 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
2938 if (Record.size() < 2)
2939 return error("Invalid record");
2940 Type *GVTy = getTypeByID(Record[0]);
2941 if (!GVTy)
2942 return error("Invalid record");
2943 GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
2944 ValueList.getConstantFwdRef(Record[1], GVTy));
2945 if (!GV)
2946 return error("Invalid record");
2947
2948 V = DSOLocalEquivalent::get(GV);
2949 break;
2950 }
2951 }
2952
2953 assert(V->getType() == flattenPointerTypes(CurFullTy) &&(static_cast <bool> (V->getType() == flattenPointerTypes
(CurFullTy) && "Incorrect fully structured type provided for Constant"
) ? void (0) : __assert_fail ("V->getType() == flattenPointerTypes(CurFullTy) && \"Incorrect fully structured type provided for Constant\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2954, __extension__ __PRETTY_FUNCTION__))
2954 "Incorrect fully structured type provided for Constant")(static_cast <bool> (V->getType() == flattenPointerTypes
(CurFullTy) && "Incorrect fully structured type provided for Constant"
) ? void (0) : __assert_fail ("V->getType() == flattenPointerTypes(CurFullTy) && \"Incorrect fully structured type provided for Constant\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 2954, __extension__ __PRETTY_FUNCTION__))
;
2955 ValueList.assignValue(V, NextCstNo, CurFullTy);
2956 ++NextCstNo;
2957 }
2958}
2959
2960Error BitcodeReader::parseUseLists() {
2961 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2962 return Err;
2963
2964 // Read all the records.
2965 SmallVector<uint64_t, 64> Record;
2966
2967 while (true) {
2968 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2969 if (!MaybeEntry)
2970 return MaybeEntry.takeError();
2971 BitstreamEntry Entry = MaybeEntry.get();
2972
2973 switch (Entry.Kind) {
2974 case BitstreamEntry::SubBlock: // Handled for us already.
2975 case BitstreamEntry::Error:
2976 return error("Malformed block");
2977 case BitstreamEntry::EndBlock:
2978 return Error::success();
2979 case BitstreamEntry::Record:
2980 // The interesting case.
2981 break;
2982 }
2983
2984 // Read a use list record.
2985 Record.clear();
2986 bool IsBB = false;
2987 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2988 if (!MaybeRecord)
2989 return MaybeRecord.takeError();
2990 switch (MaybeRecord.get()) {
2991 default: // Default behavior: unknown type.
2992 break;
2993 case bitc::USELIST_CODE_BB:
2994 IsBB = true;
2995 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2996 case bitc::USELIST_CODE_DEFAULT: {
2997 unsigned RecordLength = Record.size();
2998 if (RecordLength < 3)
2999 // Records should have at least an ID and two indexes.
3000 return error("Invalid record");
3001 unsigned ID = Record.pop_back_val();
3002
3003 Value *V;
3004 if (IsBB) {
3005 assert(ID < FunctionBBs.size() && "Basic block not found")(static_cast <bool> (ID < FunctionBBs.size() &&
"Basic block not found") ? void (0) : __assert_fail ("ID < FunctionBBs.size() && \"Basic block not found\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3005, __extension__ __PRETTY_FUNCTION__))
;
3006 V = FunctionBBs[ID];
3007 } else
3008 V = ValueList[ID];
3009 unsigned NumUses = 0;
3010 SmallDenseMap<const Use *, unsigned, 16> Order;
3011 for (const Use &U : V->materialized_uses()) {
3012 if (++NumUses > Record.size())
3013 break;
3014 Order[&U] = Record[NumUses - 1];
3015 }
3016 if (Order.size() != Record.size() || NumUses > Record.size())
3017 // Mismatches can happen if the functions are being materialized lazily
3018 // (out-of-order), or a value has been upgraded.
3019 break;
3020
3021 V->sortUseList([&](const Use &L, const Use &R) {
3022 return Order.lookup(&L) < Order.lookup(&R);
3023 });
3024 break;
3025 }
3026 }
3027 }
3028}
3029
3030/// When we see the block for metadata, remember where it is and then skip it.
3031/// This lets us lazily deserialize the metadata.
3032Error BitcodeReader::rememberAndSkipMetadata() {
3033 // Save the current stream state.
3034 uint64_t CurBit = Stream.GetCurrentBitNo();
3035 DeferredMetadataInfo.push_back(CurBit);
3036
3037 // Skip over the block for now.
3038 if (Error Err = Stream.SkipBlock())
3039 return Err;
3040 return Error::success();
3041}
3042
3043Error BitcodeReader::materializeMetadata() {
3044 for (uint64_t BitPos : DeferredMetadataInfo) {
3045 // Move the bit stream to the saved position.
3046 if (Error JumpFailed = Stream.JumpToBit(BitPos))
3047 return JumpFailed;
3048 if (Error Err = MDLoader->parseModuleMetadata())
3049 return Err;
3050 }
3051
3052 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3053 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3054 // multiple times.
3055 if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3056 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3057 NamedMDNode *LinkerOpts =
3058 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3059 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3060 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3061 }
3062 }
3063
3064 DeferredMetadataInfo.clear();
3065 return Error::success();
3066}
3067
3068void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3069
3070/// When we see the block for a function body, remember where it is and then
3071/// skip it. This lets us lazily deserialize the functions.
3072Error BitcodeReader::rememberAndSkipFunctionBody() {
3073 // Get the function we are talking about.
3074 if (FunctionsWithBodies.empty())
3075 return error("Insufficient function protos");
3076
3077 Function *Fn = FunctionsWithBodies.back();
3078 FunctionsWithBodies.pop_back();
3079
3080 // Save the current stream state.
3081 uint64_t CurBit = Stream.GetCurrentBitNo();
3082 assert((static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo
[Fn] == CurBit) && "Mismatch between VST and scanned function offsets"
) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3084, __extension__ __PRETTY_FUNCTION__))
3083 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&(static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo
[Fn] == CurBit) && "Mismatch between VST and scanned function offsets"
) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3084, __extension__ __PRETTY_FUNCTION__))
3084 "Mismatch between VST and scanned function offsets")(static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo
[Fn] == CurBit) && "Mismatch between VST and scanned function offsets"
) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3084, __extension__ __PRETTY_FUNCTION__))
;
3085 DeferredFunctionInfo[Fn] = CurBit;
3086
3087 // Skip over the function block for now.
3088 if (Error Err = Stream.SkipBlock())
3089 return Err;
3090 return Error::success();
3091}
3092
3093Error BitcodeReader::globalCleanup() {
3094 // Patch the initializers for globals and aliases up.
3095 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3096 return Err;
3097 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3098 return error("Malformed global initializer set");
3099
3100 // Look for intrinsic functions which need to be upgraded at some point
3101 // and functions that need to have their function attributes upgraded.
3102 for (Function &F : *TheModule) {
3103 MDLoader->upgradeDebugIntrinsics(F);
3104 Function *NewFn;
3105 if (UpgradeIntrinsicFunction(&F, NewFn))
3106 UpgradedIntrinsics[&F] = NewFn;
3107 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3108 // Some types could be renamed during loading if several modules are
3109 // loaded in the same LLVMContext (LTO scenario). In this case we should
3110 // remangle intrinsics names as well.
3111 RemangledIntrinsics[&F] = Remangled.getValue();
3112 // Look for functions that rely on old function attribute behavior.
3113 UpgradeFunctionAttributes(F);
3114 }
3115
3116 // Look for global variables which need to be renamed.
3117 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3118 for (GlobalVariable &GV : TheModule->globals())
3119 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3120 UpgradedVariables.emplace_back(&GV, Upgraded);
3121 for (auto &Pair : UpgradedVariables) {
3122 Pair.first->eraseFromParent();
3123 TheModule->getGlobalList().push_back(Pair.second);
3124 }
3125
3126 // Force deallocation of memory for these vectors to favor the client that
3127 // want lazy deserialization.
3128 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3129 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
3130 IndirectSymbolInits);
3131 return Error::success();
3132}
3133
3134/// Support for lazy parsing of function bodies. This is required if we
3135/// either have an old bitcode file without a VST forward declaration record,
3136/// or if we have an anonymous function being materialized, since anonymous
3137/// functions do not have a name and are therefore not in the VST.
3138Error BitcodeReader::rememberAndSkipFunctionBodies() {
3139 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3140 return JumpFailed;
3141
3142 if (Stream.AtEndOfStream())
3143 return error("Could not find function in stream");
3144
3145 if (!SeenFirstFunctionBody)
3146 return error("Trying to materialize functions before seeing function blocks");
3147
3148 // An old bitcode file with the symbol table at the end would have
3149 // finished the parse greedily.
3150 assert(SeenValueSymbolTable)(static_cast <bool> (SeenValueSymbolTable) ? void (0) :
__assert_fail ("SeenValueSymbolTable", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3150, __extension__ __PRETTY_FUNCTION__))
;
3151
3152 SmallVector<uint64_t, 64> Record;
3153
3154 while (true) {
3155 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3156 if (!MaybeEntry)
3157 return MaybeEntry.takeError();
3158 llvm::BitstreamEntry Entry = MaybeEntry.get();
3159
3160 switch (Entry.Kind) {
3161 default:
3162 return error("Expect SubBlock");
3163 case BitstreamEntry::SubBlock:
3164 switch (Entry.ID) {
3165 default:
3166 return error("Expect function block");
3167 case bitc::FUNCTION_BLOCK_ID:
3168 if (Error Err = rememberAndSkipFunctionBody())
3169 return Err;
3170 NextUnreadBit = Stream.GetCurrentBitNo();
3171 return Error::success();
3172 }
3173 }
3174 }
3175}
3176
3177bool BitcodeReaderBase::readBlockInfo() {
3178 Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3179 Stream.ReadBlockInfoBlock();
3180 if (!MaybeNewBlockInfo)
3181 return true; // FIXME Handle the error.
3182 Optional<BitstreamBlockInfo> NewBlockInfo =
3183 std::move(MaybeNewBlockInfo.get());
3184 if (!NewBlockInfo)
3185 return true;
3186 BlockInfo = std::move(*NewBlockInfo);
3187 return false;
3188}
3189
3190Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3191 // v1: [selection_kind, name]
3192 // v2: [strtab_offset, strtab_size, selection_kind]
3193 StringRef Name;
3194 std::tie(Name, Record) = readNameFromStrtab(Record);
3195
3196 if (Record.empty())
3197 return error("Invalid record");
3198 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3199 std::string OldFormatName;
3200 if (!UseStrtab) {
3201 if (Record.size() < 2)
3202 return error("Invalid record");
3203 unsigned ComdatNameSize = Record[1];
3204 OldFormatName.reserve(ComdatNameSize);
3205 for (unsigned i = 0; i != ComdatNameSize; ++i)
3206 OldFormatName += (char)Record[2 + i];
3207 Name = OldFormatName;
3208 }
3209 Comdat *C = TheModule->getOrInsertComdat(Name);
3210 C->setSelectionKind(SK);
3211 ComdatList.push_back(C);
3212 return Error::success();
3213}
3214
3215static void inferDSOLocal(GlobalValue *GV) {
3216 // infer dso_local from linkage and visibility if it is not encoded.
3217 if (GV->hasLocalLinkage() ||
3218 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3219 GV->setDSOLocal(true);
3220}
3221
3222Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3223 // v1: [pointer type, isconst, initid, linkage, alignment, section,
3224 // visibility, threadlocal, unnamed_addr, externally_initialized,
3225 // dllstorageclass, comdat, attributes, preemption specifier,
3226 // partition strtab offset, partition strtab size] (name in VST)
3227 // v2: [strtab_offset, strtab_size, v1]
3228 StringRef Name;
3229 std::tie(Name, Record) = readNameFromStrtab(Record);
3230
3231 if (Record.size() < 6)
3232 return error("Invalid record");
3233 Type *FullTy = getFullyStructuredTypeByID(Record[0]);
3234 Type *Ty = flattenPointerTypes(FullTy);
3235 if (!Ty)
3236 return error("Invalid record");
3237 bool isConstant = Record[1] & 1;
3238 bool explicitType = Record[1] & 2;
3239 unsigned AddressSpace;
3240 if (explicitType) {
3241 AddressSpace = Record[1] >> 2;
3242 } else {
3243 if (!Ty->isPointerTy())
3244 return error("Invalid type for value");
3245 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3246 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3247 }
3248
3249 uint64_t RawLinkage = Record[3];
3250 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3251 MaybeAlign Alignment;
3252 if (Error Err = parseAlignmentValue(Record[4], Alignment))
3253 return Err;
3254 std::string Section;
3255 if (Record[5]) {
3256 if (Record[5] - 1 >= SectionTable.size())
3257 return error("Invalid ID");
3258 Section = SectionTable[Record[5] - 1];
3259 }
3260 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3261 // Local linkage must have default visibility.
3262 // auto-upgrade `hidden` and `protected` for old bitcode.
3263 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3264 Visibility = getDecodedVisibility(Record[6]);
3265
3266 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3267 if (Record.size() > 7)
3268 TLM = getDecodedThreadLocalMode(Record[7]);
3269
3270 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3271 if (Record.size() > 8)
3272 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3273
3274 bool ExternallyInitialized = false;
3275 if (Record.size() > 9)
3276 ExternallyInitialized = Record[9];
3277
3278 GlobalVariable *NewGV =
3279 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3280 nullptr, TLM, AddressSpace, ExternallyInitialized);
3281 NewGV->setAlignment(Alignment);
3282 if (!Section.empty())
3283 NewGV->setSection(Section);
3284 NewGV->setVisibility(Visibility);
3285 NewGV->setUnnamedAddr(UnnamedAddr);
3286
3287 if (Record.size() > 10)
3288 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3289 else
3290 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3291
3292 FullTy = PointerType::get(FullTy, AddressSpace);
3293 assert(NewGV->getType() == flattenPointerTypes(FullTy) &&(static_cast <bool> (NewGV->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully specified type for GlobalVariable"
) ? void (0) : __assert_fail ("NewGV->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type for GlobalVariable\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3294, __extension__ __PRETTY_FUNCTION__))
3294 "Incorrect fully specified type for GlobalVariable")(static_cast <bool> (NewGV->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully specified type for GlobalVariable"
) ? void (0) : __assert_fail ("NewGV->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type for GlobalVariable\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3294, __extension__ __PRETTY_FUNCTION__))
;
3295 ValueList.push_back(NewGV, FullTy);
3296
3297 // Remember which value to use for the global initializer.
3298 if (unsigned InitID = Record[2])
3299 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3300
3301 if (Record.size() > 11) {
3302 if (unsigned ComdatID = Record[11]) {
3303 if (ComdatID > ComdatList.size())
3304 return error("Invalid global variable comdat ID");
3305 NewGV->setComdat(ComdatList[ComdatID - 1]);
3306 }
3307 } else if (hasImplicitComdat(RawLinkage)) {
3308 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3309 }
3310
3311 if (Record.size() > 12) {
3312 auto AS = getAttributes(Record[12]).getFnAttributes();
3313 NewGV->setAttributes(AS);
3314 }
3315
3316 if (Record.size() > 13) {
3317 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3318 }
3319 inferDSOLocal(NewGV);
3320
3321 // Check whether we have enough values to read a partition name.
3322 if (Record.size() > 15)
3323 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3324
3325 return Error::success();
3326}
3327
3328Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3329 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3330 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3331 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
3332 // v2: [strtab_offset, strtab_size, v1]
3333 StringRef Name;
3334 std::tie(Name, Record) = readNameFromStrtab(Record);
3335
3336 if (Record.size() < 8)
3337 return error("Invalid record");
3338 Type *FullFTy = getFullyStructuredTypeByID(Record[0]);
3339 Type *FTy = flattenPointerTypes(FullFTy);
3340 if (!FTy)
3341 return error("Invalid record");
3342 if (isa<PointerType>(FTy))
3343 std::tie(FullFTy, FTy) = getPointerElementTypes(FullFTy);
3344
3345 if (!isa<FunctionType>(FTy))
3346 return error("Invalid type for value");
3347 auto CC = static_cast<CallingConv::ID>(Record[1]);
3348 if (CC & ~CallingConv::MaxID)
3349 return error("Invalid calling convention ID");
3350
3351 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3352 if (Record.size() > 16)
3353 AddrSpace = Record[16];
3354
3355 Function *Func =
3356 Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3357 AddrSpace, Name, TheModule);
3358
3359 assert(Func->getFunctionType() == flattenPointerTypes(FullFTy) &&(static_cast <bool> (Func->getFunctionType() == flattenPointerTypes
(FullFTy) && "Incorrect fully specified type provided for function"
) ? void (0) : __assert_fail ("Func->getFunctionType() == flattenPointerTypes(FullFTy) && \"Incorrect fully specified type provided for function\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3360, __extension__ __PRETTY_FUNCTION__))
3360 "Incorrect fully specified type provided for function")(static_cast <bool> (Func->getFunctionType() == flattenPointerTypes
(FullFTy) && "Incorrect fully specified type provided for function"
) ? void (0) : __assert_fail ("Func->getFunctionType() == flattenPointerTypes(FullFTy) && \"Incorrect fully specified type provided for function\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3360, __extension__ __PRETTY_FUNCTION__))
;
3361 FunctionTypes[Func] = cast<FunctionType>(FullFTy);
3362
3363 Func->setCallingConv(CC);
3364 bool isProto = Record[2];
3365 uint64_t RawLinkage = Record[3];
3366 Func->setLinkage(getDecodedLinkage(RawLinkage));
3367 Func->setAttributes(getAttributes(Record[4]));
3368
3369 // Upgrade any old-style byval or sret without a type by propagating the
3370 // argument's pointee type. There should be no opaque pointers where the byval
3371 // type is implicit.
3372 for (unsigned i = 0; i != Func->arg_size(); ++i) {
3373 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3374 Attribute::InAlloca}) {
3375 if (!Func->hasParamAttribute(i, Kind))
3376 continue;
3377
3378 Func->removeParamAttr(i, Kind);
3379
3380 Type *PTy = cast<FunctionType>(FullFTy)->getParamType(i);
3381 Type *PtrEltTy = getPointerElementFlatType(PTy);
3382 Attribute NewAttr;
3383 switch (Kind) {
3384 case Attribute::ByVal:
3385 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3386 break;
3387 case Attribute::StructRet:
3388 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3389 break;
3390 case Attribute::InAlloca:
3391 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3392 break;
3393 default:
3394 llvm_unreachable("not an upgraded type attribute")::llvm::llvm_unreachable_internal("not an upgraded type attribute"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3394)
;
3395 }
3396
3397 Func->addParamAttr(i, NewAttr);
3398 }
3399 }
3400
3401 MaybeAlign Alignment;
3402 if (Error Err = parseAlignmentValue(Record[5], Alignment))
3403 return Err;
3404 Func->setAlignment(Alignment);
3405 if (Record[6]) {
3406 if (Record[6] - 1 >= SectionTable.size())
3407 return error("Invalid ID");
3408 Func->setSection(SectionTable[Record[6] - 1]);
3409 }
3410 // Local linkage must have default visibility.
3411 // auto-upgrade `hidden` and `protected` for old bitcode.
3412 if (!Func->hasLocalLinkage())
3413 Func->setVisibility(getDecodedVisibility(Record[7]));
3414 if (Record.size() > 8 && Record[8]) {
3415 if (Record[8] - 1 >= GCTable.size())
3416 return error("Invalid ID");
3417 Func->setGC(GCTable[Record[8] - 1]);
3418 }
3419 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3420 if (Record.size() > 9)
3421 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3422 Func->setUnnamedAddr(UnnamedAddr);
3423 if (Record.size() > 10 && Record[10] != 0)
3424 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3425
3426 if (Record.size() > 11)
3427 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3428 else
3429 upgradeDLLImportExportLinkage(Func, RawLinkage);
3430
3431 if (Record.size() > 12) {
3432 if (unsigned ComdatID = Record[12]) {
3433 if (ComdatID > ComdatList.size())
3434 return error("Invalid function comdat ID");
3435 Func->setComdat(ComdatList[ComdatID - 1]);
3436 }
3437 } else if (hasImplicitComdat(RawLinkage)) {
3438 Func->setComdat(reinterpret_cast<Comdat *>(1));
3439 }
3440
3441 if (Record.size() > 13 && Record[13] != 0)
3442 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3443
3444 if (Record.size() > 14 && Record[14] != 0)
3445 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3446
3447 if (Record.size() > 15) {
3448 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3449 }
3450 inferDSOLocal(Func);
3451
3452 // Record[16] is the address space number.
3453
3454 // Check whether we have enough values to read a partition name.
3455 if (Record.size() > 18)
3456 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3457
3458 Type *FullTy = PointerType::get(FullFTy, AddrSpace);
3459 assert(Func->getType() == flattenPointerTypes(FullTy) &&(static_cast <bool> (Func->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully specified type provided for Function"
) ? void (0) : __assert_fail ("Func->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type provided for Function\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3460, __extension__ __PRETTY_FUNCTION__))
3460 "Incorrect fully specified type provided for Function")(static_cast <bool> (Func->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully specified type provided for Function"
) ? void (0) : __assert_fail ("Func->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type provided for Function\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3460, __extension__ __PRETTY_FUNCTION__))
;
3461 ValueList.push_back(Func, FullTy);
3462
3463 // If this is a function with a body, remember the prototype we are
3464 // creating now, so that we can match up the body with them later.
3465 if (!isProto) {
3466 Func->setIsMaterializable(true);
3467 FunctionsWithBodies.push_back(Func);
3468 DeferredFunctionInfo[Func] = 0;
3469 }
3470 return Error::success();
3471}
3472
3473Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3474 unsigned BitCode, ArrayRef<uint64_t> Record) {
3475 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3476 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3477 // dllstorageclass, threadlocal, unnamed_addr,
3478 // preemption specifier] (name in VST)
3479 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3480 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3481 // preemption specifier] (name in VST)
3482 // v2: [strtab_offset, strtab_size, v1]
3483 StringRef Name;
3484 std::tie(Name, Record) = readNameFromStrtab(Record);
3485
3486 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3487 if (Record.size() < (3 + (unsigned)NewRecord))
3488 return error("Invalid record");
3489 unsigned OpNum = 0;
3490 Type *FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
3491 Type *Ty = flattenPointerTypes(FullTy);
3492 if (!Ty)
3493 return error("Invalid record");
3494
3495 unsigned AddrSpace;
3496 if (!NewRecord) {
3497 auto *PTy = dyn_cast<PointerType>(Ty);
3498 if (!PTy)
3499 return error("Invalid type for value");
3500 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3501 AddrSpace = PTy->getAddressSpace();
3502 } else {
3503 AddrSpace = Record[OpNum++];
3504 }
3505
3506 auto Val = Record[OpNum++];
3507 auto Linkage = Record[OpNum++];
3508 GlobalIndirectSymbol *NewGA;
3509 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3510 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3511 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3512 TheModule);
3513 else
3514 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3515 nullptr, TheModule);
3516
3517 assert(NewGA->getValueType() == flattenPointerTypes(FullTy) &&(static_cast <bool> (NewGA->getValueType() == flattenPointerTypes
(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol"
) ? void (0) : __assert_fail ("NewGA->getValueType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3518, __extension__ __PRETTY_FUNCTION__))
3518 "Incorrect fully structured type provided for GlobalIndirectSymbol")(static_cast <bool> (NewGA->getValueType() == flattenPointerTypes
(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol"
) ? void (0) : __assert_fail ("NewGA->getValueType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3518, __extension__ __PRETTY_FUNCTION__))
;
3519 // Local linkage must have default visibility.
3520 // auto-upgrade `hidden` and `protected` for old bitcode.
3521 if (OpNum != Record.size()) {
3522 auto VisInd = OpNum++;
3523 if (!NewGA->hasLocalLinkage())
3524 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3525 }
3526 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3527 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3528 if (OpNum != Record.size())
3529 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3530 else
3531 upgradeDLLImportExportLinkage(NewGA, Linkage);
3532 if (OpNum != Record.size())
3533 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3534 if (OpNum != Record.size())
3535 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3536 }
3537 if (OpNum != Record.size())
3538 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3539 inferDSOLocal(NewGA);
3540
3541 // Check whether we have enough values to read a partition name.
3542 if (OpNum + 1 < Record.size()) {
3543 NewGA->setPartition(
3544 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3545 OpNum += 2;
Value stored to 'OpNum' is never read
3546 }
3547
3548 FullTy = PointerType::get(FullTy, AddrSpace);
3549 assert(NewGA->getType() == flattenPointerTypes(FullTy) &&(static_cast <bool> (NewGA->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol"
) ? void (0) : __assert_fail ("NewGA->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3550, __extension__ __PRETTY_FUNCTION__))
3550 "Incorrect fully structured type provided for GlobalIndirectSymbol")(static_cast <bool> (NewGA->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol"
) ? void (0) : __assert_fail ("NewGA->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3550, __extension__ __PRETTY_FUNCTION__))
;
3551 ValueList.push_back(NewGA, FullTy);
3552 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3553 return Error::success();
3554}
3555
3556Error BitcodeReader::parseModule(uint64_t ResumeBit,
3557 bool ShouldLazyLoadMetadata,
3558 DataLayoutCallbackTy DataLayoutCallback) {
3559 if (ResumeBit) {
3560 if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3561 return JumpFailed;
3562 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3563 return Err;
3564
3565 SmallVector<uint64_t, 64> Record;
3566
3567 // Parts of bitcode parsing depend on the datalayout. Make sure we
3568 // finalize the datalayout before we run any of that code.
3569 bool ResolvedDataLayout = false;
3570 auto ResolveDataLayout = [&] {
3571 if (ResolvedDataLayout)
3572 return;
3573
3574 // datalayout and triple can't be parsed after this point.
3575 ResolvedDataLayout = true;
3576
3577 // Upgrade data layout string.
3578 std::string DL = llvm::UpgradeDataLayoutString(
3579 TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
3580 TheModule->setDataLayout(DL);
3581
3582 if (auto LayoutOverride =
3583 DataLayoutCallback(TheModule->getTargetTriple()))
3584 TheModule->setDataLayout(*LayoutOverride);
3585 };
3586
3587 // Read all the records for this module.
3588 while (true) {
3589 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3590 if (!MaybeEntry)
3591 return MaybeEntry.takeError();
3592 llvm::BitstreamEntry Entry = MaybeEntry.get();
3593
3594 switch (Entry.Kind) {
3595 case BitstreamEntry::Error:
3596 return error("Malformed block");
3597 case BitstreamEntry::EndBlock:
3598 ResolveDataLayout();
3599 return globalCleanup();
3600
3601 case BitstreamEntry::SubBlock:
3602 switch (Entry.ID) {
3603 default: // Skip unknown content.
3604 if (Error Err = Stream.SkipBlock())
3605 return Err;
3606 break;
3607 case bitc::BLOCKINFO_BLOCK_ID:
3608 if (readBlockInfo())
3609 return error("Malformed block");
3610 break;
3611 case bitc::PARAMATTR_BLOCK_ID:
3612 if (Error Err = parseAttributeBlock())
3613 return Err;
3614 break;
3615 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3616 if (Error Err = parseAttributeGroupBlock())
3617 return Err;
3618 break;
3619 case bitc::TYPE_BLOCK_ID_NEW:
3620 if (Error Err = parseTypeTable())
3621 return Err;
3622 break;
3623 case bitc::VALUE_SYMTAB_BLOCK_ID:
3624 if (!SeenValueSymbolTable) {
3625 // Either this is an old form VST without function index and an
3626 // associated VST forward declaration record (which would have caused
3627 // the VST to be jumped to and parsed before it was encountered
3628 // normally in the stream), or there were no function blocks to
3629 // trigger an earlier parsing of the VST.
3630 assert(VSTOffset == 0 || FunctionsWithBodies.empty())(static_cast <bool> (VSTOffset == 0 || FunctionsWithBodies
.empty()) ? void (0) : __assert_fail ("VSTOffset == 0 || FunctionsWithBodies.empty()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3630, __extension__ __PRETTY_FUNCTION__))
;
3631 if (Error Err = parseValueSymbolTable())
3632 return Err;
3633 SeenValueSymbolTable = true;
3634 } else {
3635 // We must have had a VST forward declaration record, which caused
3636 // the parser to jump to and parse the VST earlier.
3637 assert(VSTOffset > 0)(static_cast <bool> (VSTOffset > 0) ? void (0) : __assert_fail
("VSTOffset > 0", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3637, __extension__ __PRETTY_FUNCTION__))
;
3638 if (Error Err = Stream.SkipBlock())
3639 return Err;
3640 }
3641 break;
3642 case bitc::CONSTANTS_BLOCK_ID:
3643 if (Error Err = parseConstants())
3644 return Err;
3645 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3646 return Err;
3647 break;
3648 case bitc::METADATA_BLOCK_ID:
3649 if (ShouldLazyLoadMetadata) {
3650 if (Error Err = rememberAndSkipMetadata())
3651 return Err;
3652 break;
3653 }
3654 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata")(static_cast <bool> (DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata") ? void (0) : __assert_fail (
"DeferredMetadataInfo.empty() && \"Unexpected deferred metadata\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3654, __extension__ __PRETTY_FUNCTION__))
;
3655 if (Error Err = MDLoader->parseModuleMetadata())
3656 return Err;
3657 break;
3658 case bitc::METADATA_KIND_BLOCK_ID:
3659 if (Error Err = MDLoader->parseMetadataKinds())
3660 return Err;
3661 break;
3662 case bitc::FUNCTION_BLOCK_ID:
3663 ResolveDataLayout();
3664
3665 // If this is the first function body we've seen, reverse the
3666 // FunctionsWithBodies list.
3667 if (!SeenFirstFunctionBody) {
3668 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3669 if (Error Err = globalCleanup())
3670 return Err;
3671 SeenFirstFunctionBody = true;
3672 }
3673
3674 if (VSTOffset > 0) {
3675 // If we have a VST forward declaration record, make sure we
3676 // parse the VST now if we haven't already. It is needed to
3677 // set up the DeferredFunctionInfo vector for lazy reading.
3678 if (!SeenValueSymbolTable) {
3679 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3680 return Err;
3681 SeenValueSymbolTable = true;
3682 // Fall through so that we record the NextUnreadBit below.
3683 // This is necessary in case we have an anonymous function that
3684 // is later materialized. Since it will not have a VST entry we
3685 // need to fall back to the lazy parse to find its offset.
3686 } else {
3687 // If we have a VST forward declaration record, but have already
3688 // parsed the VST (just above, when the first function body was
3689 // encountered here), then we are resuming the parse after
3690 // materializing functions. The ResumeBit points to the
3691 // start of the last function block recorded in the
3692 // DeferredFunctionInfo map. Skip it.
3693 if (Error Err = Stream.SkipBlock())
3694 return Err;
3695 continue;
3696 }
3697 }
3698
3699 // Support older bitcode files that did not have the function
3700 // index in the VST, nor a VST forward declaration record, as
3701 // well as anonymous functions that do not have VST entries.
3702 // Build the DeferredFunctionInfo vector on the fly.
3703 if (Error Err = rememberAndSkipFunctionBody())
3704 return Err;
3705
3706 // Suspend parsing when we reach the function bodies. Subsequent
3707 // materialization calls will resume it when necessary. If the bitcode
3708 // file is old, the symbol table will be at the end instead and will not
3709 // have been seen yet. In this case, just finish the parse now.
3710 if (SeenValueSymbolTable) {
3711 NextUnreadBit = Stream.GetCurrentBitNo();
3712 // After the VST has been parsed, we need to make sure intrinsic name
3713 // are auto-upgraded.
3714 return globalCleanup();
3715 }
3716 break;
3717 case bitc::USELIST_BLOCK_ID:
3718 if (Error Err = parseUseLists())
3719 return Err;
3720 break;
3721 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3722 if (Error Err = parseOperandBundleTags())
3723 return Err;
3724 break;
3725 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3726 if (Error Err = parseSyncScopeNames())
3727 return Err;
3728 break;
3729 }
3730 continue;
3731
3732 case BitstreamEntry::Record:
3733 // The interesting case.
3734 break;
3735 }
3736
3737 // Read a record.
3738 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3739 if (!MaybeBitCode)
3740 return MaybeBitCode.takeError();
3741 switch (unsigned BitCode = MaybeBitCode.get()) {
3742 default: break; // Default behavior, ignore unknown content.
3743 case bitc::MODULE_CODE_VERSION: {
3744 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3745 if (!VersionOrErr)
3746 return VersionOrErr.takeError();
3747 UseRelativeIDs = *VersionOrErr >= 1;
3748 break;
3749 }
3750 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3751 if (ResolvedDataLayout)
3752 return error("target triple too late in module");
3753 std::string S;
3754 if (convertToString(Record, 0, S))
3755 return error("Invalid record");
3756 TheModule->setTargetTriple(S);
3757 break;
3758 }
3759 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3760 if (ResolvedDataLayout)
3761 return error("datalayout too late in module");
3762 std::string S;
3763 if (convertToString(Record, 0, S))
3764 return error("Invalid record");
3765 TheModule->setDataLayout(S);
3766 break;
3767 }
3768 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3769 std::string S;
3770 if (convertToString(Record, 0, S))
3771 return error("Invalid record");
3772 TheModule->setModuleInlineAsm(S);
3773 break;
3774 }
3775 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3776 // Deprecated, but still needed to read old bitcode files.
3777 std::string S;
3778 if (convertToString(Record, 0, S))
3779 return error("Invalid record");
3780 // Ignore value.
3781 break;
3782 }
3783 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3784 std::string S;
3785 if (convertToString(Record, 0, S))
3786 return error("Invalid record");
3787 SectionTable.push_back(S);
3788 break;
3789 }
3790 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3791 std::string S;
3792 if (convertToString(Record, 0, S))
3793 return error("Invalid record");
3794 GCTable.push_back(S);
3795 break;
3796 }
3797 case bitc::MODULE_CODE_COMDAT:
3798 if (Error Err = parseComdatRecord(Record))
3799 return Err;
3800 break;
3801 case bitc::MODULE_CODE_GLOBALVAR:
3802 if (Error Err = parseGlobalVarRecord(Record))
3803 return Err;
3804 break;
3805 case bitc::MODULE_CODE_FUNCTION:
3806 ResolveDataLayout();
3807 if (Error Err = parseFunctionRecord(Record))
3808 return Err;
3809 break;
3810 case bitc::MODULE_CODE_IFUNC:
3811 case bitc::MODULE_CODE_ALIAS:
3812 case bitc::MODULE_CODE_ALIAS_OLD:
3813 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3814 return Err;
3815 break;
3816 /// MODULE_CODE_VSTOFFSET: [offset]
3817 case bitc::MODULE_CODE_VSTOFFSET:
3818 if (Record.empty())
3819 return error("Invalid record");
3820 // Note that we subtract 1 here because the offset is relative to one word
3821 // before the start of the identification or module block, which was
3822 // historically always the start of the regular bitcode header.
3823 VSTOffset = Record[0] - 1;
3824 break;
3825 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3826 case bitc::MODULE_CODE_SOURCE_FILENAME:
3827 SmallString<128> ValueName;
3828 if (convertToString(Record, 0, ValueName))
3829 return error("Invalid record");
3830 TheModule->setSourceFileName(ValueName);
3831 break;
3832 }
3833 Record.clear();
3834 }
3835}
3836
3837Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3838 bool IsImporting,
3839 DataLayoutCallbackTy DataLayoutCallback) {
3840 TheModule = M;
3841 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3842 [&](unsigned ID) { return getTypeByID(ID); });
3843 return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
3844}
3845
3846Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3847 if (!isa<PointerType>(PtrType))
3848 return error("Load/Store operand is not a pointer type");
3849
3850 if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
3851 return error("Explicit load/store type does not match pointee "
3852 "type of pointer operand");
3853 if (!PointerType::isLoadableOrStorableType(ValType))
3854 return error("Cannot load/store from pointer");
3855 return Error::success();
3856}
3857
3858void BitcodeReader::propagateByValSRetTypes(CallBase *CB,
3859 ArrayRef<Type *> ArgsFullTys) {
3860 for (unsigned i = 0; i != CB->arg_size(); ++i) {
3861 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3862 Attribute::InAlloca}) {
3863 if (!CB->paramHasAttr(i, Kind))
3864 continue;
3865
3866 CB->removeParamAttr(i, Kind);
3867
3868 Type *PtrEltTy = getPointerElementFlatType(ArgsFullTys[i]);
3869 Attribute NewAttr;
3870 switch (Kind) {
3871 case Attribute::ByVal:
3872 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3873 break;
3874 case Attribute::StructRet:
3875 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3876 break;
3877 case Attribute::InAlloca:
3878 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3879 break;
3880 default:
3881 llvm_unreachable("not an upgraded type attribute")::llvm::llvm_unreachable_internal("not an upgraded type attribute"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3881)
;
3882 }
3883
3884 CB->addParamAttr(i, NewAttr);
3885 }
3886 }
3887}
3888
3889/// Lazily parse the specified function body block.
3890Error BitcodeReader::parseFunctionBody(Function *F) {
3891 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3892 return Err;
3893
3894 // Unexpected unresolved metadata when parsing function.
3895 if (MDLoader->hasFwdRefs())
3896 return error("Invalid function metadata: incoming forward references");
3897
3898 InstructionList.clear();
3899 unsigned ModuleValueListSize = ValueList.size();
3900 unsigned ModuleMDLoaderSize = MDLoader->size();
3901
3902 // Add all the function arguments to the value table.
3903 unsigned ArgNo = 0;
3904 FunctionType *FullFTy = FunctionTypes[F];
3905 for (Argument &I : F->args()) {
3906 assert(I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) &&(static_cast <bool> (I.getType() == flattenPointerTypes
(FullFTy->getParamType(ArgNo)) && "Incorrect fully specified type for Function Argument"
) ? void (0) : __assert_fail ("I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) && \"Incorrect fully specified type for Function Argument\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3907, __extension__ __PRETTY_FUNCTION__))
3907 "Incorrect fully specified type for Function Argument")(static_cast <bool> (I.getType() == flattenPointerTypes
(FullFTy->getParamType(ArgNo)) && "Incorrect fully specified type for Function Argument"
) ? void (0) : __assert_fail ("I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) && \"Incorrect fully specified type for Function Argument\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3907, __extension__ __PRETTY_FUNCTION__))
;
3908 ValueList.push_back(&I, FullFTy->getParamType(ArgNo++));
3909 }
3910 unsigned NextValueNo = ValueList.size();
3911 BasicBlock *CurBB = nullptr;
3912 unsigned CurBBNo = 0;
3913
3914 DebugLoc LastLoc;
3915 auto getLastInstruction = [&]() -> Instruction * {
3916 if (CurBB && !CurBB->empty())
3917 return &CurBB->back();
3918 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3919 !FunctionBBs[CurBBNo - 1]->empty())
3920 return &FunctionBBs[CurBBNo - 1]->back();
3921 return nullptr;
3922 };
3923
3924 std::vector<OperandBundleDef> OperandBundles;
3925
3926 // Read all the records.
3927 SmallVector<uint64_t, 64> Record;
3928
3929 while (true) {
3930 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3931 if (!MaybeEntry)
3932 return MaybeEntry.takeError();
3933 llvm::BitstreamEntry Entry = MaybeEntry.get();
3934
3935 switch (Entry.Kind) {
3936 case BitstreamEntry::Error:
3937 return error("Malformed block");
3938 case BitstreamEntry::EndBlock:
3939 goto OutOfRecordLoop;
3940
3941 case BitstreamEntry::SubBlock:
3942 switch (Entry.ID) {
3943 default: // Skip unknown content.
3944 if (Error Err = Stream.SkipBlock())
3945 return Err;
3946 break;
3947 case bitc::CONSTANTS_BLOCK_ID:
3948 if (Error Err = parseConstants())
3949 return Err;
3950 NextValueNo = ValueList.size();
3951 break;
3952 case bitc::VALUE_SYMTAB_BLOCK_ID:
3953 if (Error Err = parseValueSymbolTable())
3954 return Err;
3955 break;
3956 case bitc::METADATA_ATTACHMENT_ID:
3957 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3958 return Err;
3959 break;
3960 case bitc::METADATA_BLOCK_ID:
3961 assert(DeferredMetadataInfo.empty() &&(static_cast <bool> (DeferredMetadataInfo.empty() &&
"Must read all module-level metadata before function-level")
? void (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3962, __extension__ __PRETTY_FUNCTION__))
3962 "Must read all module-level metadata before function-level")(static_cast <bool> (DeferredMetadataInfo.empty() &&
"Must read all module-level metadata before function-level")
? void (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 3962, __extension__ __PRETTY_FUNCTION__))
;
3963 if (Error Err = MDLoader->parseFunctionMetadata())
3964 return Err;
3965 break;
3966 case bitc::USELIST_BLOCK_ID:
3967 if (Error Err = parseUseLists())
3968 return Err;
3969 break;
3970 }
3971 continue;
3972
3973 case BitstreamEntry::Record:
3974 // The interesting case.
3975 break;
3976 }
3977
3978 // Read a record.
3979 Record.clear();
3980 Instruction *I = nullptr;
3981 Type *FullTy = nullptr;
3982 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3983 if (!MaybeBitCode)
3984 return MaybeBitCode.takeError();
3985 switch (unsigned BitCode = MaybeBitCode.get()) {
3986 default: // Default behavior: reject
3987 return error("Invalid value");
3988 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3989 if (Record.empty() || Record[0] == 0)
3990 return error("Invalid record");
3991 // Create all the basic blocks for the function.
3992 FunctionBBs.resize(Record[0]);
3993
3994 // See if anything took the address of blocks in this function.
3995 auto BBFRI = BasicBlockFwdRefs.find(F);
3996 if (BBFRI == BasicBlockFwdRefs.end()) {
3997 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3998 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3999 } else {
4000 auto &BBRefs = BBFRI->second;
4001 // Check for invalid basic block references.
4002 if (BBRefs.size() > FunctionBBs.size())
4003 return error("Invalid ID");
4004 assert(!BBRefs.empty() && "Unexpected empty array")(static_cast <bool> (!BBRefs.empty() && "Unexpected empty array"
) ? void (0) : __assert_fail ("!BBRefs.empty() && \"Unexpected empty array\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4004, __extension__ __PRETTY_FUNCTION__))
;
4005 assert(!BBRefs.front() && "Invalid reference to entry block")(static_cast <bool> (!BBRefs.front() && "Invalid reference to entry block"
) ? void (0) : __assert_fail ("!BBRefs.front() && \"Invalid reference to entry block\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4005, __extension__ __PRETTY_FUNCTION__))
;
4006 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4007 ++I)
4008 if (I < RE && BBRefs[I]) {
4009 BBRefs[I]->insertInto(F);
4010 FunctionBBs[I] = BBRefs[I];
4011 } else {
4012 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4013 }
4014
4015 // Erase from the table.
4016 BasicBlockFwdRefs.erase(BBFRI);
4017 }
4018
4019 CurBB = FunctionBBs[0];
4020 continue;
4021 }
4022
4023 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4024 // This record indicates that the last instruction is at the same
4025 // location as the previous instruction with a location.
4026 I = getLastInstruction();
4027
4028 if (!I)
4029 return error("Invalid record");
4030 I->setDebugLoc(LastLoc);
4031 I = nullptr;
4032 continue;
4033
4034 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4035 I = getLastInstruction();
4036 if (!I || Record.size() < 4)
4037 return error("Invalid record");
4038
4039 unsigned Line = Record[0], Col = Record[1];
4040 unsigned ScopeID = Record[2], IAID = Record[3];
4041 bool isImplicitCode = Record.size() == 5 && Record[4];
4042
4043 MDNode *Scope = nullptr, *IA = nullptr;
4044 if (ScopeID) {
4045 Scope = dyn_cast_or_null<MDNode>(
4046 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4047 if (!Scope)
4048 return error("Invalid record");
4049 }
4050 if (IAID) {
4051 IA = dyn_cast_or_null<MDNode>(
4052 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4053 if (!IA)
4054 return error("Invalid record");
4055 }
4056 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4057 isImplicitCode);
4058 I->setDebugLoc(LastLoc);
4059 I = nullptr;
4060 continue;
4061 }
4062 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
4063 unsigned OpNum = 0;
4064 Value *LHS;
4065 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4066 OpNum+1 > Record.size())
4067 return error("Invalid record");
4068
4069 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4070 if (Opc == -1)
4071 return error("Invalid record");
4072 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4073 InstructionList.push_back(I);
4074 if (OpNum < Record.size()) {
4075 if (isa<FPMathOperator>(I)) {
4076 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4077 if (FMF.any())
4078 I->setFastMathFlags(FMF);
4079 }
4080 }
4081 break;
4082 }
4083 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4084 unsigned OpNum = 0;
4085 Value *LHS, *RHS;
4086 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4087 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4088 OpNum+1 > Record.size())
4089 return error("Invalid record");
4090
4091 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4092 if (Opc == -1)
4093 return error("Invalid record");
4094 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4095 InstructionList.push_back(I);
4096 if (OpNum < Record.size()) {
4097 if (Opc == Instruction::Add ||
4098 Opc == Instruction::Sub ||
4099 Opc == Instruction::Mul ||
4100 Opc == Instruction::Shl) {
4101 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4102 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4103 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4104 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4105 } else if (Opc == Instruction::SDiv ||
4106 Opc == Instruction::UDiv ||
4107 Opc == Instruction::LShr ||
4108 Opc == Instruction::AShr) {
4109 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4110 cast<BinaryOperator>(I)->setIsExact(true);
4111 } else if (isa<FPMathOperator>(I)) {
4112 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4113 if (FMF.any())
4114 I->setFastMathFlags(FMF);
4115 }
4116
4117 }
4118 break;
4119 }
4120 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4121 unsigned OpNum = 0;
4122 Value *Op;
4123 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4124 OpNum+2 != Record.size())
4125 return error("Invalid record");
4126
4127 FullTy = getFullyStructuredTypeByID(Record[OpNum]);
4128 Type *ResTy = flattenPointerTypes(FullTy);
4129 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4130 if (Opc == -1 || !ResTy)
4131 return error("Invalid record");
4132 Instruction *Temp = nullptr;
4133 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4134 if (Temp) {
4135 InstructionList.push_back(Temp);
4136 assert(CurBB && "No current BB?")(static_cast <bool> (CurBB && "No current BB?")
? void (0) : __assert_fail ("CurBB && \"No current BB?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4136, __extension__ __PRETTY_FUNCTION__))
;
4137 CurBB->getInstList().push_back(Temp);
4138 }
4139 } else {
4140 auto CastOp = (Instruction::CastOps)Opc;
4141 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4142 return error("Invalid cast");
4143 I = CastInst::Create(CastOp, Op, ResTy);
4144 }
4145 InstructionList.push_back(I);
4146 break;
4147 }
4148 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4149 case bitc::FUNC_CODE_INST_GEP_OLD:
4150 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4151 unsigned OpNum = 0;
4152
4153 Type *Ty;
4154 bool InBounds;
4155
4156 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4157 InBounds = Record[OpNum++];
4158 FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4159 Ty = flattenPointerTypes(FullTy);
4160 } else {
4161 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4162 Ty = nullptr;
4163 }
4164
4165 Value *BasePtr;
4166 Type *FullBaseTy = nullptr;
4167 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, &FullBaseTy))
4168 return error("Invalid record");
4169
4170 if (!Ty) {
4171 std::tie(FullTy, Ty) =
4172 getPointerElementTypes(FullBaseTy->getScalarType());
4173 } else if (!cast<PointerType>(FullBaseTy->getScalarType())
4174 ->isOpaqueOrPointeeTypeMatches(Ty))
4175 return error(
4176 "Explicit gep type does not match pointee type of pointer operand");
4177
4178 SmallVector<Value*, 16> GEPIdx;
4179 while (OpNum != Record.size()) {
4180 Value *Op;
4181 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4182 return error("Invalid record");
4183 GEPIdx.push_back(Op);
4184 }
4185
4186 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4187 FullTy = GetElementPtrInst::getGEPReturnType(FullTy, I, GEPIdx);
4188
4189 InstructionList.push_back(I);
4190 if (InBounds)
4191 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4192 break;
4193 }
4194
4195 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4196 // EXTRACTVAL: [opty, opval, n x indices]
4197 unsigned OpNum = 0;
4198 Value *Agg;
4199 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4200 return error("Invalid record");
4201
4202 unsigned RecSize = Record.size();
4203 if (OpNum == RecSize)
4204 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4205
4206 SmallVector<unsigned, 4> EXTRACTVALIdx;
4207 for (; OpNum != RecSize; ++OpNum) {
4208 bool IsArray = FullTy->isArrayTy();
4209 bool IsStruct = FullTy->isStructTy();
4210 uint64_t Index = Record[OpNum];
4211
4212 if (!IsStruct && !IsArray)
4213 return error("EXTRACTVAL: Invalid type");
4214 if ((unsigned)Index != Index)
4215 return error("Invalid value");
4216 if (IsStruct && Index >= FullTy->getStructNumElements())
4217 return error("EXTRACTVAL: Invalid struct index");
4218 if (IsArray && Index >= FullTy->getArrayNumElements())
4219 return error("EXTRACTVAL: Invalid array index");
4220 EXTRACTVALIdx.push_back((unsigned)Index);
4221
4222 if (IsStruct)
4223 FullTy = FullTy->getStructElementType(Index);
4224 else
4225 FullTy = FullTy->getArrayElementType();
4226 }
4227
4228 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4229 InstructionList.push_back(I);
4230 break;
4231 }
4232
4233 case bitc::FUNC_CODE_INST_INSERTVAL: {
4234 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4235 unsigned OpNum = 0;
4236 Value *Agg;
4237 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4238 return error("Invalid record");
4239 Value *Val;
4240 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4241 return error("Invalid record");
4242
4243 unsigned RecSize = Record.size();
4244 if (OpNum == RecSize)
4245 return error("INSERTVAL: Invalid instruction with 0 indices");
4246
4247 SmallVector<unsigned, 4> INSERTVALIdx;
4248 Type *CurTy = Agg->getType();
4249 for (; OpNum != RecSize; ++OpNum) {
4250 bool IsArray = CurTy->isArrayTy();
4251 bool IsStruct = CurTy->isStructTy();
4252 uint64_t Index = Record[OpNum];
4253
4254 if (!IsStruct && !IsArray)
4255 return error("INSERTVAL: Invalid type");
4256 if ((unsigned)Index != Index)
4257 return error("Invalid value");
4258 if (IsStruct && Index >= CurTy->getStructNumElements())
4259 return error("INSERTVAL: Invalid struct index");
4260 if (IsArray && Index >= CurTy->getArrayNumElements())
4261 return error("INSERTVAL: Invalid array index");
4262
4263 INSERTVALIdx.push_back((unsigned)Index);
4264 if (IsStruct)
4265 CurTy = CurTy->getStructElementType(Index);
4266 else
4267 CurTy = CurTy->getArrayElementType();
4268 }
4269
4270 if (CurTy != Val->getType())
4271 return error("Inserted value type doesn't match aggregate type");
4272
4273 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4274 InstructionList.push_back(I);
4275 break;
4276 }
4277
4278 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4279 // obsolete form of select
4280 // handles select i1 ... in old bitcode
4281 unsigned OpNum = 0;
4282 Value *TrueVal, *FalseVal, *Cond;
4283 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4284 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4285 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4286 return error("Invalid record");
4287
4288 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4289 InstructionList.push_back(I);
4290 break;
4291 }
4292
4293 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4294 // new form of select
4295 // handles select i1 or select [N x i1]
4296 unsigned OpNum = 0;
4297 Value *TrueVal, *FalseVal, *Cond;
4298 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4299 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4300 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4301 return error("Invalid record");
4302
4303 // select condition can be either i1 or [N x i1]
4304 if (VectorType* vector_type =
4305 dyn_cast<VectorType>(Cond->getType())) {
4306 // expect <n x i1>
4307 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4308 return error("Invalid type for value");
4309 } else {
4310 // expect i1
4311 if (Cond->getType() != Type::getInt1Ty(Context))
4312 return error("Invalid type for value");
4313 }
4314
4315 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4316 InstructionList.push_back(I);
4317 if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4318 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4319 if (FMF.any())
4320 I->setFastMathFlags(FMF);
4321 }
4322 break;
4323 }
4324
4325 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4326 unsigned OpNum = 0;
4327 Value *Vec, *Idx;
4328 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy) ||
4329 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4330 return error("Invalid record");
4331 if (!Vec->getType()->isVectorTy())
4332 return error("Invalid type for value");
4333 I = ExtractElementInst::Create(Vec, Idx);
4334 FullTy = cast<VectorType>(FullTy)->getElementType();
4335 InstructionList.push_back(I);
4336 break;
4337 }
4338
4339 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4340 unsigned OpNum = 0;
4341 Value *Vec, *Elt, *Idx;
4342 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy))
4343 return error("Invalid record");
4344 if (!Vec->getType()->isVectorTy())
4345 return error("Invalid type for value");
4346 if (popValue(Record, OpNum, NextValueNo,
4347 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4348 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4349 return error("Invalid record");
4350 I = InsertElementInst::Create(Vec, Elt, Idx);
4351 InstructionList.push_back(I);
4352 break;
4353 }
4354
4355 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4356 unsigned OpNum = 0;
4357 Value *Vec1, *Vec2, *Mask;
4358 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, &FullTy) ||
4359 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4360 return error("Invalid record");
4361
4362 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4363 return error("Invalid record");
4364 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4365 return error("Invalid type for value");
4366
4367 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4368 FullTy =
4369 VectorType::get(cast<VectorType>(FullTy)->getElementType(),
4370 cast<VectorType>(Mask->getType())->getElementCount());
4371 InstructionList.push_back(I);
4372 break;
4373 }
4374
4375 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4376 // Old form of ICmp/FCmp returning bool
4377 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4378 // both legal on vectors but had different behaviour.
4379 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4380 // FCmp/ICmp returning bool or vector of bool
4381
4382 unsigned OpNum = 0;
4383 Value *LHS, *RHS;
4384 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4385 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4386 return error("Invalid record");
4387
4388 if (OpNum >= Record.size())
4389 return error(
4390 "Invalid record: operand number exceeded available operands");
4391
4392 unsigned PredVal = Record[OpNum];
4393 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4394 FastMathFlags FMF;
4395 if (IsFP && Record.size() > OpNum+1)
4396 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4397
4398 if (OpNum+1 != Record.size())
4399 return error("Invalid record");
4400
4401 if (LHS->getType()->isFPOrFPVectorTy())
4402 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4403 else
4404 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4405
4406 if (FMF.any())
4407 I->setFastMathFlags(FMF);
4408 InstructionList.push_back(I);
4409 break;
4410 }
4411
4412 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4413 {
4414 unsigned Size = Record.size();
4415 if (Size == 0) {
4416 I = ReturnInst::Create(Context);
4417 InstructionList.push_back(I);
4418 break;
4419 }
4420
4421 unsigned OpNum = 0;
4422 Value *Op = nullptr;
4423 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4424 return error("Invalid record");
4425 if (OpNum != Record.size())
4426 return error("Invalid record");
4427
4428 I = ReturnInst::Create(Context, Op);
4429 InstructionList.push_back(I);
4430 break;
4431 }
4432 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4433 if (Record.size() != 1 && Record.size() != 3)
4434 return error("Invalid record");
4435 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4436 if (!TrueDest)
4437 return error("Invalid record");
4438
4439 if (Record.size() == 1) {
4440 I = BranchInst::Create(TrueDest);
4441 InstructionList.push_back(I);
4442 }
4443 else {
4444 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4445 Value *Cond = getValue(Record, 2, NextValueNo,
4446 Type::getInt1Ty(Context));
4447 if (!FalseDest || !Cond)
4448 return error("Invalid record");
4449 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4450 InstructionList.push_back(I);
4451 }
4452 break;
4453 }
4454 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4455 if (Record.size() != 1 && Record.size() != 2)
4456 return error("Invalid record");
4457 unsigned Idx = 0;
4458 Value *CleanupPad =
4459 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4460 if (!CleanupPad)
4461 return error("Invalid record");
4462 BasicBlock *UnwindDest = nullptr;
4463 if (Record.size() == 2) {
4464 UnwindDest = getBasicBlock(Record[Idx++]);
4465 if (!UnwindDest)
4466 return error("Invalid record");
4467 }
4468
4469 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4470 InstructionList.push_back(I);
4471 break;
4472 }
4473 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4474 if (Record.size() != 2)
4475 return error("Invalid record");
4476 unsigned Idx = 0;
4477 Value *CatchPad =
4478 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4479 if (!CatchPad)
4480 return error("Invalid record");
4481 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4482 if (!BB)
4483 return error("Invalid record");
4484
4485 I = CatchReturnInst::Create(CatchPad, BB);
4486 InstructionList.push_back(I);
4487 break;
4488 }
4489 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4490 // We must have, at minimum, the outer scope and the number of arguments.
4491 if (Record.size() < 2)
4492 return error("Invalid record");
4493
4494 unsigned Idx = 0;
4495
4496 Value *ParentPad =
4497 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4498
4499 unsigned NumHandlers = Record[Idx++];
4500
4501 SmallVector<BasicBlock *, 2> Handlers;
4502 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4503 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4504 if (!BB)
4505 return error("Invalid record");
4506 Handlers.push_back(BB);
4507 }
4508
4509 BasicBlock *UnwindDest = nullptr;
4510 if (Idx + 1 == Record.size()) {
4511 UnwindDest = getBasicBlock(Record[Idx++]);
4512 if (!UnwindDest)
4513 return error("Invalid record");
4514 }
4515
4516 if (Record.size() != Idx)
4517 return error("Invalid record");
4518
4519 auto *CatchSwitch =
4520 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4521 for (BasicBlock *Handler : Handlers)
4522 CatchSwitch->addHandler(Handler);
4523 I = CatchSwitch;
4524 InstructionList.push_back(I);
4525 break;
4526 }
4527 case bitc::FUNC_CODE_INST_CATCHPAD:
4528 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4529 // We must have, at minimum, the outer scope and the number of arguments.
4530 if (Record.size() < 2)
4531 return error("Invalid record");
4532
4533 unsigned Idx = 0;
4534
4535 Value *ParentPad =
4536 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4537
4538 unsigned NumArgOperands = Record[Idx++];
4539
4540 SmallVector<Value *, 2> Args;
4541 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4542 Value *Val;
4543 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4544 return error("Invalid record");
4545 Args.push_back(Val);
4546 }
4547
4548 if (Record.size() != Idx)
4549 return error("Invalid record");
4550
4551 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4552 I = CleanupPadInst::Create(ParentPad, Args);
4553 else
4554 I = CatchPadInst::Create(ParentPad, Args);
4555 InstructionList.push_back(I);
4556 break;
4557 }
4558 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4559 // Check magic
4560 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4561 // "New" SwitchInst format with case ranges. The changes to write this
4562 // format were reverted but we still recognize bitcode that uses it.
4563 // Hopefully someday we will have support for case ranges and can use
4564 // this format again.
4565
4566 Type *OpTy = getTypeByID(Record[1]);
4567 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4568
4569 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4570 BasicBlock *Default = getBasicBlock(Record[3]);
4571 if (!OpTy || !Cond || !Default)
4572 return error("Invalid record");
4573
4574 unsigned NumCases = Record[4];
4575
4576 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4577 InstructionList.push_back(SI);
4578
4579 unsigned CurIdx = 5;
4580 for (unsigned i = 0; i != NumCases; ++i) {
4581 SmallVector<ConstantInt*, 1> CaseVals;
4582 unsigned NumItems = Record[CurIdx++];
4583 for (unsigned ci = 0; ci != NumItems; ++ci) {
4584 bool isSingleNumber = Record[CurIdx++];
4585
4586 APInt Low;
4587 unsigned ActiveWords = 1;
4588 if (ValueBitWidth > 64)
4589 ActiveWords = Record[CurIdx++];
4590 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4591 ValueBitWidth);
4592 CurIdx += ActiveWords;
4593
4594 if (!isSingleNumber) {
4595 ActiveWords = 1;
4596 if (ValueBitWidth > 64)
4597 ActiveWords = Record[CurIdx++];
4598 APInt High = readWideAPInt(
4599 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4600 CurIdx += ActiveWords;
4601
4602 // FIXME: It is not clear whether values in the range should be
4603 // compared as signed or unsigned values. The partially
4604 // implemented changes that used this format in the past used
4605 // unsigned comparisons.
4606 for ( ; Low.ule(High); ++Low)
4607 CaseVals.push_back(ConstantInt::get(Context, Low));
4608 } else
4609 CaseVals.push_back(ConstantInt::get(Context, Low));
4610 }
4611 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4612 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4613 cve = CaseVals.end(); cvi != cve; ++cvi)
4614 SI->addCase(*cvi, DestBB);
4615 }
4616 I = SI;
4617 break;
4618 }
4619
4620 // Old SwitchInst format without case ranges.
4621
4622 if (Record.size() < 3 || (Record.size() & 1) == 0)
4623 return error("Invalid record");
4624 Type *OpTy = getTypeByID(Record[0]);
4625 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4626 BasicBlock *Default = getBasicBlock(Record[2]);
4627 if (!OpTy || !Cond || !Default)
4628 return error("Invalid record");
4629 unsigned NumCases = (Record.size()-3)/2;
4630 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4631 InstructionList.push_back(SI);
4632 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4633 ConstantInt *CaseVal =
4634 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4635 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4636 if (!CaseVal || !DestBB) {
4637 delete SI;
4638 return error("Invalid record");
4639 }
4640 SI->addCase(CaseVal, DestBB);
4641 }
4642 I = SI;
4643 break;
4644 }
4645 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4646 if (Record.size() < 2)
4647 return error("Invalid record");
4648 Type *OpTy = getTypeByID(Record[0]);
4649 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4650 if (!OpTy || !Address)
4651 return error("Invalid record");
4652 unsigned NumDests = Record.size()-2;
4653 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4654 InstructionList.push_back(IBI);
4655 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4656 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4657 IBI->addDestination(DestBB);
4658 } else {
4659 delete IBI;
4660 return error("Invalid record");
4661 }
4662 }
4663 I = IBI;
4664 break;
4665 }
4666
4667 case bitc::FUNC_CODE_INST_INVOKE: {
4668 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4669 if (Record.size() < 4)
4670 return error("Invalid record");
4671 unsigned OpNum = 0;
4672 AttributeList PAL = getAttributes(Record[OpNum++]);
4673 unsigned CCInfo = Record[OpNum++];
4674 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4675 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4676
4677 FunctionType *FTy = nullptr;
4678 FunctionType *FullFTy = nullptr;
4679 if ((CCInfo >> 13) & 1) {
4680 FullFTy =
4681 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4682 if (!FullFTy)
4683 return error("Explicit invoke type is not a function type");
4684 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4685 }
4686
4687 Value *Callee;
4688 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4689 return error("Invalid record");
4690
4691 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4692 if (!CalleeTy)
4693 return error("Callee is not a pointer");
4694 if (!FTy) {
4695 FullFTy =
4696 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4697 if (!FullFTy)
4698 return error("Callee is not of pointer to function type");
4699 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4700 } else if (getPointerElementFlatType(FullTy) != FTy)
4701 return error("Explicit invoke type does not match pointee type of "
4702 "callee operand");
4703 if (Record.size() < FTy->getNumParams() + OpNum)
4704 return error("Insufficient operands to call");
4705
4706 SmallVector<Value*, 16> Ops;
4707 SmallVector<Type *, 16> ArgsFullTys;
4708 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4709 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4710 FTy->getParamType(i)));
4711 ArgsFullTys.push_back(FullFTy->getParamType(i));
4712 if (!Ops.back())
4713 return error("Invalid record");
4714 }
4715
4716 if (!FTy->isVarArg()) {
4717 if (Record.size() != OpNum)
4718 return error("Invalid record");
4719 } else {
4720 // Read type/value pairs for varargs params.
4721 while (OpNum != Record.size()) {
4722 Value *Op;
4723 Type *FullTy;
4724 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
4725 return error("Invalid record");
4726 Ops.push_back(Op);
4727 ArgsFullTys.push_back(FullTy);
4728 }
4729 }
4730
4731 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4732 OperandBundles);
4733 FullTy = FullFTy->getReturnType();
4734 OperandBundles.clear();
4735 InstructionList.push_back(I);
4736 cast<InvokeInst>(I)->setCallingConv(
4737 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4738 cast<InvokeInst>(I)->setAttributes(PAL);
4739 propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys);
4740
4741 break;
4742 }
4743 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4744 unsigned Idx = 0;
4745 Value *Val = nullptr;
4746 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4747 return error("Invalid record");
4748 I = ResumeInst::Create(Val);
4749 InstructionList.push_back(I);
4750 break;
4751 }
4752 case bitc::FUNC_CODE_INST_CALLBR: {
4753 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4754 unsigned OpNum = 0;
4755 AttributeList PAL = getAttributes(Record[OpNum++]);
4756 unsigned CCInfo = Record[OpNum++];
4757
4758 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4759 unsigned NumIndirectDests = Record[OpNum++];
4760 SmallVector<BasicBlock *, 16> IndirectDests;
4761 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4762 IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4763
4764 FunctionType *FTy = nullptr;
4765 FunctionType *FullFTy = nullptr;
4766 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4767 FullFTy =
4768 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4769 if (!FullFTy)
4770 return error("Explicit call type is not a function type");
4771 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4772 }
4773
4774 Value *Callee;
4775 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4776 return error("Invalid record");
4777
4778 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4779 if (!OpTy)
4780 return error("Callee is not a pointer type");
4781 if (!FTy) {
4782 FullFTy =
4783 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4784 if (!FullFTy)
4785 return error("Callee is not of pointer to function type");
4786 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4787 } else if (getPointerElementFlatType(FullTy) != FTy)
4788 return error("Explicit call type does not match pointee type of "
4789 "callee operand");
4790 if (Record.size() < FTy->getNumParams() + OpNum)
4791 return error("Insufficient operands to call");
4792
4793 SmallVector<Value*, 16> Args;
4794 // Read the fixed params.
4795 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4796 if (FTy->getParamType(i)->isLabelTy())
4797 Args.push_back(getBasicBlock(Record[OpNum]));
4798 else
4799 Args.push_back(getValue(Record, OpNum, NextValueNo,
4800 FTy->getParamType(i)));
4801 if (!Args.back())
4802 return error("Invalid record");
4803 }
4804
4805 // Read type/value pairs for varargs params.
4806 if (!FTy->isVarArg()) {
4807 if (OpNum != Record.size())
4808 return error("Invalid record");
4809 } else {
4810 while (OpNum != Record.size()) {
4811 Value *Op;
4812 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4813 return error("Invalid record");
4814 Args.push_back(Op);
4815 }
4816 }
4817
4818 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4819 OperandBundles);
4820 FullTy = FullFTy->getReturnType();
4821 OperandBundles.clear();
4822 InstructionList.push_back(I);
4823 cast<CallBrInst>(I)->setCallingConv(
4824 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4825 cast<CallBrInst>(I)->setAttributes(PAL);
4826 break;
4827 }
4828 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4829 I = new UnreachableInst(Context);
4830 InstructionList.push_back(I);
4831 break;
4832 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4833 if (Record.empty())
4834 return error("Invalid record");
4835 // The first record specifies the type.
4836 FullTy = getFullyStructuredTypeByID(Record[0]);
4837 Type *Ty = flattenPointerTypes(FullTy);
4838 if (!Ty)
4839 return error("Invalid record");
4840
4841 // Phi arguments are pairs of records of [value, basic block].
4842 // There is an optional final record for fast-math-flags if this phi has a
4843 // floating-point type.
4844 size_t NumArgs = (Record.size() - 1) / 2;
4845 PHINode *PN = PHINode::Create(Ty, NumArgs);
4846 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
4847 return error("Invalid record");
4848 InstructionList.push_back(PN);
4849
4850 for (unsigned i = 0; i != NumArgs; i++) {
4851 Value *V;
4852 // With the new function encoding, it is possible that operands have
4853 // negative IDs (for forward references). Use a signed VBR
4854 // representation to keep the encoding small.
4855 if (UseRelativeIDs)
4856 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty);
4857 else
4858 V = getValue(Record, i * 2 + 1, NextValueNo, Ty);
4859 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
4860 if (!V || !BB)
4861 return error("Invalid record");
4862 PN->addIncoming(V, BB);
4863 }
4864 I = PN;
4865
4866 // If there are an even number of records, the final record must be FMF.
4867 if (Record.size() % 2 == 0) {
4868 assert(isa<FPMathOperator>(I) && "Unexpected phi type")(static_cast <bool> (isa<FPMathOperator>(I) &&
"Unexpected phi type") ? void (0) : __assert_fail ("isa<FPMathOperator>(I) && \"Unexpected phi type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4868, __extension__ __PRETTY_FUNCTION__))
;
4869 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
4870 if (FMF.any())
4871 I->setFastMathFlags(FMF);
4872 }
4873
4874 break;
4875 }
4876
4877 case bitc::FUNC_CODE_INST_LANDINGPAD:
4878 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4879 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4880 unsigned Idx = 0;
4881 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4882 if (Record.size() < 3)
4883 return error("Invalid record");
4884 } else {
4885 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD)(static_cast <bool> (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD
) ? void (0) : __assert_fail ("BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4885, __extension__ __PRETTY_FUNCTION__))
;
4886 if (Record.size() < 4)
4887 return error("Invalid record");
4888 }
4889 FullTy = getFullyStructuredTypeByID(Record[Idx++]);
4890 Type *Ty = flattenPointerTypes(FullTy);
4891 if (!Ty)
4892 return error("Invalid record");
4893 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4894 Value *PersFn = nullptr;
4895 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4896 return error("Invalid record");
4897
4898 if (!F->hasPersonalityFn())
4899 F->setPersonalityFn(cast<Constant>(PersFn));
4900 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4901 return error("Personality function mismatch");
4902 }
4903
4904 bool IsCleanup = !!Record[Idx++];
4905 unsigned NumClauses = Record[Idx++];
4906 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4907 LP->setCleanup(IsCleanup);
4908 for (unsigned J = 0; J != NumClauses; ++J) {
4909 LandingPadInst::ClauseType CT =
4910 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4911 Value *Val;
4912
4913 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4914 delete LP;
4915 return error("Invalid record");
4916 }
4917
4918 assert((CT != LandingPadInst::Catch ||(static_cast <bool> ((CT != LandingPadInst::Catch || !isa
<ArrayType>(Val->getType())) && "Catch clause has a invalid type!"
) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4920, __extension__ __PRETTY_FUNCTION__))
4919 !isa<ArrayType>(Val->getType())) &&(static_cast <bool> ((CT != LandingPadInst::Catch || !isa
<ArrayType>(Val->getType())) && "Catch clause has a invalid type!"
) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4920, __extension__ __PRETTY_FUNCTION__))
4920 "Catch clause has a invalid type!")(static_cast <bool> ((CT != LandingPadInst::Catch || !isa
<ArrayType>(Val->getType())) && "Catch clause has a invalid type!"
) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4920, __extension__ __PRETTY_FUNCTION__))
;
4921 assert((CT != LandingPadInst::Filter ||(static_cast <bool> ((CT != LandingPadInst::Filter || isa
<ArrayType>(Val->getType())) && "Filter clause has invalid type!"
) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4923, __extension__ __PRETTY_FUNCTION__))
4922 isa<ArrayType>(Val->getType())) &&(static_cast <bool> ((CT != LandingPadInst::Filter || isa
<ArrayType>(Val->getType())) && "Filter clause has invalid type!"
) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4923, __extension__ __PRETTY_FUNCTION__))
4923 "Filter clause has invalid type!")(static_cast <bool> ((CT != LandingPadInst::Filter || isa
<ArrayType>(Val->getType())) && "Filter clause has invalid type!"
) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 4923, __extension__ __PRETTY_FUNCTION__))
;
4924 LP->addClause(cast<Constant>(Val));
4925 }
4926
4927 I = LP;
4928 InstructionList.push_back(I);
4929 break;
4930 }
4931
4932 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4933 if (Record.size() != 4)
4934 return error("Invalid record");
4935 using APV = AllocaPackedValues;
4936 const uint64_t Rec = Record[3];
4937 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
4938 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
4939 FullTy = getFullyStructuredTypeByID(Record[0]);
4940 Type *Ty = flattenPointerTypes(FullTy);
4941 if (!Bitfield::get<APV::ExplicitType>(Rec)) {
4942 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4943 if (!PTy)
4944 return error("Old-style alloca with a non-pointer type");
4945 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4946 }
4947 Type *OpTy = getTypeByID(Record[1]);
4948 Value *Size = getFnValueByID(Record[2], OpTy);
4949 MaybeAlign Align;
4950 if (Error Err =
4951 parseAlignmentValue(Bitfield::get<APV::Align>(Rec), Align)) {
4952 return Err;
4953 }
4954 if (!Ty || !Size)
4955 return error("Invalid record");
4956
4957 // FIXME: Make this an optional field.
4958 const DataLayout &DL = TheModule->getDataLayout();
4959 unsigned AS = DL.getAllocaAddrSpace();
4960
4961 SmallPtrSet<Type *, 4> Visited;
4962 if (!Align && !Ty->isSized(&Visited))
4963 return error("alloca of unsized type");
4964 if (!Align)
4965 Align = DL.getPrefTypeAlign(Ty);
4966
4967 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
4968 AI->setUsedWithInAlloca(InAlloca);
4969 AI->setSwiftError(SwiftError);
4970 I = AI;
4971 FullTy = PointerType::get(FullTy, AS);
4972 InstructionList.push_back(I);
4973 break;
4974 }
4975 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4976 unsigned OpNum = 0;
4977 Value *Op;
4978 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
4979 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4980 return error("Invalid record");
4981
4982 if (!isa<PointerType>(Op->getType()))
4983 return error("Load operand is not a pointer type");
4984
4985 Type *Ty = nullptr;
4986 if (OpNum + 3 == Record.size()) {
4987 FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4988 Ty = flattenPointerTypes(FullTy);
4989 } else
4990 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4991
4992 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4993 return Err;
4994
4995 MaybeAlign Align;
4996 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4997 return Err;
4998 SmallPtrSet<Type *, 4> Visited;
4999 if (!Align && !Ty->isSized(&Visited))
5000 return error("load of unsized type");
5001 if (!Align)
5002 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
5003 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5004 InstructionList.push_back(I);
5005 break;
5006 }
5007 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5008 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5009 unsigned OpNum = 0;
5010 Value *Op;
5011 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
5012 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5013 return error("Invalid record");
5014
5015 if (!isa<PointerType>(Op->getType()))
5016 return error("Load operand is not a pointer type");
5017
5018 Type *Ty = nullptr;
5019 if (OpNum + 5 == Record.size()) {
5020 FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
5021 Ty = flattenPointerTypes(FullTy);
5022 } else
5023 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
5024
5025 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5026 return Err;
5027
5028 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5029 if (Ordering == AtomicOrdering::NotAtomic ||
5030 Ordering == AtomicOrdering::Release ||
5031 Ordering == AtomicOrdering::AcquireRelease)
5032 return error("Invalid record");
5033 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5034 return error("Invalid record");
5035 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5036
5037 MaybeAlign Align;
5038 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5039 return Err;
5040 if (!Align)
5041 return error("Alignment missing from atomic load");
5042 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5043 InstructionList.push_back(I);
5044 break;
5045 }
5046 case bitc::FUNC_CODE_INST_STORE:
5047 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5048 unsigned OpNum = 0;
5049 Value *Val, *Ptr;
5050 Type *FullTy;
5051 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
5052 (BitCode == bitc::FUNC_CODE_INST_STORE
5053 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5054 : popValue(Record, OpNum, NextValueNo,
5055 getPointerElementFlatType(FullTy), Val)) ||
5056 OpNum + 2 != Record.size())
5057 return error("Invalid record");
5058
5059 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5060 return Err;
5061 MaybeAlign Align;
5062 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5063 return Err;
5064 SmallPtrSet<Type *, 4> Visited;
5065 if (!Align && !Val->getType()->isSized(&Visited))
5066 return error("store of unsized type");
5067 if (!Align)
5068 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
5069 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5070 InstructionList.push_back(I);
5071 break;
5072 }
5073 case bitc::FUNC_CODE_INST_STOREATOMIC:
5074 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5075 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5076 unsigned OpNum = 0;
5077 Value *Val, *Ptr;
5078 Type *FullTy;
5079 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
5080 !isa<PointerType>(Ptr->getType()) ||
5081 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5082 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5083 : popValue(Record, OpNum, NextValueNo,
5084 getPointerElementFlatType(FullTy), Val)) ||
5085 OpNum + 4 != Record.size())
5086 return error("Invalid record");
5087
5088 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5089 return Err;
5090 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5091 if (Ordering == AtomicOrdering::NotAtomic ||
5092 Ordering == AtomicOrdering::Acquire ||
5093 Ordering == AtomicOrdering::AcquireRelease)
5094 return error("Invalid record");
5095 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5096 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5097 return error("Invalid record");
5098
5099 MaybeAlign Align;
5100 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5101 return Err;
5102 if (!Align)
5103 return error("Alignment missing from atomic store");
5104 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5105 InstructionList.push_back(I);
5106 break;
5107 }
5108 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5109 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5110 // failure_ordering?, weak?]
5111 const size_t NumRecords = Record.size();
5112 unsigned OpNum = 0;
5113 Value *Ptr = nullptr;
5114 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5115 return error("Invalid record");
5116
5117 if (!isa<PointerType>(Ptr->getType()))
5118 return error("Cmpxchg operand is not a pointer type");
5119
5120 Value *Cmp = nullptr;
5121 if (popValue(Record, OpNum, NextValueNo,
5122 getPointerElementFlatType(FullTy), Cmp))
5123 return error("Invalid record");
5124
5125 FullTy = cast<PointerType>(FullTy)->getElementType();
5126
5127 Value *New = nullptr;
5128 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5129 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5130 return error("Invalid record");
5131
5132 const AtomicOrdering SuccessOrdering =
5133 getDecodedOrdering(Record[OpNum + 1]);
5134 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5135 SuccessOrdering == AtomicOrdering::Unordered)
5136 return error("Invalid record");
5137
5138 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5139
5140 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5141 return Err;
5142
5143 const AtomicOrdering FailureOrdering =
5144 NumRecords < 7
5145 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5146 : getDecodedOrdering(Record[OpNum + 3]);
5147
5148 if (FailureOrdering == AtomicOrdering::NotAtomic ||
5149 FailureOrdering == AtomicOrdering::Unordered)
5150 return error("Invalid record");
5151
5152 const Align Alignment(
5153 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5154
5155 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
5156 FailureOrdering, SSID);
5157 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5158 FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
5159
5160 if (NumRecords < 8) {
5161 // Before weak cmpxchgs existed, the instruction simply returned the
5162 // value loaded from memory, so bitcode files from that era will be
5163 // expecting the first component of a modern cmpxchg.
5164 CurBB->getInstList().push_back(I);
5165 I = ExtractValueInst::Create(I, 0);
5166 FullTy = cast<StructType>(FullTy)->getElementType(0);
5167 } else {
5168 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5169 }
5170
5171 InstructionList.push_back(I);
5172 break;
5173 }
5174 case bitc::FUNC_CODE_INST_CMPXCHG: {
5175 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5176 // failure_ordering, weak, align?]
5177 const size_t NumRecords = Record.size();
5178 unsigned OpNum = 0;
5179 Value *Ptr = nullptr;
5180 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5181 return error("Invalid record");
5182
5183 if (!isa<PointerType>(Ptr->getType()))
5184 return error("Cmpxchg operand is not a pointer type");
5185
5186 Value *Cmp = nullptr;
5187 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, &FullTy))
5188 return error("Invalid record");
5189
5190 Value *Val = nullptr;
5191 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val))
5192 return error("Invalid record");
5193
5194 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5195 return error("Invalid record");
5196
5197 const bool IsVol = Record[OpNum];
5198
5199 const AtomicOrdering SuccessOrdering =
5200 getDecodedOrdering(Record[OpNum + 1]);
5201 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5202 return error("Invalid cmpxchg success ordering");
5203
5204 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5205
5206 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5207 return Err;
5208
5209 const AtomicOrdering FailureOrdering =
5210 getDecodedOrdering(Record[OpNum + 3]);
5211 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5212 return error("Invalid cmpxchg failure ordering");
5213
5214 const bool IsWeak = Record[OpNum + 4];
5215
5216 MaybeAlign Alignment;
5217
5218 if (NumRecords == (OpNum + 6)) {
5219 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5220 return Err;
5221 }
5222 if (!Alignment)
5223 Alignment =
5224 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5225
5226 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5227 FailureOrdering, SSID);
5228 FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
5229 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5230 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5231
5232 InstructionList.push_back(I);
5233 break;
5234 }
5235 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
5236 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5237 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
5238 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
5239 const size_t NumRecords = Record.size();
5240 unsigned OpNum = 0;
5241
5242 Value *Ptr = nullptr;
5243 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5244 return error("Invalid record");
5245
5246 if (!isa<PointerType>(Ptr->getType()))
5247 return error("Invalid record");
5248
5249 Value *Val = nullptr;
5250 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
5251 if (popValue(Record, OpNum, NextValueNo,
5252 getPointerElementFlatType(FullTy), Val))
5253 return error("Invalid record");
5254 FullTy = getPointerElementFlatType(FullTy);
5255 } else {
5256 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
5257 return error("Invalid record");
5258 FullTy = Val->getType();
5259 }
5260
5261 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5262 return error("Invalid record");
5263
5264 const AtomicRMWInst::BinOp Operation =
5265 getDecodedRMWOperation(Record[OpNum]);
5266 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5267 Operation > AtomicRMWInst::LAST_BINOP)
5268 return error("Invalid record");
5269
5270 const bool IsVol = Record[OpNum + 1];
5271
5272 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5273 if (Ordering == AtomicOrdering::NotAtomic ||
5274 Ordering == AtomicOrdering::Unordered)
5275 return error("Invalid record");
5276
5277 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5278
5279 MaybeAlign Alignment;
5280
5281 if (NumRecords == (OpNum + 5)) {
5282 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5283 return Err;
5284 }
5285
5286 if (!Alignment)
5287 Alignment =
5288 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5289
5290 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5291 cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5292
5293 InstructionList.push_back(I);
5294 break;
5295 }
5296 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5297 if (2 != Record.size())
5298 return error("Invalid record");
5299 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5300 if (Ordering == AtomicOrdering::NotAtomic ||
5301 Ordering == AtomicOrdering::Unordered ||
5302 Ordering == AtomicOrdering::Monotonic)
5303 return error("Invalid record");
5304 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5305 I = new FenceInst(Context, Ordering, SSID);
5306 InstructionList.push_back(I);
5307 break;
5308 }
5309 case bitc::FUNC_CODE_INST_CALL: {
5310 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5311 if (Record.size() < 3)
5312 return error("Invalid record");
5313
5314 unsigned OpNum = 0;
5315 AttributeList PAL = getAttributes(Record[OpNum++]);
5316 unsigned CCInfo = Record[OpNum++];
5317
5318 FastMathFlags FMF;
5319 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5320 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5321 if (!FMF.any())
5322 return error("Fast math flags indicator set for call with no FMF");
5323 }
5324
5325 FunctionType *FTy = nullptr;
5326 FunctionType *FullFTy = nullptr;
5327 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5328 FullFTy =
5329 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
5330 if (!FullFTy)
5331 return error("Explicit call type is not a function type");
5332 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
5333 }
5334
5335 Value *Callee;
5336 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
5337 return error("Invalid record");
5338
5339 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5340 if (!OpTy)
5341 return error("Callee is not a pointer type");
5342 if (!FTy) {
5343 FullFTy =
5344 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
5345 if (!FullFTy)
5346 return error("Callee is not of pointer to function type");
5347 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
5348 } else if (getPointerElementFlatType(FullTy) != FTy)
5349 return error("Explicit call type does not match pointee type of "
5350 "callee operand");
5351 if (Record.size() < FTy->getNumParams() + OpNum)
5352 return error("Insufficient operands to call");
5353
5354 SmallVector<Value*, 16> Args;
5355 SmallVector<Type*, 16> ArgsFullTys;
5356 // Read the fixed params.
5357 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5358 if (FTy->getParamType(i)->isLabelTy())
5359 Args.push_back(getBasicBlock(Record[OpNum]));
5360 else
5361 Args.push_back(getValue(Record, OpNum, NextValueNo,
5362 FTy->getParamType(i)));
5363 ArgsFullTys.push_back(FullFTy->getParamType(i));
5364 if (!Args.back())
5365 return error("Invalid record");
5366 }
5367
5368 // Read type/value pairs for varargs params.
5369 if (!FTy->isVarArg()) {
5370 if (OpNum != Record.size())
5371 return error("Invalid record");
5372 } else {
5373 while (OpNum != Record.size()) {
5374 Value *Op;
5375 Type *FullTy;
5376 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5377 return error("Invalid record");
5378 Args.push_back(Op);
5379 ArgsFullTys.push_back(FullTy);
5380 }
5381 }
5382
5383 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5384 FullTy = FullFTy->getReturnType();
5385 OperandBundles.clear();
5386 InstructionList.push_back(I);
5387 cast<CallInst>(I)->setCallingConv(
5388 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5389 CallInst::TailCallKind TCK = CallInst::TCK_None;
5390 if (CCInfo & 1 << bitc::CALL_TAIL)
5391 TCK = CallInst::TCK_Tail;
5392 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5393 TCK = CallInst::TCK_MustTail;
5394 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5395 TCK = CallInst::TCK_NoTail;
5396 cast<CallInst>(I)->setTailCallKind(TCK);
5397 cast<CallInst>(I)->setAttributes(PAL);
5398 propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys);
5399 if (FMF.any()) {
5400 if (!isa<FPMathOperator>(I))
5401 return error("Fast-math-flags specified for call without "
5402 "floating-point scalar or vector return type");
5403 I->setFastMathFlags(FMF);
5404 }
5405 break;
5406 }
5407 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5408 if (Record.size() < 3)
5409 return error("Invalid record");
5410 Type *OpTy = getTypeByID(Record[0]);
5411 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5412 FullTy = getFullyStructuredTypeByID(Record[2]);
5413 Type *ResTy = flattenPointerTypes(FullTy);
5414 if (!OpTy || !Op || !ResTy)
5415 return error("Invalid record");
5416 I = new VAArgInst(Op, ResTy);
5417 InstructionList.push_back(I);
5418 break;
5419 }
5420
5421 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5422 // A call or an invoke can be optionally prefixed with some variable
5423 // number of operand bundle blocks. These blocks are read into
5424 // OperandBundles and consumed at the next call or invoke instruction.
5425
5426 if (Record.empty() || Record[0] >= BundleTags.size())
5427 return error("Invalid record");
5428
5429 std::vector<Value *> Inputs;
5430
5431 unsigned OpNum = 1;
5432 while (OpNum != Record.size()) {
5433 Value *Op;
5434 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5435 return error("Invalid record");
5436 Inputs.push_back(Op);
5437 }
5438
5439 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5440 continue;
5441 }
5442
5443 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5444 unsigned OpNum = 0;
5445 Value *Op = nullptr;
5446 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5447 return error("Invalid record");
5448 if (OpNum != Record.size())
5449 return error("Invalid record");
5450
5451 I = new FreezeInst(Op);
5452 InstructionList.push_back(I);
5453 break;
5454 }
5455 }
5456
5457 // Add instruction to end of current BB. If there is no current BB, reject
5458 // this file.
5459 if (!CurBB) {
5460 I->deleteValue();
5461 return error("Invalid instruction with no BB");
5462 }
5463 if (!OperandBundles.empty()) {
5464 I->deleteValue();
5465 return error("Operand bundles found with no consumer");
5466 }
5467 CurBB->getInstList().push_back(I);
5468
5469 // If this was a terminator instruction, move to the next block.
5470 if (I->isTerminator()) {
5471 ++CurBBNo;
5472 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5473 }
5474
5475 // Non-void values get registered in the value table for future use.
5476 if (!I->getType()->isVoidTy()) {
5477 if (!FullTy) {
5478 FullTy = I->getType();
5479 assert((static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5480 !FullTy->isPointerTy() && !isa<StructType>(FullTy) &&(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5481 !isa<ArrayType>(FullTy) &&(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5482 (!isa<VectorType>(FullTy) ||(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5483 cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() ||(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5484 cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) &&(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5485 "Structured types must be assigned with corresponding non-opaque "(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5486 "pointer type")(static_cast <bool> (!FullTy->isPointerTy() &&
!isa<StructType>(FullTy) && !isa<ArrayType>
(FullTy) && (!isa<VectorType>(FullTy) || cast<
VectorType>(FullTy)->getElementType()->isFloatingPointTy
() || cast<VectorType>(FullTy)->getElementType()->
isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque "
"pointer type") ? void (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() || cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
;
5487 }
5488
5489 assert(I->getType() == flattenPointerTypes(FullTy) &&(static_cast <bool> (I->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully structured type provided for Instruction"
) ? void (0) : __assert_fail ("I->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for Instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5490, __extension__ __PRETTY_FUNCTION__))
5490 "Incorrect fully structured type provided for Instruction")(static_cast <bool> (I->getType() == flattenPointerTypes
(FullTy) && "Incorrect fully structured type provided for Instruction"
) ? void (0) : __assert_fail ("I->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for Instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5490, __extension__ __PRETTY_FUNCTION__))
;
5491 ValueList.assignValue(I, NextValueNo++, FullTy);
5492 }
5493 }
5494
5495OutOfRecordLoop:
5496
5497 if (!OperandBundles.empty())
5498 return error("Operand bundles found with no consumer");
5499
5500 // Check the function list for unresolved values.
5501 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5502 if (!A->getParent()) {
5503 // We found at least one unresolved value. Nuke them all to avoid leaks.
5504 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5505 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5506 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5507 delete A;
5508 }
5509 }
5510 return error("Never resolved value found in function");
5511 }
5512 }
5513
5514 // Unexpected unresolved metadata about to be dropped.
5515 if (MDLoader->hasFwdRefs())
5516 return error("Invalid function metadata: outgoing forward refs");
5517
5518 // Trim the value list down to the size it was before we parsed this function.
5519 ValueList.shrinkTo(ModuleValueListSize);
5520 MDLoader->shrinkTo(ModuleMDLoaderSize);
5521 std::vector<BasicBlock*>().swap(FunctionBBs);
5522 return Error::success();
5523}
5524
5525/// Find the function body in the bitcode stream
5526Error BitcodeReader::findFunctionInStream(
5527 Function *F,
5528 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5529 while (DeferredFunctionInfoIterator->second == 0) {
5530 // This is the fallback handling for the old format bitcode that
5531 // didn't contain the function index in the VST, or when we have
5532 // an anonymous function which would not have a VST entry.
5533 // Assert that we have one of those two cases.
5534 assert(VSTOffset == 0 || !F->hasName())(static_cast <bool> (VSTOffset == 0 || !F->hasName()
) ? void (0) : __assert_fail ("VSTOffset == 0 || !F->hasName()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5534, __extension__ __PRETTY_FUNCTION__))
;
5535 // Parse the next body in the stream and set its position in the
5536 // DeferredFunctionInfo map.
5537 if (Error Err = rememberAndSkipFunctionBodies())
5538 return Err;
5539 }
5540 return Error::success();
5541}
5542
5543SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5544 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5545 return SyncScope::ID(Val);
5546 if (Val >= SSIDs.size())
5547 return SyncScope::System; // Map unknown synchronization scopes to system.
5548 return SSIDs[Val];
5549}
5550
5551//===----------------------------------------------------------------------===//
5552// GVMaterializer implementation
5553//===----------------------------------------------------------------------===//
5554
5555Error BitcodeReader::materialize(GlobalValue *GV) {
5556 Function *F = dyn_cast<Function>(GV);
5557 // If it's not a function or is already material, ignore the request.
5558 if (!F || !F->isMaterializable())
5559 return Error::success();
5560
5561 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5562 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!")(static_cast <bool> (DFII != DeferredFunctionInfo.end()
&& "Deferred function not found!") ? void (0) : __assert_fail
("DFII != DeferredFunctionInfo.end() && \"Deferred function not found!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5562, __extension__ __PRETTY_FUNCTION__))
;
5563 // If its position is recorded as 0, its body is somewhere in the stream
5564 // but we haven't seen it yet.
5565 if (DFII->second == 0)
5566 if (Error Err = findFunctionInStream(F, DFII))
5567 return Err;
5568
5569 // Materialize metadata before parsing any function bodies.
5570 if (Error Err = materializeMetadata())
5571 return Err;
5572
5573 // Move the bit stream to the saved position of the deferred function body.
5574 if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5575 return JumpFailed;
5576 if (Error Err = parseFunctionBody(F))
5577 return Err;
5578 F->setIsMaterializable(false);
5579
5580 if (StripDebugInfo)
5581 stripDebugInfo(*F);
5582
5583 // Upgrade any old intrinsic calls in the function.
5584 for (auto &I : UpgradedIntrinsics) {
5585 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5586 UI != UE;) {
5587 User *U = *UI;
5588 ++UI;
5589 if (CallInst *CI = dyn_cast<CallInst>(U))
5590 UpgradeIntrinsicCall(CI, I.second);
5591 }
5592 }
5593
5594 // Update calls to the remangled intrinsics
5595 for (auto &I : RemangledIntrinsics)
5596 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5597 UI != UE;)
5598 // Don't expect any other users than call sites
5599 cast<CallBase>(*UI++)->setCalledFunction(I.second);
5600
5601 // Finish fn->subprogram upgrade for materialized functions.
5602 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5603 F->setSubprogram(SP);
5604
5605 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5606 if (!MDLoader->isStrippingTBAA()) {
5607 for (auto &I : instructions(F)) {
5608 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5609 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5610 continue;
5611 MDLoader->setStripTBAA(true);
5612 stripTBAA(F->getParent());
5613 }
5614 }
5615
5616 for (auto &I : instructions(F)) {
5617 // "Upgrade" older incorrect branch weights by dropping them.
5618 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5619 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5620 MDString *MDS = cast<MDString>(MD->getOperand(0));
5621 StringRef ProfName = MDS->getString();
5622 // Check consistency of !prof branch_weights metadata.
5623 if (!ProfName.equals("branch_weights"))
5624 continue;
5625 unsigned ExpectedNumOperands = 0;
5626 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5627 ExpectedNumOperands = BI->getNumSuccessors();
5628 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5629 ExpectedNumOperands = SI->getNumSuccessors();
5630 else if (isa<CallInst>(&I))
5631 ExpectedNumOperands = 1;
5632 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5633 ExpectedNumOperands = IBI->getNumDestinations();
5634 else if (isa<SelectInst>(&I))
5635 ExpectedNumOperands = 2;
5636 else
5637 continue; // ignore and continue.
5638
5639 // If branch weight doesn't match, just strip branch weight.
5640 if (MD->getNumOperands() != 1 + ExpectedNumOperands)
5641 I.setMetadata(LLVMContext::MD_prof, nullptr);
5642 }
5643 }
5644
5645 // Remove incompatible attributes on function calls.
5646 if (auto *CI = dyn_cast<CallBase>(&I)) {
5647 CI->removeAttributes(AttributeList::ReturnIndex,
5648 AttributeFuncs::typeIncompatible(
5649 CI->getFunctionType()->getReturnType()));
5650
5651 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
5652 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
5653 CI->getArgOperand(ArgNo)->getType()));
5654 }
5655 }
5656
5657 // Look for functions that rely on old function attribute behavior.
5658 UpgradeFunctionAttributes(*F);
5659
5660 // Bring in any functions that this function forward-referenced via
5661 // blockaddresses.
5662 return materializeForwardReferencedFunctions();
5663}
5664
5665Error BitcodeReader::materializeModule() {
5666 if (Error Err = materializeMetadata())
5667 return Err;
5668
5669 // Promise to materialize all forward references.
5670 WillMaterializeAllForwardRefs = true;
5671
5672 // Iterate over the module, deserializing any functions that are still on
5673 // disk.
5674 for (Function &F : *TheModule) {
5675 if (Error Err = materialize(&F))
5676 return Err;
5677 }
5678 // At this point, if there are any function bodies, parse the rest of
5679 // the bits in the module past the last function block we have recorded
5680 // through either lazy scanning or the VST.
5681 if (LastFunctionBlockBit || NextUnreadBit)
5682 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
5683 ? LastFunctionBlockBit
5684 : NextUnreadBit))
5685 return Err;
5686
5687 // Check that all block address forward references got resolved (as we
5688 // promised above).
5689 if (!BasicBlockFwdRefs.empty())
5690 return error("Never resolved function from blockaddress");
5691
5692 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5693 // delete the old functions to clean up. We can't do this unless the entire
5694 // module is materialized because there could always be another function body
5695 // with calls to the old function.
5696 for (auto &I : UpgradedIntrinsics) {
5697 for (auto *U : I.first->users()) {
5698 if (CallInst *CI = dyn_cast<CallInst>(U))
5699 UpgradeIntrinsicCall(CI, I.second);
5700 }
5701 if (!I.first->use_empty())
5702 I.first->replaceAllUsesWith(I.second);
5703 I.first->eraseFromParent();
5704 }
5705 UpgradedIntrinsics.clear();
5706 // Do the same for remangled intrinsics
5707 for (auto &I : RemangledIntrinsics) {
5708 I.first->replaceAllUsesWith(I.second);
5709 I.first->eraseFromParent();
5710 }
5711 RemangledIntrinsics.clear();
5712
5713 UpgradeDebugInfo(*TheModule);
5714
5715 UpgradeModuleFlags(*TheModule);
5716
5717 UpgradeARCRuntime(*TheModule);
5718
5719 return Error::success();
5720}
5721
5722std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5723 return IdentifiedStructTypes;
5724}
5725
5726ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5727 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5728 StringRef ModulePath, unsigned ModuleId)
5729 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5730 ModulePath(ModulePath), ModuleId(ModuleId) {}
5731
5732void ModuleSummaryIndexBitcodeReader::addThisModule() {
5733 TheIndex.addModule(ModulePath, ModuleId);
5734}
5735
5736ModuleSummaryIndex::ModuleInfo *
5737ModuleSummaryIndexBitcodeReader::getThisModule() {
5738 return TheIndex.getModule(ModulePath);
5739}
5740
5741std::pair<ValueInfo, GlobalValue::GUID>
5742ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5743 auto VGI = ValueIdToValueInfoMap[ValueId];
5744 assert(VGI.first)(static_cast <bool> (VGI.first) ? void (0) : __assert_fail
("VGI.first", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5744, __extension__ __PRETTY_FUNCTION__))
;
5745 return VGI;
5746}
5747
5748void ModuleSummaryIndexBitcodeReader::setValueGUID(
5749 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5750 StringRef SourceFileName) {
5751 std::string GlobalId =
5752 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5753 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5754 auto OriginalNameID = ValueGUID;
5755 if (GlobalValue::isLocalLinkage(Linkage))
5756 OriginalNameID = GlobalValue::getGUID(ValueName);
5757 if (PrintSummaryGUIDs)
5758 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5759 << ValueName << "\n";
5760
5761 // UseStrtab is false for legacy summary formats and value names are
5762 // created on stack. In that case we save the name in a string saver in
5763 // the index so that the value name can be recorded.
5764 ValueIdToValueInfoMap[ValueID] = std::make_pair(
5765 TheIndex.getOrInsertValueInfo(
5766 ValueGUID,
5767 UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5768 OriginalNameID);
5769}
5770
5771// Specialized value symbol table parser used when reading module index
5772// blocks where we don't actually create global values. The parsed information
5773// is saved in the bitcode reader for use when later parsing summaries.
5774Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5775 uint64_t Offset,
5776 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5777 // With a strtab the VST is not required to parse the summary.
5778 if (UseStrtab)
5779 return Error::success();
5780
5781 assert(Offset > 0 && "Expected non-zero VST offset")(static_cast <bool> (Offset > 0 && "Expected non-zero VST offset"
) ? void (0) : __assert_fail ("Offset > 0 && \"Expected non-zero VST offset\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5781, __extension__ __PRETTY_FUNCTION__))
;
5782 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5783 if (!MaybeCurrentBit)
5784 return MaybeCurrentBit.takeError();
5785 uint64_t CurrentBit = MaybeCurrentBit.get();
5786
5787 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5788 return Err;
5789
5790 SmallVector<uint64_t, 64> Record;
5791
5792 // Read all the records for this value table.
5793 SmallString<128> ValueName;
5794
5795 while (true) {
5796 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5797 if (!MaybeEntry)
5798 return MaybeEntry.takeError();
5799 BitstreamEntry Entry = MaybeEntry.get();
5800
5801 switch (Entry.Kind) {
5802 case BitstreamEntry::SubBlock: // Handled for us already.
5803 case BitstreamEntry::Error:
5804 return error("Malformed block");
5805 case BitstreamEntry::EndBlock:
5806 // Done parsing VST, jump back to wherever we came from.
5807 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5808 return JumpFailed;
5809 return Error::success();
5810 case BitstreamEntry::Record:
5811 // The interesting case.
5812 break;
5813 }
5814
5815 // Read a record.
5816 Record.clear();
5817 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5818 if (!MaybeRecord)
5819 return MaybeRecord.takeError();
5820 switch (MaybeRecord.get()) {
5821 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5822 break;
5823 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5824 if (convertToString(Record, 1, ValueName))
5825 return error("Invalid record");
5826 unsigned ValueID = Record[0];
5827 assert(!SourceFileName.empty())(static_cast <bool> (!SourceFileName.empty()) ? void (0
) : __assert_fail ("!SourceFileName.empty()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5827, __extension__ __PRETTY_FUNCTION__))
;
5828 auto VLI = ValueIdToLinkageMap.find(ValueID);
5829 assert(VLI != ValueIdToLinkageMap.end() &&(static_cast <bool> (VLI != ValueIdToLinkageMap.end() &&
"No linkage found for VST entry?") ? void (0) : __assert_fail
("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5830, __extension__ __PRETTY_FUNCTION__))
5830 "No linkage found for VST entry?")(static_cast <bool> (VLI != ValueIdToLinkageMap.end() &&
"No linkage found for VST entry?") ? void (0) : __assert_fail
("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5830, __extension__ __PRETTY_FUNCTION__))
;
5831 auto Linkage = VLI->second;
5832 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5833 ValueName.clear();
5834 break;
5835 }
5836 case bitc::VST_CODE_FNENTRY: {
5837 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5838 if (convertToString(Record, 2, ValueName))
5839 return error("Invalid record");
5840 unsigned ValueID = Record[0];
5841 assert(!SourceFileName.empty())(static_cast <bool> (!SourceFileName.empty()) ? void (0
) : __assert_fail ("!SourceFileName.empty()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5841, __extension__ __PRETTY_FUNCTION__))
;
5842 auto VLI = ValueIdToLinkageMap.find(ValueID);
5843 assert(VLI != ValueIdToLinkageMap.end() &&(static_cast <bool> (VLI != ValueIdToLinkageMap.end() &&
"No linkage found for VST entry?") ? void (0) : __assert_fail
("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5844, __extension__ __PRETTY_FUNCTION__))
5844 "No linkage found for VST entry?")(static_cast <bool> (VLI != ValueIdToLinkageMap.end() &&
"No linkage found for VST entry?") ? void (0) : __assert_fail
("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5844, __extension__ __PRETTY_FUNCTION__))
;
5845 auto Linkage = VLI->second;
5846 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5847 ValueName.clear();
5848 break;
5849 }
5850 case bitc::VST_CODE_COMBINED_ENTRY: {
5851 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5852 unsigned ValueID = Record[0];
5853 GlobalValue::GUID RefGUID = Record[1];
5854 // The "original name", which is the second value of the pair will be
5855 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5856 ValueIdToValueInfoMap[ValueID] =
5857 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5858 break;
5859 }
5860 }
5861 }
5862}
5863
5864// Parse just the blocks needed for building the index out of the module.
5865// At the end of this routine the module Index is populated with a map
5866// from global value id to GlobalValueSummary objects.
5867Error ModuleSummaryIndexBitcodeReader::parseModule() {
5868 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5869 return Err;
5870
5871 SmallVector<uint64_t, 64> Record;
5872 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5873 unsigned ValueId = 0;
5874
5875 // Read the index for this module.
5876 while (true) {
5877 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5878 if (!MaybeEntry)
5879 return MaybeEntry.takeError();
5880 llvm::BitstreamEntry Entry = MaybeEntry.get();
5881
5882 switch (Entry.Kind) {
5883 case BitstreamEntry::Error:
5884 return error("Malformed block");
5885 case BitstreamEntry::EndBlock:
5886 return Error::success();
5887
5888 case BitstreamEntry::SubBlock:
5889 switch (Entry.ID) {
5890 default: // Skip unknown content.
5891 if (Error Err = Stream.SkipBlock())
5892 return Err;
5893 break;
5894 case bitc::BLOCKINFO_BLOCK_ID:
5895 // Need to parse these to get abbrev ids (e.g. for VST)
5896 if (readBlockInfo())
5897 return error("Malformed block");
5898 break;
5899 case bitc::VALUE_SYMTAB_BLOCK_ID:
5900 // Should have been parsed earlier via VSTOffset, unless there
5901 // is no summary section.
5902 assert(((SeenValueSymbolTable && VSTOffset > 0) ||(static_cast <bool> (((SeenValueSymbolTable && VSTOffset
> 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record"
) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5904, __extension__ __PRETTY_FUNCTION__))
5903 !SeenGlobalValSummary) &&(static_cast <bool> (((SeenValueSymbolTable && VSTOffset
> 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record"
) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5904, __extension__ __PRETTY_FUNCTION__))
5904 "Expected early VST parse via VSTOffset record")(static_cast <bool> (((SeenValueSymbolTable && VSTOffset
> 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record"
) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5904, __extension__ __PRETTY_FUNCTION__))
;
5905 if (Error Err = Stream.SkipBlock())
5906 return Err;
5907 break;
5908 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5909 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5910 // Add the module if it is a per-module index (has a source file name).
5911 if (!SourceFileName.empty())
5912 addThisModule();
5913 assert(!SeenValueSymbolTable &&(static_cast <bool> (!SeenValueSymbolTable && "Already read VST when parsing summary block?"
) ? void (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5914, __extension__ __PRETTY_FUNCTION__))
5914 "Already read VST when parsing summary block?")(static_cast <bool> (!SeenValueSymbolTable && "Already read VST when parsing summary block?"
) ? void (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5914, __extension__ __PRETTY_FUNCTION__))
;
5915 // We might not have a VST if there were no values in the
5916 // summary. An empty summary block generated when we are
5917 // performing ThinLTO compiles so we don't later invoke
5918 // the regular LTO process on them.
5919 if (VSTOffset > 0) {
5920 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5921 return Err;
5922 SeenValueSymbolTable = true;
5923 }
5924 SeenGlobalValSummary = true;
5925 if (Error Err = parseEntireSummary(Entry.ID))
5926 return Err;
5927 break;
5928 case bitc::MODULE_STRTAB_BLOCK_ID:
5929 if (Error Err = parseModuleStringTable())
5930 return Err;
5931 break;
5932 }
5933 continue;
5934
5935 case BitstreamEntry::Record: {
5936 Record.clear();
5937 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5938 if (!MaybeBitCode)
5939 return MaybeBitCode.takeError();
5940 switch (MaybeBitCode.get()) {
5941 default:
5942 break; // Default behavior, ignore unknown content.
5943 case bitc::MODULE_CODE_VERSION: {
5944 if (Error Err = parseVersionRecord(Record).takeError())
5945 return Err;
5946 break;
5947 }
5948 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5949 case bitc::MODULE_CODE_SOURCE_FILENAME: {
5950 SmallString<128> ValueName;
5951 if (convertToString(Record, 0, ValueName))
5952 return error("Invalid record");
5953 SourceFileName = ValueName.c_str();
5954 break;
5955 }
5956 /// MODULE_CODE_HASH: [5*i32]
5957 case bitc::MODULE_CODE_HASH: {
5958 if (Record.size() != 5)
5959 return error("Invalid hash length " + Twine(Record.size()).str());
5960 auto &Hash = getThisModule()->second.second;
5961 int Pos = 0;
5962 for (auto &Val : Record) {
5963 assert(!(Val >> 32) && "Unexpected high bits set")(static_cast <bool> (!(Val >> 32) && "Unexpected high bits set"
) ? void (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 5963, __extension__ __PRETTY_FUNCTION__))
;
5964 Hash[Pos++] = Val;
5965 }
5966 break;
5967 }
5968 /// MODULE_CODE_VSTOFFSET: [offset]
5969 case bitc::MODULE_CODE_VSTOFFSET:
5970 if (Record.empty())
5971 return error("Invalid record");
5972 // Note that we subtract 1 here because the offset is relative to one
5973 // word before the start of the identification or module block, which
5974 // was historically always the start of the regular bitcode header.
5975 VSTOffset = Record[0] - 1;
5976 break;
5977 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5978 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5979 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5980 // v2: [strtab offset, strtab size, v1]
5981 case bitc::MODULE_CODE_GLOBALVAR:
5982 case bitc::MODULE_CODE_FUNCTION:
5983 case bitc::MODULE_CODE_ALIAS: {
5984 StringRef Name;
5985 ArrayRef<uint64_t> GVRecord;
5986 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5987 if (GVRecord.size() <= 3)
5988 return error("Invalid record");
5989 uint64_t RawLinkage = GVRecord[3];
5990 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5991 if (!UseStrtab) {
5992 ValueIdToLinkageMap[ValueId++] = Linkage;
5993 break;
5994 }
5995
5996 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5997 break;
5998 }
5999 }
6000 }
6001 continue;
6002 }
6003 }
6004}
6005
6006std::vector<ValueInfo>
6007ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6008 std::vector<ValueInfo> Ret;
6009 Ret.reserve(Record.size());
6010 for (uint64_t RefValueId : Record)
6011 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6012 return Ret;
6013}
6014
6015std::vector<FunctionSummary::EdgeTy>
6016ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6017 bool IsOldProfileFormat,
6018 bool HasProfile, bool HasRelBF) {
6019 std::vector<FunctionSummary::EdgeTy> Ret;
6020 Ret.reserve(Record.size());
6021 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6022 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6023 uint64_t RelBF = 0;
6024 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6025 if (IsOldProfileFormat) {
6026 I += 1; // Skip old callsitecount field
6027 if (HasProfile)
6028 I += 1; // Skip old profilecount field
6029 } else if (HasProfile)
6030 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6031 else if (HasRelBF)
6032 RelBF = Record[++I];
6033 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6034 }
6035 return Ret;
6036}
6037
6038static void
6039parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6040 WholeProgramDevirtResolution &Wpd) {
6041 uint64_t ArgNum = Record[Slot++];
6042 WholeProgramDevirtResolution::ByArg &B =
6043 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6044 Slot += ArgNum;
6045
6046 B.TheKind =
6047 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6048 B.Info = Record[Slot++];
6049 B.Byte = Record[Slot++];
6050 B.Bit = Record[Slot++];
6051}
6052
6053static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6054 StringRef Strtab, size_t &Slot,
6055 TypeIdSummary &TypeId) {
6056 uint64_t Id = Record[Slot++];
6057 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6058
6059 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6060 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6061 static_cast<size_t>(Record[Slot + 1])};
6062 Slot += 2;
6063
6064 uint64_t ResByArgNum = Record[Slot++];
6065 for (uint64_t I = 0; I != ResByArgNum; ++I)
6066 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6067}
6068
6069static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6070 StringRef Strtab,
6071 ModuleSummaryIndex &TheIndex) {
6072 size_t Slot = 0;
6073 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6074 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6075 Slot += 2;
6076
6077 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6078 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6079 TypeId.TTRes.AlignLog2 = Record[Slot++];
6080 TypeId.TTRes.SizeM1 = Record[Slot++];
6081 TypeId.TTRes.BitMask = Record[Slot++];
6082 TypeId.TTRes.InlineBits = Record[Slot++];
6083
6084 while (Slot < Record.size())
6085 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6086}
6087
6088std::vector<FunctionSummary::ParamAccess>
6089ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
6090 auto ReadRange = [&]() {
6091 APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
6092 BitcodeReader::decodeSignRotatedValue(Record.front()));
6093 Record = Record.drop_front();
6094 APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
6095 BitcodeReader::decodeSignRotatedValue(Record.front()));
6096 Record = Record.drop_front();
6097 ConstantRange Range{Lower, Upper};
6098 assert(!Range.isFullSet())(static_cast <bool> (!Range.isFullSet()) ? void (0) : __assert_fail
("!Range.isFullSet()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6098, __extension__ __PRETTY_FUNCTION__))
;
6099 assert(!Range.isUpperSignWrapped())(static_cast <bool> (!Range.isUpperSignWrapped()) ? void
(0) : __assert_fail ("!Range.isUpperSignWrapped()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6099, __extension__ __PRETTY_FUNCTION__))
;
6100 return Range;
6101 };
6102
6103 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6104 while (!Record.empty()) {
6105 PendingParamAccesses.emplace_back();
6106 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
6107 ParamAccess.ParamNo = Record.front();
6108 Record = Record.drop_front();
6109 ParamAccess.Use = ReadRange();
6110 ParamAccess.Calls.resize(Record.front());
6111 Record = Record.drop_front();
6112 for (auto &Call : ParamAccess.Calls) {
6113 Call.ParamNo = Record.front();
6114 Record = Record.drop_front();
6115 Call.Callee = getValueInfoFromValueId(Record.front()).first;
6116 Record = Record.drop_front();
6117 Call.Offsets = ReadRange();
6118 }
6119 }
6120 return PendingParamAccesses;
6121}
6122
6123void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6124 ArrayRef<uint64_t> Record, size_t &Slot,
6125 TypeIdCompatibleVtableInfo &TypeId) {
6126 uint64_t Offset = Record[Slot++];
6127 ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6128 TypeId.push_back({Offset, Callee});
6129}
6130
6131void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6132 ArrayRef<uint64_t> Record) {
6133 size_t Slot = 0;
6134 TypeIdCompatibleVtableInfo &TypeId =
6135 TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6136 {Strtab.data() + Record[Slot],
6137 static_cast<size_t>(Record[Slot + 1])});
6138 Slot += 2;
6139
6140 while (Slot < Record.size())
6141 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6142}
6143
6144static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6145 unsigned WOCnt) {
6146 // Readonly and writeonly refs are in the end of the refs list.
6147 assert(ROCnt + WOCnt <= Refs.size())(static_cast <bool> (ROCnt + WOCnt <= Refs.size()) ?
void (0) : __assert_fail ("ROCnt + WOCnt <= Refs.size()",
"/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6147, __extension__ __PRETTY_FUNCTION__))
;
6148 unsigned FirstWORef = Refs.size() - WOCnt;
6149 unsigned RefNo = FirstWORef - ROCnt;
6150 for (; RefNo < FirstWORef; ++RefNo)
6151 Refs[RefNo].setReadOnly();
6152 for (; RefNo < Refs.size(); ++RefNo)
6153 Refs[RefNo].setWriteOnly();
6154}
6155
6156// Eagerly parse the entire summary block. This populates the GlobalValueSummary
6157// objects in the index.
6158Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6159 if (Error Err = Stream.EnterSubBlock(ID))
6160 return Err;
6161 SmallVector<uint64_t, 64> Record;
6162
6163 // Parse version
6164 {
6165 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6166 if (!MaybeEntry)
6167 return MaybeEntry.takeError();
6168 BitstreamEntry Entry = MaybeEntry.get();
6169
6170 if (Entry.Kind != BitstreamEntry::Record)
6171 return error("Invalid Summary Block: record for version expected");
6172 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6173 if (!MaybeRecord)
6174 return MaybeRecord.takeError();
6175 if (MaybeRecord.get() != bitc::FS_VERSION)
6176 return error("Invalid Summary Block: version expected");
6177 }
6178 const uint64_t Version = Record[0];
6179 const bool IsOldProfileFormat = Version == 1;
6180 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6181 return error("Invalid summary version " + Twine(Version) +
6182 ". Version should be in the range [1-" +
6183 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6184 "].");
6185 Record.clear();
6186
6187 // Keep around the last seen summary to be used when we see an optional
6188 // "OriginalName" attachement.
6189 GlobalValueSummary *LastSeenSummary = nullptr;
6190 GlobalValue::GUID LastSeenGUID = 0;
6191
6192 // We can expect to see any number of type ID information records before
6193 // each function summary records; these variables store the information
6194 // collected so far so that it can be used to create the summary object.
6195 std::vector<GlobalValue::GUID> PendingTypeTests;
6196 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6197 PendingTypeCheckedLoadVCalls;
6198 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6199 PendingTypeCheckedLoadConstVCalls;
6200 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6201
6202 while (true) {
6203 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6204 if (!MaybeEntry)
6205 return MaybeEntry.takeError();
6206 BitstreamEntry Entry = MaybeEntry.get();
6207
6208 switch (Entry.Kind) {
6209 case BitstreamEntry::SubBlock: // Handled for us already.
6210 case BitstreamEntry::Error:
6211 return error("Malformed block");
6212 case BitstreamEntry::EndBlock:
6213 return Error::success();
6214 case BitstreamEntry::Record:
6215 // The interesting case.
6216 break;
6217 }
6218
6219 // Read a record. The record format depends on whether this
6220 // is a per-module index or a combined index file. In the per-module
6221 // case the records contain the associated value's ID for correlation
6222 // with VST entries. In the combined index the correlation is done
6223 // via the bitcode offset of the summary records (which were saved
6224 // in the combined index VST entries). The records also contain
6225 // information used for ThinLTO renaming and importing.
6226 Record.clear();
6227 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6228 if (!MaybeBitCode)
6229 return MaybeBitCode.takeError();
6230 switch (unsigned BitCode = MaybeBitCode.get()) {
6231 default: // Default behavior: ignore.
6232 break;
6233 case bitc::FS_FLAGS: { // [flags]
6234 TheIndex.setFlags(Record[0]);
6235 break;
6236 }
6237 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6238 uint64_t ValueID = Record[0];
6239 GlobalValue::GUID RefGUID = Record[1];
6240 ValueIdToValueInfoMap[ValueID] =
6241 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6242 break;
6243 }
6244 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6245 // numrefs x valueid, n x (valueid)]
6246 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6247 // numrefs x valueid,
6248 // n x (valueid, hotness)]
6249 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6250 // numrefs x valueid,
6251 // n x (valueid, relblockfreq)]
6252 case bitc::FS_PERMODULE:
6253 case bitc::FS_PERMODULE_RELBF:
6254 case bitc::FS_PERMODULE_PROFILE: {
6255 unsigned ValueID = Record[0];
6256 uint64_t RawFlags = Record[1];
6257 unsigned InstCount = Record[2];
6258 uint64_t RawFunFlags = 0;
6259 unsigned NumRefs = Record[3];
6260 unsigned NumRORefs = 0, NumWORefs = 0;
6261 int RefListStartIndex = 4;
6262 if (Version >= 4) {
6263 RawFunFlags = Record[3];
6264 NumRefs = Record[4];
6265 RefListStartIndex = 5;
6266 if (Version >= 5) {
6267 NumRORefs = Record[5];
6268 RefListStartIndex = 6;
6269 if (Version >= 7) {
6270 NumWORefs = Record[6];
6271 RefListStartIndex = 7;
6272 }
6273 }
6274 }
6275
6276 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6277 // The module path string ref set in the summary must be owned by the
6278 // index's module string table. Since we don't have a module path
6279 // string table section in the per-module index, we create a single
6280 // module path string table entry with an empty (0) ID to take
6281 // ownership.
6282 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6283 assert(Record.size() >= RefListStartIndex + NumRefs &&(static_cast <bool> (Record.size() >= RefListStartIndex
+ NumRefs && "Record size inconsistent with number of references"
) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6284, __extension__ __PRETTY_FUNCTION__))
6284 "Record size inconsistent with number of references")(static_cast <bool> (Record.size() >= RefListStartIndex
+ NumRefs && "Record size inconsistent with number of references"
) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6284, __extension__ __PRETTY_FUNCTION__))
;
6285 std::vector<ValueInfo> Refs = makeRefList(
6286 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6287 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6288 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6289 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6290 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6291 IsOldProfileFormat, HasProfile, HasRelBF);
6292 setSpecialRefs(Refs, NumRORefs, NumWORefs);
6293 auto FS = std::make_unique<FunctionSummary>(
6294 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6295 std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6296 std::move(PendingTypeTestAssumeVCalls),
6297 std::move(PendingTypeCheckedLoadVCalls),
6298 std::move(PendingTypeTestAssumeConstVCalls),
6299 std::move(PendingTypeCheckedLoadConstVCalls),
6300 std::move(PendingParamAccesses));
6301 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6302 FS->setModulePath(getThisModule()->first());
6303 FS->setOriginalName(VIAndOriginalGUID.second);
6304 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6305 break;
6306 }
6307 // FS_ALIAS: [valueid, flags, valueid]
6308 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6309 // they expect all aliasee summaries to be available.
6310 case bitc::FS_ALIAS: {
6311 unsigned ValueID = Record[0];
6312 uint64_t RawFlags = Record[1];
6313 unsigned AliaseeID = Record[2];
6314 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6315 auto AS = std::make_unique<AliasSummary>(Flags);
6316 // The module path string ref set in the summary must be owned by the
6317 // index's module string table. Since we don't have a module path
6318 // string table section in the per-module index, we create a single
6319 // module path string table entry with an empty (0) ID to take
6320 // ownership.
6321 AS->setModulePath(getThisModule()->first());
6322
6323 auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6324 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6325 if (!AliaseeInModule)
6326 return error("Alias expects aliasee summary to be parsed");
6327 AS->setAliasee(AliaseeVI, AliaseeInModule);
6328
6329 auto GUID = getValueInfoFromValueId(ValueID);
6330 AS->setOriginalName(GUID.second);
6331 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6332 break;
6333 }
6334 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6335 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6336 unsigned ValueID = Record[0];
6337 uint64_t RawFlags = Record[1];
6338 unsigned RefArrayStart = 2;
6339 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6340 /* WriteOnly */ false,
6341 /* Constant */ false,
6342 GlobalObject::VCallVisibilityPublic);
6343 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6344 if (Version >= 5) {
6345 GVF = getDecodedGVarFlags(Record[2]);
6346 RefArrayStart = 3;
6347 }
6348 std::vector<ValueInfo> Refs =
6349 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6350 auto FS =
6351 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6352 FS->setModulePath(getThisModule()->first());
6353 auto GUID = getValueInfoFromValueId(ValueID);
6354 FS->setOriginalName(GUID.second);
6355 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6356 break;
6357 }
6358 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6359 // numrefs, numrefs x valueid,
6360 // n x (valueid, offset)]
6361 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6362 unsigned ValueID = Record[0];
6363 uint64_t RawFlags = Record[1];
6364 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6365 unsigned NumRefs = Record[3];
6366 unsigned RefListStartIndex = 4;
6367 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6368 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6369 std::vector<ValueInfo> Refs = makeRefList(
6370 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6371 VTableFuncList VTableFuncs;
6372 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6373 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6374 uint64_t Offset = Record[++I];
6375 VTableFuncs.push_back({Callee, Offset});
6376 }
6377 auto VS =
6378 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6379 VS->setModulePath(getThisModule()->first());
6380 VS->setVTableFuncs(VTableFuncs);
6381 auto GUID = getValueInfoFromValueId(ValueID);
6382 VS->setOriginalName(GUID.second);
6383 TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6384 break;
6385 }
6386 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6387 // numrefs x valueid, n x (valueid)]
6388 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6389 // numrefs x valueid, n x (valueid, hotness)]
6390 case bitc::FS_COMBINED:
6391 case bitc::FS_COMBINED_PROFILE: {
6392 unsigned ValueID = Record[0];
6393 uint64_t ModuleId = Record[1];
6394 uint64_t RawFlags = Record[2];
6395 unsigned InstCount = Record[3];
6396 uint64_t RawFunFlags = 0;
6397 uint64_t EntryCount = 0;
6398 unsigned NumRefs = Record[4];
6399 unsigned NumRORefs = 0, NumWORefs = 0;
6400 int RefListStartIndex = 5;
6401
6402 if (Version >= 4) {
6403 RawFunFlags = Record[4];
6404 RefListStartIndex = 6;
6405 size_t NumRefsIndex = 5;
6406 if (Version >= 5) {
6407 unsigned NumRORefsOffset = 1;
6408 RefListStartIndex = 7;
6409 if (Version >= 6) {
6410 NumRefsIndex = 6;
6411 EntryCount = Record[5];
6412 RefListStartIndex = 8;
6413 if (Version >= 7) {
6414 RefListStartIndex = 9;
6415 NumWORefs = Record[8];
6416 NumRORefsOffset = 2;
6417 }
6418 }
6419 NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6420 }
6421 NumRefs = Record[NumRefsIndex];
6422 }
6423
6424 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6425 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6426 assert(Record.size() >= RefListStartIndex + NumRefs &&(static_cast <bool> (Record.size() >= RefListStartIndex
+ NumRefs && "Record size inconsistent with number of references"
) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6427, __extension__ __PRETTY_FUNCTION__))
6427 "Record size inconsistent with number of references")(static_cast <bool> (Record.size() >= RefListStartIndex
+ NumRefs && "Record size inconsistent with number of references"
) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6427, __extension__ __PRETTY_FUNCTION__))
;
6428 std::vector<ValueInfo> Refs = makeRefList(
6429 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6430 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6431 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6432 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6433 IsOldProfileFormat, HasProfile, false);
6434 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6435 setSpecialRefs(Refs, NumRORefs, NumWORefs);
6436 auto FS = std::make_unique<FunctionSummary>(
6437 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6438 std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6439 std::move(PendingTypeTestAssumeVCalls),
6440 std::move(PendingTypeCheckedLoadVCalls),
6441 std::move(PendingTypeTestAssumeConstVCalls),
6442 std::move(PendingTypeCheckedLoadConstVCalls),
6443 std::move(PendingParamAccesses));
6444 LastSeenSummary = FS.get();
6445 LastSeenGUID = VI.getGUID();
6446 FS->setModulePath(ModuleIdMap[ModuleId]);
6447 TheIndex.addGlobalValueSummary(VI, std::move(FS));
6448 break;
6449 }
6450 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6451 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6452 // they expect all aliasee summaries to be available.
6453 case bitc::FS_COMBINED_ALIAS: {
6454 unsigned ValueID = Record[0];
6455 uint64_t ModuleId = Record[1];
6456 uint64_t RawFlags = Record[2];
6457 unsigned AliaseeValueId = Record[3];
6458 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6459 auto AS = std::make_unique<AliasSummary>(Flags);
6460 LastSeenSummary = AS.get();
6461 AS->setModulePath(ModuleIdMap[ModuleId]);
6462
6463 auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6464 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6465 AS->setAliasee(AliaseeVI, AliaseeInModule);
6466
6467 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6468 LastSeenGUID = VI.getGUID();
6469 TheIndex.addGlobalValueSummary(VI, std::move(AS));
6470 break;
6471 }
6472 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6473 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6474 unsigned ValueID = Record[0];
6475 uint64_t ModuleId = Record[1];
6476 uint64_t RawFlags = Record[2];
6477 unsigned RefArrayStart = 3;
6478 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6479 /* WriteOnly */ false,
6480 /* Constant */ false,
6481 GlobalObject::VCallVisibilityPublic);
6482 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6483 if (Version >= 5) {
6484 GVF = getDecodedGVarFlags(Record[3]);
6485 RefArrayStart = 4;
6486 }
6487 std::vector<ValueInfo> Refs =
6488 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6489 auto FS =
6490 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6491 LastSeenSummary = FS.get();
6492 FS->setModulePath(ModuleIdMap[ModuleId]);
6493 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6494 LastSeenGUID = VI.getGUID();
6495 TheIndex.addGlobalValueSummary(VI, std::move(FS));
6496 break;
6497 }
6498 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6499 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6500 uint64_t OriginalName = Record[0];
6501 if (!LastSeenSummary)
6502 return error("Name attachment that does not follow a combined record");
6503 LastSeenSummary->setOriginalName(OriginalName);
6504 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6505 // Reset the LastSeenSummary
6506 LastSeenSummary = nullptr;
6507 LastSeenGUID = 0;
6508 break;
6509 }
6510 case bitc::FS_TYPE_TESTS:
6511 assert(PendingTypeTests.empty())(static_cast <bool> (PendingTypeTests.empty()) ? void (
0) : __assert_fail ("PendingTypeTests.empty()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6511, __extension__ __PRETTY_FUNCTION__))
;
6512 llvm::append_range(PendingTypeTests, Record);
6513 break;
6514
6515 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6516 assert(PendingTypeTestAssumeVCalls.empty())(static_cast <bool> (PendingTypeTestAssumeVCalls.empty(
)) ? void (0) : __assert_fail ("PendingTypeTestAssumeVCalls.empty()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6516, __extension__ __PRETTY_FUNCTION__))
;
6517 for (unsigned I = 0; I != Record.size(); I += 2)
6518 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6519 break;
6520
6521 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6522 assert(PendingTypeCheckedLoadVCalls.empty())(static_cast <bool> (PendingTypeCheckedLoadVCalls.empty
()) ? void (0) : __assert_fail ("PendingTypeCheckedLoadVCalls.empty()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6522, __extension__ __PRETTY_FUNCTION__))
;
6523 for (unsigned I = 0; I != Record.size(); I += 2)
6524 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6525 break;
6526
6527 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6528 PendingTypeTestAssumeConstVCalls.push_back(
6529 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6530 break;
6531
6532 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6533 PendingTypeCheckedLoadConstVCalls.push_back(
6534 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6535 break;
6536
6537 case bitc::FS_CFI_FUNCTION_DEFS: {
6538 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6539 for (unsigned I = 0; I != Record.size(); I += 2)
6540 CfiFunctionDefs.insert(
6541 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6542 break;
6543 }
6544
6545 case bitc::FS_CFI_FUNCTION_DECLS: {
6546 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6547 for (unsigned I = 0; I != Record.size(); I += 2)
6548 CfiFunctionDecls.insert(
6549 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6550 break;
6551 }
6552
6553 case bitc::FS_TYPE_ID:
6554 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6555 break;
6556
6557 case bitc::FS_TYPE_ID_METADATA:
6558 parseTypeIdCompatibleVtableSummaryRecord(Record);
6559 break;
6560
6561 case bitc::FS_BLOCK_COUNT:
6562 TheIndex.addBlockCount(Record[0]);
6563 break;
6564
6565 case bitc::FS_PARAM_ACCESS: {
6566 PendingParamAccesses = parseParamAccesses(Record);
6567 break;
6568 }
6569 }
6570 }
6571 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6571)
;
6572}
6573
6574// Parse the module string table block into the Index.
6575// This populates the ModulePathStringTable map in the index.
6576Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6577 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6578 return Err;
6579
6580 SmallVector<uint64_t, 64> Record;
6581
6582 SmallString<128> ModulePath;
6583 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6584
6585 while (true) {
6586 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6587 if (!MaybeEntry)
6588 return MaybeEntry.takeError();
6589 BitstreamEntry Entry = MaybeEntry.get();
6590
6591 switch (Entry.Kind) {
6592 case BitstreamEntry::SubBlock: // Handled for us already.
6593 case BitstreamEntry::Error:
6594 return error("Malformed block");
6595 case BitstreamEntry::EndBlock:
6596 return Error::success();
6597 case BitstreamEntry::Record:
6598 // The interesting case.
6599 break;
6600 }
6601
6602 Record.clear();
6603 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6604 if (!MaybeRecord)
6605 return MaybeRecord.takeError();
6606 switch (MaybeRecord.get()) {
6607 default: // Default behavior: ignore.
6608 break;
6609 case bitc::MST_CODE_ENTRY: {
6610 // MST_ENTRY: [modid, namechar x N]
6611 uint64_t ModuleId = Record[0];
6612
6613 if (convertToString(Record, 1, ModulePath))
6614 return error("Invalid record");
6615
6616 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6617 ModuleIdMap[ModuleId] = LastSeenModule->first();
6618
6619 ModulePath.clear();
6620 break;
6621 }
6622 /// MST_CODE_HASH: [5*i32]
6623 case bitc::MST_CODE_HASH: {
6624 if (Record.size() != 5)
6625 return error("Invalid hash length " + Twine(Record.size()).str());
6626 if (!LastSeenModule)
6627 return error("Invalid hash that does not follow a module path");
6628 int Pos = 0;
6629 for (auto &Val : Record) {
6630 assert(!(Val >> 32) && "Unexpected high bits set")(static_cast <bool> (!(Val >> 32) && "Unexpected high bits set"
) ? void (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6630, __extension__ __PRETTY_FUNCTION__))
;
6631 LastSeenModule->second.second[Pos++] = Val;
6632 }
6633 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6634 LastSeenModule = nullptr;
6635 break;
6636 }
6637 }
6638 }
6639 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6639)
;
6640}
6641
6642namespace {
6643
6644// FIXME: This class is only here to support the transition to llvm::Error. It
6645// will be removed once this transition is complete. Clients should prefer to
6646// deal with the Error value directly, rather than converting to error_code.
6647class BitcodeErrorCategoryType : public std::error_category {
6648 const char *name() const noexcept override {
6649 return "llvm.bitcode";
6650 }
6651
6652 std::string message(int IE) const override {
6653 BitcodeError E = static_cast<BitcodeError>(IE);
6654 switch (E) {
6655 case BitcodeError::CorruptedBitcode:
6656 return "Corrupted bitcode";
6657 }
6658 llvm_unreachable("Unknown error type!")::llvm::llvm_unreachable_internal("Unknown error type!", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6658)
;
6659 }
6660};
6661
6662} // end anonymous namespace
6663
6664static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6665
6666const std::error_category &llvm::BitcodeErrorCategory() {
6667 return *ErrorCategory;
6668}
6669
6670static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
6671 unsigned Block, unsigned RecordID) {
6672 if (Error Err = Stream.EnterSubBlock(Block))
6673 return std::move(Err);
6674
6675 StringRef Strtab;
6676 while (true) {
6677 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6678 if (!MaybeEntry)
6679 return MaybeEntry.takeError();
6680 llvm::BitstreamEntry Entry = MaybeEntry.get();
6681
6682 switch (Entry.Kind) {
6683 case BitstreamEntry::EndBlock:
6684 return Strtab;
6685
6686 case BitstreamEntry::Error:
6687 return error("Malformed block");
6688
6689 case BitstreamEntry::SubBlock:
6690 if (Error Err = Stream.SkipBlock())
6691 return std::move(Err);
6692 break;
6693
6694 case BitstreamEntry::Record:
6695 StringRef Blob;
6696 SmallVector<uint64_t, 1> Record;
6697 Expected<unsigned> MaybeRecord =
6698 Stream.readRecord(Entry.ID, Record, &Blob);
6699 if (!MaybeRecord)
6700 return MaybeRecord.takeError();
6701 if (MaybeRecord.get() == RecordID)
6702 Strtab = Blob;
6703 break;
6704 }
6705 }
6706}
6707
6708//===----------------------------------------------------------------------===//
6709// External interface
6710//===----------------------------------------------------------------------===//
6711
6712Expected<std::vector<BitcodeModule>>
6713llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
6714 auto FOrErr = getBitcodeFileContents(Buffer);
6715 if (!FOrErr)
6716 return FOrErr.takeError();
6717 return std::move(FOrErr->Mods);
6718}
6719
6720Expected<BitcodeFileContents>
6721llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
6722 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6723 if (!StreamOrErr)
6724 return StreamOrErr.takeError();
6725 BitstreamCursor &Stream = *StreamOrErr;
6726
6727 BitcodeFileContents F;
6728 while (true) {
6729 uint64_t BCBegin = Stream.getCurrentByteNo();
6730
6731 // We may be consuming bitcode from a client that leaves garbage at the end
6732 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6733 // the end that there cannot possibly be another module, stop looking.
6734 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
6735 return F;
6736
6737 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6738 if (!MaybeEntry)
6739 return MaybeEntry.takeError();
6740 llvm::BitstreamEntry Entry = MaybeEntry.get();
6741
6742 switch (Entry.Kind) {
6743 case BitstreamEntry::EndBlock:
6744 case BitstreamEntry::Error:
6745 return error("Malformed block");
6746
6747 case BitstreamEntry::SubBlock: {
6748 uint64_t IdentificationBit = -1ull;
6749 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
6750 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6751 if (Error Err = Stream.SkipBlock())
6752 return std::move(Err);
6753
6754 {
6755 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6756 if (!MaybeEntry)
6757 return MaybeEntry.takeError();
6758 Entry = MaybeEntry.get();
6759 }
6760
6761 if (Entry.Kind != BitstreamEntry::SubBlock ||
6762 Entry.ID != bitc::MODULE_BLOCK_ID)
6763 return error("Malformed block");
6764 }
6765
6766 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
6767 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6768 if (Error Err = Stream.SkipBlock())
6769 return std::move(Err);
6770
6771 F.Mods.push_back({Stream.getBitcodeBytes().slice(
6772 BCBegin, Stream.getCurrentByteNo() - BCBegin),
6773 Buffer.getBufferIdentifier(), IdentificationBit,
6774 ModuleBit});
6775 continue;
6776 }
6777
6778 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
6779 Expected<StringRef> Strtab =
6780 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
6781 if (!Strtab)
6782 return Strtab.takeError();
6783 // This string table is used by every preceding bitcode module that does
6784 // not have its own string table. A bitcode file may have multiple
6785 // string tables if it was created by binary concatenation, for example
6786 // with "llvm-cat -b".
6787 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
6788 if (!I->Strtab.empty())
6789 break;
6790 I->Strtab = *Strtab;
6791 }
6792 // Similarly, the string table is used by every preceding symbol table;
6793 // normally there will be just one unless the bitcode file was created
6794 // by binary concatenation.
6795 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
6796 F.StrtabForSymtab = *Strtab;
6797 continue;
6798 }
6799
6800 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
6801 Expected<StringRef> SymtabOrErr =
6802 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
6803 if (!SymtabOrErr)
6804 return SymtabOrErr.takeError();
6805
6806 // We can expect the bitcode file to have multiple symbol tables if it
6807 // was created by binary concatenation. In that case we silently
6808 // ignore any subsequent symbol tables, which is fine because this is a
6809 // low level function. The client is expected to notice that the number
6810 // of modules in the symbol table does not match the number of modules
6811 // in the input file and regenerate the symbol table.
6812 if (F.Symtab.empty())
6813 F.Symtab = *SymtabOrErr;
6814 continue;
6815 }
6816
6817 if (Error Err = Stream.SkipBlock())
6818 return std::move(Err);
6819 continue;
6820 }
6821 case BitstreamEntry::Record:
6822 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
6823 continue;
6824 else
6825 return StreamFailed.takeError();
6826 }
6827 }
6828}
6829
6830/// Get a lazy one-at-time loading module from bitcode.
6831///
6832/// This isn't always used in a lazy context. In particular, it's also used by
6833/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
6834/// in forward-referenced functions from block address references.
6835///
6836/// \param[in] MaterializeAll Set to \c true if we should materialize
6837/// everything.
6838Expected<std::unique_ptr<Module>>
6839BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
6840 bool ShouldLazyLoadMetadata, bool IsImporting,
6841 DataLayoutCallbackTy DataLayoutCallback) {
6842 BitstreamCursor Stream(Buffer);
6843
6844 std::string ProducerIdentification;
6845 if (IdentificationBit != -1ull) {
6846 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6847 return std::move(JumpFailed);
6848 Expected<std::string> ProducerIdentificationOrErr =
6849 readIdentificationBlock(Stream);
6850 if (!ProducerIdentificationOrErr)
6851 return ProducerIdentificationOrErr.takeError();
6852
6853 ProducerIdentification = *ProducerIdentificationOrErr;
6854 }
6855
6856 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6857 return std::move(JumpFailed);
6858 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
6859 Context);
6860
6861 std::unique_ptr<Module> M =
6862 std::make_unique<Module>(ModuleIdentifier, Context);
6863 M->setMaterializer(R);
6864
6865 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6866 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
6867 IsImporting, DataLayoutCallback))
6868 return std::move(Err);
6869
6870 if (MaterializeAll) {
6871 // Read in the entire module, and destroy the BitcodeReader.
6872 if (Error Err = M->materializeAll())
6873 return std::move(Err);
6874 } else {
6875 // Resolve forward references from blockaddresses.
6876 if (Error Err = R->materializeForwardReferencedFunctions())
6877 return std::move(Err);
6878 }
6879 return std::move(M);
6880}
6881
6882Expected<std::unique_ptr<Module>>
6883BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
6884 bool IsImporting) {
6885 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
6886 [](StringRef) { return None; });
6887}
6888
6889// Parse the specified bitcode buffer and merge the index into CombinedIndex.
6890// We don't use ModuleIdentifier here because the client may need to control the
6891// module path used in the combined summary (e.g. when reading summaries for
6892// regular LTO modules).
6893Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
6894 StringRef ModulePath, uint64_t ModuleId) {
6895 BitstreamCursor Stream(Buffer);
6896 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6897 return JumpFailed;
6898
6899 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
6900 ModulePath, ModuleId);
6901 return R.parseModule();
6902}
6903
6904// Parse the specified bitcode buffer, returning the function info index.
6905Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
6906 BitstreamCursor Stream(Buffer);
6907 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6908 return std::move(JumpFailed);
6909
6910 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
6911 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
6912 ModuleIdentifier, 0);
6913
6914 if (Error Err = R.parseModule())
6915 return std::move(Err);
6916
6917 return std::move(Index);
6918}
6919
6920static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
6921 unsigned ID) {
6922 if (Error Err = Stream.EnterSubBlock(ID))
6923 return std::move(Err);
6924 SmallVector<uint64_t, 64> Record;
6925
6926 while (true) {
6927 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6928 if (!MaybeEntry)
6929 return MaybeEntry.takeError();
6930 BitstreamEntry Entry = MaybeEntry.get();
6931
6932 switch (Entry.Kind) {
6933 case BitstreamEntry::SubBlock: // Handled for us already.
6934 case BitstreamEntry::Error:
6935 return error("Malformed block");
6936 case BitstreamEntry::EndBlock:
6937 // If no flags record found, conservatively return true to mimic
6938 // behavior before this flag was added.
6939 return true;
6940 case BitstreamEntry::Record:
6941 // The interesting case.
6942 break;
6943 }
6944
6945 // Look for the FS_FLAGS record.
6946 Record.clear();
6947 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6948 if (!MaybeBitCode)
6949 return MaybeBitCode.takeError();
6950 switch (MaybeBitCode.get()) {
6951 default: // Default behavior: ignore.
6952 break;
6953 case bitc::FS_FLAGS: { // [flags]
6954 uint64_t Flags = Record[0];
6955 // Scan flags.
6956 assert(Flags <= 0x7f && "Unexpected bits in flag")(static_cast <bool> (Flags <= 0x7f && "Unexpected bits in flag"
) ? void (0) : __assert_fail ("Flags <= 0x7f && \"Unexpected bits in flag\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6956, __extension__ __PRETTY_FUNCTION__))
;
6957
6958 return Flags & 0x8;
6959 }
6960 }
6961 }
6962 llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Bitcode/Reader/BitcodeReader.cpp"
, 6962)
;
6963}
6964
6965// Check if the given bitcode buffer contains a global value summary block.
6966Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
6967 BitstreamCursor Stream(Buffer);
6968 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6969 return std::move(JumpFailed);
6970
6971 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6972 return std::move(Err);
6973
6974 while (true) {
6975 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6976 if (!MaybeEntry)
6977 return MaybeEntry.takeError();
6978 llvm::BitstreamEntry Entry = MaybeEntry.get();
6979
6980 switch (Entry.Kind) {
6981 case BitstreamEntry::Error:
6982 return error("Malformed block");
6983 case BitstreamEntry::EndBlock:
6984 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
6985 /*EnableSplitLTOUnit=*/false};
6986
6987 case BitstreamEntry::SubBlock:
6988 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6989 Expected<bool> EnableSplitLTOUnit =
6990 getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6991 if (!EnableSplitLTOUnit)
6992 return EnableSplitLTOUnit.takeError();
6993 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
6994 *EnableSplitLTOUnit};
6995 }
6996
6997 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
6998 Expected<bool> EnableSplitLTOUnit =
6999 getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7000 if (!EnableSplitLTOUnit)
7001 return EnableSplitLTOUnit.takeError();
7002 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
7003 *EnableSplitLTOUnit};
7004 }
7005
7006 // Ignore other sub-blocks.
7007 if (Error Err = Stream.SkipBlock())
7008 return std::move(Err);
7009 continue;
7010
7011 case BitstreamEntry::Record:
7012 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7013 continue;
7014 else
7015 return StreamFailed.takeError();
7016 }
7017 }
7018}
7019
7020static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7021 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7022 if (!MsOrErr)
7023 return MsOrErr.takeError();
7024
7025 if (MsOrErr->size() != 1)
7026 return error("Expected a single module");
7027
7028 return (*MsOrErr)[0];
7029}
7030
7031Expected<std::unique_ptr<Module>>
7032llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7033 bool ShouldLazyLoadMetadata, bool IsImporting) {
7034 Expected<BitcodeModule> BM = getSingleModule(Buffer);
7035 if (!BM)
7036 return BM.takeError();
7037
7038 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7039}
7040
7041Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7042 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7043 bool ShouldLazyLoadMetadata, bool IsImporting) {
7044 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7045 IsImporting);
7046 if (MOrErr)
7047 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7048 return MOrErr;
7049}
7050
7051Expected<std::unique_ptr<Module>>
7052BitcodeModule::parseModule(LLVMContext &Context,
7053 DataLayoutCallbackTy DataLayoutCallback) {
7054 return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7055 // TODO: Restore the use-lists to the in-memory state when the bitcode was
7056 // written. We must defer until the Module has been fully materialized.
7057}
7058
7059Expected<std::unique_ptr<Module>>
7060llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
7061 DataLayoutCallbackTy DataLayoutCallback) {
7062 Expected<BitcodeModule> BM = getSingleModule(Buffer);
7063 if (!BM)
7064 return BM.takeError();
7065
7066 return BM->parseModule(Context, DataLayoutCallback);
7067}
7068
7069Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7070 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7071 if (!StreamOrErr)
7072 return StreamOrErr.takeError();
7073
7074 return readTriple(*StreamOrErr);
7075}
7076
7077Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7078 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7079 if (!StreamOrErr)
7080 return StreamOrErr.takeError();
7081
7082 return hasObjCCategory(*StreamOrErr);
7083}
7084
7085Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7086 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7087 if (!StreamOrErr)
7088 return StreamOrErr.takeError();
7089
7090 return readIdentificationCode(*StreamOrErr);
7091}
7092
7093Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7094 ModuleSummaryIndex &CombinedIndex,
7095 uint64_t ModuleId) {
7096 Expected<BitcodeModule> BM = getSingleModule(Buffer);
7097 if (!BM)
7098 return BM.takeError();
7099
7100 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7101}
7102
7103Expected<std::unique_ptr<ModuleSummaryIndex>>
7104llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7105 Expected<BitcodeModule> BM = getSingleModule(Buffer);
7106 if (!BM)
7107 return BM.takeError();
7108
7109 return BM->getSummary();
7110}
7111
7112Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7113 Expected<BitcodeModule> BM = getSingleModule(Buffer);
7114 if (!BM)
7115 return BM.takeError();
7116
7117 return BM->getLTOInfo();
7118}
7119
7120Expected<std::unique_ptr<ModuleSummaryIndex>>
7121llvm::getModuleSummaryIndexForFile(StringRef Path,
7122 bool IgnoreEmptyThinLTOIndexFile) {
7123 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7124 MemoryBuffer::getFileOrSTDIN(Path);
7125 if (!FileOrErr)
7126 return errorCodeToError(FileOrErr.getError());
7127 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7128 return nullptr;
7129 return getModuleSummaryIndex(**FileOrErr);
7130}