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/STLExtras.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Bitcode/BitcodeCommon.h"
22#include "llvm/Bitcode/LLVMBitCodes.h"
23#include "llvm/Bitstream/BitstreamReader.h"
24#include "llvm/Config/llvm-config.h"
25#include "llvm/IR/Argument.h"
26#include "llvm/IR/AttributeMask.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/CallingConv.h"
31#include "llvm/IR/Comdat.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/ConstantRangeList.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/GetElementPtrTypeIterator.h"
43#include "llvm/IR/GlobalAlias.h"
44#include "llvm/IR/GlobalIFunc.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/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
56#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/Metadata.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/ModuleSummaryIndex.h"
60#include "llvm/IR/Operator.h"
61#include "llvm/IR/ProfDataUtils.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Value.h"
64#include "llvm/IR/Verifier.h"
65#include "llvm/Support/AtomicOrdering.h"
66#include "llvm/Support/Casting.h"
67#include "llvm/Support/CommandLine.h"
68#include "llvm/Support/Compiler.h"
69#include "llvm/Support/Debug.h"
70#include "llvm/Support/Error.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/ErrorOr.h"
73#include "llvm/Support/MathExtras.h"
74#include "llvm/Support/MemoryBuffer.h"
75#include "llvm/Support/ModRef.h"
76#include "llvm/Support/raw_ostream.h"
77#include "llvm/TargetParser/Triple.h"
78#include <algorithm>
79#include <cassert>
80#include <cstddef>
81#include <cstdint>
82#include <deque>
83#include <map>
84#include <memory>
85#include <optional>
86#include <string>
87#include <system_error>
88#include <tuple>
89#include <utility>
90#include <vector>
91
92using namespace llvm;
93
94static cl::opt<bool> PrintSummaryGUIDs(
95 "print-summary-global-ids", cl::init(Val: false), cl::Hidden,
96 cl::desc(
97 "Print the global id for each value when reading the module summary"));
98
99static cl::opt<bool> ExpandConstantExprs(
100 "expand-constant-exprs", cl::Hidden,
101 cl::desc(
102 "Expand constant expressions to instructions for testing purposes"));
103
104namespace {
105
106enum {
107 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
108};
109
110} // end anonymous namespace
111
112static Error error(const Twine &Message) {
113 return make_error<StringError>(
114 Args: Message, Args: make_error_code(E: BitcodeError::CorruptedBitcode));
115}
116
117static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
118 if (!Stream.canSkipToPos(pos: 4))
119 return createStringError(EC: std::errc::illegal_byte_sequence,
120 Fmt: "file too small to contain bitcode header");
121 for (unsigned C : {'B', 'C'})
122 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(NumBits: 8)) {
123 if (Res.get() != C)
124 return createStringError(EC: std::errc::illegal_byte_sequence,
125 Fmt: "file doesn't start with bitcode header");
126 } else
127 return Res.takeError();
128 for (unsigned C : {0x0, 0xC, 0xE, 0xD})
129 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(NumBits: 4)) {
130 if (Res.get() != C)
131 return createStringError(EC: std::errc::illegal_byte_sequence,
132 Fmt: "file doesn't start with bitcode header");
133 } else
134 return Res.takeError();
135 return Error::success();
136}
137
138static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
139 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
140 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
141
142 if (Buffer.getBufferSize() & 3)
143 return error(Message: "Invalid bitcode signature");
144
145 // If we have a wrapper header, parse it and ignore the non-bc file contents.
146 // The magic number is 0x0B17C0DE stored in little endian.
147 if (isBitcodeWrapper(BufPtr, BufEnd))
148 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, VerifyBufferSize: true))
149 return error(Message: "Invalid bitcode wrapper header");
150
151 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
152 if (Error Err = hasInvalidBitcodeHeader(Stream))
153 return std::move(Err);
154
155 return std::move(Stream);
156}
157
158/// Convert a string from a record into an std::string, return true on failure.
159template <typename StrTy>
160static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
161 StrTy &Result) {
162 if (Idx > Record.size())
163 return true;
164
165 Result.append(Record.begin() + Idx, Record.end());
166 return false;
167}
168
169// Strip all the TBAA attachment for the module.
170static void stripTBAA(Module *M) {
171 for (auto &F : *M) {
172 if (F.isMaterializable())
173 continue;
174 for (auto &I : instructions(F))
175 I.setMetadata(KindID: LLVMContext::MD_tbaa, Node: nullptr);
176 }
177}
178
179/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
180/// "epoch" encoded in the bitcode, and return the producer name if any.
181static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
182 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::IDENTIFICATION_BLOCK_ID))
183 return std::move(Err);
184
185 // Read all the records.
186 SmallVector<uint64_t, 64> Record;
187
188 std::string ProducerIdentification;
189
190 while (true) {
191 BitstreamEntry Entry;
192 if (Error E = Stream.advance().moveInto(Value&: Entry))
193 return std::move(E);
194
195 switch (Entry.Kind) {
196 default:
197 case BitstreamEntry::Error:
198 return error(Message: "Malformed block");
199 case BitstreamEntry::EndBlock:
200 return ProducerIdentification;
201 case BitstreamEntry::Record:
202 // The interesting case.
203 break;
204 }
205
206 // Read a record.
207 Record.clear();
208 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
209 if (!MaybeBitCode)
210 return MaybeBitCode.takeError();
211 switch (MaybeBitCode.get()) {
212 default: // Default behavior: reject
213 return error(Message: "Invalid value");
214 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
215 convertToString(Record, Idx: 0, Result&: ProducerIdentification);
216 break;
217 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
218 unsigned epoch = (unsigned)Record[0];
219 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
220 return error(
221 Message: Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
222 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
223 }
224 }
225 }
226 }
227}
228
229static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
230 // We expect a number of well-defined blocks, though we don't necessarily
231 // need to understand them all.
232 while (true) {
233 if (Stream.AtEndOfStream())
234 return "";
235
236 BitstreamEntry Entry;
237 if (Error E = Stream.advance().moveInto(Value&: Entry))
238 return std::move(E);
239
240 switch (Entry.Kind) {
241 case BitstreamEntry::EndBlock:
242 case BitstreamEntry::Error:
243 return error(Message: "Malformed block");
244
245 case BitstreamEntry::SubBlock:
246 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
247 return readIdentificationBlock(Stream);
248
249 // Ignore other sub-blocks.
250 if (Error Err = Stream.SkipBlock())
251 return std::move(Err);
252 continue;
253 case BitstreamEntry::Record:
254 if (Error E = Stream.skipRecord(AbbrevID: Entry.ID).takeError())
255 return std::move(E);
256 continue;
257 }
258 }
259}
260
261static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
262 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID))
263 return std::move(Err);
264
265 SmallVector<uint64_t, 64> Record;
266 // Read all the records for this module.
267
268 while (true) {
269 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
270 if (!MaybeEntry)
271 return MaybeEntry.takeError();
272 BitstreamEntry Entry = MaybeEntry.get();
273
274 switch (Entry.Kind) {
275 case BitstreamEntry::SubBlock: // Handled for us already.
276 case BitstreamEntry::Error:
277 return error(Message: "Malformed block");
278 case BitstreamEntry::EndBlock:
279 return false;
280 case BitstreamEntry::Record:
281 // The interesting case.
282 break;
283 }
284
285 // Read a record.
286 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
287 if (!MaybeRecord)
288 return MaybeRecord.takeError();
289 switch (MaybeRecord.get()) {
290 default:
291 break; // Default behavior, ignore unknown content.
292 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
293 std::string S;
294 if (convertToString(Record, Idx: 0, Result&: S))
295 return error(Message: "Invalid section name record");
296
297 // Check for the i386 and other (x86_64, ARM) conventions
298
299 auto [Segment, Section] = StringRef(S).split(Separator: ",");
300 Segment = Segment.trim();
301 Section = Section.trim();
302
303 if (Segment == "__DATA" && Section.starts_with(Prefix: "__objc_catlist"))
304 return true;
305 if (Segment == "__OBJC" && Section.starts_with(Prefix: "__category"))
306 return true;
307 if (Segment == "__TEXT" && Section.starts_with(Prefix: "__swift"))
308 return true;
309 break;
310 }
311 }
312 Record.clear();
313 }
314 llvm_unreachable("Exit infinite loop");
315}
316
317static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
318 // We expect a number of well-defined blocks, though we don't necessarily
319 // need to understand them all.
320 while (true) {
321 BitstreamEntry Entry;
322 if (Error E = Stream.advance().moveInto(Value&: Entry))
323 return std::move(E);
324
325 switch (Entry.Kind) {
326 case BitstreamEntry::Error:
327 return error(Message: "Malformed block");
328 case BitstreamEntry::EndBlock:
329 return false;
330
331 case BitstreamEntry::SubBlock:
332 if (Entry.ID == bitc::MODULE_BLOCK_ID)
333 return hasObjCCategoryInModule(Stream);
334
335 // Ignore other sub-blocks.
336 if (Error Err = Stream.SkipBlock())
337 return std::move(Err);
338 continue;
339
340 case BitstreamEntry::Record:
341 if (Error E = Stream.skipRecord(AbbrevID: Entry.ID).takeError())
342 return std::move(E);
343 continue;
344 }
345 }
346}
347
348static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
349 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID))
350 return std::move(Err);
351
352 SmallVector<uint64_t, 64> Record;
353
354 std::string Triple;
355
356 // Read all the records for this module.
357 while (true) {
358 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
359 if (!MaybeEntry)
360 return MaybeEntry.takeError();
361 BitstreamEntry Entry = MaybeEntry.get();
362
363 switch (Entry.Kind) {
364 case BitstreamEntry::SubBlock: // Handled for us already.
365 case BitstreamEntry::Error:
366 return error(Message: "Malformed block");
367 case BitstreamEntry::EndBlock:
368 return Triple;
369 case BitstreamEntry::Record:
370 // The interesting case.
371 break;
372 }
373
374 // Read a record.
375 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
376 if (!MaybeRecord)
377 return MaybeRecord.takeError();
378 switch (MaybeRecord.get()) {
379 default: break; // Default behavior, ignore unknown content.
380 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
381 std::string S;
382 if (convertToString(Record, Idx: 0, Result&: S))
383 return error(Message: "Invalid triple record");
384 Triple = S;
385 break;
386 }
387 }
388 Record.clear();
389 }
390 llvm_unreachable("Exit infinite loop");
391}
392
393static Expected<std::string> readTriple(BitstreamCursor &Stream) {
394 // We expect a number of well-defined blocks, though we don't necessarily
395 // need to understand them all.
396 while (true) {
397 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
398 if (!MaybeEntry)
399 return MaybeEntry.takeError();
400 BitstreamEntry Entry = MaybeEntry.get();
401
402 switch (Entry.Kind) {
403 case BitstreamEntry::Error:
404 return error(Message: "Malformed block");
405 case BitstreamEntry::EndBlock:
406 return "";
407
408 case BitstreamEntry::SubBlock:
409 if (Entry.ID == bitc::MODULE_BLOCK_ID)
410 return readModuleTriple(Stream);
411
412 // Ignore other sub-blocks.
413 if (Error Err = Stream.SkipBlock())
414 return std::move(Err);
415 continue;
416
417 case BitstreamEntry::Record:
418 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(AbbrevID: Entry.ID))
419 continue;
420 else
421 return Skipped.takeError();
422 }
423 }
424}
425
426namespace {
427
428class BitcodeReaderBase {
429protected:
430 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
431 : Stream(std::move(Stream)), Strtab(Strtab) {
432 this->Stream.setBlockInfo(&BlockInfo);
433 }
434
435 BitstreamBlockInfo BlockInfo;
436 BitstreamCursor Stream;
437 StringRef Strtab;
438
439 /// In version 2 of the bitcode we store names of global values and comdats in
440 /// a string table rather than in the VST.
441 bool UseStrtab = false;
442
443 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
444
445 /// If this module uses a string table, pop the reference to the string table
446 /// and return the referenced string and the rest of the record. Otherwise
447 /// just return the record itself.
448 std::pair<StringRef, ArrayRef<uint64_t>>
449 readNameFromStrtab(ArrayRef<uint64_t> Record);
450
451 Error readBlockInfo();
452
453 // Contains an arbitrary and optional string identifying the bitcode producer
454 std::string ProducerIdentification;
455
456 Error error(const Twine &Message);
457};
458
459} // end anonymous namespace
460
461Error BitcodeReaderBase::error(const Twine &Message) {
462 std::string FullMsg = Message.str();
463 if (!ProducerIdentification.empty())
464 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
465 LLVM_VERSION_STRING "')";
466 return ::error(Message: FullMsg);
467}
468
469Expected<unsigned>
470BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
471 if (Record.empty())
472 return error(Message: "Invalid version record");
473 unsigned ModuleVersion = Record[0];
474 if (ModuleVersion > 2)
475 return error(Message: "Invalid value");
476 UseStrtab = ModuleVersion >= 2;
477 return ModuleVersion;
478}
479
480std::pair<StringRef, ArrayRef<uint64_t>>
481BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
482 if (!UseStrtab)
483 return {"", Record};
484 // Invalid reference. Let the caller complain about the record being empty.
485 if (Record[0] + Record[1] > Strtab.size())
486 return {"", {}};
487 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(N: 2)};
488}
489
490namespace {
491
492/// This represents a constant expression or constant aggregate using a custom
493/// structure internal to the bitcode reader. Later, this structure will be
494/// expanded by materializeValue() either into a constant expression/aggregate,
495/// or into an instruction sequence at the point of use. This allows us to
496/// upgrade bitcode using constant expressions even if this kind of constant
497/// expression is no longer supported.
498class BitcodeConstant final : public Value,
499 TrailingObjects<BitcodeConstant, unsigned> {
500 friend TrailingObjects;
501
502 // Value subclass ID: Pick largest possible value to avoid any clashes.
503 static constexpr uint8_t SubclassID = 255;
504
505public:
506 // Opcodes used for non-expressions. This includes constant aggregates
507 // (struct, array, vector) that might need expansion, as well as non-leaf
508 // constants that don't need expansion (no_cfi, dso_local, blockaddress),
509 // but still go through BitcodeConstant to avoid different uselist orders
510 // between the two cases.
511 static constexpr uint8_t ConstantStructOpcode = 255;
512 static constexpr uint8_t ConstantArrayOpcode = 254;
513 static constexpr uint8_t ConstantVectorOpcode = 253;
514 static constexpr uint8_t NoCFIOpcode = 252;
515 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
516 static constexpr uint8_t BlockAddressOpcode = 250;
517 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
518 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
519
520 // Separate struct to make passing different number of parameters to
521 // BitcodeConstant::create() more convenient.
522 struct ExtraInfo {
523 uint8_t Opcode;
524 uint8_t Flags;
525 unsigned BlockAddressBB = 0;
526 Type *SrcElemTy = nullptr;
527 std::optional<ConstantRange> InRange;
528
529 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, Type *SrcElemTy = nullptr,
530 std::optional<ConstantRange> InRange = std::nullopt)
531 : Opcode(Opcode), Flags(Flags), SrcElemTy(SrcElemTy),
532 InRange(std::move(InRange)) {}
533
534 ExtraInfo(uint8_t Opcode, uint8_t Flags, unsigned BlockAddressBB)
535 : Opcode(Opcode), Flags(Flags), BlockAddressBB(BlockAddressBB) {}
536 };
537
538 uint8_t Opcode;
539 uint8_t Flags;
540 unsigned NumOperands;
541 unsigned BlockAddressBB;
542 Type *SrcElemTy; // GEP source element type.
543 std::optional<ConstantRange> InRange; // GEP inrange attribute.
544
545private:
546 BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
547 : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
548 NumOperands(OpIDs.size()), BlockAddressBB(Info.BlockAddressBB),
549 SrcElemTy(Info.SrcElemTy), InRange(Info.InRange) {
550 llvm::uninitialized_copy(Src&: OpIDs, Dst: getTrailingObjects());
551 }
552
553 BitcodeConstant &operator=(const BitcodeConstant &) = delete;
554
555public:
556 static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
557 const ExtraInfo &Info,
558 ArrayRef<unsigned> OpIDs) {
559 void *Mem = A.Allocate(Size: totalSizeToAlloc<unsigned>(Counts: OpIDs.size()),
560 Alignment: alignof(BitcodeConstant));
561 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
562 }
563
564 static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
565
566 ArrayRef<unsigned> getOperandIDs() const {
567 return ArrayRef(getTrailingObjects(), NumOperands);
568 }
569
570 std::optional<ConstantRange> getInRange() const {
571 assert(Opcode == Instruction::GetElementPtr);
572 return InRange;
573 }
574
575 const char *getOpcodeName() const {
576 return Instruction::getOpcodeName(Opcode);
577 }
578};
579
580class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
581 LLVMContext &Context;
582 Module *TheModule = nullptr;
583 // Next offset to start scanning for lazy parsing of function bodies.
584 uint64_t NextUnreadBit = 0;
585 // Last function offset found in the VST.
586 uint64_t LastFunctionBlockBit = 0;
587 bool SeenValueSymbolTable = false;
588 uint64_t VSTOffset = 0;
589
590 std::vector<std::string> SectionTable;
591 std::vector<std::string> GCTable;
592
593 std::vector<Type *> TypeList;
594 /// Track type IDs of contained types. Order is the same as the contained
595 /// types of a Type*. This is used during upgrades of typed pointer IR in
596 /// opaque pointer mode.
597 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
598 /// In some cases, we need to create a type ID for a type that was not
599 /// explicitly encoded in the bitcode, or we don't know about at the current
600 /// point. For example, a global may explicitly encode the value type ID, but
601 /// not have a type ID for the pointer to value type, for which we create a
602 /// virtual type ID instead. This map stores the new type ID that was created
603 /// for the given pair of Type and contained type ID.
604 DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
605 DenseMap<Function *, unsigned> FunctionTypeIDs;
606 /// Allocator for BitcodeConstants. This should come before ValueList,
607 /// because the ValueList might hold ValueHandles to these constants, so
608 /// ValueList must be destroyed before Alloc.
609 BumpPtrAllocator Alloc;
610 BitcodeReaderValueList ValueList;
611 std::optional<MetadataLoader> MDLoader;
612 std::vector<Comdat *> ComdatList;
613 DenseSet<GlobalObject *> ImplicitComdatObjects;
614 SmallVector<Instruction *, 64> InstructionList;
615
616 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
617 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
618
619 struct FunctionOperandInfo {
620 Function *F;
621 unsigned PersonalityFn;
622 unsigned Prefix;
623 unsigned Prologue;
624 };
625 std::vector<FunctionOperandInfo> FunctionOperands;
626
627 /// The set of attributes by index. Index zero in the file is for null, and
628 /// is thus not represented here. As such all indices are off by one.
629 std::vector<AttributeList> MAttributes;
630
631 /// The set of attribute groups.
632 std::map<unsigned, AttributeList> MAttributeGroups;
633
634 /// While parsing a function body, this is a list of the basic blocks for the
635 /// function.
636 std::vector<BasicBlock*> FunctionBBs;
637
638 // When reading the module header, this list is populated with functions that
639 // have bodies later in the file.
640 std::vector<Function*> FunctionsWithBodies;
641
642 // When intrinsic functions are encountered which require upgrading they are
643 // stored here with their replacement function.
644 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
645 UpdatedIntrinsicMap UpgradedIntrinsics;
646
647 // Several operations happen after the module header has been read, but
648 // before function bodies are processed. This keeps track of whether
649 // we've done this yet.
650 bool SeenFirstFunctionBody = false;
651
652 /// When function bodies are initially scanned, this map contains info about
653 /// where to find deferred function body in the stream.
654 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
655
656 /// When Metadata block is initially scanned when parsing the module, we may
657 /// choose to defer parsing of the metadata. This vector contains info about
658 /// which Metadata blocks are deferred.
659 std::vector<uint64_t> DeferredMetadataInfo;
660
661 /// These are basic blocks forward-referenced by block addresses. They are
662 /// inserted lazily into functions when they're loaded. The basic block ID is
663 /// its index into the vector.
664 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
665 std::deque<Function *> BasicBlockFwdRefQueue;
666
667 /// These are Functions that contain BlockAddresses which refer a different
668 /// Function. When parsing the different Function, queue Functions that refer
669 /// to the different Function. Those Functions must be materialized in order
670 /// to resolve their BlockAddress constants before the different Function
671 /// gets moved into another Module.
672 std::vector<Function *> BackwardRefFunctions;
673
674 /// Indicates that we are using a new encoding for instruction operands where
675 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
676 /// instruction number, for a more compact encoding. Some instruction
677 /// operands are not relative to the instruction ID: basic block numbers, and
678 /// types. Once the old style function blocks have been phased out, we would
679 /// not need this flag.
680 bool UseRelativeIDs = false;
681
682 /// True if all functions will be materialized, negating the need to process
683 /// (e.g.) blockaddress forward references.
684 bool WillMaterializeAllForwardRefs = false;
685
686 /// Tracks whether we have seen debug intrinsics or records in this bitcode;
687 /// seeing both in a single module is currently a fatal error.
688 bool SeenDebugIntrinsic = false;
689 bool SeenDebugRecord = false;
690
691 bool StripDebugInfo = false;
692 TBAAVerifier TBAAVerifyHelper;
693
694 std::vector<std::string> BundleTags;
695 SmallVector<SyncScope::ID, 8> SSIDs;
696
697 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
698
699public:
700 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
701 StringRef ProducerIdentification, LLVMContext &Context);
702
703 Error materializeForwardReferencedFunctions();
704
705 Error materialize(GlobalValue *GV) override;
706 Error materializeModule() override;
707 std::vector<StructType *> getIdentifiedStructTypes() const override;
708
709 /// Main interface to parsing a bitcode buffer.
710 /// \returns true if an error occurred.
711 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
712 bool IsImporting, ParserCallbacks Callbacks = {});
713
714 static uint64_t decodeSignRotatedValue(uint64_t V);
715
716 /// Materialize any deferred Metadata block.
717 Error materializeMetadata() override;
718
719 void setStripDebugInfo() override;
720
721private:
722 std::vector<StructType *> IdentifiedStructTypes;
723 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
724 StructType *createIdentifiedStructType(LLVMContext &Context);
725
726 static constexpr unsigned InvalidTypeID = ~0u;
727
728 Type *getTypeByID(unsigned ID);
729 Type *getPtrElementTypeByID(unsigned ID);
730 unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
731 unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
732
733 void callValueTypeCallback(Value *F, unsigned TypeID);
734 Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
735 Expected<Constant *> getValueForInitializer(unsigned ID);
736
737 Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
738 BasicBlock *ConstExprInsertBB) {
739 if (Ty && Ty->isMetadataTy())
740 return MetadataAsValue::get(Context&: Ty->getContext(), MD: getFnMetadataByID(ID));
741 return ValueList.getValueFwdRef(Idx: ID, Ty, TyID, ConstExprInsertBB);
742 }
743
744 Metadata *getFnMetadataByID(unsigned ID) {
745 return MDLoader->getMetadataFwdRefOrLoad(Idx: ID);
746 }
747
748 BasicBlock *getBasicBlock(unsigned ID) const {
749 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
750 return FunctionBBs[ID];
751 }
752
753 AttributeList getAttributes(unsigned i) const {
754 if (i-1 < MAttributes.size())
755 return MAttributes[i-1];
756 return AttributeList();
757 }
758
759 /// Read a value/type pair out of the specified record from slot 'Slot'.
760 /// Increment Slot past the number of slots used in the record. Return true on
761 /// failure.
762 bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
763 unsigned InstNum, Value *&ResVal, unsigned &TypeID,
764 BasicBlock *ConstExprInsertBB) {
765 if (Slot == Record.size()) return true;
766 unsigned ValNo = (unsigned)Record[Slot++];
767 // Adjust the ValNo, if it was encoded relative to the InstNum.
768 if (UseRelativeIDs)
769 ValNo = InstNum - ValNo;
770 if (ValNo < InstNum) {
771 // If this is not a forward reference, just return the value we already
772 // have.
773 TypeID = ValueList.getTypeID(ValNo);
774 ResVal = getFnValueByID(ID: ValNo, Ty: nullptr, TyID: TypeID, ConstExprInsertBB);
775 assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
776 "Incorrect type ID stored for value");
777 return ResVal == nullptr;
778 }
779 if (Slot == Record.size())
780 return true;
781
782 TypeID = (unsigned)Record[Slot++];
783 ResVal = getFnValueByID(ID: ValNo, Ty: getTypeByID(ID: TypeID), TyID: TypeID,
784 ConstExprInsertBB);
785 return ResVal == nullptr;
786 }
787
788 bool getValueOrMetadata(const SmallVectorImpl<uint64_t> &Record,
789 unsigned &Slot, unsigned InstNum, Value *&ResVal,
790 BasicBlock *ConstExprInsertBB) {
791 if (Slot == Record.size())
792 return true;
793 unsigned ValID = Record[Slot++];
794 if (ValID != static_cast<unsigned>(bitc::OB_METADATA)) {
795 unsigned TypeId;
796 return getValueTypePair(Record, Slot&: --Slot, InstNum, ResVal, TypeID&: TypeId,
797 ConstExprInsertBB);
798 }
799 if (Slot == Record.size())
800 return true;
801 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
802 ResVal = MetadataAsValue::get(Context, MD: getFnMetadataByID(ID: ValNo));
803 return false;
804 }
805
806 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
807 /// past the number of slots used by the value in the record. Return true if
808 /// there is an error.
809 bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
810 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
811 BasicBlock *ConstExprInsertBB) {
812 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
813 return true;
814 // All values currently take a single record slot.
815 ++Slot;
816 return false;
817 }
818
819 /// Like popValue, but does not increment the Slot number.
820 bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
821 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
822 BasicBlock *ConstExprInsertBB) {
823 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
824 return ResVal == nullptr;
825 }
826
827 /// Version of getValue that returns ResVal directly, or 0 if there is an
828 /// error.
829 Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
830 unsigned InstNum, Type *Ty, unsigned TyID,
831 BasicBlock *ConstExprInsertBB) {
832 if (Slot == Record.size()) return nullptr;
833 unsigned ValNo = (unsigned)Record[Slot];
834 // Adjust the ValNo, if it was encoded relative to the InstNum.
835 if (UseRelativeIDs)
836 ValNo = InstNum - ValNo;
837 return getFnValueByID(ID: ValNo, Ty, TyID, ConstExprInsertBB);
838 }
839
840 /// Like getValue, but decodes signed VBRs.
841 Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
842 unsigned InstNum, Type *Ty, unsigned TyID,
843 BasicBlock *ConstExprInsertBB) {
844 if (Slot == Record.size()) return nullptr;
845 unsigned ValNo = (unsigned)decodeSignRotatedValue(V: Record[Slot]);
846 // Adjust the ValNo, if it was encoded relative to the InstNum.
847 if (UseRelativeIDs)
848 ValNo = InstNum - ValNo;
849 return getFnValueByID(ID: ValNo, Ty, TyID, ConstExprInsertBB);
850 }
851
852 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
853 unsigned &OpNum,
854 unsigned BitWidth) {
855 if (Record.size() - OpNum < 2)
856 return error(Message: "Too few records for range");
857 if (BitWidth > 64) {
858 unsigned LowerActiveWords = Record[OpNum];
859 unsigned UpperActiveWords = Record[OpNum++] >> 32;
860 if (Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
861 return error(Message: "Too few records for range");
862 APInt Lower =
863 readWideAPInt(Vals: ArrayRef(&Record[OpNum], LowerActiveWords), TypeBits: BitWidth);
864 OpNum += LowerActiveWords;
865 APInt Upper =
866 readWideAPInt(Vals: ArrayRef(&Record[OpNum], UpperActiveWords), TypeBits: BitWidth);
867 OpNum += UpperActiveWords;
868 return ConstantRange(Lower, Upper);
869 } else {
870 int64_t Start = BitcodeReader::decodeSignRotatedValue(V: Record[OpNum++]);
871 int64_t End = BitcodeReader::decodeSignRotatedValue(V: Record[OpNum++]);
872 return ConstantRange(APInt(BitWidth, Start, true),
873 APInt(BitWidth, End, true));
874 }
875 }
876
877 Expected<ConstantRange>
878 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record, unsigned &OpNum) {
879 if (Record.size() - OpNum < 1)
880 return error(Message: "Too few records for range");
881 unsigned BitWidth = Record[OpNum++];
882 return readConstantRange(Record, OpNum, BitWidth);
883 }
884
885 /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
886 /// corresponding argument's pointee type. Also upgrades intrinsics that now
887 /// require an elementtype attribute.
888 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
889
890 /// Converts alignment exponent (i.e. power of two (or zero)) to the
891 /// corresponding alignment to use. If alignment is too large, returns
892 /// a corresponding error code.
893 Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
894 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
895 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
896 ParserCallbacks Callbacks = {});
897
898 Error parseComdatRecord(ArrayRef<uint64_t> Record);
899 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
900 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
901 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
902 ArrayRef<uint64_t> Record);
903
904 Error parseAttributeBlock();
905 Error parseAttributeGroupBlock();
906 Error parseTypeTable();
907 Error parseTypeTableBody();
908 Error parseOperandBundleTags();
909 Error parseSyncScopeNames();
910
911 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
912 unsigned NameIndex, Triple &TT);
913 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
914 ArrayRef<uint64_t> Record);
915 Error parseValueSymbolTable(uint64_t Offset = 0);
916 Error parseGlobalValueSymbolTable();
917 Error parseConstants();
918 Error rememberAndSkipFunctionBodies();
919 Error rememberAndSkipFunctionBody();
920 /// Save the positions of the Metadata blocks and skip parsing the blocks.
921 Error rememberAndSkipMetadata();
922 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
923 Error parseFunctionBody(Function *F);
924 Error globalCleanup();
925 Error resolveGlobalAndIndirectSymbolInits();
926 Error parseUseLists();
927 Error findFunctionInStream(
928 Function *F,
929 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
930
931 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
932};
933
934/// Class to manage reading and parsing function summary index bitcode
935/// files/sections.
936class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
937 /// The module index built during parsing.
938 ModuleSummaryIndex &TheIndex;
939
940 /// Indicates whether we have encountered a global value summary section
941 /// yet during parsing.
942 bool SeenGlobalValSummary = false;
943
944 /// Indicates whether we have already parsed the VST, used for error checking.
945 bool SeenValueSymbolTable = false;
946
947 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
948 /// Used to enable on-demand parsing of the VST.
949 uint64_t VSTOffset = 0;
950
951 // Map to save ValueId to ValueInfo association that was recorded in the
952 // ValueSymbolTable. It is used after the VST is parsed to convert
953 // call graph edges read from the function summary from referencing
954 // callees by their ValueId to using the ValueInfo instead, which is how
955 // they are recorded in the summary index being built.
956 // We save a GUID which refers to the same global as the ValueInfo, but
957 // ignoring the linkage, i.e. for values other than local linkage they are
958 // identical (this is the second member). ValueInfo has the real GUID.
959 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
960 ValueIdToValueInfoMap;
961
962 /// Map populated during module path string table parsing, from the
963 /// module ID to a string reference owned by the index's module
964 /// path string table, used to correlate with combined index
965 /// summary records.
966 DenseMap<uint64_t, StringRef> ModuleIdMap;
967
968 /// Original source file name recorded in a bitcode record.
969 std::string SourceFileName;
970
971 /// The string identifier given to this module by the client, normally the
972 /// path to the bitcode file.
973 StringRef ModulePath;
974
975 /// Callback to ask whether a symbol is the prevailing copy when invoked
976 /// during combined index building.
977 std::function<bool(GlobalValue::GUID)> IsPrevailing;
978
979 /// Saves the stack ids from the STACK_IDS record to consult when adding stack
980 /// ids from the lists in the callsite and alloc entries to the index.
981 std::vector<uint64_t> StackIds;
982
983 /// Linearized radix tree of allocation contexts. See the description above
984 /// the CallStackRadixTreeBuilder class in ProfileData/MemProf.h for format.
985 std::vector<uint64_t> RadixArray;
986
987 /// Map from the module's stack id index to the index in the
988 /// ModuleSummaryIndex's StackIds vector. Populated lazily from the StackIds
989 /// list and used to avoid repeated hash lookups.
990 std::vector<unsigned> StackIdToIndex;
991
992public:
993 ModuleSummaryIndexBitcodeReader(
994 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
995 StringRef ModulePath,
996 std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
997
998 Error parseModule();
999
1000private:
1001 void setValueGUID(uint64_t ValueID, StringRef ValueName,
1002 GlobalValue::LinkageTypes Linkage,
1003 StringRef SourceFileName);
1004 Error parseValueSymbolTable(
1005 uint64_t Offset,
1006 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1007 SmallVector<ValueInfo, 0> makeRefList(ArrayRef<uint64_t> Record);
1008 SmallVector<FunctionSummary::EdgeTy, 0>
1009 makeCallList(ArrayRef<uint64_t> Record, bool IsOldProfileFormat,
1010 bool HasProfile, bool HasRelBF);
1011 Error parseEntireSummary(unsigned ID);
1012 Error parseModuleStringTable();
1013 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1014 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
1015 TypeIdCompatibleVtableInfo &TypeId);
1016 std::vector<FunctionSummary::ParamAccess>
1017 parseParamAccesses(ArrayRef<uint64_t> Record);
1018 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1019 unsigned &I);
1020
1021 // Mark uninitialized stack ID mappings for lazy population.
1022 static constexpr unsigned UninitializedStackIdIndex =
1023 std::numeric_limits<unsigned>::max();
1024
1025 unsigned getStackIdIndex(unsigned LocalIndex) {
1026 unsigned &Index = StackIdToIndex[LocalIndex];
1027 // Add the stack id to the ModuleSummaryIndex map only when first requested
1028 // and cache the result in the local StackIdToIndex map.
1029 if (Index == UninitializedStackIdIndex)
1030 Index = TheIndex.addOrGetStackIdIndex(StackId: StackIds[LocalIndex]);
1031 return Index;
1032 }
1033
1034 template <bool AllowNullValueInfo = false>
1035 std::pair<ValueInfo, GlobalValue::GUID>
1036 getValueInfoFromValueId(unsigned ValueId);
1037
1038 void addThisModule();
1039 ModuleSummaryIndex::ModuleInfo *getThisModule();
1040};
1041
1042} // end anonymous namespace
1043
1044std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
1045 Error Err) {
1046 if (Err) {
1047 std::error_code EC;
1048 handleAllErrors(E: std::move(Err), Handlers: [&](ErrorInfoBase &EIB) {
1049 EC = EIB.convertToErrorCode();
1050 Ctx.emitError(ErrorStr: EIB.message());
1051 });
1052 return EC;
1053 }
1054 return std::error_code();
1055}
1056
1057BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
1058 StringRef ProducerIdentification,
1059 LLVMContext &Context)
1060 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
1061 ValueList(this->Stream.SizeInBytes(),
1062 [this](unsigned ValID, BasicBlock *InsertBB) {
1063 return materializeValue(ValID, InsertBB);
1064 }) {
1065 this->ProducerIdentification = std::string(ProducerIdentification);
1066}
1067
1068Error BitcodeReader::materializeForwardReferencedFunctions() {
1069 if (WillMaterializeAllForwardRefs)
1070 return Error::success();
1071
1072 // Prevent recursion.
1073 WillMaterializeAllForwardRefs = true;
1074
1075 while (!BasicBlockFwdRefQueue.empty()) {
1076 Function *F = BasicBlockFwdRefQueue.front();
1077 BasicBlockFwdRefQueue.pop_front();
1078 assert(F && "Expected valid function");
1079 if (!BasicBlockFwdRefs.count(Val: F))
1080 // Already materialized.
1081 continue;
1082
1083 // Check for a function that isn't materializable to prevent an infinite
1084 // loop. When parsing a blockaddress stored in a global variable, there
1085 // isn't a trivial way to check if a function will have a body without a
1086 // linear search through FunctionsWithBodies, so just check it here.
1087 if (!F->isMaterializable())
1088 return error(Message: "Never resolved function from blockaddress");
1089
1090 // Try to materialize F.
1091 if (Error Err = materialize(GV: F))
1092 return Err;
1093 }
1094 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
1095
1096 for (Function *F : BackwardRefFunctions)
1097 if (Error Err = materialize(GV: F))
1098 return Err;
1099 BackwardRefFunctions.clear();
1100
1101 // Reset state.
1102 WillMaterializeAllForwardRefs = false;
1103 return Error::success();
1104}
1105
1106//===----------------------------------------------------------------------===//
1107// Helper functions to implement forward reference resolution, etc.
1108//===----------------------------------------------------------------------===//
1109
1110static bool hasImplicitComdat(size_t Val) {
1111 switch (Val) {
1112 default:
1113 return false;
1114 case 1: // Old WeakAnyLinkage
1115 case 4: // Old LinkOnceAnyLinkage
1116 case 10: // Old WeakODRLinkage
1117 case 11: // Old LinkOnceODRLinkage
1118 return true;
1119 }
1120}
1121
1122static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
1123 switch (Val) {
1124 default: // Map unknown/new linkages to external
1125 case 0:
1126 return GlobalValue::ExternalLinkage;
1127 case 2:
1128 return GlobalValue::AppendingLinkage;
1129 case 3:
1130 return GlobalValue::InternalLinkage;
1131 case 5:
1132 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
1133 case 6:
1134 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
1135 case 7:
1136 return GlobalValue::ExternalWeakLinkage;
1137 case 8:
1138 return GlobalValue::CommonLinkage;
1139 case 9:
1140 return GlobalValue::PrivateLinkage;
1141 case 12:
1142 return GlobalValue::AvailableExternallyLinkage;
1143 case 13:
1144 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
1145 case 14:
1146 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
1147 case 15:
1148 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
1149 case 1: // Old value with implicit comdat.
1150 case 16:
1151 return GlobalValue::WeakAnyLinkage;
1152 case 10: // Old value with implicit comdat.
1153 case 17:
1154 return GlobalValue::WeakODRLinkage;
1155 case 4: // Old value with implicit comdat.
1156 case 18:
1157 return GlobalValue::LinkOnceAnyLinkage;
1158 case 11: // Old value with implicit comdat.
1159 case 19:
1160 return GlobalValue::LinkOnceODRLinkage;
1161 }
1162}
1163
1164static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
1165 FunctionSummary::FFlags Flags;
1166 Flags.ReadNone = RawFlags & 0x1;
1167 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1168 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1169 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1170 Flags.NoInline = (RawFlags >> 4) & 0x1;
1171 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1172 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1173 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1174 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1175 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1176 return Flags;
1177}
1178
1179// Decode the flags for GlobalValue in the summary. The bits for each attribute:
1180//
1181// linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1182// visibility: [8, 10).
1183static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
1184 uint64_t Version) {
1185 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1186 // like getDecodedLinkage() above. Any future change to the linkage enum and
1187 // to getDecodedLinkage() will need to be taken into account here as above.
1188 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1189 auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1190 auto IK = GlobalValueSummary::ImportKind((RawFlags >> 10) & 1); // 1 bit
1191 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1); // 1 bit
1192 RawFlags = RawFlags >> 4;
1193 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1194 // The Live flag wasn't introduced until version 3. For dead stripping
1195 // to work correctly on earlier versions, we must conservatively treat all
1196 // values as live.
1197 bool Live = (RawFlags & 0x2) || Version < 3;
1198 bool Local = (RawFlags & 0x4);
1199 bool AutoHide = (RawFlags & 0x8);
1200
1201 return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1202 Live, Local, AutoHide, IK,
1203 NoRenameOnPromotion);
1204}
1205
1206// Decode the flags for GlobalVariable in the summary
1207static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
1208 return GlobalVarSummary::GVarFlags(
1209 (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
1210 (RawFlags & 0x4) ? true : false,
1211 (GlobalObject::VCallVisibility)(RawFlags >> 3));
1212}
1213
1214static std::pair<CalleeInfo::HotnessType, bool>
1215getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) {
1216 CalleeInfo::HotnessType Hotness =
1217 static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1218 bool HasTailCall = (RawFlags & 0x8); // 1 bit
1219 return {Hotness, HasTailCall};
1220}
1221
1222// Deprecated, but still needed to read old bitcode files.
1223static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1224 bool &HasTailCall) {
1225 static constexpr unsigned RelBlockFreqBits = 28;
1226 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1227 RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1228 HasTailCall = (RawFlags & (1 << RelBlockFreqBits)); // 1 bit
1229}
1230
1231static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
1232 switch (Val) {
1233 default: // Map unknown visibilities to default.
1234 case 0: return GlobalValue::DefaultVisibility;
1235 case 1: return GlobalValue::HiddenVisibility;
1236 case 2: return GlobalValue::ProtectedVisibility;
1237 }
1238}
1239
1240static GlobalValue::DLLStorageClassTypes
1241getDecodedDLLStorageClass(unsigned Val) {
1242 switch (Val) {
1243 default: // Map unknown values to default.
1244 case 0: return GlobalValue::DefaultStorageClass;
1245 case 1: return GlobalValue::DLLImportStorageClass;
1246 case 2: return GlobalValue::DLLExportStorageClass;
1247 }
1248}
1249
1250static bool getDecodedDSOLocal(unsigned Val) {
1251 switch(Val) {
1252 default: // Map unknown values to preemptable.
1253 case 0: return false;
1254 case 1: return true;
1255 }
1256}
1257
1258static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1259 switch (Val) {
1260 case 1:
1261 return CodeModel::Tiny;
1262 case 2:
1263 return CodeModel::Small;
1264 case 3:
1265 return CodeModel::Kernel;
1266 case 4:
1267 return CodeModel::Medium;
1268 case 5:
1269 return CodeModel::Large;
1270 }
1271
1272 return {};
1273}
1274
1275static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1276 switch (Val) {
1277 case 0: return GlobalVariable::NotThreadLocal;
1278 default: // Map unknown non-zero value to general dynamic.
1279 case 1: return GlobalVariable::GeneralDynamicTLSModel;
1280 case 2: return GlobalVariable::LocalDynamicTLSModel;
1281 case 3: return GlobalVariable::InitialExecTLSModel;
1282 case 4: return GlobalVariable::LocalExecTLSModel;
1283 }
1284}
1285
1286static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1287 switch (Val) {
1288 default: // Map unknown to UnnamedAddr::None.
1289 case 0: return GlobalVariable::UnnamedAddr::None;
1290 case 1: return GlobalVariable::UnnamedAddr::Global;
1291 case 2: return GlobalVariable::UnnamedAddr::Local;
1292 }
1293}
1294
1295static int getDecodedCastOpcode(unsigned Val) {
1296 switch (Val) {
1297 default: return -1;
1298 case bitc::CAST_TRUNC : return Instruction::Trunc;
1299 case bitc::CAST_ZEXT : return Instruction::ZExt;
1300 case bitc::CAST_SEXT : return Instruction::SExt;
1301 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
1302 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
1303 case bitc::CAST_UITOFP : return Instruction::UIToFP;
1304 case bitc::CAST_SITOFP : return Instruction::SIToFP;
1305 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1306 case bitc::CAST_FPEXT : return Instruction::FPExt;
1307 case bitc::CAST_PTRTOADDR: return Instruction::PtrToAddr;
1308 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1309 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1310 case bitc::CAST_BITCAST : return Instruction::BitCast;
1311 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1312 }
1313}
1314
1315static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1316 bool IsFP = Ty->isFPOrFPVectorTy();
1317 // UnOps are only valid for int/fp or vector of int/fp types
1318 if (!IsFP && !Ty->isIntOrIntVectorTy())
1319 return -1;
1320
1321 switch (Val) {
1322 default:
1323 return -1;
1324 case bitc::UNOP_FNEG:
1325 return IsFP ? Instruction::FNeg : -1;
1326 }
1327}
1328
1329static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1330 bool IsFP = Ty->isFPOrFPVectorTy();
1331 // BinOps are only valid for int/fp or vector of int/fp types
1332 if (!IsFP && !Ty->isIntOrIntVectorTy())
1333 return -1;
1334
1335 switch (Val) {
1336 default:
1337 return -1;
1338 case bitc::BINOP_ADD:
1339 return IsFP ? Instruction::FAdd : Instruction::Add;
1340 case bitc::BINOP_SUB:
1341 return IsFP ? Instruction::FSub : Instruction::Sub;
1342 case bitc::BINOP_MUL:
1343 return IsFP ? Instruction::FMul : Instruction::Mul;
1344 case bitc::BINOP_UDIV:
1345 return IsFP ? -1 : Instruction::UDiv;
1346 case bitc::BINOP_SDIV:
1347 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1348 case bitc::BINOP_UREM:
1349 return IsFP ? -1 : Instruction::URem;
1350 case bitc::BINOP_SREM:
1351 return IsFP ? Instruction::FRem : Instruction::SRem;
1352 case bitc::BINOP_SHL:
1353 return IsFP ? -1 : Instruction::Shl;
1354 case bitc::BINOP_LSHR:
1355 return IsFP ? -1 : Instruction::LShr;
1356 case bitc::BINOP_ASHR:
1357 return IsFP ? -1 : Instruction::AShr;
1358 case bitc::BINOP_AND:
1359 return IsFP ? -1 : Instruction::And;
1360 case bitc::BINOP_OR:
1361 return IsFP ? -1 : Instruction::Or;
1362 case bitc::BINOP_XOR:
1363 return IsFP ? -1 : Instruction::Xor;
1364 }
1365}
1366
1367static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1368 switch (Val) {
1369 default: return AtomicRMWInst::BAD_BINOP;
1370 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1371 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1372 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1373 case bitc::RMW_AND: return AtomicRMWInst::And;
1374 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1375 case bitc::RMW_OR: return AtomicRMWInst::Or;
1376 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1377 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1378 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1379 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1380 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1381 case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1382 case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1383 case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
1384 case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
1385 case bitc::RMW_FMAXIMUM:
1386 return AtomicRMWInst::FMaximum;
1387 case bitc::RMW_FMINIMUM:
1388 return AtomicRMWInst::FMinimum;
1389 case bitc::RMW_UINC_WRAP:
1390 return AtomicRMWInst::UIncWrap;
1391 case bitc::RMW_UDEC_WRAP:
1392 return AtomicRMWInst::UDecWrap;
1393 case bitc::RMW_USUB_COND:
1394 return AtomicRMWInst::USubCond;
1395 case bitc::RMW_USUB_SAT:
1396 return AtomicRMWInst::USubSat;
1397 }
1398}
1399
1400static AtomicOrdering getDecodedOrdering(unsigned Val) {
1401 switch (Val) {
1402 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1403 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1404 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1405 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1406 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1407 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1408 default: // Map unknown orderings to sequentially-consistent.
1409 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1410 }
1411}
1412
1413static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1414 switch (Val) {
1415 default: // Map unknown selection kinds to any.
1416 case bitc::COMDAT_SELECTION_KIND_ANY:
1417 return Comdat::Any;
1418 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1419 return Comdat::ExactMatch;
1420 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1421 return Comdat::Largest;
1422 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1423 return Comdat::NoDeduplicate;
1424 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1425 return Comdat::SameSize;
1426 }
1427}
1428
1429static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1430 FastMathFlags FMF;
1431 if (0 != (Val & bitc::UnsafeAlgebra))
1432 FMF.setFast();
1433 if (0 != (Val & bitc::AllowReassoc))
1434 FMF.setAllowReassoc();
1435 if (0 != (Val & bitc::NoNaNs))
1436 FMF.setNoNaNs();
1437 if (0 != (Val & bitc::NoInfs))
1438 FMF.setNoInfs();
1439 if (0 != (Val & bitc::NoSignedZeros))
1440 FMF.setNoSignedZeros();
1441 if (0 != (Val & bitc::AllowReciprocal))
1442 FMF.setAllowReciprocal();
1443 if (0 != (Val & bitc::AllowContract))
1444 FMF.setAllowContract(true);
1445 if (0 != (Val & bitc::ApproxFunc))
1446 FMF.setApproxFunc();
1447 return FMF;
1448}
1449
1450static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1451 // A GlobalValue with local linkage cannot have a DLL storage class.
1452 if (GV->hasLocalLinkage())
1453 return;
1454 switch (Val) {
1455 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1456 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1457 }
1458}
1459
1460Type *BitcodeReader::getTypeByID(unsigned ID) {
1461 // The type table size is always specified correctly.
1462 if (ID >= TypeList.size())
1463 return nullptr;
1464
1465 if (Type *Ty = TypeList[ID])
1466 return Ty;
1467
1468 // If we have a forward reference, the only possible case is when it is to a
1469 // named struct. Just create a placeholder for now.
1470 return TypeList[ID] = createIdentifiedStructType(Context);
1471}
1472
1473unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
1474 auto It = ContainedTypeIDs.find(Val: ID);
1475 if (It == ContainedTypeIDs.end())
1476 return InvalidTypeID;
1477
1478 if (Idx >= It->second.size())
1479 return InvalidTypeID;
1480
1481 return It->second[Idx];
1482}
1483
1484Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
1485 if (ID >= TypeList.size())
1486 return nullptr;
1487
1488 Type *Ty = TypeList[ID];
1489 if (!Ty->isPointerTy())
1490 return nullptr;
1491
1492 return getTypeByID(ID: getContainedTypeID(ID, Idx: 0));
1493}
1494
1495unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
1496 ArrayRef<unsigned> ChildTypeIDs) {
1497 unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
1498 auto CacheKey = std::make_pair(x&: Ty, y&: ChildTypeID);
1499 auto It = VirtualTypeIDs.find(Val: CacheKey);
1500 if (It != VirtualTypeIDs.end()) {
1501 // The cmpxchg return value is the only place we need more than one
1502 // contained type ID, however the second one will always be the same (i1),
1503 // so we don't need to include it in the cache key. This asserts that the
1504 // contained types are indeed as expected and there are no collisions.
1505 assert((ChildTypeIDs.empty() ||
1506 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1507 "Incorrect cached contained type IDs");
1508 return It->second;
1509 }
1510
1511 unsigned TypeID = TypeList.size();
1512 TypeList.push_back(x: Ty);
1513 if (!ChildTypeIDs.empty())
1514 append_range(C&: ContainedTypeIDs[TypeID], R&: ChildTypeIDs);
1515 VirtualTypeIDs.insert(KV: {CacheKey, TypeID});
1516 return TypeID;
1517}
1518
1519static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags) {
1520 GEPNoWrapFlags NW;
1521 if (Flags & (1 << bitc::GEP_INBOUNDS))
1522 NW |= GEPNoWrapFlags::inBounds();
1523 if (Flags & (1 << bitc::GEP_NUSW))
1524 NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
1525 if (Flags & (1 << bitc::GEP_NUW))
1526 NW |= GEPNoWrapFlags::noUnsignedWrap();
1527 return NW;
1528}
1529
1530static bool isConstExprSupported(const BitcodeConstant *BC) {
1531 uint8_t Opcode = BC->Opcode;
1532
1533 // These are not real constant expressions, always consider them supported.
1534 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1535 return true;
1536
1537 // If -expand-constant-exprs is set, we want to consider all expressions
1538 // as unsupported.
1539 if (ExpandConstantExprs)
1540 return false;
1541
1542 if (Instruction::isBinaryOp(Opcode))
1543 return ConstantExpr::isSupportedBinOp(Opcode);
1544
1545 if (Instruction::isCast(Opcode))
1546 return ConstantExpr::isSupportedCastOp(Opcode);
1547
1548 if (Opcode == Instruction::GetElementPtr)
1549 return ConstantExpr::isSupportedGetElementPtr(SrcElemTy: BC->SrcElemTy);
1550
1551 switch (Opcode) {
1552 case Instruction::FNeg:
1553 case Instruction::Select:
1554 case Instruction::ICmp:
1555 case Instruction::FCmp:
1556 return false;
1557 default:
1558 return true;
1559 }
1560}
1561
1562Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
1563 BasicBlock *InsertBB) {
1564 // Quickly handle the case where there is no BitcodeConstant to resolve.
1565 if (StartValID < ValueList.size() && ValueList[StartValID] &&
1566 !isa<BitcodeConstant>(Val: ValueList[StartValID]))
1567 return ValueList[StartValID];
1568
1569 SmallDenseMap<unsigned, Value *> MaterializedValues;
1570 SmallVector<unsigned> Worklist;
1571 Worklist.push_back(Elt: StartValID);
1572 while (!Worklist.empty()) {
1573 unsigned ValID = Worklist.back();
1574 if (MaterializedValues.count(Val: ValID)) {
1575 // Duplicate expression that was already handled.
1576 Worklist.pop_back();
1577 continue;
1578 }
1579
1580 if (ValID >= ValueList.size() || !ValueList[ValID])
1581 return error(Message: "Invalid value ID");
1582
1583 Value *V = ValueList[ValID];
1584 auto *BC = dyn_cast<BitcodeConstant>(Val: V);
1585 if (!BC) {
1586 MaterializedValues.insert(KV: {ValID, V});
1587 Worklist.pop_back();
1588 continue;
1589 }
1590
1591 // Iterate in reverse, so values will get popped from the worklist in
1592 // expected order.
1593 SmallVector<Value *> Ops;
1594 for (unsigned OpID : reverse(C: BC->getOperandIDs())) {
1595 auto It = MaterializedValues.find(Val: OpID);
1596 if (It != MaterializedValues.end())
1597 Ops.push_back(Elt: It->second);
1598 else
1599 Worklist.push_back(Elt: OpID);
1600 }
1601
1602 // Some expressions have not been resolved yet, handle them first and then
1603 // revisit this one.
1604 if (Ops.size() != BC->getOperandIDs().size())
1605 continue;
1606 std::reverse(first: Ops.begin(), last: Ops.end());
1607
1608 SmallVector<Constant *> ConstOps;
1609 for (Value *Op : Ops)
1610 if (auto *C = dyn_cast<Constant>(Val: Op))
1611 ConstOps.push_back(Elt: C);
1612
1613 // Materialize as constant expression if possible.
1614 if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
1615 Constant *C;
1616 if (Instruction::isCast(Opcode: BC->Opcode)) {
1617 C = UpgradeBitCastExpr(Opc: BC->Opcode, C: ConstOps[0], DestTy: BC->getType());
1618 if (!C)
1619 C = ConstantExpr::getCast(ops: BC->Opcode, C: ConstOps[0], Ty: BC->getType());
1620 } else if (Instruction::isBinaryOp(Opcode: BC->Opcode)) {
1621 C = ConstantExpr::get(Opcode: BC->Opcode, C1: ConstOps[0], C2: ConstOps[1], Flags: BC->Flags);
1622 } else {
1623 switch (BC->Opcode) {
1624 case BitcodeConstant::ConstantPtrAuthOpcode: {
1625 auto *Key = dyn_cast<ConstantInt>(Val: ConstOps[1]);
1626 if (!Key)
1627 return error(Message: "ptrauth key operand must be ConstantInt");
1628
1629 auto *Disc = dyn_cast<ConstantInt>(Val: ConstOps[2]);
1630 if (!Disc)
1631 return error(Message: "ptrauth disc operand must be ConstantInt");
1632
1633 Constant *DeactivationSymbol =
1634 ConstOps.size() > 4 ? ConstOps[4]
1635 : ConstantPointerNull::get(T: cast<PointerType>(
1636 Val: ConstOps[3]->getType()));
1637 if (!DeactivationSymbol->getType()->isPointerTy())
1638 return error(
1639 Message: "ptrauth deactivation symbol operand must be a pointer");
1640
1641 C = ConstantPtrAuth::get(Ptr: ConstOps[0], Key, Disc, AddrDisc: ConstOps[3],
1642 DeactivationSymbol);
1643 break;
1644 }
1645 case BitcodeConstant::NoCFIOpcode: {
1646 auto *GV = dyn_cast<GlobalValue>(Val: ConstOps[0]);
1647 if (!GV)
1648 return error(Message: "no_cfi operand must be GlobalValue");
1649 C = NoCFIValue::get(GV);
1650 break;
1651 }
1652 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1653 auto *GV = dyn_cast<GlobalValue>(Val: ConstOps[0]);
1654 if (!GV)
1655 return error(Message: "dso_local operand must be GlobalValue");
1656 C = DSOLocalEquivalent::get(GV);
1657 break;
1658 }
1659 case BitcodeConstant::BlockAddressOpcode: {
1660 Function *Fn = dyn_cast<Function>(Val: ConstOps[0]);
1661 if (!Fn)
1662 return error(Message: "blockaddress operand must be a function");
1663
1664 // If the function is already parsed we can insert the block address
1665 // right away.
1666 BasicBlock *BB;
1667 unsigned BBID = BC->BlockAddressBB;
1668 if (!BBID)
1669 // Invalid reference to entry block.
1670 return error(Message: "Invalid ID");
1671 if (!Fn->empty()) {
1672 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1673 for (size_t I = 0, E = BBID; I != E; ++I) {
1674 if (BBI == BBE)
1675 return error(Message: "Invalid ID");
1676 ++BBI;
1677 }
1678 BB = &*BBI;
1679 } else {
1680 // Otherwise insert a placeholder and remember it so it can be
1681 // inserted when the function is parsed.
1682 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1683 if (FwdBBs.empty())
1684 BasicBlockFwdRefQueue.push_back(x: Fn);
1685 if (FwdBBs.size() < BBID + 1)
1686 FwdBBs.resize(new_size: BBID + 1);
1687 if (!FwdBBs[BBID])
1688 FwdBBs[BBID] = BasicBlock::Create(Context);
1689 BB = FwdBBs[BBID];
1690 }
1691 C = BlockAddress::get(Ty: Fn->getType(), BB);
1692 break;
1693 }
1694 case BitcodeConstant::ConstantStructOpcode: {
1695 auto *ST = cast<StructType>(Val: BC->getType());
1696 if (ST->getNumElements() != ConstOps.size())
1697 return error(Message: "Invalid number of elements in struct initializer");
1698
1699 for (const auto [Ty, Op] : zip(t: ST->elements(), u&: ConstOps))
1700 if (Op->getType() != Ty)
1701 return error(Message: "Incorrect type in struct initializer");
1702
1703 C = ConstantStruct::get(T: ST, V: ConstOps);
1704 break;
1705 }
1706 case BitcodeConstant::ConstantArrayOpcode: {
1707 auto *AT = cast<ArrayType>(Val: BC->getType());
1708 if (AT->getNumElements() != ConstOps.size())
1709 return error(Message: "Invalid number of elements in array initializer");
1710
1711 for (Constant *Op : ConstOps)
1712 if (Op->getType() != AT->getElementType())
1713 return error(Message: "Incorrect type in array initializer");
1714
1715 C = ConstantArray::get(T: AT, V: ConstOps);
1716 break;
1717 }
1718 case BitcodeConstant::ConstantVectorOpcode: {
1719 auto *VT = cast<FixedVectorType>(Val: BC->getType());
1720 if (VT->getNumElements() != ConstOps.size())
1721 return error(Message: "Invalid number of elements in vector initializer");
1722
1723 for (Constant *Op : ConstOps)
1724 if (Op->getType() != VT->getElementType())
1725 return error(Message: "Incorrect type in vector initializer");
1726
1727 C = ConstantVector::get(V: ConstOps);
1728 break;
1729 }
1730 case Instruction::GetElementPtr:
1731 C = ConstantExpr::getGetElementPtr(
1732 Ty: BC->SrcElemTy, C: ConstOps[0], IdxList: ArrayRef(ConstOps).drop_front(),
1733 NW: toGEPNoWrapFlags(Flags: BC->Flags), InRange: BC->getInRange());
1734 break;
1735 case Instruction::ExtractElement:
1736 C = ConstantExpr::getExtractElement(Vec: ConstOps[0], Idx: ConstOps[1]);
1737 break;
1738 case Instruction::InsertElement:
1739 C = ConstantExpr::getInsertElement(Vec: ConstOps[0], Elt: ConstOps[1],
1740 Idx: ConstOps[2]);
1741 break;
1742 case Instruction::ShuffleVector: {
1743 SmallVector<int, 16> Mask;
1744 ShuffleVectorInst::getShuffleMask(Mask: ConstOps[2], Result&: Mask);
1745 C = ConstantExpr::getShuffleVector(V1: ConstOps[0], V2: ConstOps[1], Mask);
1746 break;
1747 }
1748 default:
1749 llvm_unreachable("Unhandled bitcode constant");
1750 }
1751 }
1752
1753 // Cache resolved constant.
1754 ValueList.replaceValueWithoutRAUW(ValNo: ValID, NewV: C);
1755 MaterializedValues.insert(KV: {ValID, C});
1756 Worklist.pop_back();
1757 continue;
1758 }
1759
1760 if (!InsertBB)
1761 return error(Message: Twine("Value referenced by initializer is an unsupported "
1762 "constant expression of type ") +
1763 BC->getOpcodeName());
1764
1765 // Materialize as instructions if necessary.
1766 Instruction *I;
1767 if (Instruction::isCast(Opcode: BC->Opcode)) {
1768 I = CastInst::Create((Instruction::CastOps)BC->Opcode, S: Ops[0],
1769 Ty: BC->getType(), Name: "constexpr", InsertBefore: InsertBB);
1770 } else if (Instruction::isUnaryOp(Opcode: BC->Opcode)) {
1771 I = UnaryOperator::Create(Op: (Instruction::UnaryOps)BC->Opcode, S: Ops[0],
1772 Name: "constexpr", InsertBefore: InsertBB);
1773 } else if (Instruction::isBinaryOp(Opcode: BC->Opcode)) {
1774 I = BinaryOperator::Create(Op: (Instruction::BinaryOps)BC->Opcode, S1: Ops[0],
1775 S2: Ops[1], Name: "constexpr", InsertBefore: InsertBB);
1776 if (isa<OverflowingBinaryOperator>(Val: I)) {
1777 if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
1778 I->setHasNoSignedWrap();
1779 if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
1780 I->setHasNoUnsignedWrap();
1781 }
1782 if (isa<PossiblyExactOperator>(Val: I) &&
1783 (BC->Flags & PossiblyExactOperator::IsExact))
1784 I->setIsExact();
1785 } else {
1786 switch (BC->Opcode) {
1787 case BitcodeConstant::ConstantVectorOpcode: {
1788 Type *IdxTy = Type::getInt32Ty(C&: BC->getContext());
1789 Value *V = PoisonValue::get(T: BC->getType());
1790 for (auto Pair : enumerate(First&: Ops)) {
1791 Value *Idx = ConstantInt::get(Ty: IdxTy, V: Pair.index());
1792 V = InsertElementInst::Create(Vec: V, NewElt: Pair.value(), Idx, NameStr: "constexpr.ins",
1793 InsertBefore: InsertBB);
1794 }
1795 I = cast<Instruction>(Val: V);
1796 break;
1797 }
1798 case BitcodeConstant::ConstantStructOpcode:
1799 case BitcodeConstant::ConstantArrayOpcode: {
1800 Value *V = PoisonValue::get(T: BC->getType());
1801 for (auto Pair : enumerate(First&: Ops))
1802 V = InsertValueInst::Create(Agg: V, Val: Pair.value(), Idxs: Pair.index(),
1803 NameStr: "constexpr.ins", InsertBefore: InsertBB);
1804 I = cast<Instruction>(Val: V);
1805 break;
1806 }
1807 case Instruction::ICmp:
1808 case Instruction::FCmp:
1809 I = CmpInst::Create(Op: (Instruction::OtherOps)BC->Opcode,
1810 Pred: (CmpInst::Predicate)BC->Flags, S1: Ops[0], S2: Ops[1],
1811 Name: "constexpr", InsertBefore: InsertBB);
1812 break;
1813 case Instruction::GetElementPtr:
1814 I = GetElementPtrInst::Create(PointeeType: BC->SrcElemTy, Ptr: Ops[0],
1815 IdxList: ArrayRef(Ops).drop_front(), NameStr: "constexpr",
1816 InsertBefore: InsertBB);
1817 cast<GetElementPtrInst>(Val: I)->setNoWrapFlags(toGEPNoWrapFlags(Flags: BC->Flags));
1818 break;
1819 case Instruction::Select:
1820 I = SelectInst::Create(C: Ops[0], S1: Ops[1], S2: Ops[2], NameStr: "constexpr", InsertBefore: InsertBB);
1821 break;
1822 case Instruction::ExtractElement:
1823 I = ExtractElementInst::Create(Vec: Ops[0], Idx: Ops[1], NameStr: "constexpr", InsertBefore: InsertBB);
1824 break;
1825 case Instruction::InsertElement:
1826 I = InsertElementInst::Create(Vec: Ops[0], NewElt: Ops[1], Idx: Ops[2], NameStr: "constexpr",
1827 InsertBefore: InsertBB);
1828 break;
1829 case Instruction::ShuffleVector:
1830 I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
1831 InsertBB);
1832 break;
1833 default:
1834 llvm_unreachable("Unhandled bitcode constant");
1835 }
1836 }
1837
1838 MaterializedValues.insert(KV: {ValID, I});
1839 Worklist.pop_back();
1840 }
1841
1842 return MaterializedValues[StartValID];
1843}
1844
1845Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
1846 Expected<Value *> MaybeV = materializeValue(StartValID: ID, /* InsertBB */ nullptr);
1847 if (!MaybeV)
1848 return MaybeV.takeError();
1849
1850 // Result must be Constant if InsertBB is nullptr.
1851 return cast<Constant>(Val: MaybeV.get());
1852}
1853
1854StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1855 StringRef Name) {
1856 auto *Ret = StructType::create(Context, Name);
1857 IdentifiedStructTypes.push_back(x: Ret);
1858 return Ret;
1859}
1860
1861StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1862 auto *Ret = StructType::create(Context);
1863 IdentifiedStructTypes.push_back(x: Ret);
1864 return Ret;
1865}
1866
1867//===----------------------------------------------------------------------===//
1868// Functions for parsing blocks from the bitcode file
1869//===----------------------------------------------------------------------===//
1870
1871static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1872 switch (Val) {
1873 case Attribute::EndAttrKinds:
1874 case Attribute::EmptyKey:
1875 case Attribute::TombstoneKey:
1876 llvm_unreachable("Synthetic enumerators which should never get here");
1877
1878 case Attribute::None: return 0;
1879 case Attribute::ZExt: return 1 << 0;
1880 case Attribute::SExt: return 1 << 1;
1881 case Attribute::NoReturn: return 1 << 2;
1882 case Attribute::InReg: return 1 << 3;
1883 case Attribute::StructRet: return 1 << 4;
1884 case Attribute::NoUnwind: return 1 << 5;
1885 case Attribute::NoAlias: return 1 << 6;
1886 case Attribute::ByVal: return 1 << 7;
1887 case Attribute::Nest: return 1 << 8;
1888 case Attribute::ReadNone: return 1 << 9;
1889 case Attribute::ReadOnly: return 1 << 10;
1890 case Attribute::NoInline: return 1 << 11;
1891 case Attribute::AlwaysInline: return 1 << 12;
1892 case Attribute::OptimizeForSize: return 1 << 13;
1893 case Attribute::StackProtect: return 1 << 14;
1894 case Attribute::StackProtectReq: return 1 << 15;
1895 case Attribute::Alignment: return 31 << 16;
1896 // 1ULL << 21 is NoCapture, which is upgraded separately.
1897 case Attribute::NoRedZone: return 1 << 22;
1898 case Attribute::NoImplicitFloat: return 1 << 23;
1899 case Attribute::Naked: return 1 << 24;
1900 case Attribute::InlineHint: return 1 << 25;
1901 case Attribute::StackAlignment: return 7 << 26;
1902 case Attribute::ReturnsTwice: return 1 << 29;
1903 case Attribute::UWTable: return 1 << 30;
1904 case Attribute::NonLazyBind: return 1U << 31;
1905 case Attribute::SanitizeAddress: return 1ULL << 32;
1906 case Attribute::MinSize: return 1ULL << 33;
1907 case Attribute::NoDuplicate: return 1ULL << 34;
1908 case Attribute::StackProtectStrong: return 1ULL << 35;
1909 case Attribute::SanitizeThread: return 1ULL << 36;
1910 case Attribute::SanitizeMemory: return 1ULL << 37;
1911 case Attribute::NoBuiltin: return 1ULL << 38;
1912 case Attribute::Returned: return 1ULL << 39;
1913 case Attribute::Cold: return 1ULL << 40;
1914 case Attribute::Builtin: return 1ULL << 41;
1915 case Attribute::OptimizeNone: return 1ULL << 42;
1916 case Attribute::InAlloca: return 1ULL << 43;
1917 case Attribute::NonNull: return 1ULL << 44;
1918 case Attribute::JumpTable: return 1ULL << 45;
1919 case Attribute::Convergent: return 1ULL << 46;
1920 case Attribute::SafeStack: return 1ULL << 47;
1921 case Attribute::NoRecurse: return 1ULL << 48;
1922 // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1923 // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
1924 case Attribute::SwiftSelf: return 1ULL << 51;
1925 case Attribute::SwiftError: return 1ULL << 52;
1926 case Attribute::WriteOnly: return 1ULL << 53;
1927 case Attribute::Speculatable: return 1ULL << 54;
1928 case Attribute::StrictFP: return 1ULL << 55;
1929 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1930 case Attribute::NoCfCheck: return 1ULL << 57;
1931 case Attribute::OptForFuzzing: return 1ULL << 58;
1932 case Attribute::ShadowCallStack: return 1ULL << 59;
1933 case Attribute::SpeculativeLoadHardening:
1934 return 1ULL << 60;
1935 case Attribute::ImmArg:
1936 return 1ULL << 61;
1937 case Attribute::WillReturn:
1938 return 1ULL << 62;
1939 case Attribute::NoFree:
1940 return 1ULL << 63;
1941 default:
1942 // Other attributes are not supported in the raw format,
1943 // as we ran out of space.
1944 return 0;
1945 }
1946 llvm_unreachable("Unsupported attribute type");
1947}
1948
1949static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1950 if (!Val) return;
1951
1952 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1953 I = Attribute::AttrKind(I + 1)) {
1954 if (uint64_t A = (Val & getRawAttributeMask(Val: I))) {
1955 if (I == Attribute::Alignment)
1956 B.addAlignmentAttr(Align: 1ULL << ((A >> 16) - 1));
1957 else if (I == Attribute::StackAlignment)
1958 B.addStackAlignmentAttr(Align: 1ULL << ((A >> 26)-1));
1959 else if (Attribute::isTypeAttrKind(Kind: I))
1960 B.addTypeAttr(Kind: I, Ty: nullptr); // Type will be auto-upgraded.
1961 else
1962 B.addAttribute(Val: I);
1963 }
1964 }
1965}
1966
1967/// This fills an AttrBuilder object with the LLVM attributes that have
1968/// been decoded from the given integer.
1969static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1970 uint64_t EncodedAttrs,
1971 uint64_t AttrIdx) {
1972 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1973 // the bits above 31 down by 11 bits.
1974 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1975 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1976 "Alignment must be a power of two.");
1977
1978 if (Alignment)
1979 B.addAlignmentAttr(Align: Alignment);
1980
1981 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1982 (EncodedAttrs & 0xffff);
1983
1984 if (AttrIdx == AttributeList::FunctionIndex) {
1985 // Upgrade old memory attributes.
1986 MemoryEffects ME = MemoryEffects::unknown();
1987 if (Attrs & (1ULL << 9)) {
1988 // ReadNone
1989 Attrs &= ~(1ULL << 9);
1990 ME &= MemoryEffects::none();
1991 }
1992 if (Attrs & (1ULL << 10)) {
1993 // ReadOnly
1994 Attrs &= ~(1ULL << 10);
1995 ME &= MemoryEffects::readOnly();
1996 }
1997 if (Attrs & (1ULL << 49)) {
1998 // InaccessibleMemOnly
1999 Attrs &= ~(1ULL << 49);
2000 ME &= MemoryEffects::inaccessibleMemOnly();
2001 }
2002 if (Attrs & (1ULL << 50)) {
2003 // InaccessibleMemOrArgMemOnly
2004 Attrs &= ~(1ULL << 50);
2005 ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2006 }
2007 if (Attrs & (1ULL << 53)) {
2008 // WriteOnly
2009 Attrs &= ~(1ULL << 53);
2010 ME &= MemoryEffects::writeOnly();
2011 }
2012 if (ME != MemoryEffects::unknown())
2013 B.addMemoryAttr(ME);
2014 }
2015
2016 // Upgrade nocapture to captures(none).
2017 if (Attrs & (1ULL << 21)) {
2018 Attrs &= ~(1ULL << 21);
2019 B.addCapturesAttr(CI: CaptureInfo::none());
2020 }
2021
2022 addRawAttributeValue(B, Val: Attrs);
2023}
2024
2025Error BitcodeReader::parseAttributeBlock() {
2026 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::PARAMATTR_BLOCK_ID))
2027 return Err;
2028
2029 if (!MAttributes.empty())
2030 return error(Message: "Invalid multiple blocks");
2031
2032 SmallVector<uint64_t, 64> Record;
2033
2034 SmallVector<AttributeList, 8> Attrs;
2035
2036 // Read all the records.
2037 while (true) {
2038 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2039 if (!MaybeEntry)
2040 return MaybeEntry.takeError();
2041 BitstreamEntry Entry = MaybeEntry.get();
2042
2043 switch (Entry.Kind) {
2044 case BitstreamEntry::SubBlock: // Handled for us already.
2045 case BitstreamEntry::Error:
2046 return error(Message: "Malformed block");
2047 case BitstreamEntry::EndBlock:
2048 return Error::success();
2049 case BitstreamEntry::Record:
2050 // The interesting case.
2051 break;
2052 }
2053
2054 // Read a record.
2055 Record.clear();
2056 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
2057 if (!MaybeRecord)
2058 return MaybeRecord.takeError();
2059 switch (MaybeRecord.get()) {
2060 default: // Default behavior: ignore.
2061 break;
2062 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
2063 // Deprecated, but still needed to read old bitcode files.
2064 if (Record.size() & 1)
2065 return error(Message: "Invalid parameter attribute record");
2066
2067 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
2068 AttrBuilder B(Context);
2069 decodeLLVMAttributesForBitcode(B, EncodedAttrs: Record[i+1], AttrIdx: Record[i]);
2070 Attrs.push_back(Elt: AttributeList::get(C&: Context, Index: Record[i], B));
2071 }
2072
2073 MAttributes.push_back(x: AttributeList::get(C&: Context, Attrs));
2074 Attrs.clear();
2075 break;
2076 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
2077 for (uint64_t Val : Record)
2078 Attrs.push_back(Elt: MAttributeGroups[Val]);
2079
2080 MAttributes.push_back(x: AttributeList::get(C&: Context, Attrs));
2081 Attrs.clear();
2082 break;
2083 }
2084 }
2085}
2086
2087// Returns Attribute::None on unrecognized codes.
2088static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
2089 switch (Code) {
2090 default:
2091 return Attribute::None;
2092 case bitc::ATTR_KIND_ALIGNMENT:
2093 return Attribute::Alignment;
2094 case bitc::ATTR_KIND_ALWAYS_INLINE:
2095 return Attribute::AlwaysInline;
2096 case bitc::ATTR_KIND_BUILTIN:
2097 return Attribute::Builtin;
2098 case bitc::ATTR_KIND_BY_VAL:
2099 return Attribute::ByVal;
2100 case bitc::ATTR_KIND_IN_ALLOCA:
2101 return Attribute::InAlloca;
2102 case bitc::ATTR_KIND_COLD:
2103 return Attribute::Cold;
2104 case bitc::ATTR_KIND_CONVERGENT:
2105 return Attribute::Convergent;
2106 case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
2107 return Attribute::DisableSanitizerInstrumentation;
2108 case bitc::ATTR_KIND_ELEMENTTYPE:
2109 return Attribute::ElementType;
2110 case bitc::ATTR_KIND_FNRETTHUNK_EXTERN:
2111 return Attribute::FnRetThunkExtern;
2112 case bitc::ATTR_KIND_INLINE_HINT:
2113 return Attribute::InlineHint;
2114 case bitc::ATTR_KIND_IN_REG:
2115 return Attribute::InReg;
2116 case bitc::ATTR_KIND_JUMP_TABLE:
2117 return Attribute::JumpTable;
2118 case bitc::ATTR_KIND_MEMORY:
2119 return Attribute::Memory;
2120 case bitc::ATTR_KIND_NOFPCLASS:
2121 return Attribute::NoFPClass;
2122 case bitc::ATTR_KIND_MIN_SIZE:
2123 return Attribute::MinSize;
2124 case bitc::ATTR_KIND_NAKED:
2125 return Attribute::Naked;
2126 case bitc::ATTR_KIND_NEST:
2127 return Attribute::Nest;
2128 case bitc::ATTR_KIND_NO_ALIAS:
2129 return Attribute::NoAlias;
2130 case bitc::ATTR_KIND_NO_BUILTIN:
2131 return Attribute::NoBuiltin;
2132 case bitc::ATTR_KIND_NO_CALLBACK:
2133 return Attribute::NoCallback;
2134 case bitc::ATTR_KIND_NO_DIVERGENCE_SOURCE:
2135 return Attribute::NoDivergenceSource;
2136 case bitc::ATTR_KIND_NO_DUPLICATE:
2137 return Attribute::NoDuplicate;
2138 case bitc::ATTR_KIND_NOFREE:
2139 return Attribute::NoFree;
2140 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
2141 return Attribute::NoImplicitFloat;
2142 case bitc::ATTR_KIND_NO_INLINE:
2143 return Attribute::NoInline;
2144 case bitc::ATTR_KIND_NO_RECURSE:
2145 return Attribute::NoRecurse;
2146 case bitc::ATTR_KIND_NO_MERGE:
2147 return Attribute::NoMerge;
2148 case bitc::ATTR_KIND_NON_LAZY_BIND:
2149 return Attribute::NonLazyBind;
2150 case bitc::ATTR_KIND_NON_NULL:
2151 return Attribute::NonNull;
2152 case bitc::ATTR_KIND_DEREFERENCEABLE:
2153 return Attribute::Dereferenceable;
2154 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
2155 return Attribute::DereferenceableOrNull;
2156 case bitc::ATTR_KIND_ALLOC_ALIGN:
2157 return Attribute::AllocAlign;
2158 case bitc::ATTR_KIND_ALLOC_KIND:
2159 return Attribute::AllocKind;
2160 case bitc::ATTR_KIND_ALLOC_SIZE:
2161 return Attribute::AllocSize;
2162 case bitc::ATTR_KIND_ALLOCATED_POINTER:
2163 return Attribute::AllocatedPointer;
2164 case bitc::ATTR_KIND_NO_RED_ZONE:
2165 return Attribute::NoRedZone;
2166 case bitc::ATTR_KIND_NO_RETURN:
2167 return Attribute::NoReturn;
2168 case bitc::ATTR_KIND_NOSYNC:
2169 return Attribute::NoSync;
2170 case bitc::ATTR_KIND_NOCF_CHECK:
2171 return Attribute::NoCfCheck;
2172 case bitc::ATTR_KIND_NO_PROFILE:
2173 return Attribute::NoProfile;
2174 case bitc::ATTR_KIND_SKIP_PROFILE:
2175 return Attribute::SkipProfile;
2176 case bitc::ATTR_KIND_NO_UNWIND:
2177 return Attribute::NoUnwind;
2178 case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
2179 return Attribute::NoSanitizeBounds;
2180 case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
2181 return Attribute::NoSanitizeCoverage;
2182 case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
2183 return Attribute::NullPointerIsValid;
2184 case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
2185 return Attribute::OptimizeForDebugging;
2186 case bitc::ATTR_KIND_OPT_FOR_FUZZING:
2187 return Attribute::OptForFuzzing;
2188 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
2189 return Attribute::OptimizeForSize;
2190 case bitc::ATTR_KIND_OPTIMIZE_NONE:
2191 return Attribute::OptimizeNone;
2192 case bitc::ATTR_KIND_READ_NONE:
2193 return Attribute::ReadNone;
2194 case bitc::ATTR_KIND_READ_ONLY:
2195 return Attribute::ReadOnly;
2196 case bitc::ATTR_KIND_RETURNED:
2197 return Attribute::Returned;
2198 case bitc::ATTR_KIND_RETURNS_TWICE:
2199 return Attribute::ReturnsTwice;
2200 case bitc::ATTR_KIND_S_EXT:
2201 return Attribute::SExt;
2202 case bitc::ATTR_KIND_SPECULATABLE:
2203 return Attribute::Speculatable;
2204 case bitc::ATTR_KIND_STACK_ALIGNMENT:
2205 return Attribute::StackAlignment;
2206 case bitc::ATTR_KIND_STACK_PROTECT:
2207 return Attribute::StackProtect;
2208 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
2209 return Attribute::StackProtectReq;
2210 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
2211 return Attribute::StackProtectStrong;
2212 case bitc::ATTR_KIND_SAFESTACK:
2213 return Attribute::SafeStack;
2214 case bitc::ATTR_KIND_SHADOWCALLSTACK:
2215 return Attribute::ShadowCallStack;
2216 case bitc::ATTR_KIND_STRICT_FP:
2217 return Attribute::StrictFP;
2218 case bitc::ATTR_KIND_STRUCT_RET:
2219 return Attribute::StructRet;
2220 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
2221 return Attribute::SanitizeAddress;
2222 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
2223 return Attribute::SanitizeHWAddress;
2224 case bitc::ATTR_KIND_SANITIZE_THREAD:
2225 return Attribute::SanitizeThread;
2226 case bitc::ATTR_KIND_SANITIZE_TYPE:
2227 return Attribute::SanitizeType;
2228 case bitc::ATTR_KIND_SANITIZE_MEMORY:
2229 return Attribute::SanitizeMemory;
2230 case bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY:
2231 return Attribute::SanitizeNumericalStability;
2232 case bitc::ATTR_KIND_SANITIZE_REALTIME:
2233 return Attribute::SanitizeRealtime;
2234 case bitc::ATTR_KIND_SANITIZE_REALTIME_BLOCKING:
2235 return Attribute::SanitizeRealtimeBlocking;
2236 case bitc::ATTR_KIND_SANITIZE_ALLOC_TOKEN:
2237 return Attribute::SanitizeAllocToken;
2238 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
2239 return Attribute::SpeculativeLoadHardening;
2240 case bitc::ATTR_KIND_SWIFT_ERROR:
2241 return Attribute::SwiftError;
2242 case bitc::ATTR_KIND_SWIFT_SELF:
2243 return Attribute::SwiftSelf;
2244 case bitc::ATTR_KIND_SWIFT_ASYNC:
2245 return Attribute::SwiftAsync;
2246 case bitc::ATTR_KIND_UW_TABLE:
2247 return Attribute::UWTable;
2248 case bitc::ATTR_KIND_VSCALE_RANGE:
2249 return Attribute::VScaleRange;
2250 case bitc::ATTR_KIND_WILLRETURN:
2251 return Attribute::WillReturn;
2252 case bitc::ATTR_KIND_WRITEONLY:
2253 return Attribute::WriteOnly;
2254 case bitc::ATTR_KIND_Z_EXT:
2255 return Attribute::ZExt;
2256 case bitc::ATTR_KIND_IMMARG:
2257 return Attribute::ImmArg;
2258 case bitc::ATTR_KIND_SANITIZE_MEMTAG:
2259 return Attribute::SanitizeMemTag;
2260 case bitc::ATTR_KIND_PREALLOCATED:
2261 return Attribute::Preallocated;
2262 case bitc::ATTR_KIND_NOUNDEF:
2263 return Attribute::NoUndef;
2264 case bitc::ATTR_KIND_BYREF:
2265 return Attribute::ByRef;
2266 case bitc::ATTR_KIND_MUSTPROGRESS:
2267 return Attribute::MustProgress;
2268 case bitc::ATTR_KIND_HOT:
2269 return Attribute::Hot;
2270 case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
2271 return Attribute::PresplitCoroutine;
2272 case bitc::ATTR_KIND_WRITABLE:
2273 return Attribute::Writable;
2274 case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE:
2275 return Attribute::CoroDestroyOnlyWhenComplete;
2276 case bitc::ATTR_KIND_DEAD_ON_UNWIND:
2277 return Attribute::DeadOnUnwind;
2278 case bitc::ATTR_KIND_RANGE:
2279 return Attribute::Range;
2280 case bitc::ATTR_KIND_INITIALIZES:
2281 return Attribute::Initializes;
2282 case bitc::ATTR_KIND_CORO_ELIDE_SAFE:
2283 return Attribute::CoroElideSafe;
2284 case bitc::ATTR_KIND_NO_EXT:
2285 return Attribute::NoExt;
2286 case bitc::ATTR_KIND_CAPTURES:
2287 return Attribute::Captures;
2288 case bitc::ATTR_KIND_DEAD_ON_RETURN:
2289 return Attribute::DeadOnReturn;
2290 case bitc::ATTR_KIND_NO_CREATE_UNDEF_OR_POISON:
2291 return Attribute::NoCreateUndefOrPoison;
2292 case bitc::ATTR_KIND_DENORMAL_FPENV:
2293 return Attribute::DenormalFPEnv;
2294 case bitc::ATTR_KIND_NOOUTLINE:
2295 return Attribute::NoOutline;
2296 }
2297}
2298
2299Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
2300 MaybeAlign &Alignment) {
2301 // Note: Alignment in bitcode files is incremented by 1, so that zero
2302 // can be used for default alignment.
2303 if (Exponent > Value::MaxAlignmentExponent + 1)
2304 return error(Message: "Invalid alignment value");
2305 Alignment = decodeMaybeAlign(Value: Exponent);
2306 return Error::success();
2307}
2308
2309Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2310 *Kind = getAttrFromCode(Code);
2311 if (*Kind == Attribute::None)
2312 return error(Message: "Unknown attribute kind (" + Twine(Code) + ")");
2313 return Error::success();
2314}
2315
2316static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2317 switch (EncodedKind) {
2318 case bitc::ATTR_KIND_READ_NONE:
2319 ME &= MemoryEffects::none();
2320 return true;
2321 case bitc::ATTR_KIND_READ_ONLY:
2322 ME &= MemoryEffects::readOnly();
2323 return true;
2324 case bitc::ATTR_KIND_WRITEONLY:
2325 ME &= MemoryEffects::writeOnly();
2326 return true;
2327 case bitc::ATTR_KIND_ARGMEMONLY:
2328 ME &= MemoryEffects::argMemOnly();
2329 return true;
2330 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
2331 ME &= MemoryEffects::inaccessibleMemOnly();
2332 return true;
2333 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
2334 ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2335 return true;
2336 default:
2337 return false;
2338 }
2339}
2340
2341Error BitcodeReader::parseAttributeGroupBlock() {
2342 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::PARAMATTR_GROUP_BLOCK_ID))
2343 return Err;
2344
2345 if (!MAttributeGroups.empty())
2346 return error(Message: "Invalid multiple blocks");
2347
2348 SmallVector<uint64_t, 64> Record;
2349
2350 // Read all the records.
2351 while (true) {
2352 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2353 if (!MaybeEntry)
2354 return MaybeEntry.takeError();
2355 BitstreamEntry Entry = MaybeEntry.get();
2356
2357 switch (Entry.Kind) {
2358 case BitstreamEntry::SubBlock: // Handled for us already.
2359 case BitstreamEntry::Error:
2360 return error(Message: "Malformed block");
2361 case BitstreamEntry::EndBlock:
2362 return Error::success();
2363 case BitstreamEntry::Record:
2364 // The interesting case.
2365 break;
2366 }
2367
2368 // Read a record.
2369 Record.clear();
2370 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
2371 if (!MaybeRecord)
2372 return MaybeRecord.takeError();
2373 switch (MaybeRecord.get()) {
2374 default: // Default behavior: ignore.
2375 break;
2376 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2377 if (Record.size() < 3)
2378 return error(Message: "Invalid grp record");
2379
2380 uint64_t GrpID = Record[0];
2381 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2382
2383 AttrBuilder B(Context);
2384 MemoryEffects ME = MemoryEffects::unknown();
2385 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2386 if (Record[i] == 0) { // Enum attribute
2387 Attribute::AttrKind Kind;
2388 uint64_t EncodedKind = Record[++i];
2389 if (Idx == AttributeList::FunctionIndex &&
2390 upgradeOldMemoryAttribute(ME, EncodedKind))
2391 continue;
2392
2393 if (EncodedKind == bitc::ATTR_KIND_NO_CAPTURE) {
2394 B.addCapturesAttr(CI: CaptureInfo::none());
2395 continue;
2396 }
2397
2398 if (Error Err = parseAttrKind(Code: EncodedKind, Kind: &Kind))
2399 return Err;
2400
2401 // Upgrade old-style byval attribute to one with a type, even if it's
2402 // nullptr. We will have to insert the real type when we associate
2403 // this AttributeList with a function.
2404 if (Kind == Attribute::ByVal)
2405 B.addByValAttr(Ty: nullptr);
2406 else if (Kind == Attribute::StructRet)
2407 B.addStructRetAttr(Ty: nullptr);
2408 else if (Kind == Attribute::InAlloca)
2409 B.addInAllocaAttr(Ty: nullptr);
2410 else if (Kind == Attribute::UWTable)
2411 B.addUWTableAttr(Kind: UWTableKind::Default);
2412 else if (Kind == Attribute::DeadOnReturn)
2413 B.addDeadOnReturnAttr(Info: DeadOnReturnInfo());
2414 else if (Attribute::isEnumAttrKind(Kind))
2415 B.addAttribute(Val: Kind);
2416 else
2417 return error(Message: "Not an enum attribute");
2418 } else if (Record[i] == 1) { // Integer attribute
2419 Attribute::AttrKind Kind;
2420 if (Error Err = parseAttrKind(Code: Record[++i], Kind: &Kind))
2421 return Err;
2422 if (!Attribute::isIntAttrKind(Kind))
2423 return error(Message: "Not an int attribute");
2424 if (Kind == Attribute::Alignment)
2425 B.addAlignmentAttr(Align: Record[++i]);
2426 else if (Kind == Attribute::StackAlignment)
2427 B.addStackAlignmentAttr(Align: Record[++i]);
2428 else if (Kind == Attribute::Dereferenceable)
2429 B.addDereferenceableAttr(Bytes: Record[++i]);
2430 else if (Kind == Attribute::DereferenceableOrNull)
2431 B.addDereferenceableOrNullAttr(Bytes: Record[++i]);
2432 else if (Kind == Attribute::DeadOnReturn)
2433 B.addDeadOnReturnAttr(
2434 Info: DeadOnReturnInfo::createFromIntValue(Data: Record[++i]));
2435 else if (Kind == Attribute::AllocSize)
2436 B.addAllocSizeAttrFromRawRepr(RawAllocSizeRepr: Record[++i]);
2437 else if (Kind == Attribute::VScaleRange)
2438 B.addVScaleRangeAttrFromRawRepr(RawVScaleRangeRepr: Record[++i]);
2439 else if (Kind == Attribute::UWTable)
2440 B.addUWTableAttr(Kind: UWTableKind(Record[++i]));
2441 else if (Kind == Attribute::AllocKind)
2442 B.addAllocKindAttr(Kind: static_cast<AllocFnKind>(Record[++i]));
2443 else if (Kind == Attribute::Memory) {
2444 uint64_t EncodedME = Record[++i];
2445 const uint8_t Version = (EncodedME >> 56);
2446 if (Version == 0) {
2447 // Errno memory location was previously encompassed into default
2448 // memory. Ensure this is taken into account while reconstructing
2449 // the memory attribute prior to its introduction.
2450 ModRefInfo ArgMem = ModRefInfo((EncodedME >> 0) & 3);
2451 ModRefInfo InaccessibleMem = ModRefInfo((EncodedME >> 2) & 3);
2452 ModRefInfo OtherMem = ModRefInfo((EncodedME >> 4) & 3);
2453 auto ME = MemoryEffects::inaccessibleMemOnly(MR: InaccessibleMem) |
2454 MemoryEffects::argMemOnly(MR: ArgMem) |
2455 MemoryEffects::errnoMemOnly(MR: OtherMem) |
2456 MemoryEffects::otherMemOnly(MR: OtherMem);
2457 B.addMemoryAttr(ME);
2458 } else {
2459 // Construct the memory attribute directly from the encoded base
2460 // on newer versions.
2461 B.addMemoryAttr(ME: MemoryEffects::createFromIntValue(
2462 Data: EncodedME & 0x00FFFFFFFFFFFFFFULL));
2463 }
2464 } else if (Kind == Attribute::Captures)
2465 B.addCapturesAttr(CI: CaptureInfo::createFromIntValue(Data: Record[++i]));
2466 else if (Kind == Attribute::NoFPClass)
2467 B.addNoFPClassAttr(
2468 NoFPClassMask: static_cast<FPClassTest>(Record[++i] & fcAllFlags));
2469 else if (Kind == Attribute::DenormalFPEnv) {
2470 B.addDenormalFPEnvAttr(
2471 Mode: DenormalFPEnv::createFromIntValue(Data: Record[++i]));
2472 }
2473 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2474 bool HasValue = (Record[i++] == 4);
2475 SmallString<64> KindStr;
2476 SmallString<64> ValStr;
2477
2478 while (Record[i] != 0 && i != e)
2479 KindStr += Record[i++];
2480 assert(Record[i] == 0 && "Kind string not null terminated");
2481
2482 if (HasValue) {
2483 // Has a value associated with it.
2484 ++i; // Skip the '0' that terminates the "kind" string.
2485 while (Record[i] != 0 && i != e)
2486 ValStr += Record[i++];
2487 assert(Record[i] == 0 && "Value string not null terminated");
2488 }
2489
2490 B.addAttribute(A: KindStr.str(), V: ValStr.str());
2491 } else if (Record[i] == 5 || Record[i] == 6) {
2492 bool HasType = Record[i] == 6;
2493 Attribute::AttrKind Kind;
2494 if (Error Err = parseAttrKind(Code: Record[++i], Kind: &Kind))
2495 return Err;
2496 if (!Attribute::isTypeAttrKind(Kind))
2497 return error(Message: "Not a type attribute");
2498
2499 B.addTypeAttr(Kind, Ty: HasType ? getTypeByID(ID: Record[++i]) : nullptr);
2500 } else if (Record[i] == 7) {
2501 Attribute::AttrKind Kind;
2502
2503 i++;
2504 if (Error Err = parseAttrKind(Code: Record[i++], Kind: &Kind))
2505 return Err;
2506 if (!Attribute::isConstantRangeAttrKind(Kind))
2507 return error(Message: "Not a ConstantRange attribute");
2508
2509 Expected<ConstantRange> MaybeCR =
2510 readBitWidthAndConstantRange(Record, OpNum&: i);
2511 if (!MaybeCR)
2512 return MaybeCR.takeError();
2513 i--;
2514
2515 B.addConstantRangeAttr(Kind, CR: MaybeCR.get());
2516 } else if (Record[i] == 8) {
2517 Attribute::AttrKind Kind;
2518
2519 i++;
2520 if (Error Err = parseAttrKind(Code: Record[i++], Kind: &Kind))
2521 return Err;
2522 if (!Attribute::isConstantRangeListAttrKind(Kind))
2523 return error(Message: "Not a constant range list attribute");
2524
2525 SmallVector<ConstantRange, 2> Val;
2526 if (i + 2 > e)
2527 return error(Message: "Too few records for constant range list");
2528 unsigned RangeSize = Record[i++];
2529 unsigned BitWidth = Record[i++];
2530 for (unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2531 Expected<ConstantRange> MaybeCR =
2532 readConstantRange(Record, OpNum&: i, BitWidth);
2533 if (!MaybeCR)
2534 return MaybeCR.takeError();
2535 Val.push_back(Elt: MaybeCR.get());
2536 }
2537 i--;
2538
2539 if (!ConstantRangeList::isOrderedRanges(RangesRef: Val))
2540 return error(Message: "Invalid (unordered or overlapping) range list");
2541 B.addConstantRangeListAttr(Kind, Val);
2542 } else {
2543 return error(Message: "Invalid attribute group entry");
2544 }
2545 }
2546
2547 if (ME != MemoryEffects::unknown())
2548 B.addMemoryAttr(ME);
2549
2550 UpgradeAttributes(B);
2551 MAttributeGroups[GrpID] = AttributeList::get(C&: Context, Index: Idx, B);
2552 break;
2553 }
2554 }
2555 }
2556}
2557
2558Error BitcodeReader::parseTypeTable() {
2559 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::TYPE_BLOCK_ID_NEW))
2560 return Err;
2561
2562 return parseTypeTableBody();
2563}
2564
2565Error BitcodeReader::parseTypeTableBody() {
2566 if (!TypeList.empty())
2567 return error(Message: "Invalid multiple blocks");
2568
2569 SmallVector<uint64_t, 64> Record;
2570 unsigned NumRecords = 0;
2571
2572 SmallString<64> TypeName;
2573
2574 // Read all the records for this type table.
2575 while (true) {
2576 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2577 if (!MaybeEntry)
2578 return MaybeEntry.takeError();
2579 BitstreamEntry Entry = MaybeEntry.get();
2580
2581 switch (Entry.Kind) {
2582 case BitstreamEntry::SubBlock: // Handled for us already.
2583 case BitstreamEntry::Error:
2584 return error(Message: "Malformed block");
2585 case BitstreamEntry::EndBlock:
2586 if (NumRecords != TypeList.size())
2587 return error(Message: "Malformed block");
2588 return Error::success();
2589 case BitstreamEntry::Record:
2590 // The interesting case.
2591 break;
2592 }
2593
2594 // Read a record.
2595 Record.clear();
2596 Type *ResultTy = nullptr;
2597 SmallVector<unsigned> ContainedIDs;
2598 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
2599 if (!MaybeRecord)
2600 return MaybeRecord.takeError();
2601 switch (MaybeRecord.get()) {
2602 default:
2603 return error(Message: "Invalid value");
2604 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2605 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2606 // type list. This allows us to reserve space.
2607 if (Record.empty())
2608 return error(Message: "Invalid numentry record");
2609 TypeList.resize(new_size: Record[0]);
2610 continue;
2611 case bitc::TYPE_CODE_VOID: // VOID
2612 ResultTy = Type::getVoidTy(C&: Context);
2613 break;
2614 case bitc::TYPE_CODE_HALF: // HALF
2615 ResultTy = Type::getHalfTy(C&: Context);
2616 break;
2617 case bitc::TYPE_CODE_BFLOAT: // BFLOAT
2618 ResultTy = Type::getBFloatTy(C&: Context);
2619 break;
2620 case bitc::TYPE_CODE_FLOAT: // FLOAT
2621 ResultTy = Type::getFloatTy(C&: Context);
2622 break;
2623 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
2624 ResultTy = Type::getDoubleTy(C&: Context);
2625 break;
2626 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
2627 ResultTy = Type::getX86_FP80Ty(C&: Context);
2628 break;
2629 case bitc::TYPE_CODE_FP128: // FP128
2630 ResultTy = Type::getFP128Ty(C&: Context);
2631 break;
2632 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2633 ResultTy = Type::getPPC_FP128Ty(C&: Context);
2634 break;
2635 case bitc::TYPE_CODE_LABEL: // LABEL
2636 ResultTy = Type::getLabelTy(C&: Context);
2637 break;
2638 case bitc::TYPE_CODE_METADATA: // METADATA
2639 ResultTy = Type::getMetadataTy(C&: Context);
2640 break;
2641 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
2642 // Deprecated: decodes as <1 x i64>
2643 ResultTy =
2644 llvm::FixedVectorType::get(ElementType: llvm::IntegerType::get(C&: Context, NumBits: 64), NumElts: 1);
2645 break;
2646 case bitc::TYPE_CODE_X86_AMX: // X86_AMX
2647 ResultTy = Type::getX86_AMXTy(C&: Context);
2648 break;
2649 case bitc::TYPE_CODE_TOKEN: // TOKEN
2650 ResultTy = Type::getTokenTy(C&: Context);
2651 break;
2652 case bitc::TYPE_CODE_BYTE: { // BYTE: [width]
2653 if (Record.empty())
2654 return error(Message: "Invalid record");
2655
2656 uint64_t NumBits = Record[0];
2657 if (NumBits < ByteType::MIN_BYTE_BITS ||
2658 NumBits > ByteType::MAX_BYTE_BITS)
2659 return error(Message: "Bitwidth for byte type out of range");
2660 ResultTy = ByteType::get(C&: Context, NumBits);
2661 break;
2662 }
2663 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2664 if (Record.empty())
2665 return error(Message: "Invalid integer record");
2666
2667 uint64_t NumBits = Record[0];
2668 if (NumBits < IntegerType::MIN_INT_BITS ||
2669 NumBits > IntegerType::MAX_INT_BITS)
2670 return error(Message: "Bitwidth for integer type out of range");
2671 ResultTy = IntegerType::get(C&: Context, NumBits);
2672 break;
2673 }
2674 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2675 // [pointee type, address space]
2676 if (Record.empty())
2677 return error(Message: "Invalid pointer record");
2678 unsigned AddressSpace = 0;
2679 if (Record.size() == 2)
2680 AddressSpace = Record[1];
2681 ResultTy = getTypeByID(ID: Record[0]);
2682 if (!ResultTy ||
2683 !PointerType::isValidElementType(ElemTy: ResultTy))
2684 return error(Message: "Invalid type");
2685 ContainedIDs.push_back(Elt: Record[0]);
2686 ResultTy = PointerType::get(C&: ResultTy->getContext(), AddressSpace);
2687 break;
2688 }
2689 case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2690 if (Record.size() != 1)
2691 return error(Message: "Invalid opaque pointer record");
2692 unsigned AddressSpace = Record[0];
2693 ResultTy = PointerType::get(C&: Context, AddressSpace);
2694 break;
2695 }
2696 case bitc::TYPE_CODE_FUNCTION_OLD: {
2697 // Deprecated, but still needed to read old bitcode files.
2698 // FUNCTION: [vararg, attrid, retty, paramty x N]
2699 if (Record.size() < 3)
2700 return error(Message: "Invalid function record");
2701 SmallVector<Type*, 8> ArgTys;
2702 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2703 if (Type *T = getTypeByID(ID: Record[i]))
2704 ArgTys.push_back(Elt: T);
2705 else
2706 break;
2707 }
2708
2709 ResultTy = getTypeByID(ID: Record[2]);
2710 if (!ResultTy || ArgTys.size() < Record.size()-3)
2711 return error(Message: "Invalid type");
2712
2713 ContainedIDs.append(in_start: Record.begin() + 2, in_end: Record.end());
2714 ResultTy = FunctionType::get(Result: ResultTy, Params: ArgTys, isVarArg: Record[0]);
2715 break;
2716 }
2717 case bitc::TYPE_CODE_FUNCTION: {
2718 // FUNCTION: [vararg, retty, paramty x N]
2719 if (Record.size() < 2)
2720 return error(Message: "Invalid function record");
2721 SmallVector<Type*, 8> ArgTys;
2722 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2723 if (Type *T = getTypeByID(ID: Record[i])) {
2724 if (!FunctionType::isValidArgumentType(ArgTy: T))
2725 return error(Message: "Invalid function argument type");
2726 ArgTys.push_back(Elt: T);
2727 }
2728 else
2729 break;
2730 }
2731
2732 ResultTy = getTypeByID(ID: Record[1]);
2733 if (!ResultTy || ArgTys.size() < Record.size()-2)
2734 return error(Message: "Invalid type");
2735
2736 ContainedIDs.append(in_start: Record.begin() + 1, in_end: Record.end());
2737 ResultTy = FunctionType::get(Result: ResultTy, Params: ArgTys, isVarArg: Record[0]);
2738 break;
2739 }
2740 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
2741 if (Record.empty())
2742 return error(Message: "Invalid anon struct record");
2743 SmallVector<Type*, 8> EltTys;
2744 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2745 if (Type *T = getTypeByID(ID: Record[i]))
2746 EltTys.push_back(Elt: T);
2747 else
2748 break;
2749 }
2750 if (EltTys.size() != Record.size()-1)
2751 return error(Message: "Invalid type");
2752 ContainedIDs.append(in_start: Record.begin() + 1, in_end: Record.end());
2753 ResultTy = StructType::get(Context, Elements: EltTys, isPacked: Record[0]);
2754 break;
2755 }
2756 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
2757 if (convertToString(Record, Idx: 0, Result&: TypeName))
2758 return error(Message: "Invalid struct name record");
2759 continue;
2760
2761 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2762 if (Record.empty())
2763 return error(Message: "Invalid named struct record");
2764
2765 if (NumRecords >= TypeList.size())
2766 return error(Message: "Invalid TYPE table");
2767
2768 // Check to see if this was forward referenced, if so fill in the temp.
2769 StructType *Res = cast_or_null<StructType>(Val: TypeList[NumRecords]);
2770 if (Res) {
2771 Res->setName(TypeName);
2772 TypeList[NumRecords] = nullptr;
2773 } else // Otherwise, create a new struct.
2774 Res = createIdentifiedStructType(Context, Name: TypeName);
2775 TypeName.clear();
2776
2777 SmallVector<Type*, 8> EltTys;
2778 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2779 if (Type *T = getTypeByID(ID: Record[i]))
2780 EltTys.push_back(Elt: T);
2781 else
2782 break;
2783 }
2784 if (EltTys.size() != Record.size()-1)
2785 return error(Message: "Invalid named struct record");
2786 if (auto E = Res->setBodyOrError(Elements: EltTys, isPacked: Record[0]))
2787 return E;
2788 ContainedIDs.append(in_start: Record.begin() + 1, in_end: Record.end());
2789 ResultTy = Res;
2790 break;
2791 }
2792 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
2793 if (Record.size() != 1)
2794 return error(Message: "Invalid opaque type record");
2795
2796 if (NumRecords >= TypeList.size())
2797 return error(Message: "Invalid TYPE table");
2798
2799 // Check to see if this was forward referenced, if so fill in the temp.
2800 StructType *Res = cast_or_null<StructType>(Val: TypeList[NumRecords]);
2801 if (Res) {
2802 Res->setName(TypeName);
2803 TypeList[NumRecords] = nullptr;
2804 } else // Otherwise, create a new struct with no body.
2805 Res = createIdentifiedStructType(Context, Name: TypeName);
2806 TypeName.clear();
2807 ResultTy = Res;
2808 break;
2809 }
2810 case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2811 if (Record.size() < 1)
2812 return error(Message: "Invalid target extension type record");
2813
2814 if (NumRecords >= TypeList.size())
2815 return error(Message: "Invalid TYPE table");
2816
2817 if (Record[0] >= Record.size())
2818 return error(Message: "Too many type parameters");
2819
2820 unsigned NumTys = Record[0];
2821 SmallVector<Type *, 4> TypeParams;
2822 SmallVector<unsigned, 8> IntParams;
2823 for (unsigned i = 0; i < NumTys; i++) {
2824 if (Type *T = getTypeByID(ID: Record[i + 1]))
2825 TypeParams.push_back(Elt: T);
2826 else
2827 return error(Message: "Invalid type");
2828 }
2829
2830 for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2831 if (Record[i] > UINT_MAX)
2832 return error(Message: "Integer parameter too large");
2833 IntParams.push_back(Elt: Record[i]);
2834 }
2835 auto TTy =
2836 TargetExtType::getOrError(Context, Name: TypeName, Types: TypeParams, Ints: IntParams);
2837 if (auto E = TTy.takeError())
2838 return E;
2839 ResultTy = *TTy;
2840 TypeName.clear();
2841 break;
2842 }
2843 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
2844 if (Record.size() < 2)
2845 return error(Message: "Invalid array type record");
2846 ResultTy = getTypeByID(ID: Record[1]);
2847 if (!ResultTy || !ArrayType::isValidElementType(ElemTy: ResultTy))
2848 return error(Message: "Invalid type");
2849 ContainedIDs.push_back(Elt: Record[1]);
2850 ResultTy = ArrayType::get(ElementType: ResultTy, NumElements: Record[0]);
2851 break;
2852 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
2853 // [numelts, eltty, scalable]
2854 if (Record.size() < 2)
2855 return error(Message: "Invalid vector type record");
2856 if (Record[0] == 0)
2857 return error(Message: "Invalid vector length");
2858 ResultTy = getTypeByID(ID: Record[1]);
2859 if (!ResultTy || !VectorType::isValidElementType(ElemTy: ResultTy))
2860 return error(Message: "Invalid type");
2861 bool Scalable = Record.size() > 2 ? Record[2] : false;
2862 ContainedIDs.push_back(Elt: Record[1]);
2863 ResultTy = VectorType::get(ElementType: ResultTy, NumElements: Record[0], Scalable);
2864 break;
2865 }
2866
2867 if (NumRecords >= TypeList.size())
2868 return error(Message: "Invalid TYPE table");
2869 if (TypeList[NumRecords])
2870 return error(
2871 Message: "Invalid TYPE table: Only named structs can be forward referenced");
2872 assert(ResultTy && "Didn't read a type?");
2873 TypeList[NumRecords] = ResultTy;
2874 if (!ContainedIDs.empty())
2875 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2876 ++NumRecords;
2877 }
2878}
2879
2880Error BitcodeReader::parseOperandBundleTags() {
2881 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2882 return Err;
2883
2884 if (!BundleTags.empty())
2885 return error(Message: "Invalid multiple blocks");
2886
2887 SmallVector<uint64_t, 64> Record;
2888
2889 while (true) {
2890 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2891 if (!MaybeEntry)
2892 return MaybeEntry.takeError();
2893 BitstreamEntry Entry = MaybeEntry.get();
2894
2895 switch (Entry.Kind) {
2896 case BitstreamEntry::SubBlock: // Handled for us already.
2897 case BitstreamEntry::Error:
2898 return error(Message: "Malformed block");
2899 case BitstreamEntry::EndBlock:
2900 return Error::success();
2901 case BitstreamEntry::Record:
2902 // The interesting case.
2903 break;
2904 }
2905
2906 // Tags are implicitly mapped to integers by their order.
2907
2908 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
2909 if (!MaybeRecord)
2910 return MaybeRecord.takeError();
2911 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2912 return error(Message: "Invalid operand bundle record");
2913
2914 // OPERAND_BUNDLE_TAG: [strchr x N]
2915 BundleTags.emplace_back();
2916 if (convertToString(Record, Idx: 0, Result&: BundleTags.back()))
2917 return error(Message: "Invalid operand bundle record");
2918 Record.clear();
2919 }
2920}
2921
2922Error BitcodeReader::parseSyncScopeNames() {
2923 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2924 return Err;
2925
2926 if (!SSIDs.empty())
2927 return error(Message: "Invalid multiple synchronization scope names blocks");
2928
2929 SmallVector<uint64_t, 64> Record;
2930 while (true) {
2931 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2932 if (!MaybeEntry)
2933 return MaybeEntry.takeError();
2934 BitstreamEntry Entry = MaybeEntry.get();
2935
2936 switch (Entry.Kind) {
2937 case BitstreamEntry::SubBlock: // Handled for us already.
2938 case BitstreamEntry::Error:
2939 return error(Message: "Malformed block");
2940 case BitstreamEntry::EndBlock:
2941 if (SSIDs.empty())
2942 return error(Message: "Invalid empty synchronization scope names block");
2943 return Error::success();
2944 case BitstreamEntry::Record:
2945 // The interesting case.
2946 break;
2947 }
2948
2949 // Synchronization scope names are implicitly mapped to synchronization
2950 // scope IDs by their order.
2951
2952 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
2953 if (!MaybeRecord)
2954 return MaybeRecord.takeError();
2955 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2956 return error(Message: "Invalid sync scope record");
2957
2958 SmallString<16> SSN;
2959 if (convertToString(Record, Idx: 0, Result&: SSN))
2960 return error(Message: "Invalid sync scope record");
2961
2962 SSIDs.push_back(Elt: Context.getOrInsertSyncScopeID(SSN));
2963 Record.clear();
2964 }
2965}
2966
2967/// Associate a value with its name from the given index in the provided record.
2968Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2969 unsigned NameIndex, Triple &TT) {
2970 SmallString<128> ValueName;
2971 if (convertToString(Record, Idx: NameIndex, Result&: ValueName))
2972 return error(Message: "Invalid record");
2973 unsigned ValueID = Record[0];
2974 if (ValueID >= ValueList.size() || !ValueList[ValueID])
2975 return error(Message: "Invalid record");
2976 Value *V = ValueList[ValueID];
2977
2978 StringRef NameStr(ValueName.data(), ValueName.size());
2979 if (NameStr.contains(C: 0))
2980 return error(Message: "Invalid value name");
2981 V->setName(NameStr);
2982 auto *GO = dyn_cast<GlobalObject>(Val: V);
2983 if (GO && ImplicitComdatObjects.contains(V: GO) && TT.supportsCOMDAT())
2984 GO->setComdat(TheModule->getOrInsertComdat(Name: V->getName()));
2985 return V;
2986}
2987
2988/// Helper to note and return the current location, and jump to the given
2989/// offset.
2990static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2991 BitstreamCursor &Stream) {
2992 // Save the current parsing location so we can jump back at the end
2993 // of the VST read.
2994 uint64_t CurrentBit = Stream.GetCurrentBitNo();
2995 if (Error JumpFailed = Stream.JumpToBit(BitNo: Offset * 32))
2996 return std::move(JumpFailed);
2997 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2998 if (!MaybeEntry)
2999 return MaybeEntry.takeError();
3000 if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
3001 MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
3002 return error(Message: "Expected value symbol table subblock");
3003 return CurrentBit;
3004}
3005
3006void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
3007 Function *F,
3008 ArrayRef<uint64_t> Record) {
3009 // Note that we subtract 1 here because the offset is relative to one word
3010 // before the start of the identification or module block, which was
3011 // historically always the start of the regular bitcode header.
3012 uint64_t FuncWordOffset = Record[1] - 1;
3013 uint64_t FuncBitOffset = FuncWordOffset * 32;
3014 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3015 // Set the LastFunctionBlockBit to point to the last function block.
3016 // Later when parsing is resumed after function materialization,
3017 // we can simply skip that last function block.
3018 if (FuncBitOffset > LastFunctionBlockBit)
3019 LastFunctionBlockBit = FuncBitOffset;
3020}
3021
3022/// Read a new-style GlobalValue symbol table.
3023Error BitcodeReader::parseGlobalValueSymbolTable() {
3024 unsigned FuncBitcodeOffsetDelta =
3025 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
3026
3027 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::VALUE_SYMTAB_BLOCK_ID))
3028 return Err;
3029
3030 SmallVector<uint64_t, 64> Record;
3031 while (true) {
3032 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3033 if (!MaybeEntry)
3034 return MaybeEntry.takeError();
3035 BitstreamEntry Entry = MaybeEntry.get();
3036
3037 switch (Entry.Kind) {
3038 case BitstreamEntry::SubBlock:
3039 case BitstreamEntry::Error:
3040 return error(Message: "Malformed block");
3041 case BitstreamEntry::EndBlock:
3042 return Error::success();
3043 case BitstreamEntry::Record:
3044 break;
3045 }
3046
3047 Record.clear();
3048 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
3049 if (!MaybeRecord)
3050 return MaybeRecord.takeError();
3051 switch (MaybeRecord.get()) {
3052 case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
3053 unsigned ValueID = Record[0];
3054 if (ValueID >= ValueList.size() || !ValueList[ValueID])
3055 return error(Message: "Invalid value reference in symbol table");
3056 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3057 F: cast<Function>(Val: ValueList[ValueID]), Record);
3058 break;
3059 }
3060 }
3061 }
3062}
3063
3064/// Parse the value symbol table at either the current parsing location or
3065/// at the given bit offset if provided.
3066Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
3067 uint64_t CurrentBit;
3068 // Pass in the Offset to distinguish between calling for the module-level
3069 // VST (where we want to jump to the VST offset) and the function-level
3070 // VST (where we don't).
3071 if (Offset > 0) {
3072 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
3073 if (!MaybeCurrentBit)
3074 return MaybeCurrentBit.takeError();
3075 CurrentBit = MaybeCurrentBit.get();
3076 // If this module uses a string table, read this as a module-level VST.
3077 if (UseStrtab) {
3078 if (Error Err = parseGlobalValueSymbolTable())
3079 return Err;
3080 if (Error JumpFailed = Stream.JumpToBit(BitNo: CurrentBit))
3081 return JumpFailed;
3082 return Error::success();
3083 }
3084 // Otherwise, the VST will be in a similar format to a function-level VST,
3085 // and will contain symbol names.
3086 }
3087
3088 // Compute the delta between the bitcode indices in the VST (the word offset
3089 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
3090 // expected by the lazy reader. The reader's EnterSubBlock expects to have
3091 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
3092 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
3093 // just before entering the VST subblock because: 1) the EnterSubBlock
3094 // changes the AbbrevID width; 2) the VST block is nested within the same
3095 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
3096 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
3097 // jump to the FUNCTION_BLOCK using this offset later, we don't want
3098 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
3099 unsigned FuncBitcodeOffsetDelta =
3100 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
3101
3102 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::VALUE_SYMTAB_BLOCK_ID))
3103 return Err;
3104
3105 SmallVector<uint64_t, 64> Record;
3106
3107 Triple TT(TheModule->getTargetTriple());
3108
3109 // Read all the records for this value table.
3110 SmallString<128> ValueName;
3111
3112 while (true) {
3113 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3114 if (!MaybeEntry)
3115 return MaybeEntry.takeError();
3116 BitstreamEntry Entry = MaybeEntry.get();
3117
3118 switch (Entry.Kind) {
3119 case BitstreamEntry::SubBlock: // Handled for us already.
3120 case BitstreamEntry::Error:
3121 return error(Message: "Malformed block");
3122 case BitstreamEntry::EndBlock:
3123 if (Offset > 0)
3124 if (Error JumpFailed = Stream.JumpToBit(BitNo: CurrentBit))
3125 return JumpFailed;
3126 return Error::success();
3127 case BitstreamEntry::Record:
3128 // The interesting case.
3129 break;
3130 }
3131
3132 // Read a record.
3133 Record.clear();
3134 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
3135 if (!MaybeRecord)
3136 return MaybeRecord.takeError();
3137 switch (MaybeRecord.get()) {
3138 default: // Default behavior: unknown type.
3139 break;
3140 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
3141 Expected<Value *> ValOrErr = recordValue(Record, NameIndex: 1, TT);
3142 if (Error Err = ValOrErr.takeError())
3143 return Err;
3144 ValOrErr.get();
3145 break;
3146 }
3147 case bitc::VST_CODE_FNENTRY: {
3148 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
3149 Expected<Value *> ValOrErr = recordValue(Record, NameIndex: 2, TT);
3150 if (Error Err = ValOrErr.takeError())
3151 return Err;
3152 Value *V = ValOrErr.get();
3153
3154 // Ignore function offsets emitted for aliases of functions in older
3155 // versions of LLVM.
3156 if (auto *F = dyn_cast<Function>(Val: V))
3157 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
3158 break;
3159 }
3160 case bitc::VST_CODE_BBENTRY: {
3161 if (convertToString(Record, Idx: 1, Result&: ValueName))
3162 return error(Message: "Invalid bbentry record");
3163 BasicBlock *BB = getBasicBlock(ID: Record[0]);
3164 if (!BB)
3165 return error(Message: "Invalid bbentry record");
3166
3167 BB->setName(ValueName.str());
3168 ValueName.clear();
3169 break;
3170 }
3171 }
3172 }
3173}
3174
3175/// Decode a signed value stored with the sign bit in the LSB for dense VBR
3176/// encoding.
3177uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3178 if ((V & 1) == 0)
3179 return V >> 1;
3180 if (V != 1)
3181 return -(V >> 1);
3182 // There is no such thing as -0 with integers. "-0" really means MININT.
3183 return 1ULL << 63;
3184}
3185
3186/// Resolve all of the initializers for global values and aliases that we can.
3187Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3188 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3189 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3190 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3191
3192 GlobalInitWorklist.swap(x&: GlobalInits);
3193 IndirectSymbolInitWorklist.swap(x&: IndirectSymbolInits);
3194 FunctionOperandWorklist.swap(x&: FunctionOperands);
3195
3196 while (!GlobalInitWorklist.empty()) {
3197 unsigned ValID = GlobalInitWorklist.back().second;
3198 if (ValID >= ValueList.size()) {
3199 // Not ready to resolve this yet, it requires something later in the file.
3200 GlobalInits.push_back(x: GlobalInitWorklist.back());
3201 } else {
3202 Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID);
3203 if (!MaybeC)
3204 return MaybeC.takeError();
3205 GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
3206 }
3207 GlobalInitWorklist.pop_back();
3208 }
3209
3210 while (!IndirectSymbolInitWorklist.empty()) {
3211 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3212 if (ValID >= ValueList.size()) {
3213 IndirectSymbolInits.push_back(x: IndirectSymbolInitWorklist.back());
3214 } else {
3215 Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID);
3216 if (!MaybeC)
3217 return MaybeC.takeError();
3218 Constant *C = MaybeC.get();
3219 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3220 if (auto *GA = dyn_cast<GlobalAlias>(Val: GV)) {
3221 if (C->getType() != GV->getType())
3222 return error(Message: "Alias and aliasee types don't match");
3223 GA->setAliasee(C);
3224 } else if (auto *GI = dyn_cast<GlobalIFunc>(Val: GV)) {
3225 GI->setResolver(C);
3226 } else {
3227 return error(Message: "Expected an alias or an ifunc");
3228 }
3229 }
3230 IndirectSymbolInitWorklist.pop_back();
3231 }
3232
3233 while (!FunctionOperandWorklist.empty()) {
3234 FunctionOperandInfo &Info = FunctionOperandWorklist.back();
3235 if (Info.PersonalityFn) {
3236 unsigned ValID = Info.PersonalityFn - 1;
3237 if (ValID < ValueList.size()) {
3238 Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID);
3239 if (!MaybeC)
3240 return MaybeC.takeError();
3241 Info.F->setPersonalityFn(MaybeC.get());
3242 Info.PersonalityFn = 0;
3243 }
3244 }
3245 if (Info.Prefix) {
3246 unsigned ValID = Info.Prefix - 1;
3247 if (ValID < ValueList.size()) {
3248 Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID);
3249 if (!MaybeC)
3250 return MaybeC.takeError();
3251 Info.F->setPrefixData(MaybeC.get());
3252 Info.Prefix = 0;
3253 }
3254 }
3255 if (Info.Prologue) {
3256 unsigned ValID = Info.Prologue - 1;
3257 if (ValID < ValueList.size()) {
3258 Expected<Constant *> MaybeC = getValueForInitializer(ID: ValID);
3259 if (!MaybeC)
3260 return MaybeC.takeError();
3261 Info.F->setPrologueData(MaybeC.get());
3262 Info.Prologue = 0;
3263 }
3264 }
3265 if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
3266 FunctionOperands.push_back(x: Info);
3267 FunctionOperandWorklist.pop_back();
3268 }
3269
3270 return Error::success();
3271}
3272
3273APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
3274 SmallVector<uint64_t, 8> Words(Vals.size());
3275 transform(Range&: Vals, d_first: Words.begin(),
3276 F: BitcodeReader::decodeSignRotatedValue);
3277
3278 return APInt(TypeBits, Words);
3279}
3280
3281Error BitcodeReader::parseConstants() {
3282 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::CONSTANTS_BLOCK_ID))
3283 return Err;
3284
3285 SmallVector<uint64_t, 64> Record;
3286
3287 // Read all the records for this value table.
3288 Type *CurTy = Type::getInt32Ty(C&: Context);
3289 unsigned Int32TyID = getVirtualTypeID(Ty: CurTy);
3290 unsigned CurTyID = Int32TyID;
3291 Type *CurElemTy = nullptr;
3292 unsigned NextCstNo = ValueList.size();
3293
3294 while (true) {
3295 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3296 if (!MaybeEntry)
3297 return MaybeEntry.takeError();
3298 BitstreamEntry Entry = MaybeEntry.get();
3299
3300 switch (Entry.Kind) {
3301 case BitstreamEntry::SubBlock: // Handled for us already.
3302 case BitstreamEntry::Error:
3303 return error(Message: "Malformed block");
3304 case BitstreamEntry::EndBlock:
3305 if (NextCstNo != ValueList.size())
3306 return error(Message: "Invalid constant reference");
3307 return Error::success();
3308 case BitstreamEntry::Record:
3309 // The interesting case.
3310 break;
3311 }
3312
3313 // Read a record.
3314 Record.clear();
3315 Type *VoidType = Type::getVoidTy(C&: Context);
3316 Value *V = nullptr;
3317 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
3318 if (!MaybeBitCode)
3319 return MaybeBitCode.takeError();
3320 switch (unsigned BitCode = MaybeBitCode.get()) {
3321 default: // Default behavior: unknown constant
3322 case bitc::CST_CODE_UNDEF: // UNDEF
3323 V = UndefValue::get(T: CurTy);
3324 break;
3325 case bitc::CST_CODE_POISON: // POISON
3326 V = PoisonValue::get(T: CurTy);
3327 break;
3328 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3329 if (Record.empty())
3330 return error(Message: "Invalid settype record");
3331 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3332 return error(Message: "Invalid settype record");
3333 if (TypeList[Record[0]] == VoidType)
3334 return error(Message: "Invalid constant type");
3335 CurTyID = Record[0];
3336 CurTy = TypeList[CurTyID];
3337 CurElemTy = getPtrElementTypeByID(ID: CurTyID);
3338 continue; // Skip the ValueList manipulation.
3339 case bitc::CST_CODE_NULL: // NULL
3340 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
3341 return error(Message: "Invalid type for a constant null value");
3342 if (auto *TETy = dyn_cast<TargetExtType>(Val: CurTy))
3343 if (!TETy->hasProperty(Prop: TargetExtType::HasZeroInit))
3344 return error(Message: "Invalid type for a constant null value");
3345 V = Constant::getNullValue(Ty: CurTy);
3346 break;
3347 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
3348 if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3349 return error(Message: "Invalid integer const record");
3350 V = ConstantInt::getSigned(Ty: CurTy, V: decodeSignRotatedValue(V: Record[0]));
3351 break;
3352 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3353 if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3354 return error(Message: "Invalid wide integer const record");
3355
3356 auto *ScalarTy = cast<IntegerType>(Val: CurTy->getScalarType());
3357 APInt VInt = readWideAPInt(Vals: Record, TypeBits: ScalarTy->getBitWidth());
3358 V = ConstantInt::get(Ty: CurTy, V: VInt);
3359 break;
3360 }
3361 case bitc::CST_CODE_BYTE: // BYTE: [byteval]
3362 if (!CurTy->isByteOrByteVectorTy() || Record.empty())
3363 return error(Message: "Invalid byte const record");
3364 V = ConstantByte::get(Ty: CurTy, V: decodeSignRotatedValue(V: Record[0]));
3365 break;
3366 case bitc::CST_CODE_WIDE_BYTE: { // WIDE_BYTE: [n x byteval]
3367 if (!CurTy->isByteOrByteVectorTy() || Record.empty())
3368 return error(Message: "Invalid wide byte const record");
3369
3370 auto *ScalarTy = cast<ByteType>(Val: CurTy->getScalarType());
3371 APInt VByte = readWideAPInt(Vals: Record, TypeBits: ScalarTy->getBitWidth());
3372 V = ConstantByte::get(Ty: CurTy, V: VByte);
3373 break;
3374 }
3375 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
3376 if (Record.empty())
3377 return error(Message: "Invalid float const record");
3378
3379 auto *ScalarTy = CurTy->getScalarType();
3380 if (ScalarTy->isHalfTy())
3381 V = ConstantFP::get(Ty: CurTy, V: APFloat(APFloat::IEEEhalf(),
3382 APInt(16, (uint16_t)Record[0])));
3383 else if (ScalarTy->isBFloatTy())
3384 V = ConstantFP::get(
3385 Ty: CurTy, V: APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3386 else if (ScalarTy->isFloatTy())
3387 V = ConstantFP::get(Ty: CurTy, V: APFloat(APFloat::IEEEsingle(),
3388 APInt(32, (uint32_t)Record[0])));
3389 else if (ScalarTy->isDoubleTy())
3390 V = ConstantFP::get(
3391 Ty: CurTy, V: APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3392 else if (ScalarTy->isX86_FP80Ty()) {
3393 // Bits are not stored the same way as a normal i80 APInt, compensate.
3394 uint64_t Rearrange[2];
3395 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3396 Rearrange[1] = Record[0] >> 48;
3397 V = ConstantFP::get(
3398 Ty: CurTy, V: APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3399 } else if (ScalarTy->isFP128Ty())
3400 V = ConstantFP::get(Ty: CurTy,
3401 V: APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3402 else if (ScalarTy->isPPC_FP128Ty())
3403 V = ConstantFP::get(
3404 Ty: CurTy, V: APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3405 else
3406 V = PoisonValue::get(T: CurTy);
3407 break;
3408 }
3409
3410 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3411 if (Record.empty())
3412 return error(Message: "Invalid aggregate record");
3413
3414 SmallVector<unsigned, 16> Elts;
3415 llvm::append_range(C&: Elts, R&: Record);
3416
3417 if (isa<StructType>(Val: CurTy)) {
3418 V = BitcodeConstant::create(
3419 A&: Alloc, Ty: CurTy, Info: BitcodeConstant::ConstantStructOpcode, OpIDs: Elts);
3420 } else if (isa<ArrayType>(Val: CurTy)) {
3421 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy,
3422 Info: BitcodeConstant::ConstantArrayOpcode, OpIDs: Elts);
3423 } else if (isa<VectorType>(Val: CurTy)) {
3424 V = BitcodeConstant::create(
3425 A&: Alloc, Ty: CurTy, Info: BitcodeConstant::ConstantVectorOpcode, OpIDs: Elts);
3426 } else {
3427 V = PoisonValue::get(T: CurTy);
3428 }
3429 break;
3430 }
3431 case bitc::CST_CODE_STRING: // STRING: [values]
3432 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3433 if (Record.empty())
3434 return error(Message: "Invalid string record");
3435
3436 SmallString<16> Elts(Record.begin(), Record.end());
3437 V = ConstantDataArray::getString(
3438 Context, Initializer: Elts, AddNull: BitCode == bitc::CST_CODE_CSTRING,
3439 ByteString: cast<ArrayType>(Val: CurTy)->getElementType()->isByteTy());
3440 break;
3441 }
3442 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3443 if (Record.empty())
3444 return error(Message: "Invalid data record");
3445
3446 Type *EltTy;
3447 if (auto *Array = dyn_cast<ArrayType>(Val: CurTy))
3448 EltTy = Array->getElementType();
3449 else
3450 EltTy = cast<VectorType>(Val: CurTy)->getElementType();
3451 if (EltTy->isIntegerTy(Bitwidth: 8)) {
3452 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3453 if (isa<VectorType>(Val: CurTy))
3454 V = ConstantDataVector::get(Context, Elts);
3455 else
3456 V = ConstantDataArray::get(Context, Elts);
3457 } else if (EltTy->isIntegerTy(Bitwidth: 16)) {
3458 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3459 if (isa<VectorType>(Val: CurTy))
3460 V = ConstantDataVector::get(Context, Elts);
3461 else
3462 V = ConstantDataArray::get(Context, Elts);
3463 } else if (EltTy->isIntegerTy(Bitwidth: 32)) {
3464 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3465 if (isa<VectorType>(Val: CurTy))
3466 V = ConstantDataVector::get(Context, Elts);
3467 else
3468 V = ConstantDataArray::get(Context, Elts);
3469 } else if (EltTy->isIntegerTy(Bitwidth: 64)) {
3470 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3471 if (isa<VectorType>(Val: CurTy))
3472 V = ConstantDataVector::get(Context, Elts);
3473 else
3474 V = ConstantDataArray::get(Context, Elts);
3475 } else if (EltTy->isByteTy(BitWidth: 8)) {
3476 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3477 if (isa<VectorType>(Val: CurTy))
3478 V = ConstantDataVector::getByte(ElementType: EltTy, Elts);
3479 else
3480 V = ConstantDataArray::getByte(ElementType: EltTy, Elts);
3481 } else if (EltTy->isByteTy(BitWidth: 16)) {
3482 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3483 if (isa<VectorType>(Val: CurTy))
3484 V = ConstantDataVector::getByte(ElementType: EltTy, Elts);
3485 else
3486 V = ConstantDataArray::getByte(ElementType: EltTy, Elts);
3487 } else if (EltTy->isByteTy(BitWidth: 32)) {
3488 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3489 if (isa<VectorType>(Val: CurTy))
3490 V = ConstantDataVector::getByte(ElementType: EltTy, Elts);
3491 else
3492 V = ConstantDataArray::getByte(ElementType: EltTy, Elts);
3493 } else if (EltTy->isByteTy(BitWidth: 64)) {
3494 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3495 if (isa<VectorType>(Val: CurTy))
3496 V = ConstantDataVector::getByte(ElementType: EltTy, Elts);
3497 else
3498 V = ConstantDataArray::getByte(ElementType: EltTy, Elts);
3499 } else if (EltTy->isHalfTy()) {
3500 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3501 if (isa<VectorType>(Val: CurTy))
3502 V = ConstantDataVector::getFP(ElementType: EltTy, Elts);
3503 else
3504 V = ConstantDataArray::getFP(ElementType: EltTy, Elts);
3505 } else if (EltTy->isBFloatTy()) {
3506 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3507 if (isa<VectorType>(Val: CurTy))
3508 V = ConstantDataVector::getFP(ElementType: EltTy, Elts);
3509 else
3510 V = ConstantDataArray::getFP(ElementType: EltTy, Elts);
3511 } else if (EltTy->isFloatTy()) {
3512 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3513 if (isa<VectorType>(Val: CurTy))
3514 V = ConstantDataVector::getFP(ElementType: EltTy, Elts);
3515 else
3516 V = ConstantDataArray::getFP(ElementType: EltTy, Elts);
3517 } else if (EltTy->isDoubleTy()) {
3518 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3519 if (isa<VectorType>(Val: CurTy))
3520 V = ConstantDataVector::getFP(ElementType: EltTy, Elts);
3521 else
3522 V = ConstantDataArray::getFP(ElementType: EltTy, Elts);
3523 } else {
3524 return error(Message: "Invalid type for value");
3525 }
3526 break;
3527 }
3528 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
3529 if (Record.size() < 2)
3530 return error(Message: "Invalid unary op constexpr record");
3531 int Opc = getDecodedUnaryOpcode(Val: Record[0], Ty: CurTy);
3532 if (Opc < 0) {
3533 V = PoisonValue::get(T: CurTy); // Unknown unop.
3534 } else {
3535 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: Opc, OpIDs: (unsigned)Record[1]);
3536 }
3537 break;
3538 }
3539 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3540 if (Record.size() < 3)
3541 return error(Message: "Invalid binary op constexpr record");
3542 int Opc = getDecodedBinaryOpcode(Val: Record[0], Ty: CurTy);
3543 if (Opc < 0) {
3544 V = PoisonValue::get(T: CurTy); // Unknown binop.
3545 } else {
3546 uint8_t Flags = 0;
3547 if (Record.size() >= 4) {
3548 if (Opc == Instruction::Add ||
3549 Opc == Instruction::Sub ||
3550 Opc == Instruction::Mul ||
3551 Opc == Instruction::Shl) {
3552 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3553 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3554 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3555 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3556 } else if (Opc == Instruction::SDiv ||
3557 Opc == Instruction::UDiv ||
3558 Opc == Instruction::LShr ||
3559 Opc == Instruction::AShr) {
3560 if (Record[3] & (1 << bitc::PEO_EXACT))
3561 Flags |= PossiblyExactOperator::IsExact;
3562 }
3563 }
3564 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: {(uint8_t)Opc, Flags},
3565 OpIDs: {(unsigned)Record[1], (unsigned)Record[2]});
3566 }
3567 break;
3568 }
3569 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3570 if (Record.size() < 3)
3571 return error(Message: "Invalid cast constexpr record");
3572 int Opc = getDecodedCastOpcode(Val: Record[0]);
3573 if (Opc < 0) {
3574 V = PoisonValue::get(T: CurTy); // Unknown cast.
3575 } else {
3576 unsigned OpTyID = Record[1];
3577 Type *OpTy = getTypeByID(ID: OpTyID);
3578 if (!OpTy)
3579 return error(Message: "Invalid cast constexpr record");
3580 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: Opc, OpIDs: (unsigned)Record[2]);
3581 }
3582 break;
3583 }
3584 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3585 case bitc::CST_CODE_CE_GEP_OLD: // [ty, n x operands]
3586 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD: // [ty, flags, n x
3587 // operands]
3588 case bitc::CST_CODE_CE_GEP: // [ty, flags, n x operands]
3589 case bitc::CST_CODE_CE_GEP_WITH_INRANGE: { // [ty, flags, start, end, n x
3590 // operands]
3591 if (Record.size() < 2)
3592 return error(Message: "Constant GEP record must have at least two elements");
3593 unsigned OpNum = 0;
3594 Type *PointeeType = nullptr;
3595 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD ||
3596 BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE ||
3597 BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2)
3598 PointeeType = getTypeByID(ID: Record[OpNum++]);
3599
3600 uint64_t Flags = 0;
3601 std::optional<ConstantRange> InRange;
3602 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD) {
3603 uint64_t Op = Record[OpNum++];
3604 Flags = Op & 1; // inbounds
3605 unsigned InRangeIndex = Op >> 1;
3606 // "Upgrade" inrange by dropping it. The feature is too niche to
3607 // bother.
3608 (void)InRangeIndex;
3609 } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) {
3610 Flags = Record[OpNum++];
3611 Expected<ConstantRange> MaybeInRange =
3612 readBitWidthAndConstantRange(Record, OpNum);
3613 if (!MaybeInRange)
3614 return MaybeInRange.takeError();
3615 InRange = MaybeInRange.get();
3616 } else if (BitCode == bitc::CST_CODE_CE_GEP) {
3617 Flags = Record[OpNum++];
3618 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3619 Flags = (1 << bitc::GEP_INBOUNDS);
3620
3621 SmallVector<unsigned, 16> Elts;
3622 unsigned BaseTypeID = Record[OpNum];
3623 while (OpNum != Record.size()) {
3624 unsigned ElTyID = Record[OpNum++];
3625 Type *ElTy = getTypeByID(ID: ElTyID);
3626 if (!ElTy)
3627 return error(Message: "Invalid getelementptr constexpr record");
3628 Elts.push_back(Elt: Record[OpNum++]);
3629 }
3630
3631 if (Elts.size() < 1)
3632 return error(Message: "Invalid gep with no operands");
3633
3634 Type *BaseType = getTypeByID(ID: BaseTypeID);
3635 if (isa<VectorType>(Val: BaseType)) {
3636 BaseTypeID = getContainedTypeID(ID: BaseTypeID, Idx: 0);
3637 BaseType = getTypeByID(ID: BaseTypeID);
3638 }
3639
3640 PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(Val: BaseType);
3641 if (!OrigPtrTy)
3642 return error(Message: "GEP base operand must be pointer or vector of pointer");
3643
3644 if (!PointeeType) {
3645 PointeeType = getPtrElementTypeByID(ID: BaseTypeID);
3646 if (!PointeeType)
3647 return error(Message: "Missing element type for old-style constant GEP");
3648 }
3649
3650 V = BitcodeConstant::create(
3651 A&: Alloc, Ty: CurTy,
3652 Info: {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange},
3653 OpIDs: Elts);
3654 break;
3655 }
3656 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3657 if (Record.size() < 3)
3658 return error(Message: "Invalid select constexpr record");
3659
3660 V = BitcodeConstant::create(
3661 A&: Alloc, Ty: CurTy, Info: Instruction::Select,
3662 OpIDs: {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3663 break;
3664 }
3665 case bitc::CST_CODE_CE_EXTRACTELT
3666 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3667 if (Record.size() < 3)
3668 return error(Message: "Invalid extractelement constexpr record");
3669 unsigned OpTyID = Record[0];
3670 VectorType *OpTy =
3671 dyn_cast_or_null<VectorType>(Val: getTypeByID(ID: OpTyID));
3672 if (!OpTy)
3673 return error(Message: "Invalid extractelement constexpr record");
3674 unsigned IdxRecord;
3675 if (Record.size() == 4) {
3676 unsigned IdxTyID = Record[2];
3677 Type *IdxTy = getTypeByID(ID: IdxTyID);
3678 if (!IdxTy)
3679 return error(Message: "Invalid extractelement constexpr record");
3680 IdxRecord = Record[3];
3681 } else {
3682 // Deprecated, but still needed to read old bitcode files.
3683 IdxRecord = Record[2];
3684 }
3685 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: Instruction::ExtractElement,
3686 OpIDs: {(unsigned)Record[1], IdxRecord});
3687 break;
3688 }
3689 case bitc::CST_CODE_CE_INSERTELT
3690 : { // CE_INSERTELT: [opval, opval, opty, opval]
3691 VectorType *OpTy = dyn_cast<VectorType>(Val: CurTy);
3692 if (Record.size() < 3 || !OpTy)
3693 return error(Message: "Invalid insertelement constexpr record");
3694 unsigned IdxRecord;
3695 if (Record.size() == 4) {
3696 unsigned IdxTyID = Record[2];
3697 Type *IdxTy = getTypeByID(ID: IdxTyID);
3698 if (!IdxTy)
3699 return error(Message: "Invalid insertelement constexpr record");
3700 IdxRecord = Record[3];
3701 } else {
3702 // Deprecated, but still needed to read old bitcode files.
3703 IdxRecord = Record[2];
3704 }
3705 V = BitcodeConstant::create(
3706 A&: Alloc, Ty: CurTy, Info: Instruction::InsertElement,
3707 OpIDs: {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3708 break;
3709 }
3710 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3711 VectorType *OpTy = dyn_cast<VectorType>(Val: CurTy);
3712 if (Record.size() < 3 || !OpTy)
3713 return error(Message: "Invalid shufflevector constexpr record");
3714 V = BitcodeConstant::create(
3715 A&: Alloc, Ty: CurTy, Info: Instruction::ShuffleVector,
3716 OpIDs: {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3717 break;
3718 }
3719 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3720 VectorType *RTy = dyn_cast<VectorType>(Val: CurTy);
3721 VectorType *OpTy =
3722 dyn_cast_or_null<VectorType>(Val: getTypeByID(ID: Record[0]));
3723 if (Record.size() < 4 || !RTy || !OpTy)
3724 return error(Message: "Invalid shufflevector constexpr record");
3725 V = BitcodeConstant::create(
3726 A&: Alloc, Ty: CurTy, Info: Instruction::ShuffleVector,
3727 OpIDs: {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3728 break;
3729 }
3730 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3731 if (Record.size() < 4)
3732 return error(Message: "Invalid cmp constexpt record");
3733 unsigned OpTyID = Record[0];
3734 Type *OpTy = getTypeByID(ID: OpTyID);
3735 if (!OpTy)
3736 return error(Message: "Invalid cmp constexpr record");
3737 V = BitcodeConstant::create(
3738 A&: Alloc, Ty: CurTy,
3739 Info: {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3740 : Instruction::ICmp),
3741 (uint8_t)Record[3]},
3742 OpIDs: {(unsigned)Record[1], (unsigned)Record[2]});
3743 break;
3744 }
3745 // This maintains backward compatibility, pre-asm dialect keywords.
3746 // Deprecated, but still needed to read old bitcode files.
3747 case bitc::CST_CODE_INLINEASM_OLD: {
3748 if (Record.size() < 2)
3749 return error(Message: "Invalid inlineasm record");
3750 std::string AsmStr, ConstrStr;
3751 bool HasSideEffects = Record[0] & 1;
3752 bool IsAlignStack = Record[0] >> 1;
3753 unsigned AsmStrSize = Record[1];
3754 if (2+AsmStrSize >= Record.size())
3755 return error(Message: "Invalid inlineasm record");
3756 unsigned ConstStrSize = Record[2+AsmStrSize];
3757 if (3+AsmStrSize+ConstStrSize > Record.size())
3758 return error(Message: "Invalid inlineasm record");
3759
3760 for (unsigned i = 0; i != AsmStrSize; ++i)
3761 AsmStr += (char)Record[2+i];
3762 for (unsigned i = 0; i != ConstStrSize; ++i)
3763 ConstrStr += (char)Record[3+AsmStrSize+i];
3764 UpgradeInlineAsmString(AsmStr: &AsmStr);
3765 if (!CurElemTy)
3766 return error(Message: "Missing element type for old-style inlineasm");
3767 V = InlineAsm::get(Ty: cast<FunctionType>(Val: CurElemTy), AsmString: AsmStr, Constraints: ConstrStr,
3768 hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack);
3769 break;
3770 }
3771 // This version adds support for the asm dialect keywords (e.g.,
3772 // inteldialect).
3773 case bitc::CST_CODE_INLINEASM_OLD2: {
3774 if (Record.size() < 2)
3775 return error(Message: "Invalid inlineasm record");
3776 std::string AsmStr, ConstrStr;
3777 bool HasSideEffects = Record[0] & 1;
3778 bool IsAlignStack = (Record[0] >> 1) & 1;
3779 unsigned AsmDialect = Record[0] >> 2;
3780 unsigned AsmStrSize = Record[1];
3781 if (2+AsmStrSize >= Record.size())
3782 return error(Message: "Invalid inlineasm record");
3783 unsigned ConstStrSize = Record[2+AsmStrSize];
3784 if (3+AsmStrSize+ConstStrSize > Record.size())
3785 return error(Message: "Invalid inlineasm record");
3786
3787 for (unsigned i = 0; i != AsmStrSize; ++i)
3788 AsmStr += (char)Record[2+i];
3789 for (unsigned i = 0; i != ConstStrSize; ++i)
3790 ConstrStr += (char)Record[3+AsmStrSize+i];
3791 UpgradeInlineAsmString(AsmStr: &AsmStr);
3792 if (!CurElemTy)
3793 return error(Message: "Missing element type for old-style inlineasm");
3794 V = InlineAsm::get(Ty: cast<FunctionType>(Val: CurElemTy), AsmString: AsmStr, Constraints: ConstrStr,
3795 hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack,
3796 asmDialect: InlineAsm::AsmDialect(AsmDialect));
3797 break;
3798 }
3799 // This version adds support for the unwind keyword.
3800 case bitc::CST_CODE_INLINEASM_OLD3: {
3801 if (Record.size() < 2)
3802 return error(Message: "Invalid inlineasm record");
3803 unsigned OpNum = 0;
3804 std::string AsmStr, ConstrStr;
3805 bool HasSideEffects = Record[OpNum] & 1;
3806 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3807 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3808 bool CanThrow = (Record[OpNum] >> 3) & 1;
3809 ++OpNum;
3810 unsigned AsmStrSize = Record[OpNum];
3811 ++OpNum;
3812 if (OpNum + AsmStrSize >= Record.size())
3813 return error(Message: "Invalid inlineasm record");
3814 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3815 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3816 return error(Message: "Invalid inlineasm record");
3817
3818 for (unsigned i = 0; i != AsmStrSize; ++i)
3819 AsmStr += (char)Record[OpNum + i];
3820 ++OpNum;
3821 for (unsigned i = 0; i != ConstStrSize; ++i)
3822 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3823 UpgradeInlineAsmString(AsmStr: &AsmStr);
3824 if (!CurElemTy)
3825 return error(Message: "Missing element type for old-style inlineasm");
3826 V = InlineAsm::get(Ty: cast<FunctionType>(Val: CurElemTy), AsmString: AsmStr, Constraints: ConstrStr,
3827 hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack,
3828 asmDialect: InlineAsm::AsmDialect(AsmDialect), canThrow: CanThrow);
3829 break;
3830 }
3831 // This version adds explicit function type.
3832 case bitc::CST_CODE_INLINEASM: {
3833 if (Record.size() < 3)
3834 return error(Message: "Invalid inlineasm record");
3835 unsigned OpNum = 0;
3836 auto *FnTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: Record[OpNum]));
3837 ++OpNum;
3838 if (!FnTy)
3839 return error(Message: "Invalid inlineasm record");
3840 std::string AsmStr, ConstrStr;
3841 bool HasSideEffects = Record[OpNum] & 1;
3842 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3843 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3844 bool CanThrow = (Record[OpNum] >> 3) & 1;
3845 ++OpNum;
3846 unsigned AsmStrSize = Record[OpNum];
3847 ++OpNum;
3848 if (OpNum + AsmStrSize >= Record.size())
3849 return error(Message: "Invalid inlineasm record");
3850 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3851 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3852 return error(Message: "Invalid inlineasm record");
3853
3854 for (unsigned i = 0; i != AsmStrSize; ++i)
3855 AsmStr += (char)Record[OpNum + i];
3856 ++OpNum;
3857 for (unsigned i = 0; i != ConstStrSize; ++i)
3858 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3859 UpgradeInlineAsmString(AsmStr: &AsmStr);
3860 V = InlineAsm::get(Ty: FnTy, AsmString: AsmStr, Constraints: ConstrStr, hasSideEffects: HasSideEffects, isAlignStack: IsAlignStack,
3861 asmDialect: InlineAsm::AsmDialect(AsmDialect), canThrow: CanThrow);
3862 break;
3863 }
3864 case bitc::CST_CODE_BLOCKADDRESS:{
3865 if (Record.size() < 3)
3866 return error(Message: "Invalid blockaddress record");
3867 unsigned FnTyID = Record[0];
3868 Type *FnTy = getTypeByID(ID: FnTyID);
3869 if (!FnTy)
3870 return error(Message: "Invalid blockaddress record");
3871 V = BitcodeConstant::create(
3872 A&: Alloc, Ty: CurTy,
3873 Info: {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3874 OpIDs: Record[1]);
3875 break;
3876 }
3877 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3878 if (Record.size() < 2)
3879 return error(Message: "Invalid dso_local record");
3880 unsigned GVTyID = Record[0];
3881 Type *GVTy = getTypeByID(ID: GVTyID);
3882 if (!GVTy)
3883 return error(Message: "Invalid dso_local record");
3884 V = BitcodeConstant::create(
3885 A&: Alloc, Ty: CurTy, Info: BitcodeConstant::DSOLocalEquivalentOpcode, OpIDs: Record[1]);
3886 break;
3887 }
3888 case bitc::CST_CODE_NO_CFI_VALUE: {
3889 if (Record.size() < 2)
3890 return error(Message: "Invalid no_cfi record");
3891 unsigned GVTyID = Record[0];
3892 Type *GVTy = getTypeByID(ID: GVTyID);
3893 if (!GVTy)
3894 return error(Message: "Invalid no_cfi record");
3895 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy, Info: BitcodeConstant::NoCFIOpcode,
3896 OpIDs: Record[1]);
3897 break;
3898 }
3899 case bitc::CST_CODE_PTRAUTH: {
3900 if (Record.size() < 4)
3901 return error(Message: "Invalid ptrauth record");
3902 // Ptr, Key, Disc, AddrDisc
3903 V = BitcodeConstant::create(A&: Alloc, Ty: CurTy,
3904 Info: BitcodeConstant::ConstantPtrAuthOpcode,
3905 OpIDs: {(unsigned)Record[0], (unsigned)Record[1],
3906 (unsigned)Record[2], (unsigned)Record[3]});
3907 break;
3908 }
3909 case bitc::CST_CODE_PTRAUTH2: {
3910 if (Record.size() < 5)
3911 return error(Message: "Invalid ptrauth record");
3912 // Ptr, Key, Disc, AddrDisc, DeactivationSymbol
3913 V = BitcodeConstant::create(
3914 A&: Alloc, Ty: CurTy, Info: BitcodeConstant::ConstantPtrAuthOpcode,
3915 OpIDs: {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2],
3916 (unsigned)Record[3], (unsigned)Record[4]});
3917 break;
3918 }
3919 }
3920
3921 assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3922 if (Error Err = ValueList.assignValue(Idx: NextCstNo, V, TypeID: CurTyID))
3923 return Err;
3924 ++NextCstNo;
3925 }
3926}
3927
3928Error BitcodeReader::parseUseLists() {
3929 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::USELIST_BLOCK_ID))
3930 return Err;
3931
3932 // Read all the records.
3933 SmallVector<uint64_t, 64> Record;
3934
3935 while (true) {
3936 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3937 if (!MaybeEntry)
3938 return MaybeEntry.takeError();
3939 BitstreamEntry Entry = MaybeEntry.get();
3940
3941 switch (Entry.Kind) {
3942 case BitstreamEntry::SubBlock: // Handled for us already.
3943 case BitstreamEntry::Error:
3944 return error(Message: "Malformed block");
3945 case BitstreamEntry::EndBlock:
3946 return Error::success();
3947 case BitstreamEntry::Record:
3948 // The interesting case.
3949 break;
3950 }
3951
3952 // Read a use list record.
3953 Record.clear();
3954 bool IsBB = false;
3955 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
3956 if (!MaybeRecord)
3957 return MaybeRecord.takeError();
3958 switch (MaybeRecord.get()) {
3959 default: // Default behavior: unknown type.
3960 break;
3961 case bitc::USELIST_CODE_BB:
3962 IsBB = true;
3963 [[fallthrough]];
3964 case bitc::USELIST_CODE_DEFAULT: {
3965 unsigned RecordLength = Record.size();
3966 if (RecordLength < 3)
3967 // Records should have at least an ID and two indexes.
3968 return error(Message: "Invalid uselist record");
3969 unsigned ID = Record.pop_back_val();
3970
3971 Value *V;
3972 if (IsBB) {
3973 assert(ID < FunctionBBs.size() && "Basic block not found");
3974 V = FunctionBBs[ID];
3975 } else
3976 V = ValueList[ID];
3977
3978 if (!V->hasUseList())
3979 break;
3980
3981 unsigned NumUses = 0;
3982 SmallDenseMap<const Use *, unsigned, 16> Order;
3983 for (const Use &U : V->materialized_uses()) {
3984 if (++NumUses > Record.size())
3985 break;
3986 Order[&U] = Record[NumUses - 1];
3987 }
3988 if (Order.size() != Record.size() || NumUses > Record.size())
3989 // Mismatches can happen if the functions are being materialized lazily
3990 // (out-of-order), or a value has been upgraded.
3991 break;
3992
3993 V->sortUseList(Cmp: [&](const Use &L, const Use &R) {
3994 return Order.lookup(Val: &L) < Order.lookup(Val: &R);
3995 });
3996 break;
3997 }
3998 }
3999 }
4000}
4001
4002/// When we see the block for metadata, remember where it is and then skip it.
4003/// This lets us lazily deserialize the metadata.
4004Error BitcodeReader::rememberAndSkipMetadata() {
4005 // Save the current stream state.
4006 uint64_t CurBit = Stream.GetCurrentBitNo();
4007 DeferredMetadataInfo.push_back(x: CurBit);
4008
4009 // Skip over the block for now.
4010 if (Error Err = Stream.SkipBlock())
4011 return Err;
4012 return Error::success();
4013}
4014
4015Error BitcodeReader::materializeMetadata() {
4016 for (uint64_t BitPos : DeferredMetadataInfo) {
4017 // Move the bit stream to the saved position.
4018 if (Error JumpFailed = Stream.JumpToBit(BitNo: BitPos))
4019 return JumpFailed;
4020 if (Error Err = MDLoader->parseModuleMetadata())
4021 return Err;
4022 }
4023
4024 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
4025 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
4026 // multiple times.
4027 if (!TheModule->getNamedMetadata(Name: "llvm.linker.options")) {
4028 if (Metadata *Val = TheModule->getModuleFlag(Key: "Linker Options")) {
4029 NamedMDNode *LinkerOpts =
4030 TheModule->getOrInsertNamedMetadata(Name: "llvm.linker.options");
4031 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
4032 LinkerOpts->addOperand(M: cast<MDNode>(Val: MDOptions));
4033 }
4034 }
4035
4036 DeferredMetadataInfo.clear();
4037 return Error::success();
4038}
4039
4040void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
4041
4042/// When we see the block for a function body, remember where it is and then
4043/// skip it. This lets us lazily deserialize the functions.
4044Error BitcodeReader::rememberAndSkipFunctionBody() {
4045 // Get the function we are talking about.
4046 if (FunctionsWithBodies.empty())
4047 return error(Message: "Insufficient function protos");
4048
4049 Function *Fn = FunctionsWithBodies.back();
4050 FunctionsWithBodies.pop_back();
4051
4052 // Save the current stream state.
4053 uint64_t CurBit = Stream.GetCurrentBitNo();
4054 assert(
4055 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4056 "Mismatch between VST and scanned function offsets");
4057 DeferredFunctionInfo[Fn] = CurBit;
4058
4059 // Skip over the function block for now.
4060 if (Error Err = Stream.SkipBlock())
4061 return Err;
4062 return Error::success();
4063}
4064
4065Error BitcodeReader::globalCleanup() {
4066 // Patch the initializers for globals and aliases up.
4067 if (Error Err = resolveGlobalAndIndirectSymbolInits())
4068 return Err;
4069 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4070 return error(Message: "Malformed global initializer set");
4071
4072 // Look for intrinsic functions which need to be upgraded at some point
4073 // and functions that need to have their function attributes upgraded.
4074 for (Function &F : *TheModule) {
4075 MDLoader->upgradeDebugIntrinsics(F);
4076 Function *NewFn;
4077 if (UpgradeIntrinsicFunction(F: &F, NewFn))
4078 UpgradedIntrinsics[&F] = NewFn;
4079 // Look for functions that rely on old function attribute behavior.
4080 UpgradeFunctionAttributes(F);
4081 }
4082
4083 // Look for global variables which need to be renamed.
4084 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4085 for (GlobalVariable &GV : TheModule->globals())
4086 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(GV: &GV))
4087 UpgradedVariables.emplace_back(args: &GV, args&: Upgraded);
4088 for (auto &Pair : UpgradedVariables) {
4089 Pair.first->eraseFromParent();
4090 TheModule->insertGlobalVariable(GV: Pair.second);
4091 }
4092
4093 // Force deallocation of memory for these vectors to favor the client that
4094 // want lazy deserialization.
4095 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(x&: GlobalInits);
4096 std::vector<std::pair<GlobalValue *, unsigned>>().swap(x&: IndirectSymbolInits);
4097 return Error::success();
4098}
4099
4100/// Support for lazy parsing of function bodies. This is required if we
4101/// either have an old bitcode file without a VST forward declaration record,
4102/// or if we have an anonymous function being materialized, since anonymous
4103/// functions do not have a name and are therefore not in the VST.
4104Error BitcodeReader::rememberAndSkipFunctionBodies() {
4105 if (Error JumpFailed = Stream.JumpToBit(BitNo: NextUnreadBit))
4106 return JumpFailed;
4107
4108 if (Stream.AtEndOfStream())
4109 return error(Message: "Could not find function in stream");
4110
4111 if (!SeenFirstFunctionBody)
4112 return error(Message: "Trying to materialize functions before seeing function blocks");
4113
4114 // An old bitcode file with the symbol table at the end would have
4115 // finished the parse greedily.
4116 assert(SeenValueSymbolTable);
4117
4118 while (true) {
4119 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4120 if (!MaybeEntry)
4121 return MaybeEntry.takeError();
4122 llvm::BitstreamEntry Entry = MaybeEntry.get();
4123
4124 switch (Entry.Kind) {
4125 default:
4126 return error(Message: "Expect SubBlock");
4127 case BitstreamEntry::SubBlock:
4128 switch (Entry.ID) {
4129 default:
4130 return error(Message: "Expect function block");
4131 case bitc::FUNCTION_BLOCK_ID:
4132 if (Error Err = rememberAndSkipFunctionBody())
4133 return Err;
4134 NextUnreadBit = Stream.GetCurrentBitNo();
4135 return Error::success();
4136 }
4137 }
4138 }
4139}
4140
4141Error BitcodeReaderBase::readBlockInfo() {
4142 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4143 Stream.ReadBlockInfoBlock();
4144 if (!MaybeNewBlockInfo)
4145 return MaybeNewBlockInfo.takeError();
4146 std::optional<BitstreamBlockInfo> NewBlockInfo =
4147 std::move(MaybeNewBlockInfo.get());
4148 if (!NewBlockInfo)
4149 return error(Message: "Malformed block");
4150 BlockInfo = std::move(*NewBlockInfo);
4151 return Error::success();
4152}
4153
4154Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4155 // v1: [selection_kind, name]
4156 // v2: [strtab_offset, strtab_size, selection_kind]
4157 StringRef Name;
4158 std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record);
4159
4160 if (Record.empty())
4161 return error(Message: "Invalid comdat record");
4162 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Val: Record[0]);
4163 std::string OldFormatName;
4164 if (!UseStrtab) {
4165 if (Record.size() < 2)
4166 return error(Message: "Invalid comdat record");
4167 unsigned ComdatNameSize = Record[1];
4168 if (ComdatNameSize > Record.size() - 2)
4169 return error(Message: "Comdat name size too large");
4170 OldFormatName.reserve(res_arg: ComdatNameSize);
4171 for (unsigned i = 0; i != ComdatNameSize; ++i)
4172 OldFormatName += (char)Record[2 + i];
4173 Name = OldFormatName;
4174 }
4175 Comdat *C = TheModule->getOrInsertComdat(Name);
4176 C->setSelectionKind(SK);
4177 ComdatList.push_back(x: C);
4178 return Error::success();
4179}
4180
4181static void inferDSOLocal(GlobalValue *GV) {
4182 // infer dso_local from linkage and visibility if it is not encoded.
4183 if (GV->hasLocalLinkage() ||
4184 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
4185 GV->setDSOLocal(true);
4186}
4187
4188GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
4189 GlobalValue::SanitizerMetadata Meta;
4190 if (V & (1 << 0))
4191 Meta.NoAddress = true;
4192 if (V & (1 << 1))
4193 Meta.NoHWAddress = true;
4194 if (V & (1 << 2))
4195 Meta.Memtag = true;
4196 if (V & (1 << 3))
4197 Meta.IsDynInit = true;
4198 return Meta;
4199}
4200
4201Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4202 // v1: [pointer type, isconst, initid, linkage, alignment, section,
4203 // visibility, threadlocal, unnamed_addr, externally_initialized,
4204 // dllstorageclass, comdat, attributes, preemption specifier,
4205 // partition strtab offset, partition strtab size] (name in VST)
4206 // v2: [strtab_offset, strtab_size, v1]
4207 // v3: [v2, code_model]
4208 StringRef Name;
4209 std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record);
4210
4211 if (Record.size() < 6)
4212 return error(Message: "Invalid global variable record");
4213 unsigned TyID = Record[0];
4214 Type *Ty = getTypeByID(ID: TyID);
4215 if (!Ty)
4216 return error(Message: "Invalid global variable record");
4217 bool isConstant = Record[1] & 1;
4218 bool explicitType = Record[1] & 2;
4219 unsigned AddressSpace;
4220 if (explicitType) {
4221 AddressSpace = Record[1] >> 2;
4222 } else {
4223 if (!Ty->isPointerTy())
4224 return error(Message: "Invalid type for value");
4225 AddressSpace = cast<PointerType>(Val: Ty)->getAddressSpace();
4226 TyID = getContainedTypeID(ID: TyID);
4227 Ty = getTypeByID(ID: TyID);
4228 if (!Ty)
4229 return error(Message: "Missing element type for old-style global");
4230 }
4231
4232 uint64_t RawLinkage = Record[3];
4233 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Val: RawLinkage);
4234 MaybeAlign Alignment;
4235 if (Error Err = parseAlignmentValue(Exponent: Record[4], Alignment))
4236 return Err;
4237 std::string Section;
4238 if (Record[5]) {
4239 if (Record[5] - 1 >= SectionTable.size())
4240 return error(Message: "Invalid ID");
4241 Section = SectionTable[Record[5] - 1];
4242 }
4243 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
4244 // Local linkage must have default visibility.
4245 // auto-upgrade `hidden` and `protected` for old bitcode.
4246 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
4247 Visibility = getDecodedVisibility(Val: Record[6]);
4248
4249 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4250 if (Record.size() > 7)
4251 TLM = getDecodedThreadLocalMode(Val: Record[7]);
4252
4253 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4254 if (Record.size() > 8)
4255 UnnamedAddr = getDecodedUnnamedAddrType(Val: Record[8]);
4256
4257 bool ExternallyInitialized = false;
4258 if (Record.size() > 9)
4259 ExternallyInitialized = Record[9];
4260
4261 GlobalVariable *NewGV =
4262 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
4263 nullptr, TLM, AddressSpace, ExternallyInitialized);
4264 if (Alignment)
4265 NewGV->setAlignment(*Alignment);
4266 if (!Section.empty())
4267 NewGV->setSection(Section);
4268 NewGV->setVisibility(Visibility);
4269 NewGV->setUnnamedAddr(UnnamedAddr);
4270
4271 if (Record.size() > 10) {
4272 // A GlobalValue with local linkage cannot have a DLL storage class.
4273 if (!NewGV->hasLocalLinkage()) {
4274 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Val: Record[10]));
4275 }
4276 } else {
4277 upgradeDLLImportExportLinkage(GV: NewGV, Val: RawLinkage);
4278 }
4279
4280 ValueList.push_back(V: NewGV, TypeID: getVirtualTypeID(Ty: NewGV->getType(), ChildTypeIDs: TyID));
4281
4282 // Remember which value to use for the global initializer.
4283 if (unsigned InitID = Record[2])
4284 GlobalInits.push_back(x: std::make_pair(x&: NewGV, y: InitID - 1));
4285
4286 if (Record.size() > 11) {
4287 if (unsigned ComdatID = Record[11]) {
4288 if (ComdatID > ComdatList.size())
4289 return error(Message: "Invalid global variable comdat ID");
4290 NewGV->setComdat(ComdatList[ComdatID - 1]);
4291 }
4292 } else if (hasImplicitComdat(Val: RawLinkage)) {
4293 ImplicitComdatObjects.insert(V: NewGV);
4294 }
4295
4296 if (Record.size() > 12) {
4297 auto AS = getAttributes(i: Record[12]).getFnAttrs();
4298 NewGV->setAttributes(AS);
4299 }
4300
4301 if (Record.size() > 13) {
4302 NewGV->setDSOLocal(getDecodedDSOLocal(Val: Record[13]));
4303 }
4304 inferDSOLocal(GV: NewGV);
4305
4306 // Check whether we have enough values to read a partition name.
4307 if (Record.size() > 15)
4308 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
4309
4310 if (Record.size() > 16 && Record[16]) {
4311 llvm::GlobalValue::SanitizerMetadata Meta =
4312 deserializeSanitizerMetadata(V: Record[16]);
4313 NewGV->setSanitizerMetadata(Meta);
4314 }
4315
4316 if (Record.size() > 17 && Record[17]) {
4317 if (auto CM = getDecodedCodeModel(Val: Record[17]))
4318 NewGV->setCodeModel(*CM);
4319 else
4320 return error(Message: "Invalid global variable code model");
4321 }
4322
4323 return Error::success();
4324}
4325
4326void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
4327 if (ValueTypeCallback) {
4328 (*ValueTypeCallback)(
4329 F, TypeID, [this](unsigned I) { return getTypeByID(ID: I); },
4330 [this](unsigned I, unsigned J) { return getContainedTypeID(ID: I, Idx: J); });
4331 }
4332}
4333
4334Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4335 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
4336 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
4337 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
4338 // v2: [strtab_offset, strtab_size, v1]
4339 StringRef Name;
4340 std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record);
4341
4342 if (Record.size() < 8)
4343 return error(Message: "Invalid function record");
4344 unsigned FTyID = Record[0];
4345 Type *FTy = getTypeByID(ID: FTyID);
4346 if (!FTy)
4347 return error(Message: "Invalid function record");
4348 if (isa<PointerType>(Val: FTy)) {
4349 FTyID = getContainedTypeID(ID: FTyID, Idx: 0);
4350 FTy = getTypeByID(ID: FTyID);
4351 if (!FTy)
4352 return error(Message: "Missing element type for old-style function");
4353 }
4354
4355 if (!isa<FunctionType>(Val: FTy))
4356 return error(Message: "Invalid type for value");
4357 auto CC = static_cast<CallingConv::ID>(Record[1]);
4358 if (CC & ~CallingConv::MaxID)
4359 return error(Message: "Invalid calling convention ID");
4360
4361 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4362 if (Record.size() > 16)
4363 AddrSpace = Record[16];
4364
4365 Function *Func =
4366 Function::Create(Ty: cast<FunctionType>(Val: FTy), Linkage: GlobalValue::ExternalLinkage,
4367 AddrSpace, N: Name, M: TheModule);
4368
4369 assert(Func->getFunctionType() == FTy &&
4370 "Incorrect fully specified type provided for function");
4371 FunctionTypeIDs[Func] = FTyID;
4372
4373 Func->setCallingConv(CC);
4374 bool isProto = Record[2];
4375 uint64_t RawLinkage = Record[3];
4376 Func->setLinkage(getDecodedLinkage(Val: RawLinkage));
4377 Func->setAttributes(getAttributes(i: Record[4]));
4378 callValueTypeCallback(F: Func, TypeID: FTyID);
4379
4380 // Upgrade any old-style byval or sret without a type by propagating the
4381 // argument's pointee type. There should be no opaque pointers where the byval
4382 // type is implicit.
4383 for (unsigned i = 0; i != Func->arg_size(); ++i) {
4384 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4385 Attribute::InAlloca}) {
4386 if (!Func->hasParamAttribute(ArgNo: i, Kind))
4387 continue;
4388
4389 if (Func->getParamAttribute(ArgNo: i, Kind).getValueAsType())
4390 continue;
4391
4392 Func->removeParamAttr(ArgNo: i, Kind);
4393
4394 unsigned ParamTypeID = getContainedTypeID(ID: FTyID, Idx: i + 1);
4395 Type *PtrEltTy = getPtrElementTypeByID(ID: ParamTypeID);
4396 if (!PtrEltTy)
4397 return error(Message: "Missing param element type for attribute upgrade");
4398
4399 Attribute NewAttr;
4400 switch (Kind) {
4401 case Attribute::ByVal:
4402 NewAttr = Attribute::getWithByValType(Context, Ty: PtrEltTy);
4403 break;
4404 case Attribute::StructRet:
4405 NewAttr = Attribute::getWithStructRetType(Context, Ty: PtrEltTy);
4406 break;
4407 case Attribute::InAlloca:
4408 NewAttr = Attribute::getWithInAllocaType(Context, Ty: PtrEltTy);
4409 break;
4410 default:
4411 llvm_unreachable("not an upgraded type attribute");
4412 }
4413
4414 Func->addParamAttr(ArgNo: i, Attr: NewAttr);
4415 }
4416 }
4417
4418 if (Func->getCallingConv() == CallingConv::X86_INTR &&
4419 !Func->arg_empty() && !Func->hasParamAttribute(ArgNo: 0, Kind: Attribute::ByVal)) {
4420 unsigned ParamTypeID = getContainedTypeID(ID: FTyID, Idx: 1);
4421 Type *ByValTy = getPtrElementTypeByID(ID: ParamTypeID);
4422 if (!ByValTy)
4423 return error(Message: "Missing param element type for x86_intrcc upgrade");
4424 Attribute NewAttr = Attribute::getWithByValType(Context, Ty: ByValTy);
4425 Func->addParamAttr(ArgNo: 0, Attr: NewAttr);
4426 }
4427
4428 MaybeAlign Alignment;
4429 if (Error Err = parseAlignmentValue(Exponent: Record[5], Alignment))
4430 return Err;
4431 if (Alignment)
4432 Func->setAlignment(*Alignment);
4433 if (Record[6]) {
4434 if (Record[6] - 1 >= SectionTable.size())
4435 return error(Message: "Invalid ID");
4436 Func->setSection(SectionTable[Record[6] - 1]);
4437 }
4438 // Local linkage must have default visibility.
4439 // auto-upgrade `hidden` and `protected` for old bitcode.
4440 if (!Func->hasLocalLinkage())
4441 Func->setVisibility(getDecodedVisibility(Val: Record[7]));
4442 if (Record.size() > 8 && Record[8]) {
4443 if (Record[8] - 1 >= GCTable.size())
4444 return error(Message: "Invalid ID");
4445 Func->setGC(GCTable[Record[8] - 1]);
4446 }
4447 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4448 if (Record.size() > 9)
4449 UnnamedAddr = getDecodedUnnamedAddrType(Val: Record[9]);
4450 Func->setUnnamedAddr(UnnamedAddr);
4451
4452 FunctionOperandInfo OperandInfo = {.F: Func, .PersonalityFn: 0, .Prefix: 0, .Prologue: 0};
4453 if (Record.size() > 10)
4454 OperandInfo.Prologue = Record[10];
4455
4456 if (Record.size() > 11) {
4457 // A GlobalValue with local linkage cannot have a DLL storage class.
4458 if (!Func->hasLocalLinkage()) {
4459 Func->setDLLStorageClass(getDecodedDLLStorageClass(Val: Record[11]));
4460 }
4461 } else {
4462 upgradeDLLImportExportLinkage(GV: Func, Val: RawLinkage);
4463 }
4464
4465 if (Record.size() > 12) {
4466 if (unsigned ComdatID = Record[12]) {
4467 if (ComdatID > ComdatList.size())
4468 return error(Message: "Invalid function comdat ID");
4469 Func->setComdat(ComdatList[ComdatID - 1]);
4470 }
4471 } else if (hasImplicitComdat(Val: RawLinkage)) {
4472 ImplicitComdatObjects.insert(V: Func);
4473 }
4474
4475 if (Record.size() > 13)
4476 OperandInfo.Prefix = Record[13];
4477
4478 if (Record.size() > 14)
4479 OperandInfo.PersonalityFn = Record[14];
4480
4481 if (Record.size() > 15) {
4482 Func->setDSOLocal(getDecodedDSOLocal(Val: Record[15]));
4483 }
4484 inferDSOLocal(GV: Func);
4485
4486 // Record[16] is the address space number.
4487
4488 // Check whether we have enough values to read a partition name. Also make
4489 // sure Strtab has enough values.
4490 if (Record.size() > 18 && Strtab.data() &&
4491 Record[17] + Record[18] <= Strtab.size()) {
4492 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4493 }
4494
4495 if (Record.size() > 19) {
4496 MaybeAlign PrefAlignment;
4497 if (Error Err = parseAlignmentValue(Exponent: Record[19], Alignment&: PrefAlignment))
4498 return Err;
4499 Func->setPreferredAlignment(PrefAlignment);
4500 }
4501
4502 ValueList.push_back(V: Func, TypeID: getVirtualTypeID(Ty: Func->getType(), ChildTypeIDs: FTyID));
4503
4504 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4505 FunctionOperands.push_back(x: OperandInfo);
4506
4507 // If this is a function with a body, remember the prototype we are
4508 // creating now, so that we can match up the body with them later.
4509 if (!isProto) {
4510 Func->setIsMaterializable(true);
4511 FunctionsWithBodies.push_back(x: Func);
4512 DeferredFunctionInfo[Func] = 0;
4513 }
4514 return Error::success();
4515}
4516
4517Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4518 unsigned BitCode, ArrayRef<uint64_t> Record) {
4519 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4520 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4521 // dllstorageclass, threadlocal, unnamed_addr,
4522 // preemption specifier] (name in VST)
4523 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4524 // visibility, dllstorageclass, threadlocal, unnamed_addr,
4525 // preemption specifier] (name in VST)
4526 // v2: [strtab_offset, strtab_size, v1]
4527 StringRef Name;
4528 std::tie(args&: Name, args&: Record) = readNameFromStrtab(Record);
4529
4530 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4531 if (Record.size() < (3 + (unsigned)NewRecord))
4532 return error(Message: "Invalid global indirect symbol record");
4533 unsigned OpNum = 0;
4534 unsigned TypeID = Record[OpNum++];
4535 Type *Ty = getTypeByID(ID: TypeID);
4536 if (!Ty)
4537 return error(Message: "Invalid global indirect symbol record");
4538
4539 unsigned AddrSpace;
4540 if (!NewRecord) {
4541 auto *PTy = dyn_cast<PointerType>(Val: Ty);
4542 if (!PTy)
4543 return error(Message: "Invalid type for value");
4544 AddrSpace = PTy->getAddressSpace();
4545 TypeID = getContainedTypeID(ID: TypeID);
4546 Ty = getTypeByID(ID: TypeID);
4547 if (!Ty)
4548 return error(Message: "Missing element type for old-style indirect symbol");
4549 } else {
4550 AddrSpace = Record[OpNum++];
4551 }
4552
4553 auto Val = Record[OpNum++];
4554 auto Linkage = Record[OpNum++];
4555 GlobalValue *NewGA;
4556 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4557 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4558 NewGA = GlobalAlias::create(Ty, AddressSpace: AddrSpace, Linkage: getDecodedLinkage(Val: Linkage), Name,
4559 Parent: TheModule);
4560 else
4561 NewGA = GlobalIFunc::create(Ty, AddressSpace: AddrSpace, Linkage: getDecodedLinkage(Val: Linkage), Name,
4562 Resolver: nullptr, Parent: TheModule);
4563
4564 // Local linkage must have default visibility.
4565 // auto-upgrade `hidden` and `protected` for old bitcode.
4566 if (OpNum != Record.size()) {
4567 auto VisInd = OpNum++;
4568 if (!NewGA->hasLocalLinkage())
4569 NewGA->setVisibility(getDecodedVisibility(Val: Record[VisInd]));
4570 }
4571 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4572 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4573 if (OpNum != Record.size()) {
4574 auto S = Record[OpNum++];
4575 // A GlobalValue with local linkage cannot have a DLL storage class.
4576 if (!NewGA->hasLocalLinkage())
4577 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Val: S));
4578 }
4579 else
4580 upgradeDLLImportExportLinkage(GV: NewGA, Val: Linkage);
4581 if (OpNum != Record.size())
4582 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Val: Record[OpNum++]));
4583 if (OpNum != Record.size())
4584 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Val: Record[OpNum++]));
4585 }
4586 if (OpNum != Record.size())
4587 NewGA->setDSOLocal(getDecodedDSOLocal(Val: Record[OpNum++]));
4588 inferDSOLocal(GV: NewGA);
4589
4590 // Check whether we have enough values to read a partition name.
4591 if (OpNum + 1 < Record.size()) {
4592 // Check Strtab has enough values for the partition.
4593 if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4594 return error(Message: "Malformed partition, too large.");
4595 NewGA->setPartition(
4596 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4597 }
4598
4599 ValueList.push_back(V: NewGA, TypeID: getVirtualTypeID(Ty: NewGA->getType(), ChildTypeIDs: TypeID));
4600 IndirectSymbolInits.push_back(x: std::make_pair(x&: NewGA, y&: Val));
4601 return Error::success();
4602}
4603
4604Error BitcodeReader::parseModule(uint64_t ResumeBit,
4605 bool ShouldLazyLoadMetadata,
4606 ParserCallbacks Callbacks) {
4607 this->ValueTypeCallback = std::move(Callbacks.ValueType);
4608 if (ResumeBit) {
4609 if (Error JumpFailed = Stream.JumpToBit(BitNo: ResumeBit))
4610 return JumpFailed;
4611 } else if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID))
4612 return Err;
4613
4614 SmallVector<uint64_t, 64> Record;
4615
4616 // Parts of bitcode parsing depend on the datalayout. Make sure we
4617 // finalize the datalayout before we run any of that code.
4618 bool ResolvedDataLayout = false;
4619 // In order to support importing modules with illegal data layout strings,
4620 // delay parsing the data layout string until after upgrades and overrides
4621 // have been applied, allowing to fix illegal data layout strings.
4622 // Initialize to the current module's layout string in case none is specified.
4623 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4624
4625 auto ResolveDataLayout = [&]() -> Error {
4626 if (ResolvedDataLayout)
4627 return Error::success();
4628
4629 // Datalayout and triple can't be parsed after this point.
4630 ResolvedDataLayout = true;
4631
4632 // Auto-upgrade the layout string
4633 TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4634 DL: TentativeDataLayoutStr, Triple: TheModule->getTargetTriple().str());
4635
4636 // Apply override
4637 if (Callbacks.DataLayout) {
4638 if (auto LayoutOverride = (*Callbacks.DataLayout)(
4639 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4640 TentativeDataLayoutStr = *LayoutOverride;
4641 }
4642
4643 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4644 Expected<DataLayout> MaybeDL = DataLayout::parse(LayoutString: TentativeDataLayoutStr);
4645 if (!MaybeDL)
4646 return MaybeDL.takeError();
4647
4648 TheModule->setDataLayout(MaybeDL.get());
4649 return Error::success();
4650 };
4651
4652 // Read all the records for this module.
4653 while (true) {
4654 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4655 if (!MaybeEntry)
4656 return MaybeEntry.takeError();
4657 llvm::BitstreamEntry Entry = MaybeEntry.get();
4658
4659 switch (Entry.Kind) {
4660 case BitstreamEntry::Error:
4661 return error(Message: "Malformed block");
4662 case BitstreamEntry::EndBlock:
4663 if (Error Err = ResolveDataLayout())
4664 return Err;
4665 return globalCleanup();
4666
4667 case BitstreamEntry::SubBlock:
4668 switch (Entry.ID) {
4669 default: // Skip unknown content.
4670 if (Error Err = Stream.SkipBlock())
4671 return Err;
4672 break;
4673 case bitc::BLOCKINFO_BLOCK_ID:
4674 if (Error Err = readBlockInfo())
4675 return Err;
4676 break;
4677 case bitc::PARAMATTR_BLOCK_ID:
4678 if (Error Err = parseAttributeBlock())
4679 return Err;
4680 break;
4681 case bitc::PARAMATTR_GROUP_BLOCK_ID:
4682 if (Error Err = parseAttributeGroupBlock())
4683 return Err;
4684 break;
4685 case bitc::TYPE_BLOCK_ID_NEW:
4686 if (Error Err = parseTypeTable())
4687 return Err;
4688 break;
4689 case bitc::VALUE_SYMTAB_BLOCK_ID:
4690 if (!SeenValueSymbolTable) {
4691 // Either this is an old form VST without function index and an
4692 // associated VST forward declaration record (which would have caused
4693 // the VST to be jumped to and parsed before it was encountered
4694 // normally in the stream), or there were no function blocks to
4695 // trigger an earlier parsing of the VST.
4696 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4697 if (Error Err = parseValueSymbolTable())
4698 return Err;
4699 SeenValueSymbolTable = true;
4700 } else {
4701 // We must have had a VST forward declaration record, which caused
4702 // the parser to jump to and parse the VST earlier.
4703 assert(VSTOffset > 0);
4704 if (Error Err = Stream.SkipBlock())
4705 return Err;
4706 }
4707 break;
4708 case bitc::CONSTANTS_BLOCK_ID:
4709 if (Error Err = parseConstants())
4710 return Err;
4711 if (Error Err = resolveGlobalAndIndirectSymbolInits())
4712 return Err;
4713 break;
4714 case bitc::METADATA_BLOCK_ID:
4715 if (ShouldLazyLoadMetadata) {
4716 if (Error Err = rememberAndSkipMetadata())
4717 return Err;
4718 break;
4719 }
4720 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4721 if (Error Err = MDLoader->parseModuleMetadata())
4722 return Err;
4723 break;
4724 case bitc::METADATA_KIND_BLOCK_ID:
4725 if (Error Err = MDLoader->parseMetadataKinds())
4726 return Err;
4727 break;
4728 case bitc::FUNCTION_BLOCK_ID:
4729 if (Error Err = ResolveDataLayout())
4730 return Err;
4731
4732 // If this is the first function body we've seen, reverse the
4733 // FunctionsWithBodies list.
4734 if (!SeenFirstFunctionBody) {
4735 std::reverse(first: FunctionsWithBodies.begin(), last: FunctionsWithBodies.end());
4736 if (Error Err = globalCleanup())
4737 return Err;
4738 SeenFirstFunctionBody = true;
4739 }
4740
4741 if (VSTOffset > 0) {
4742 // If we have a VST forward declaration record, make sure we
4743 // parse the VST now if we haven't already. It is needed to
4744 // set up the DeferredFunctionInfo vector for lazy reading.
4745 if (!SeenValueSymbolTable) {
4746 if (Error Err = BitcodeReader::parseValueSymbolTable(Offset: VSTOffset))
4747 return Err;
4748 SeenValueSymbolTable = true;
4749 // Fall through so that we record the NextUnreadBit below.
4750 // This is necessary in case we have an anonymous function that
4751 // is later materialized. Since it will not have a VST entry we
4752 // need to fall back to the lazy parse to find its offset.
4753 } else {
4754 // If we have a VST forward declaration record, but have already
4755 // parsed the VST (just above, when the first function body was
4756 // encountered here), then we are resuming the parse after
4757 // materializing functions. The ResumeBit points to the
4758 // start of the last function block recorded in the
4759 // DeferredFunctionInfo map. Skip it.
4760 if (Error Err = Stream.SkipBlock())
4761 return Err;
4762 continue;
4763 }
4764 }
4765
4766 // Support older bitcode files that did not have the function
4767 // index in the VST, nor a VST forward declaration record, as
4768 // well as anonymous functions that do not have VST entries.
4769 // Build the DeferredFunctionInfo vector on the fly.
4770 if (Error Err = rememberAndSkipFunctionBody())
4771 return Err;
4772
4773 // Suspend parsing when we reach the function bodies. Subsequent
4774 // materialization calls will resume it when necessary. If the bitcode
4775 // file is old, the symbol table will be at the end instead and will not
4776 // have been seen yet. In this case, just finish the parse now.
4777 if (SeenValueSymbolTable) {
4778 NextUnreadBit = Stream.GetCurrentBitNo();
4779 // After the VST has been parsed, we need to make sure intrinsic name
4780 // are auto-upgraded.
4781 return globalCleanup();
4782 }
4783 break;
4784 case bitc::USELIST_BLOCK_ID:
4785 if (Error Err = parseUseLists())
4786 return Err;
4787 break;
4788 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
4789 if (Error Err = parseOperandBundleTags())
4790 return Err;
4791 break;
4792 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
4793 if (Error Err = parseSyncScopeNames())
4794 return Err;
4795 break;
4796 }
4797 continue;
4798
4799 case BitstreamEntry::Record:
4800 // The interesting case.
4801 break;
4802 }
4803
4804 // Read a record.
4805 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
4806 if (!MaybeBitCode)
4807 return MaybeBitCode.takeError();
4808 switch (unsigned BitCode = MaybeBitCode.get()) {
4809 default: break; // Default behavior, ignore unknown content.
4810 case bitc::MODULE_CODE_VERSION: {
4811 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4812 if (!VersionOrErr)
4813 return VersionOrErr.takeError();
4814 UseRelativeIDs = *VersionOrErr >= 1;
4815 break;
4816 }
4817 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4818 if (ResolvedDataLayout)
4819 return error(Message: "target triple too late in module");
4820 std::string S;
4821 if (convertToString(Record, Idx: 0, Result&: S))
4822 return error(Message: "Invalid triple record");
4823 TheModule->setTargetTriple(Triple(std::move(S)));
4824 break;
4825 }
4826 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
4827 if (ResolvedDataLayout)
4828 return error(Message: "datalayout too late in module");
4829 if (convertToString(Record, Idx: 0, Result&: TentativeDataLayoutStr))
4830 return error(Message: "Invalid data layout record");
4831 break;
4832 }
4833 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
4834 std::string S;
4835 if (convertToString(Record, Idx: 0, Result&: S))
4836 return error(Message: "Invalid asm record");
4837 TheModule->setModuleInlineAsm(S);
4838 break;
4839 }
4840 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
4841 // Deprecated, but still needed to read old bitcode files.
4842 std::string S;
4843 if (convertToString(Record, Idx: 0, Result&: S))
4844 return error(Message: "Invalid deplib record");
4845 // Ignore value.
4846 break;
4847 }
4848 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4849 std::string S;
4850 if (convertToString(Record, Idx: 0, Result&: S))
4851 return error(Message: "Invalid section name record");
4852 SectionTable.push_back(x: S);
4853 break;
4854 }
4855 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
4856 std::string S;
4857 if (convertToString(Record, Idx: 0, Result&: S))
4858 return error(Message: "Invalid gcname record");
4859 GCTable.push_back(x: S);
4860 break;
4861 }
4862 case bitc::MODULE_CODE_COMDAT:
4863 if (Error Err = parseComdatRecord(Record))
4864 return Err;
4865 break;
4866 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4867 // written by ThinLinkBitcodeWriter. See
4868 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4869 // record
4870 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4871 case bitc::MODULE_CODE_GLOBALVAR:
4872 if (Error Err = parseGlobalVarRecord(Record))
4873 return Err;
4874 break;
4875 case bitc::MODULE_CODE_FUNCTION:
4876 if (Error Err = ResolveDataLayout())
4877 return Err;
4878 if (Error Err = parseFunctionRecord(Record))
4879 return Err;
4880 break;
4881 case bitc::MODULE_CODE_IFUNC:
4882 case bitc::MODULE_CODE_ALIAS:
4883 case bitc::MODULE_CODE_ALIAS_OLD:
4884 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4885 return Err;
4886 break;
4887 /// MODULE_CODE_VSTOFFSET: [offset]
4888 case bitc::MODULE_CODE_VSTOFFSET:
4889 if (Record.empty())
4890 return error(Message: "Invalid vstoffset record");
4891 // Note that we subtract 1 here because the offset is relative to one word
4892 // before the start of the identification or module block, which was
4893 // historically always the start of the regular bitcode header.
4894 VSTOffset = Record[0] - 1;
4895 break;
4896 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4897 case bitc::MODULE_CODE_SOURCE_FILENAME:
4898 SmallString<128> ValueName;
4899 if (convertToString(Record, Idx: 0, Result&: ValueName))
4900 return error(Message: "Invalid source filename record");
4901 TheModule->setSourceFileName(ValueName);
4902 break;
4903 }
4904 Record.clear();
4905 }
4906 this->ValueTypeCallback = std::nullopt;
4907 return Error::success();
4908}
4909
4910Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4911 bool IsImporting,
4912 ParserCallbacks Callbacks) {
4913 TheModule = M;
4914 MetadataLoaderCallbacks MDCallbacks;
4915 MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4916 MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4917 return getContainedTypeID(ID: I, Idx: J);
4918 };
4919 MDCallbacks.MDType = Callbacks.MDType;
4920 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4921 return parseModule(ResumeBit: 0, ShouldLazyLoadMetadata, Callbacks);
4922}
4923
4924Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4925 if (!isa<PointerType>(Val: PtrType))
4926 return error(Message: "Load/Store operand is not a pointer type");
4927 if (!PointerType::isLoadableOrStorableType(ElemTy: ValType))
4928 return error(Message: "Cannot load/store from pointer");
4929 return Error::success();
4930}
4931
4932Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4933 ArrayRef<unsigned> ArgTyIDs) {
4934 AttributeList Attrs = CB->getAttributes();
4935 for (unsigned i = 0; i != CB->arg_size(); ++i) {
4936 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4937 Attribute::InAlloca}) {
4938 if (!Attrs.hasParamAttr(ArgNo: i, Kind) ||
4939 Attrs.getParamAttr(ArgNo: i, Kind).getValueAsType())
4940 continue;
4941
4942 Type *PtrEltTy = getPtrElementTypeByID(ID: ArgTyIDs[i]);
4943 if (!PtrEltTy)
4944 return error(Message: "Missing element type for typed attribute upgrade");
4945
4946 Attribute NewAttr;
4947 switch (Kind) {
4948 case Attribute::ByVal:
4949 NewAttr = Attribute::getWithByValType(Context, Ty: PtrEltTy);
4950 break;
4951 case Attribute::StructRet:
4952 NewAttr = Attribute::getWithStructRetType(Context, Ty: PtrEltTy);
4953 break;
4954 case Attribute::InAlloca:
4955 NewAttr = Attribute::getWithInAllocaType(Context, Ty: PtrEltTy);
4956 break;
4957 default:
4958 llvm_unreachable("not an upgraded type attribute");
4959 }
4960
4961 Attrs = Attrs.addParamAttribute(C&: Context, ArgNos: i, A: NewAttr);
4962 }
4963 }
4964
4965 if (CB->isInlineAsm()) {
4966 const InlineAsm *IA = cast<InlineAsm>(Val: CB->getCalledOperand());
4967 unsigned ArgNo = 0;
4968 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4969 if (!CI.hasArg())
4970 continue;
4971
4972 if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4973 Type *ElemTy = getPtrElementTypeByID(ID: ArgTyIDs[ArgNo]);
4974 if (!ElemTy)
4975 return error(Message: "Missing element type for inline asm upgrade");
4976 Attrs = Attrs.addParamAttribute(
4977 C&: Context, ArgNos: ArgNo,
4978 A: Attribute::get(Context, Kind: Attribute::ElementType, Ty: ElemTy));
4979 }
4980
4981 ArgNo++;
4982 }
4983 }
4984
4985 switch (CB->getIntrinsicID()) {
4986 case Intrinsic::preserve_array_access_index:
4987 case Intrinsic::preserve_struct_access_index:
4988 case Intrinsic::aarch64_ldaxr:
4989 case Intrinsic::aarch64_ldxr:
4990 case Intrinsic::aarch64_stlxr:
4991 case Intrinsic::aarch64_stxr:
4992 case Intrinsic::arm_ldaex:
4993 case Intrinsic::arm_ldrex:
4994 case Intrinsic::arm_stlex:
4995 case Intrinsic::arm_strex: {
4996 unsigned ArgNo;
4997 switch (CB->getIntrinsicID()) {
4998 case Intrinsic::aarch64_stlxr:
4999 case Intrinsic::aarch64_stxr:
5000 case Intrinsic::arm_stlex:
5001 case Intrinsic::arm_strex:
5002 ArgNo = 1;
5003 break;
5004 default:
5005 ArgNo = 0;
5006 break;
5007 }
5008 if (!Attrs.getParamElementType(ArgNo)) {
5009 Type *ElTy = getPtrElementTypeByID(ID: ArgTyIDs[ArgNo]);
5010 if (!ElTy)
5011 return error(Message: "Missing element type for elementtype upgrade");
5012 Attribute NewAttr = Attribute::get(Context, Kind: Attribute::ElementType, Ty: ElTy);
5013 Attrs = Attrs.addParamAttribute(C&: Context, ArgNos: ArgNo, A: NewAttr);
5014 }
5015 break;
5016 }
5017 default:
5018 break;
5019 }
5020
5021 CB->setAttributes(Attrs);
5022 return Error::success();
5023}
5024
5025/// Lazily parse the specified function body block.
5026Error BitcodeReader::parseFunctionBody(Function *F) {
5027 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::FUNCTION_BLOCK_ID))
5028 return Err;
5029
5030 // Unexpected unresolved metadata when parsing function.
5031 if (MDLoader->hasFwdRefs())
5032 return error(Message: "Invalid function metadata: incoming forward references");
5033
5034 InstructionList.clear();
5035 unsigned ModuleValueListSize = ValueList.size();
5036 unsigned ModuleMDLoaderSize = MDLoader->size();
5037
5038 // Add all the function arguments to the value table.
5039 unsigned ArgNo = 0;
5040 unsigned FTyID = FunctionTypeIDs[F];
5041 for (Argument &I : F->args()) {
5042 unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: ArgNo + 1);
5043 assert(I.getType() == getTypeByID(ArgTyID) &&
5044 "Incorrect fully specified type for Function Argument");
5045 ValueList.push_back(V: &I, TypeID: ArgTyID);
5046 ++ArgNo;
5047 }
5048 unsigned NextValueNo = ValueList.size();
5049 BasicBlock *CurBB = nullptr;
5050 unsigned CurBBNo = 0;
5051 // Block into which constant expressions from phi nodes are materialized.
5052 BasicBlock *PhiConstExprBB = nullptr;
5053 // Edge blocks for phi nodes into which constant expressions have been
5054 // expanded.
5055 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
5056 ConstExprEdgeBBs;
5057
5058 DebugLoc LastLoc;
5059 auto getLastInstruction = [&]() -> Instruction * {
5060 if (CurBB && !CurBB->empty())
5061 return &CurBB->back();
5062 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5063 !FunctionBBs[CurBBNo - 1]->empty())
5064 return &FunctionBBs[CurBBNo - 1]->back();
5065 return nullptr;
5066 };
5067
5068 std::vector<OperandBundleDef> OperandBundles;
5069
5070 // Read all the records.
5071 SmallVector<uint64_t, 64> Record;
5072
5073 while (true) {
5074 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5075 if (!MaybeEntry)
5076 return MaybeEntry.takeError();
5077 llvm::BitstreamEntry Entry = MaybeEntry.get();
5078
5079 switch (Entry.Kind) {
5080 case BitstreamEntry::Error:
5081 return error(Message: "Malformed block");
5082 case BitstreamEntry::EndBlock:
5083 goto OutOfRecordLoop;
5084
5085 case BitstreamEntry::SubBlock:
5086 switch (Entry.ID) {
5087 default: // Skip unknown content.
5088 if (Error Err = Stream.SkipBlock())
5089 return Err;
5090 break;
5091 case bitc::CONSTANTS_BLOCK_ID:
5092 if (Error Err = parseConstants())
5093 return Err;
5094 NextValueNo = ValueList.size();
5095 break;
5096 case bitc::VALUE_SYMTAB_BLOCK_ID:
5097 if (Error Err = parseValueSymbolTable())
5098 return Err;
5099 break;
5100 case bitc::METADATA_ATTACHMENT_ID:
5101 if (Error Err = MDLoader->parseMetadataAttachment(F&: *F, InstructionList))
5102 return Err;
5103 break;
5104 case bitc::METADATA_BLOCK_ID:
5105 assert(DeferredMetadataInfo.empty() &&
5106 "Must read all module-level metadata before function-level");
5107 if (Error Err = MDLoader->parseFunctionMetadata())
5108 return Err;
5109 break;
5110 case bitc::USELIST_BLOCK_ID:
5111 if (Error Err = parseUseLists())
5112 return Err;
5113 break;
5114 }
5115 continue;
5116
5117 case BitstreamEntry::Record:
5118 // The interesting case.
5119 break;
5120 }
5121
5122 // Read a record.
5123 Record.clear();
5124 Instruction *I = nullptr;
5125 unsigned ResTypeID = InvalidTypeID;
5126 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
5127 if (!MaybeBitCode)
5128 return MaybeBitCode.takeError();
5129 switch (unsigned BitCode = MaybeBitCode.get()) {
5130 default: // Default behavior: reject
5131 return error(Message: "Invalid value");
5132 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
5133 if (Record.empty() || Record[0] == 0)
5134 return error(Message: "Invalid declareblocks record");
5135 // Create all the basic blocks for the function.
5136 FunctionBBs.resize(new_size: Record[0]);
5137
5138 // See if anything took the address of blocks in this function.
5139 auto BBFRI = BasicBlockFwdRefs.find(Val: F);
5140 if (BBFRI == BasicBlockFwdRefs.end()) {
5141 for (BasicBlock *&BB : FunctionBBs)
5142 BB = BasicBlock::Create(Context, Name: "", Parent: F);
5143 } else {
5144 auto &BBRefs = BBFRI->second;
5145 // Check for invalid basic block references.
5146 if (BBRefs.size() > FunctionBBs.size())
5147 return error(Message: "Invalid ID");
5148 assert(!BBRefs.empty() && "Unexpected empty array");
5149 assert(!BBRefs.front() && "Invalid reference to entry block");
5150 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
5151 ++I)
5152 if (I < RE && BBRefs[I]) {
5153 BBRefs[I]->insertInto(Parent: F);
5154 FunctionBBs[I] = BBRefs[I];
5155 } else {
5156 FunctionBBs[I] = BasicBlock::Create(Context, Name: "", Parent: F);
5157 }
5158
5159 // Erase from the table.
5160 BasicBlockFwdRefs.erase(I: BBFRI);
5161 }
5162
5163 CurBB = FunctionBBs[0];
5164 continue;
5165 }
5166
5167 case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
5168 // The record should not be emitted if it's an empty list.
5169 if (Record.empty())
5170 return error(Message: "Invalid blockaddr users record");
5171 // When we have the RARE case of a BlockAddress Constant that is not
5172 // scoped to the Function it refers to, we need to conservatively
5173 // materialize the referred to Function, regardless of whether or not
5174 // that Function will ultimately be linked, otherwise users of
5175 // BitcodeReader might start splicing out Function bodies such that we
5176 // might no longer be able to materialize the BlockAddress since the
5177 // BasicBlock (and entire body of the Function) the BlockAddress refers
5178 // to may have been moved. In the case that the user of BitcodeReader
5179 // decides ultimately not to link the Function body, materializing here
5180 // could be considered wasteful, but it's better than a deserialization
5181 // failure as described. This keeps BitcodeReader unaware of complex
5182 // linkage policy decisions such as those use by LTO, leaving those
5183 // decisions "one layer up."
5184 for (uint64_t ValID : Record)
5185 if (auto *F = dyn_cast<Function>(Val: ValueList[ValID]))
5186 BackwardRefFunctions.push_back(x: F);
5187 else
5188 return error(Message: "Invalid blockaddr users record");
5189
5190 continue;
5191
5192 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
5193 // This record indicates that the last instruction is at the same
5194 // location as the previous instruction with a location.
5195 I = getLastInstruction();
5196
5197 if (!I)
5198 return error(Message: "Invalid debug_loc_again record");
5199 I->setDebugLoc(LastLoc);
5200 I = nullptr;
5201 continue;
5202
5203 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
5204 I = getLastInstruction();
5205 if (!I || Record.size() < 4)
5206 return error(Message: "Invalid debug loc record");
5207
5208 unsigned Line = Record[0], Col = Record[1];
5209 unsigned ScopeID = Record[2], IAID = Record[3];
5210 bool isImplicitCode = Record.size() >= 5 && Record[4];
5211 uint64_t AtomGroup = Record.size() == 7 ? Record[5] : 0;
5212 uint8_t AtomRank = Record.size() == 7 ? Record[6] : 0;
5213
5214 MDNode *Scope = nullptr, *IA = nullptr;
5215 if (ScopeID) {
5216 Scope = dyn_cast_or_null<MDNode>(
5217 Val: MDLoader->getMetadataFwdRefOrLoad(Idx: ScopeID - 1));
5218 if (!Scope)
5219 return error(Message: "Invalid debug loc record");
5220 }
5221 if (IAID) {
5222 IA = dyn_cast_or_null<MDNode>(
5223 Val: MDLoader->getMetadataFwdRefOrLoad(Idx: IAID - 1));
5224 if (!IA)
5225 return error(Message: "Invalid debug loc record");
5226 }
5227
5228 LastLoc = DILocation::get(Context&: Scope->getContext(), Line, Column: Col, Scope, InlinedAt: IA,
5229 ImplicitCode: isImplicitCode, AtomGroup, AtomRank);
5230 I->setDebugLoc(LastLoc);
5231 I = nullptr;
5232 continue;
5233 }
5234 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
5235 unsigned OpNum = 0;
5236 Value *LHS;
5237 unsigned TypeID;
5238 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: LHS, TypeID, ConstExprInsertBB: CurBB) ||
5239 OpNum+1 > Record.size())
5240 return error(Message: "Invalid unary operator record");
5241
5242 int Opc = getDecodedUnaryOpcode(Val: Record[OpNum++], Ty: LHS->getType());
5243 if (Opc == -1)
5244 return error(Message: "Invalid unary operator record");
5245 I = UnaryOperator::Create(Op: (Instruction::UnaryOps)Opc, S: LHS);
5246 ResTypeID = TypeID;
5247 InstructionList.push_back(Elt: I);
5248 if (OpNum < Record.size()) {
5249 if (isa<FPMathOperator>(Val: I)) {
5250 FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]);
5251 if (FMF.any())
5252 I->setFastMathFlags(FMF);
5253 }
5254 }
5255 break;
5256 }
5257 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
5258 unsigned OpNum = 0;
5259 Value *LHS, *RHS;
5260 unsigned TypeID;
5261 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: LHS, TypeID, ConstExprInsertBB: CurBB) ||
5262 popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: LHS->getType(), TyID: TypeID, ResVal&: RHS,
5263 ConstExprInsertBB: CurBB) ||
5264 OpNum+1 > Record.size())
5265 return error(Message: "Invalid binary operator record");
5266
5267 int Opc = getDecodedBinaryOpcode(Val: Record[OpNum++], Ty: LHS->getType());
5268 if (Opc == -1)
5269 return error(Message: "Invalid binary operator record");
5270 I = BinaryOperator::Create(Op: (Instruction::BinaryOps)Opc, S1: LHS, S2: RHS);
5271 ResTypeID = TypeID;
5272 InstructionList.push_back(Elt: I);
5273 if (OpNum < Record.size()) {
5274 if (Opc == Instruction::Add ||
5275 Opc == Instruction::Sub ||
5276 Opc == Instruction::Mul ||
5277 Opc == Instruction::Shl) {
5278 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
5279 cast<BinaryOperator>(Val: I)->setHasNoSignedWrap(true);
5280 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
5281 cast<BinaryOperator>(Val: I)->setHasNoUnsignedWrap(true);
5282 } else if (Opc == Instruction::SDiv ||
5283 Opc == Instruction::UDiv ||
5284 Opc == Instruction::LShr ||
5285 Opc == Instruction::AShr) {
5286 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
5287 cast<BinaryOperator>(Val: I)->setIsExact(true);
5288 } else if (Opc == Instruction::Or) {
5289 if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
5290 cast<PossiblyDisjointInst>(Val: I)->setIsDisjoint(true);
5291 } else if (isa<FPMathOperator>(Val: I)) {
5292 FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]);
5293 if (FMF.any())
5294 I->setFastMathFlags(FMF);
5295 }
5296 }
5297 break;
5298 }
5299 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
5300 unsigned OpNum = 0;
5301 Value *Op;
5302 unsigned OpTypeID;
5303 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB) ||
5304 OpNum + 1 > Record.size())
5305 return error(Message: "Invalid cast record");
5306
5307 ResTypeID = Record[OpNum++];
5308 Type *ResTy = getTypeByID(ID: ResTypeID);
5309 int Opc = getDecodedCastOpcode(Val: Record[OpNum++]);
5310
5311 if (Opc == -1 || !ResTy)
5312 return error(Message: "Invalid cast record");
5313 Instruction *Temp = nullptr;
5314 if ((I = UpgradeBitCastInst(Opc, V: Op, DestTy: ResTy, Temp))) {
5315 if (Temp) {
5316 InstructionList.push_back(Elt: Temp);
5317 assert(CurBB && "No current BB?");
5318 Temp->insertInto(ParentBB: CurBB, It: CurBB->end());
5319 }
5320 } else {
5321 auto CastOp = (Instruction::CastOps)Opc;
5322 if (!CastInst::castIsValid(op: CastOp, S: Op, DstTy: ResTy))
5323 return error(Message: "Invalid cast");
5324 I = CastInst::Create(CastOp, S: Op, Ty: ResTy);
5325 }
5326
5327 if (OpNum < Record.size()) {
5328 if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) {
5329 if (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))
5330 cast<PossiblyNonNegInst>(Val: I)->setNonNeg(true);
5331 } else if (Opc == Instruction::Trunc) {
5332 if (Record[OpNum] & (1 << bitc::TIO_NO_UNSIGNED_WRAP))
5333 cast<TruncInst>(Val: I)->setHasNoUnsignedWrap(true);
5334 if (Record[OpNum] & (1 << bitc::TIO_NO_SIGNED_WRAP))
5335 cast<TruncInst>(Val: I)->setHasNoSignedWrap(true);
5336 }
5337 if (isa<FPMathOperator>(Val: I)) {
5338 FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]);
5339 if (FMF.any())
5340 I->setFastMathFlags(FMF);
5341 }
5342 }
5343
5344 InstructionList.push_back(Elt: I);
5345 break;
5346 }
5347 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
5348 case bitc::FUNC_CODE_INST_GEP_OLD:
5349 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
5350 unsigned OpNum = 0;
5351
5352 unsigned TyID;
5353 Type *Ty;
5354 GEPNoWrapFlags NW;
5355
5356 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5357 NW = toGEPNoWrapFlags(Flags: Record[OpNum++]);
5358 TyID = Record[OpNum++];
5359 Ty = getTypeByID(ID: TyID);
5360 } else {
5361 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD)
5362 NW = GEPNoWrapFlags::inBounds();
5363 TyID = InvalidTypeID;
5364 Ty = nullptr;
5365 }
5366
5367 Value *BasePtr;
5368 unsigned BasePtrTypeID;
5369 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: BasePtr, TypeID&: BasePtrTypeID,
5370 ConstExprInsertBB: CurBB))
5371 return error(Message: "Invalid gep record");
5372
5373 if (!Ty) {
5374 TyID = getContainedTypeID(ID: BasePtrTypeID);
5375 if (BasePtr->getType()->isVectorTy())
5376 TyID = getContainedTypeID(ID: TyID);
5377 Ty = getTypeByID(ID: TyID);
5378 }
5379
5380 SmallVector<Value*, 16> GEPIdx;
5381 while (OpNum != Record.size()) {
5382 Value *Op;
5383 unsigned OpTypeID;
5384 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB))
5385 return error(Message: "Invalid gep record");
5386 GEPIdx.push_back(Elt: Op);
5387 }
5388
5389 auto *GEP = GetElementPtrInst::Create(PointeeType: Ty, Ptr: BasePtr, IdxList: GEPIdx);
5390 I = GEP;
5391
5392 ResTypeID = TyID;
5393 if (cast<GEPOperator>(Val: I)->getNumIndices() != 0) {
5394 auto GTI = std::next(x: gep_type_begin(GEP: I));
5395 for (Value *Idx : drop_begin(RangeOrContainer: cast<GEPOperator>(Val: I)->indices())) {
5396 unsigned SubType = 0;
5397 if (GTI.isStruct()) {
5398 ConstantInt *IdxC =
5399 Idx->getType()->isVectorTy()
5400 ? cast<ConstantInt>(Val: cast<Constant>(Val: Idx)->getSplatValue())
5401 : cast<ConstantInt>(Val: Idx);
5402 SubType = IdxC->getZExtValue();
5403 }
5404 ResTypeID = getContainedTypeID(ID: ResTypeID, Idx: SubType);
5405 ++GTI;
5406 }
5407 }
5408
5409 // At this point ResTypeID is the result element type. We need a pointer
5410 // or vector of pointer to it.
5411 ResTypeID = getVirtualTypeID(Ty: I->getType()->getScalarType(), ChildTypeIDs: ResTypeID);
5412 if (I->getType()->isVectorTy())
5413 ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: ResTypeID);
5414
5415 InstructionList.push_back(Elt: I);
5416 GEP->setNoWrapFlags(NW);
5417 break;
5418 }
5419
5420 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
5421 // EXTRACTVAL: [opty, opval, n x indices]
5422 unsigned OpNum = 0;
5423 Value *Agg;
5424 unsigned AggTypeID;
5425 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Agg, TypeID&: AggTypeID, ConstExprInsertBB: CurBB))
5426 return error(Message: "Invalid extractvalue record");
5427 Type *Ty = Agg->getType();
5428
5429 unsigned RecSize = Record.size();
5430 if (OpNum == RecSize)
5431 return error(Message: "EXTRACTVAL: Invalid instruction with 0 indices");
5432
5433 SmallVector<unsigned, 4> EXTRACTVALIdx;
5434 ResTypeID = AggTypeID;
5435 for (; OpNum != RecSize; ++OpNum) {
5436 bool IsArray = Ty->isArrayTy();
5437 bool IsStruct = Ty->isStructTy();
5438 uint64_t Index = Record[OpNum];
5439
5440 if (!IsStruct && !IsArray)
5441 return error(Message: "EXTRACTVAL: Invalid type");
5442 if ((unsigned)Index != Index)
5443 return error(Message: "Invalid value");
5444 if (IsStruct && Index >= Ty->getStructNumElements())
5445 return error(Message: "EXTRACTVAL: Invalid struct index");
5446 if (IsArray && Index >= Ty->getArrayNumElements())
5447 return error(Message: "EXTRACTVAL: Invalid array index");
5448 EXTRACTVALIdx.push_back(Elt: (unsigned)Index);
5449
5450 if (IsStruct) {
5451 Ty = Ty->getStructElementType(N: Index);
5452 ResTypeID = getContainedTypeID(ID: ResTypeID, Idx: Index);
5453 } else {
5454 Ty = Ty->getArrayElementType();
5455 ResTypeID = getContainedTypeID(ID: ResTypeID);
5456 }
5457 }
5458
5459 I = ExtractValueInst::Create(Agg, Idxs: EXTRACTVALIdx);
5460 InstructionList.push_back(Elt: I);
5461 break;
5462 }
5463
5464 case bitc::FUNC_CODE_INST_INSERTVAL: {
5465 // INSERTVAL: [opty, opval, opty, opval, n x indices]
5466 unsigned OpNum = 0;
5467 Value *Agg;
5468 unsigned AggTypeID;
5469 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Agg, TypeID&: AggTypeID, ConstExprInsertBB: CurBB))
5470 return error(Message: "Invalid insertvalue record");
5471 Value *Val;
5472 unsigned ValTypeID;
5473 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB))
5474 return error(Message: "Invalid insertvalue record");
5475
5476 unsigned RecSize = Record.size();
5477 if (OpNum == RecSize)
5478 return error(Message: "INSERTVAL: Invalid instruction with 0 indices");
5479
5480 SmallVector<unsigned, 4> INSERTVALIdx;
5481 Type *CurTy = Agg->getType();
5482 for (; OpNum != RecSize; ++OpNum) {
5483 bool IsArray = CurTy->isArrayTy();
5484 bool IsStruct = CurTy->isStructTy();
5485 uint64_t Index = Record[OpNum];
5486
5487 if (!IsStruct && !IsArray)
5488 return error(Message: "INSERTVAL: Invalid type");
5489 if ((unsigned)Index != Index)
5490 return error(Message: "Invalid value");
5491 if (IsStruct && Index >= CurTy->getStructNumElements())
5492 return error(Message: "INSERTVAL: Invalid struct index");
5493 if (IsArray && Index >= CurTy->getArrayNumElements())
5494 return error(Message: "INSERTVAL: Invalid array index");
5495
5496 INSERTVALIdx.push_back(Elt: (unsigned)Index);
5497 if (IsStruct)
5498 CurTy = CurTy->getStructElementType(N: Index);
5499 else
5500 CurTy = CurTy->getArrayElementType();
5501 }
5502
5503 if (CurTy != Val->getType())
5504 return error(Message: "Inserted value type doesn't match aggregate type");
5505
5506 I = InsertValueInst::Create(Agg, Val, Idxs: INSERTVALIdx);
5507 ResTypeID = AggTypeID;
5508 InstructionList.push_back(Elt: I);
5509 break;
5510 }
5511
5512 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5513 // obsolete form of select
5514 // handles select i1 ... in old bitcode
5515 unsigned OpNum = 0;
5516 Value *TrueVal, *FalseVal, *Cond;
5517 unsigned TypeID;
5518 Type *CondType = Type::getInt1Ty(C&: Context);
5519 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: TrueVal, TypeID,
5520 ConstExprInsertBB: CurBB) ||
5521 popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: TrueVal->getType(), TyID: TypeID,
5522 ResVal&: FalseVal, ConstExprInsertBB: CurBB) ||
5523 popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: CondType,
5524 TyID: getVirtualTypeID(Ty: CondType), ResVal&: Cond, ConstExprInsertBB: CurBB))
5525 return error(Message: "Invalid select record");
5526
5527 I = SelectInst::Create(C: Cond, S1: TrueVal, S2: FalseVal);
5528 ResTypeID = TypeID;
5529 InstructionList.push_back(Elt: I);
5530 break;
5531 }
5532
5533 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5534 // new form of select
5535 // handles select i1 or select [N x i1]
5536 unsigned OpNum = 0;
5537 Value *TrueVal, *FalseVal, *Cond;
5538 unsigned ValTypeID, CondTypeID;
5539 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: TrueVal, TypeID&: ValTypeID,
5540 ConstExprInsertBB: CurBB) ||
5541 popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: TrueVal->getType(), TyID: ValTypeID,
5542 ResVal&: FalseVal, ConstExprInsertBB: CurBB) ||
5543 getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Cond, TypeID&: CondTypeID, ConstExprInsertBB: CurBB))
5544 return error(Message: "Invalid vector select record");
5545
5546 // select condition can be either i1 or [N x i1]
5547 if (VectorType* vector_type =
5548 dyn_cast<VectorType>(Val: Cond->getType())) {
5549 // expect <n x i1>
5550 if (vector_type->getElementType() != Type::getInt1Ty(C&: Context))
5551 return error(Message: "Invalid type for value");
5552 } else {
5553 // expect i1
5554 if (Cond->getType() != Type::getInt1Ty(C&: Context))
5555 return error(Message: "Invalid type for value");
5556 }
5557
5558 I = SelectInst::Create(C: Cond, S1: TrueVal, S2: FalseVal);
5559 ResTypeID = ValTypeID;
5560 InstructionList.push_back(Elt: I);
5561 if (OpNum < Record.size() && isa<FPMathOperator>(Val: I)) {
5562 FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[OpNum]);
5563 if (FMF.any())
5564 I->setFastMathFlags(FMF);
5565 }
5566 break;
5567 }
5568
5569 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5570 unsigned OpNum = 0;
5571 Value *Vec, *Idx;
5572 unsigned VecTypeID, IdxTypeID;
5573 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Vec, TypeID&: VecTypeID, ConstExprInsertBB: CurBB) ||
5574 getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Idx, TypeID&: IdxTypeID, ConstExprInsertBB: CurBB))
5575 return error(Message: "Invalid extractelement record");
5576 if (!Vec->getType()->isVectorTy())
5577 return error(Message: "Invalid type for value");
5578 I = ExtractElementInst::Create(Vec, Idx);
5579 ResTypeID = getContainedTypeID(ID: VecTypeID);
5580 InstructionList.push_back(Elt: I);
5581 break;
5582 }
5583
5584 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5585 unsigned OpNum = 0;
5586 Value *Vec, *Elt, *Idx;
5587 unsigned VecTypeID, IdxTypeID;
5588 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Vec, TypeID&: VecTypeID, ConstExprInsertBB: CurBB))
5589 return error(Message: "Invalid insertelement record");
5590 if (!Vec->getType()->isVectorTy())
5591 return error(Message: "Invalid type for value");
5592 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo,
5593 Ty: cast<VectorType>(Val: Vec->getType())->getElementType(),
5594 TyID: getContainedTypeID(ID: VecTypeID), ResVal&: Elt, ConstExprInsertBB: CurBB) ||
5595 getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Idx, TypeID&: IdxTypeID, ConstExprInsertBB: CurBB))
5596 return error(Message: "Invalid insert element record");
5597 I = InsertElementInst::Create(Vec, NewElt: Elt, Idx);
5598 ResTypeID = VecTypeID;
5599 InstructionList.push_back(Elt: I);
5600 break;
5601 }
5602
5603 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5604 unsigned OpNum = 0;
5605 Value *Vec1, *Vec2, *Mask;
5606 unsigned Vec1TypeID;
5607 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Vec1, TypeID&: Vec1TypeID,
5608 ConstExprInsertBB: CurBB) ||
5609 popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: Vec1->getType(), TyID: Vec1TypeID,
5610 ResVal&: Vec2, ConstExprInsertBB: CurBB))
5611 return error(Message: "Invalid shufflevector record");
5612
5613 unsigned MaskTypeID;
5614 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Mask, TypeID&: MaskTypeID, ConstExprInsertBB: CurBB))
5615 return error(Message: "Invalid shufflevector record");
5616 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5617 return error(Message: "Invalid type for value");
5618
5619 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5620 ResTypeID =
5621 getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: getContainedTypeID(ID: Vec1TypeID));
5622 InstructionList.push_back(Elt: I);
5623 break;
5624 }
5625
5626 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
5627 // Old form of ICmp/FCmp returning bool
5628 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5629 // both legal on vectors but had different behaviour.
5630 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5631 // FCmp/ICmp returning bool or vector of bool
5632
5633 unsigned OpNum = 0;
5634 Value *LHS, *RHS;
5635 unsigned LHSTypeID;
5636 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: LHS, TypeID&: LHSTypeID, ConstExprInsertBB: CurBB) ||
5637 popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: LHS->getType(), TyID: LHSTypeID, ResVal&: RHS,
5638 ConstExprInsertBB: CurBB))
5639 return error(Message: "Invalid comparison record");
5640
5641 if (OpNum >= Record.size())
5642 return error(
5643 Message: "Invalid record: operand number exceeded available operands");
5644
5645 CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5646 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5647 FastMathFlags FMF;
5648 if (IsFP && Record.size() > OpNum+1)
5649 FMF = getDecodedFastMathFlags(Val: Record[++OpNum]);
5650
5651 if (IsFP) {
5652 if (!CmpInst::isFPPredicate(P: PredVal))
5653 return error(Message: "Invalid fcmp predicate");
5654 I = new FCmpInst(PredVal, LHS, RHS);
5655 } else {
5656 if (!CmpInst::isIntPredicate(P: PredVal))
5657 return error(Message: "Invalid icmp predicate");
5658 I = new ICmpInst(PredVal, LHS, RHS);
5659 if (Record.size() > OpNum + 1 &&
5660 (Record[++OpNum] & (1 << bitc::ICMP_SAME_SIGN)))
5661 cast<ICmpInst>(Val: I)->setSameSign();
5662 }
5663
5664 if (OpNum + 1 != Record.size())
5665 return error(Message: "Invalid comparison record");
5666
5667 ResTypeID = getVirtualTypeID(Ty: I->getType()->getScalarType());
5668 if (LHS->getType()->isVectorTy())
5669 ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: ResTypeID);
5670
5671 if (FMF.any())
5672 I->setFastMathFlags(FMF);
5673 InstructionList.push_back(Elt: I);
5674 break;
5675 }
5676
5677 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5678 {
5679 unsigned Size = Record.size();
5680 if (Size == 0) {
5681 I = ReturnInst::Create(C&: Context);
5682 InstructionList.push_back(Elt: I);
5683 break;
5684 }
5685
5686 unsigned OpNum = 0;
5687 Value *Op = nullptr;
5688 unsigned OpTypeID;
5689 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB))
5690 return error(Message: "Invalid ret record");
5691 if (OpNum != Record.size())
5692 return error(Message: "Invalid ret record");
5693
5694 I = ReturnInst::Create(C&: Context, retVal: Op);
5695 InstructionList.push_back(Elt: I);
5696 break;
5697 }
5698 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5699 if (Record.size() != 1 && Record.size() != 3)
5700 return error(Message: "Invalid br record");
5701 BasicBlock *TrueDest = getBasicBlock(ID: Record[0]);
5702 if (!TrueDest)
5703 return error(Message: "Invalid br record");
5704
5705 if (Record.size() == 1) {
5706 I = UncondBrInst::Create(IfTrue: TrueDest);
5707 InstructionList.push_back(Elt: I);
5708 }
5709 else {
5710 BasicBlock *FalseDest = getBasicBlock(ID: Record[1]);
5711 Type *CondType = Type::getInt1Ty(C&: Context);
5712 Value *Cond = getValue(Record, Slot: 2, InstNum: NextValueNo, Ty: CondType,
5713 TyID: getVirtualTypeID(Ty: CondType), ConstExprInsertBB: CurBB);
5714 if (!FalseDest || !Cond)
5715 return error(Message: "Invalid br record");
5716 I = CondBrInst::Create(Cond, IfTrue: TrueDest, IfFalse: FalseDest);
5717 InstructionList.push_back(Elt: I);
5718 }
5719 break;
5720 }
5721 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5722 if (Record.size() != 1 && Record.size() != 2)
5723 return error(Message: "Invalid cleanupret record");
5724 unsigned Idx = 0;
5725 Type *TokenTy = Type::getTokenTy(C&: Context);
5726 Value *CleanupPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy,
5727 TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB);
5728 if (!CleanupPad)
5729 return error(Message: "Invalid cleanupret record");
5730 BasicBlock *UnwindDest = nullptr;
5731 if (Record.size() == 2) {
5732 UnwindDest = getBasicBlock(ID: Record[Idx++]);
5733 if (!UnwindDest)
5734 return error(Message: "Invalid cleanupret record");
5735 }
5736
5737 I = CleanupReturnInst::Create(CleanupPad, UnwindBB: UnwindDest);
5738 InstructionList.push_back(Elt: I);
5739 break;
5740 }
5741 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5742 if (Record.size() != 2)
5743 return error(Message: "Invalid catchret record");
5744 unsigned Idx = 0;
5745 Type *TokenTy = Type::getTokenTy(C&: Context);
5746 Value *CatchPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy,
5747 TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB);
5748 if (!CatchPad)
5749 return error(Message: "Invalid catchret record");
5750 BasicBlock *BB = getBasicBlock(ID: Record[Idx++]);
5751 if (!BB)
5752 return error(Message: "Invalid catchret record");
5753
5754 I = CatchReturnInst::Create(CatchPad, BB);
5755 InstructionList.push_back(Elt: I);
5756 break;
5757 }
5758 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5759 // We must have, at minimum, the outer scope and the number of arguments.
5760 if (Record.size() < 2)
5761 return error(Message: "Invalid catchswitch record");
5762
5763 unsigned Idx = 0;
5764
5765 Type *TokenTy = Type::getTokenTy(C&: Context);
5766 Value *ParentPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy,
5767 TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB);
5768 if (!ParentPad)
5769 return error(Message: "Invalid catchswitch record");
5770
5771 unsigned NumHandlers = Record[Idx++];
5772
5773 SmallVector<BasicBlock *, 2> Handlers;
5774 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5775 BasicBlock *BB = getBasicBlock(ID: Record[Idx++]);
5776 if (!BB)
5777 return error(Message: "Invalid catchswitch record");
5778 Handlers.push_back(Elt: BB);
5779 }
5780
5781 BasicBlock *UnwindDest = nullptr;
5782 if (Idx + 1 == Record.size()) {
5783 UnwindDest = getBasicBlock(ID: Record[Idx++]);
5784 if (!UnwindDest)
5785 return error(Message: "Invalid catchswitch record");
5786 }
5787
5788 if (Record.size() != Idx)
5789 return error(Message: "Invalid catchswitch record");
5790
5791 auto *CatchSwitch =
5792 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5793 for (BasicBlock *Handler : Handlers)
5794 CatchSwitch->addHandler(Dest: Handler);
5795 I = CatchSwitch;
5796 ResTypeID = getVirtualTypeID(Ty: I->getType());
5797 InstructionList.push_back(Elt: I);
5798 break;
5799 }
5800 case bitc::FUNC_CODE_INST_CATCHPAD:
5801 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5802 // We must have, at minimum, the outer scope and the number of arguments.
5803 if (Record.size() < 2)
5804 return error(Message: "Invalid catchpad/cleanuppad record");
5805
5806 unsigned Idx = 0;
5807
5808 Type *TokenTy = Type::getTokenTy(C&: Context);
5809 Value *ParentPad = getValue(Record, Slot: Idx++, InstNum: NextValueNo, Ty: TokenTy,
5810 TyID: getVirtualTypeID(Ty: TokenTy), ConstExprInsertBB: CurBB);
5811 if (!ParentPad)
5812 return error(Message: "Invalid catchpad/cleanuppad record");
5813
5814 unsigned NumArgOperands = Record[Idx++];
5815
5816 SmallVector<Value *, 2> Args;
5817 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5818 Value *Val;
5819 unsigned ValTypeID;
5820 if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: nullptr))
5821 return error(Message: "Invalid catchpad/cleanuppad record");
5822 Args.push_back(Elt: Val);
5823 }
5824
5825 if (Record.size() != Idx)
5826 return error(Message: "Invalid catchpad/cleanuppad record");
5827
5828 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5829 I = CleanupPadInst::Create(ParentPad, Args);
5830 else
5831 I = CatchPadInst::Create(CatchSwitch: ParentPad, Args);
5832 ResTypeID = getVirtualTypeID(Ty: I->getType());
5833 InstructionList.push_back(Elt: I);
5834 break;
5835 }
5836 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5837 // Check magic
5838 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5839 // "New" SwitchInst format with case ranges. The changes to write this
5840 // format were reverted but we still recognize bitcode that uses it.
5841 // Hopefully someday we will have support for case ranges and can use
5842 // this format again.
5843
5844 unsigned OpTyID = Record[1];
5845 Type *OpTy = getTypeByID(ID: OpTyID);
5846 unsigned ValueBitWidth = cast<IntegerType>(Val: OpTy)->getBitWidth();
5847
5848 Value *Cond = getValue(Record, Slot: 2, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB);
5849 BasicBlock *Default = getBasicBlock(ID: Record[3]);
5850 if (!OpTy || !Cond || !Default)
5851 return error(Message: "Invalid switch record");
5852
5853 unsigned NumCases = Record[4];
5854
5855 SwitchInst *SI = SwitchInst::Create(Value: Cond, Default, NumCases);
5856 InstructionList.push_back(Elt: SI);
5857
5858 unsigned CurIdx = 5;
5859 for (unsigned i = 0; i != NumCases; ++i) {
5860 SmallVector<ConstantInt*, 1> CaseVals;
5861 unsigned NumItems = Record[CurIdx++];
5862 for (unsigned ci = 0; ci != NumItems; ++ci) {
5863 bool isSingleNumber = Record[CurIdx++];
5864
5865 APInt Low;
5866 unsigned ActiveWords = 1;
5867 if (ValueBitWidth > 64)
5868 ActiveWords = Record[CurIdx++];
5869 Low = readWideAPInt(Vals: ArrayRef(&Record[CurIdx], ActiveWords),
5870 TypeBits: ValueBitWidth);
5871 CurIdx += ActiveWords;
5872
5873 if (!isSingleNumber) {
5874 ActiveWords = 1;
5875 if (ValueBitWidth > 64)
5876 ActiveWords = Record[CurIdx++];
5877 APInt High = readWideAPInt(Vals: ArrayRef(&Record[CurIdx], ActiveWords),
5878 TypeBits: ValueBitWidth);
5879 CurIdx += ActiveWords;
5880
5881 // FIXME: It is not clear whether values in the range should be
5882 // compared as signed or unsigned values. The partially
5883 // implemented changes that used this format in the past used
5884 // unsigned comparisons.
5885 for ( ; Low.ule(RHS: High); ++Low)
5886 CaseVals.push_back(Elt: ConstantInt::get(Context, V: Low));
5887 } else
5888 CaseVals.push_back(Elt: ConstantInt::get(Context, V: Low));
5889 }
5890 BasicBlock *DestBB = getBasicBlock(ID: Record[CurIdx++]);
5891 for (ConstantInt *Cst : CaseVals)
5892 SI->addCase(OnVal: Cst, Dest: DestBB);
5893 }
5894 I = SI;
5895 break;
5896 }
5897
5898 // Old SwitchInst format without case ranges.
5899
5900 if (Record.size() < 3 || (Record.size() & 1) == 0)
5901 return error(Message: "Invalid switch record");
5902 unsigned OpTyID = Record[0];
5903 Type *OpTy = getTypeByID(ID: OpTyID);
5904 Value *Cond = getValue(Record, Slot: 1, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB);
5905 BasicBlock *Default = getBasicBlock(ID: Record[2]);
5906 if (!OpTy || !Cond || !Default)
5907 return error(Message: "Invalid switch record");
5908 unsigned NumCases = (Record.size()-3)/2;
5909 SwitchInst *SI = SwitchInst::Create(Value: Cond, Default, NumCases);
5910 InstructionList.push_back(Elt: SI);
5911 for (unsigned i = 0, e = NumCases; i != e; ++i) {
5912 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5913 Val: getFnValueByID(ID: Record[3+i*2], Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: nullptr));
5914 BasicBlock *DestBB = getBasicBlock(ID: Record[1+3+i*2]);
5915 if (!CaseVal || !DestBB) {
5916 delete SI;
5917 return error(Message: "Invalid switch record");
5918 }
5919 SI->addCase(OnVal: CaseVal, Dest: DestBB);
5920 }
5921 I = SI;
5922 break;
5923 }
5924 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5925 if (Record.size() < 2)
5926 return error(Message: "Invalid indirectbr record");
5927 unsigned OpTyID = Record[0];
5928 Type *OpTy = getTypeByID(ID: OpTyID);
5929 Value *Address = getValue(Record, Slot: 1, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB);
5930 if (!OpTy || !Address)
5931 return error(Message: "Invalid indirectbr record");
5932 unsigned NumDests = Record.size()-2;
5933 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5934 InstructionList.push_back(Elt: IBI);
5935 for (unsigned i = 0, e = NumDests; i != e; ++i) {
5936 if (BasicBlock *DestBB = getBasicBlock(ID: Record[2+i])) {
5937 IBI->addDestination(Dest: DestBB);
5938 } else {
5939 delete IBI;
5940 return error(Message: "Invalid indirectbr record");
5941 }
5942 }
5943 I = IBI;
5944 break;
5945 }
5946
5947 case bitc::FUNC_CODE_INST_INVOKE: {
5948 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5949 if (Record.size() < 4)
5950 return error(Message: "Invalid invoke record");
5951 unsigned OpNum = 0;
5952 AttributeList PAL = getAttributes(i: Record[OpNum++]);
5953 unsigned CCInfo = Record[OpNum++];
5954 BasicBlock *NormalBB = getBasicBlock(ID: Record[OpNum++]);
5955 BasicBlock *UnwindBB = getBasicBlock(ID: Record[OpNum++]);
5956
5957 unsigned FTyID = InvalidTypeID;
5958 FunctionType *FTy = nullptr;
5959 if ((CCInfo >> 13) & 1) {
5960 FTyID = Record[OpNum++];
5961 FTy = dyn_cast<FunctionType>(Val: getTypeByID(ID: FTyID));
5962 if (!FTy)
5963 return error(Message: "Explicit invoke type is not a function type");
5964 }
5965
5966 Value *Callee;
5967 unsigned CalleeTypeID;
5968 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Callee, TypeID&: CalleeTypeID,
5969 ConstExprInsertBB: CurBB))
5970 return error(Message: "Invalid invoke record");
5971
5972 PointerType *CalleeTy = dyn_cast<PointerType>(Val: Callee->getType());
5973 if (!CalleeTy)
5974 return error(Message: "Callee is not a pointer");
5975 if (!FTy) {
5976 FTyID = getContainedTypeID(ID: CalleeTypeID);
5977 FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID));
5978 if (!FTy)
5979 return error(Message: "Callee is not of pointer to function type");
5980 }
5981 if (Record.size() < FTy->getNumParams() + OpNum)
5982 return error(Message: "Insufficient operands to call");
5983
5984 SmallVector<Value*, 16> Ops;
5985 SmallVector<unsigned, 16> ArgTyIDs;
5986 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5987 unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: i + 1);
5988 Ops.push_back(Elt: getValue(Record, Slot: OpNum, InstNum: NextValueNo, Ty: FTy->getParamType(i),
5989 TyID: ArgTyID, ConstExprInsertBB: CurBB));
5990 ArgTyIDs.push_back(Elt: ArgTyID);
5991 if (!Ops.back())
5992 return error(Message: "Invalid invoke record");
5993 }
5994
5995 if (!FTy->isVarArg()) {
5996 if (Record.size() != OpNum)
5997 return error(Message: "Invalid invoke record");
5998 } else {
5999 // Read type/value pairs for varargs params.
6000 while (OpNum != Record.size()) {
6001 Value *Op;
6002 unsigned OpTypeID;
6003 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB))
6004 return error(Message: "Invalid invoke record");
6005 Ops.push_back(Elt: Op);
6006 ArgTyIDs.push_back(Elt: OpTypeID);
6007 }
6008 }
6009
6010 // Upgrade the bundles if needed.
6011 if (!OperandBundles.empty())
6012 UpgradeOperandBundles(OperandBundles);
6013
6014 I = InvokeInst::Create(Ty: FTy, Func: Callee, IfNormal: NormalBB, IfException: UnwindBB, Args: Ops,
6015 Bundles: OperandBundles);
6016 ResTypeID = getContainedTypeID(ID: FTyID);
6017 OperandBundles.clear();
6018 InstructionList.push_back(Elt: I);
6019 cast<InvokeInst>(Val: I)->setCallingConv(
6020 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
6021 cast<InvokeInst>(Val: I)->setAttributes(PAL);
6022 if (Error Err = propagateAttributeTypes(CB: cast<CallBase>(Val: I), ArgTyIDs)) {
6023 I->deleteValue();
6024 return Err;
6025 }
6026
6027 break;
6028 }
6029 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
6030 unsigned Idx = 0;
6031 Value *Val = nullptr;
6032 unsigned ValTypeID;
6033 if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB))
6034 return error(Message: "Invalid resume record");
6035 I = ResumeInst::Create(Exn: Val);
6036 InstructionList.push_back(Elt: I);
6037 break;
6038 }
6039 case bitc::FUNC_CODE_INST_CALLBR: {
6040 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
6041 unsigned OpNum = 0;
6042 AttributeList PAL = getAttributes(i: Record[OpNum++]);
6043 unsigned CCInfo = Record[OpNum++];
6044
6045 BasicBlock *DefaultDest = getBasicBlock(ID: Record[OpNum++]);
6046 unsigned NumIndirectDests = Record[OpNum++];
6047 SmallVector<BasicBlock *, 16> IndirectDests;
6048 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
6049 IndirectDests.push_back(Elt: getBasicBlock(ID: Record[OpNum++]));
6050
6051 unsigned FTyID = InvalidTypeID;
6052 FunctionType *FTy = nullptr;
6053 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6054 FTyID = Record[OpNum++];
6055 FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID));
6056 if (!FTy)
6057 return error(Message: "Explicit call type is not a function type");
6058 }
6059
6060 Value *Callee;
6061 unsigned CalleeTypeID;
6062 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Callee, TypeID&: CalleeTypeID,
6063 ConstExprInsertBB: CurBB))
6064 return error(Message: "Invalid callbr record");
6065
6066 PointerType *OpTy = dyn_cast<PointerType>(Val: Callee->getType());
6067 if (!OpTy)
6068 return error(Message: "Callee is not a pointer type");
6069 if (!FTy) {
6070 FTyID = getContainedTypeID(ID: CalleeTypeID);
6071 FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID));
6072 if (!FTy)
6073 return error(Message: "Callee is not of pointer to function type");
6074 }
6075 if (Record.size() < FTy->getNumParams() + OpNum)
6076 return error(Message: "Insufficient operands to call");
6077
6078 SmallVector<Value*, 16> Args;
6079 SmallVector<unsigned, 16> ArgTyIDs;
6080 // Read the fixed params.
6081 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6082 Value *Arg;
6083 unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: i + 1);
6084 if (FTy->getParamType(i)->isLabelTy())
6085 Arg = getBasicBlock(ID: Record[OpNum]);
6086 else
6087 Arg = getValue(Record, Slot: OpNum, InstNum: NextValueNo, Ty: FTy->getParamType(i),
6088 TyID: ArgTyID, ConstExprInsertBB: CurBB);
6089 if (!Arg)
6090 return error(Message: "Invalid callbr record");
6091 Args.push_back(Elt: Arg);
6092 ArgTyIDs.push_back(Elt: ArgTyID);
6093 }
6094
6095 // Read type/value pairs for varargs params.
6096 if (!FTy->isVarArg()) {
6097 if (OpNum != Record.size())
6098 return error(Message: "Invalid callbr record");
6099 } else {
6100 while (OpNum != Record.size()) {
6101 Value *Op;
6102 unsigned OpTypeID;
6103 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB))
6104 return error(Message: "Invalid callbr record");
6105 Args.push_back(Elt: Op);
6106 ArgTyIDs.push_back(Elt: OpTypeID);
6107 }
6108 }
6109
6110 // Upgrade the bundles if needed.
6111 if (!OperandBundles.empty())
6112 UpgradeOperandBundles(OperandBundles);
6113
6114 if (auto *IA = dyn_cast<InlineAsm>(Val: Callee)) {
6115 InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
6116 auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
6117 return CI.Type == InlineAsm::isLabel;
6118 };
6119 if (none_of(Range&: ConstraintInfo, P: IsLabelConstraint)) {
6120 // Upgrade explicit blockaddress arguments to label constraints.
6121 // Verify that the last arguments are blockaddress arguments that
6122 // match the indirect destinations. Clang always generates callbr
6123 // in this form. We could support reordering with more effort.
6124 unsigned FirstBlockArg = Args.size() - IndirectDests.size();
6125 for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
6126 unsigned LabelNo = ArgNo - FirstBlockArg;
6127 auto *BA = dyn_cast<BlockAddress>(Val: Args[ArgNo]);
6128 if (!BA || BA->getFunction() != F ||
6129 LabelNo > IndirectDests.size() ||
6130 BA->getBasicBlock() != IndirectDests[LabelNo])
6131 return error(Message: "callbr argument does not match indirect dest");
6132 }
6133
6134 // Remove blockaddress arguments.
6135 Args.erase(CS: Args.begin() + FirstBlockArg, CE: Args.end());
6136 ArgTyIDs.erase(CS: ArgTyIDs.begin() + FirstBlockArg, CE: ArgTyIDs.end());
6137
6138 // Recreate the function type with less arguments.
6139 SmallVector<Type *> ArgTys;
6140 for (Value *Arg : Args)
6141 ArgTys.push_back(Elt: Arg->getType());
6142 FTy =
6143 FunctionType::get(Result: FTy->getReturnType(), Params: ArgTys, isVarArg: FTy->isVarArg());
6144
6145 // Update constraint string to use label constraints.
6146 std::string Constraints = IA->getConstraintString().str();
6147 unsigned ArgNo = 0;
6148 size_t Pos = 0;
6149 for (const auto &CI : ConstraintInfo) {
6150 if (CI.hasArg()) {
6151 if (ArgNo >= FirstBlockArg)
6152 Constraints.insert(pos: Pos, s: "!");
6153 ++ArgNo;
6154 }
6155
6156 // Go to next constraint in string.
6157 Pos = Constraints.find(c: ',', pos: Pos);
6158 if (Pos == std::string::npos)
6159 break;
6160 ++Pos;
6161 }
6162
6163 Callee = InlineAsm::get(Ty: FTy, AsmString: IA->getAsmString(), Constraints,
6164 hasSideEffects: IA->hasSideEffects(), isAlignStack: IA->isAlignStack(),
6165 asmDialect: IA->getDialect(), canThrow: IA->canThrow());
6166 }
6167 }
6168
6169 I = CallBrInst::Create(Ty: FTy, Func: Callee, DefaultDest, IndirectDests, Args,
6170 Bundles: OperandBundles);
6171 ResTypeID = getContainedTypeID(ID: FTyID);
6172 OperandBundles.clear();
6173 InstructionList.push_back(Elt: I);
6174 cast<CallBrInst>(Val: I)->setCallingConv(
6175 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6176 cast<CallBrInst>(Val: I)->setAttributes(PAL);
6177 if (Error Err = propagateAttributeTypes(CB: cast<CallBase>(Val: I), ArgTyIDs)) {
6178 I->deleteValue();
6179 return Err;
6180 }
6181 break;
6182 }
6183 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
6184 I = new UnreachableInst(Context);
6185 InstructionList.push_back(Elt: I);
6186 break;
6187 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
6188 if (Record.empty())
6189 return error(Message: "Invalid phi record");
6190 // The first record specifies the type.
6191 unsigned TyID = Record[0];
6192 Type *Ty = getTypeByID(ID: TyID);
6193 if (!Ty)
6194 return error(Message: "Invalid phi record");
6195
6196 // Phi arguments are pairs of records of [value, basic block].
6197 // There is an optional final record for fast-math-flags if this phi has a
6198 // floating-point type.
6199 size_t NumArgs = (Record.size() - 1) / 2;
6200 PHINode *PN = PHINode::Create(Ty, NumReservedValues: NumArgs);
6201 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(Val: PN)) {
6202 PN->deleteValue();
6203 return error(Message: "Invalid phi record");
6204 }
6205 InstructionList.push_back(Elt: PN);
6206
6207 SmallDenseMap<BasicBlock *, Value *> Args;
6208 for (unsigned i = 0; i != NumArgs; i++) {
6209 BasicBlock *BB = getBasicBlock(ID: Record[i * 2 + 2]);
6210 if (!BB) {
6211 PN->deleteValue();
6212 return error(Message: "Invalid phi BB");
6213 }
6214
6215 // Phi nodes may contain the same predecessor multiple times, in which
6216 // case the incoming value must be identical. Directly reuse the already
6217 // seen value here, to avoid expanding a constant expression multiple
6218 // times.
6219 auto It = Args.find(Val: BB);
6220 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup(Key: {BB, CurBB});
6221 if (It != Args.end()) {
6222 // If this predecessor was also replaced with a constexpr basic
6223 // block, it must be de-duplicated.
6224 if (!EdgeBB) {
6225 PN->addIncoming(V: It->second, BB);
6226 }
6227 continue;
6228 }
6229
6230 // If there already is a block for this edge (from a different phi),
6231 // use it.
6232 if (!EdgeBB) {
6233 // Otherwise, use a temporary block (that we will discard if it
6234 // turns out to be unnecessary).
6235 if (!PhiConstExprBB)
6236 PhiConstExprBB = BasicBlock::Create(Context, Name: "phi.constexpr", Parent: F);
6237 EdgeBB = PhiConstExprBB;
6238 }
6239
6240 // With the new function encoding, it is possible that operands have
6241 // negative IDs (for forward references). Use a signed VBR
6242 // representation to keep the encoding small.
6243 Value *V;
6244 if (UseRelativeIDs)
6245 V = getValueSigned(Record, Slot: i * 2 + 1, InstNum: NextValueNo, Ty, TyID, ConstExprInsertBB: EdgeBB);
6246 else
6247 V = getValue(Record, Slot: i * 2 + 1, InstNum: NextValueNo, Ty, TyID, ConstExprInsertBB: EdgeBB);
6248 if (!V) {
6249 PN->deleteValue();
6250 PhiConstExprBB->eraseFromParent();
6251 return error(Message: "Invalid phi record");
6252 }
6253
6254 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
6255 ConstExprEdgeBBs.insert(KV: {{BB, CurBB}, EdgeBB});
6256 PhiConstExprBB = nullptr;
6257 }
6258 PN->addIncoming(V, BB);
6259 Args.insert(KV: {BB, V});
6260 }
6261 I = PN;
6262 ResTypeID = TyID;
6263
6264 // If there are an even number of records, the final record must be FMF.
6265 if (Record.size() % 2 == 0) {
6266 assert(isa<FPMathOperator>(I) && "Unexpected phi type");
6267 FastMathFlags FMF = getDecodedFastMathFlags(Val: Record[Record.size() - 1]);
6268 if (FMF.any())
6269 I->setFastMathFlags(FMF);
6270 }
6271
6272 break;
6273 }
6274
6275 case bitc::FUNC_CODE_INST_LANDINGPAD:
6276 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
6277 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6278 unsigned Idx = 0;
6279 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
6280 if (Record.size() < 3)
6281 return error(Message: "Invalid landingpad record");
6282 } else {
6283 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
6284 if (Record.size() < 4)
6285 return error(Message: "Invalid landingpad record");
6286 }
6287 ResTypeID = Record[Idx++];
6288 Type *Ty = getTypeByID(ID: ResTypeID);
6289 if (!Ty)
6290 return error(Message: "Invalid landingpad record");
6291 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
6292 Value *PersFn = nullptr;
6293 unsigned PersFnTypeID;
6294 if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: PersFn, TypeID&: PersFnTypeID,
6295 ConstExprInsertBB: nullptr))
6296 return error(Message: "Invalid landingpad record");
6297
6298 if (!F->hasPersonalityFn())
6299 F->setPersonalityFn(cast<Constant>(Val: PersFn));
6300 else if (F->getPersonalityFn() != cast<Constant>(Val: PersFn))
6301 return error(Message: "Personality function mismatch");
6302 }
6303
6304 bool IsCleanup = !!Record[Idx++];
6305 unsigned NumClauses = Record[Idx++];
6306 LandingPadInst *LP = LandingPadInst::Create(RetTy: Ty, NumReservedClauses: NumClauses);
6307 LP->setCleanup(IsCleanup);
6308 for (unsigned J = 0; J != NumClauses; ++J) {
6309 LandingPadInst::ClauseType CT =
6310 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
6311 Value *Val;
6312 unsigned ValTypeID;
6313
6314 if (getValueTypePair(Record, Slot&: Idx, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID,
6315 ConstExprInsertBB: nullptr)) {
6316 delete LP;
6317 return error(Message: "Invalid landingpad record");
6318 }
6319
6320 assert((CT != LandingPadInst::Catch ||
6321 !isa<ArrayType>(Val->getType())) &&
6322 "Catch clause has a invalid type!");
6323 assert((CT != LandingPadInst::Filter ||
6324 isa<ArrayType>(Val->getType())) &&
6325 "Filter clause has invalid type!");
6326 LP->addClause(ClauseVal: cast<Constant>(Val));
6327 }
6328
6329 I = LP;
6330 InstructionList.push_back(Elt: I);
6331 break;
6332 }
6333
6334 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
6335 if (Record.size() != 4 && Record.size() != 5)
6336 return error(Message: "Invalid alloca record");
6337 using APV = AllocaPackedValues;
6338 const uint64_t Rec = Record[3];
6339 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Packed: Rec);
6340 const bool SwiftError = Bitfield::get<APV::SwiftError>(Packed: Rec);
6341 unsigned TyID = Record[0];
6342 Type *Ty = getTypeByID(ID: TyID);
6343 if (!Bitfield::get<APV::ExplicitType>(Packed: Rec)) {
6344 TyID = getContainedTypeID(ID: TyID);
6345 Ty = getTypeByID(ID: TyID);
6346 if (!Ty)
6347 return error(Message: "Missing element type for old-style alloca");
6348 }
6349 unsigned OpTyID = Record[1];
6350 Type *OpTy = getTypeByID(ID: OpTyID);
6351 Value *Size = getFnValueByID(ID: Record[2], Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB);
6352 MaybeAlign Align;
6353 uint64_t AlignExp =
6354 Bitfield::get<APV::AlignLower>(Packed: Rec) |
6355 (Bitfield::get<APV::AlignUpper>(Packed: Rec) << APV::AlignLower::Bits);
6356 if (Error Err = parseAlignmentValue(Exponent: AlignExp, Alignment&: Align)) {
6357 return Err;
6358 }
6359 if (!Ty || !Size)
6360 return error(Message: "Invalid alloca record");
6361
6362 const DataLayout &DL = TheModule->getDataLayout();
6363 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
6364
6365 SmallPtrSet<Type *, 4> Visited;
6366 if (!Align && !Ty->isSized(Visited: &Visited))
6367 return error(Message: "alloca of unsized type");
6368 if (!Align)
6369 Align = DL.getPrefTypeAlign(Ty);
6370
6371 if (!Size->getType()->isIntegerTy())
6372 return error(Message: "alloca element count must have integer type");
6373
6374 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
6375 AI->setUsedWithInAlloca(InAlloca);
6376 AI->setSwiftError(SwiftError);
6377 I = AI;
6378 ResTypeID = getVirtualTypeID(Ty: AI->getType(), ChildTypeIDs: TyID);
6379 InstructionList.push_back(Elt: I);
6380 break;
6381 }
6382 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
6383 unsigned OpNum = 0;
6384 Value *Op;
6385 unsigned OpTypeID;
6386 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB) ||
6387 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
6388 return error(Message: "Invalid load record");
6389
6390 if (!isa<PointerType>(Val: Op->getType()))
6391 return error(Message: "Load operand is not a pointer type");
6392
6393 Type *Ty = nullptr;
6394 if (OpNum + 3 == Record.size()) {
6395 ResTypeID = Record[OpNum++];
6396 Ty = getTypeByID(ID: ResTypeID);
6397 } else {
6398 ResTypeID = getContainedTypeID(ID: OpTypeID);
6399 Ty = getTypeByID(ID: ResTypeID);
6400 }
6401
6402 if (!Ty)
6403 return error(Message: "Missing load type");
6404
6405 if (Error Err = typeCheckLoadStoreInst(ValType: Ty, PtrType: Op->getType()))
6406 return Err;
6407
6408 MaybeAlign Align;
6409 if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align))
6410 return Err;
6411 SmallPtrSet<Type *, 4> Visited;
6412 if (!Align && !Ty->isSized(Visited: &Visited))
6413 return error(Message: "load of unsized type");
6414 if (!Align)
6415 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6416 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6417 InstructionList.push_back(Elt: I);
6418 break;
6419 }
6420 case bitc::FUNC_CODE_INST_LOADATOMIC: {
6421 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6422 unsigned OpNum = 0;
6423 Value *Op;
6424 unsigned OpTypeID;
6425 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB) ||
6426 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6427 return error(Message: "Invalid load atomic record");
6428
6429 if (!isa<PointerType>(Val: Op->getType()))
6430 return error(Message: "Load operand is not a pointer type");
6431
6432 Type *Ty = nullptr;
6433 if (OpNum + 5 == Record.size()) {
6434 ResTypeID = Record[OpNum++];
6435 Ty = getTypeByID(ID: ResTypeID);
6436 } else {
6437 ResTypeID = getContainedTypeID(ID: OpTypeID);
6438 Ty = getTypeByID(ID: ResTypeID);
6439 }
6440
6441 if (!Ty)
6442 return error(Message: "Missing atomic load type");
6443
6444 if (Error Err = typeCheckLoadStoreInst(ValType: Ty, PtrType: Op->getType()))
6445 return Err;
6446
6447 AtomicOrdering Ordering = getDecodedOrdering(Val: Record[OpNum + 2]);
6448 if (Ordering == AtomicOrdering::NotAtomic ||
6449 Ordering == AtomicOrdering::Release ||
6450 Ordering == AtomicOrdering::AcquireRelease)
6451 return error(Message: "Invalid load atomic record");
6452 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6453 return error(Message: "Invalid load atomic record");
6454 SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 3]);
6455
6456 MaybeAlign Align;
6457 if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align))
6458 return Err;
6459 if (!Align)
6460 return error(Message: "Alignment missing from atomic load");
6461 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
6462 InstructionList.push_back(Elt: I);
6463 break;
6464 }
6465 case bitc::FUNC_CODE_INST_STORE:
6466 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6467 unsigned OpNum = 0;
6468 Value *Val, *Ptr;
6469 unsigned PtrTypeID, ValTypeID;
6470 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB))
6471 return error(Message: "Invalid store record");
6472
6473 if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6474 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB))
6475 return error(Message: "Invalid store record");
6476 } else {
6477 ValTypeID = getContainedTypeID(ID: PtrTypeID);
6478 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: getTypeByID(ID: ValTypeID),
6479 TyID: ValTypeID, ResVal&: Val, ConstExprInsertBB: CurBB))
6480 return error(Message: "Invalid store record");
6481 }
6482
6483 if (OpNum + 2 != Record.size())
6484 return error(Message: "Invalid store record");
6485
6486 if (Error Err = typeCheckLoadStoreInst(ValType: Val->getType(), PtrType: Ptr->getType()))
6487 return Err;
6488 MaybeAlign Align;
6489 if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align))
6490 return Err;
6491 SmallPtrSet<Type *, 4> Visited;
6492 if (!Align && !Val->getType()->isSized(Visited: &Visited))
6493 return error(Message: "store of unsized type");
6494 if (!Align)
6495 Align = TheModule->getDataLayout().getABITypeAlign(Ty: Val->getType());
6496 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6497 InstructionList.push_back(Elt: I);
6498 break;
6499 }
6500 case bitc::FUNC_CODE_INST_STOREATOMIC:
6501 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
6502 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6503 unsigned OpNum = 0;
6504 Value *Val, *Ptr;
6505 unsigned PtrTypeID, ValTypeID;
6506 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB) ||
6507 !isa<PointerType>(Val: Ptr->getType()))
6508 return error(Message: "Invalid store atomic record");
6509 if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6510 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB))
6511 return error(Message: "Invalid store atomic record");
6512 } else {
6513 ValTypeID = getContainedTypeID(ID: PtrTypeID);
6514 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: getTypeByID(ID: ValTypeID),
6515 TyID: ValTypeID, ResVal&: Val, ConstExprInsertBB: CurBB))
6516 return error(Message: "Invalid store atomic record");
6517 }
6518
6519 if (OpNum + 4 != Record.size())
6520 return error(Message: "Invalid store atomic record");
6521
6522 if (Error Err = typeCheckLoadStoreInst(ValType: Val->getType(), PtrType: Ptr->getType()))
6523 return Err;
6524 AtomicOrdering Ordering = getDecodedOrdering(Val: Record[OpNum + 2]);
6525 if (Ordering == AtomicOrdering::NotAtomic ||
6526 Ordering == AtomicOrdering::Acquire ||
6527 Ordering == AtomicOrdering::AcquireRelease)
6528 return error(Message: "Invalid store atomic record");
6529 SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 3]);
6530 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6531 return error(Message: "Invalid store atomic record");
6532
6533 MaybeAlign Align;
6534 if (Error Err = parseAlignmentValue(Exponent: Record[OpNum], Alignment&: Align))
6535 return Err;
6536 if (!Align)
6537 return error(Message: "Alignment missing from atomic store");
6538 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6539 InstructionList.push_back(Elt: I);
6540 break;
6541 }
6542 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6543 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, syncscope,
6544 // failure_ordering?, weak?]
6545 const size_t NumRecords = Record.size();
6546 unsigned OpNum = 0;
6547 Value *Ptr = nullptr;
6548 unsigned PtrTypeID;
6549 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB))
6550 return error(Message: "Invalid cmpxchg record");
6551
6552 if (!isa<PointerType>(Val: Ptr->getType()))
6553 return error(Message: "Cmpxchg operand is not a pointer type");
6554
6555 Value *Cmp = nullptr;
6556 unsigned CmpTypeID = getContainedTypeID(ID: PtrTypeID);
6557 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: getTypeByID(ID: CmpTypeID),
6558 TyID: CmpTypeID, ResVal&: Cmp, ConstExprInsertBB: CurBB))
6559 return error(Message: "Invalid cmpxchg record");
6560
6561 Value *New = nullptr;
6562 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: Cmp->getType(), TyID: CmpTypeID,
6563 ResVal&: New, ConstExprInsertBB: CurBB) ||
6564 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6565 return error(Message: "Invalid cmpxchg record");
6566
6567 const AtomicOrdering SuccessOrdering =
6568 getDecodedOrdering(Val: Record[OpNum + 1]);
6569 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6570 SuccessOrdering == AtomicOrdering::Unordered)
6571 return error(Message: "Invalid cmpxchg record");
6572
6573 const SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 2]);
6574
6575 if (Error Err = typeCheckLoadStoreInst(ValType: Cmp->getType(), PtrType: Ptr->getType()))
6576 return Err;
6577
6578 const AtomicOrdering FailureOrdering =
6579 NumRecords < 7
6580 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6581 : getDecodedOrdering(Val: Record[OpNum + 3]);
6582
6583 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6584 FailureOrdering == AtomicOrdering::Unordered)
6585 return error(Message: "Invalid cmpxchg record");
6586
6587 const Align Alignment(
6588 TheModule->getDataLayout().getTypeStoreSize(Ty: Cmp->getType()));
6589
6590 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6591 FailureOrdering, SSID);
6592 cast<AtomicCmpXchgInst>(Val: I)->setVolatile(Record[OpNum]);
6593
6594 if (NumRecords < 8) {
6595 // Before weak cmpxchgs existed, the instruction simply returned the
6596 // value loaded from memory, so bitcode files from that era will be
6597 // expecting the first component of a modern cmpxchg.
6598 I->insertInto(ParentBB: CurBB, It: CurBB->end());
6599 I = ExtractValueInst::Create(Agg: I, Idxs: 0);
6600 ResTypeID = CmpTypeID;
6601 } else {
6602 cast<AtomicCmpXchgInst>(Val: I)->setWeak(Record[OpNum + 4]);
6603 unsigned I1TypeID = getVirtualTypeID(Ty: Type::getInt1Ty(C&: Context));
6604 ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: {CmpTypeID, I1TypeID});
6605 }
6606
6607 InstructionList.push_back(Elt: I);
6608 break;
6609 }
6610 case bitc::FUNC_CODE_INST_CMPXCHG: {
6611 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, syncscope,
6612 // failure_ordering, weak, align?]
6613 const size_t NumRecords = Record.size();
6614 unsigned OpNum = 0;
6615 Value *Ptr = nullptr;
6616 unsigned PtrTypeID;
6617 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB))
6618 return error(Message: "Invalid cmpxchg record");
6619
6620 if (!isa<PointerType>(Val: Ptr->getType()))
6621 return error(Message: "Cmpxchg operand is not a pointer type");
6622
6623 Value *Cmp = nullptr;
6624 unsigned CmpTypeID;
6625 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Cmp, TypeID&: CmpTypeID, ConstExprInsertBB: CurBB))
6626 return error(Message: "Invalid cmpxchg record");
6627
6628 Value *Val = nullptr;
6629 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo, Ty: Cmp->getType(), TyID: CmpTypeID, ResVal&: Val,
6630 ConstExprInsertBB: CurBB))
6631 return error(Message: "Invalid cmpxchg record");
6632
6633 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6634 return error(Message: "Invalid cmpxchg record");
6635
6636 const bool IsVol = Record[OpNum];
6637
6638 const AtomicOrdering SuccessOrdering =
6639 getDecodedOrdering(Val: Record[OpNum + 1]);
6640 if (!AtomicCmpXchgInst::isValidSuccessOrdering(Ordering: SuccessOrdering))
6641 return error(Message: "Invalid cmpxchg success ordering");
6642
6643 const SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 2]);
6644
6645 if (Error Err = typeCheckLoadStoreInst(ValType: Cmp->getType(), PtrType: Ptr->getType()))
6646 return Err;
6647
6648 const AtomicOrdering FailureOrdering =
6649 getDecodedOrdering(Val: Record[OpNum + 3]);
6650 if (!AtomicCmpXchgInst::isValidFailureOrdering(Ordering: FailureOrdering))
6651 return error(Message: "Invalid cmpxchg failure ordering");
6652
6653 const bool IsWeak = Record[OpNum + 4];
6654
6655 MaybeAlign Alignment;
6656
6657 if (NumRecords == (OpNum + 6)) {
6658 if (Error Err = parseAlignmentValue(Exponent: Record[OpNum + 5], Alignment))
6659 return Err;
6660 }
6661 if (!Alignment)
6662 Alignment =
6663 Align(TheModule->getDataLayout().getTypeStoreSize(Ty: Cmp->getType()));
6664
6665 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6666 FailureOrdering, SSID);
6667 cast<AtomicCmpXchgInst>(Val: I)->setVolatile(IsVol);
6668 cast<AtomicCmpXchgInst>(Val: I)->setWeak(IsWeak);
6669
6670 unsigned I1TypeID = getVirtualTypeID(Ty: Type::getInt1Ty(C&: Context));
6671 ResTypeID = getVirtualTypeID(Ty: I->getType(), ChildTypeIDs: {CmpTypeID, I1TypeID});
6672
6673 InstructionList.push_back(Elt: I);
6674 break;
6675 }
6676 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
6677 case bitc::FUNC_CODE_INST_ATOMICRMW: {
6678 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6679 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6680 const size_t NumRecords = Record.size();
6681 unsigned OpNum = 0;
6682
6683 Value *Ptr = nullptr;
6684 unsigned PtrTypeID;
6685 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Ptr, TypeID&: PtrTypeID, ConstExprInsertBB: CurBB))
6686 return error(Message: "Invalid atomicrmw record");
6687
6688 if (!isa<PointerType>(Val: Ptr->getType()))
6689 return error(Message: "Invalid atomicrmw record");
6690
6691 Value *Val = nullptr;
6692 unsigned ValTypeID = InvalidTypeID;
6693 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6694 ValTypeID = getContainedTypeID(ID: PtrTypeID);
6695 if (popValue(Record, Slot&: OpNum, InstNum: NextValueNo,
6696 Ty: getTypeByID(ID: ValTypeID), TyID: ValTypeID, ResVal&: Val, ConstExprInsertBB: CurBB))
6697 return error(Message: "Invalid atomicrmw record");
6698 } else {
6699 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Val, TypeID&: ValTypeID, ConstExprInsertBB: CurBB))
6700 return error(Message: "Invalid atomicrmw record");
6701 }
6702
6703 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6704 return error(Message: "Invalid atomicrmw record");
6705
6706 const AtomicRMWInst::BinOp Operation =
6707 getDecodedRMWOperation(Val: Record[OpNum]);
6708 if (Operation < AtomicRMWInst::FIRST_BINOP ||
6709 Operation > AtomicRMWInst::LAST_BINOP)
6710 return error(Message: "Invalid atomicrmw record");
6711
6712 const bool IsVol = Record[OpNum + 1];
6713
6714 const AtomicOrdering Ordering = getDecodedOrdering(Val: Record[OpNum + 2]);
6715 if (Ordering == AtomicOrdering::NotAtomic ||
6716 Ordering == AtomicOrdering::Unordered)
6717 return error(Message: "Invalid atomicrmw record");
6718
6719 const SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[OpNum + 3]);
6720
6721 MaybeAlign Alignment;
6722
6723 if (NumRecords == (OpNum + 5)) {
6724 if (Error Err = parseAlignmentValue(Exponent: Record[OpNum + 4], Alignment))
6725 return Err;
6726 }
6727
6728 if (!Alignment)
6729 Alignment =
6730 Align(TheModule->getDataLayout().getTypeStoreSize(Ty: Val->getType()));
6731
6732 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6733 ResTypeID = ValTypeID;
6734 cast<AtomicRMWInst>(Val: I)->setVolatile(IsVol);
6735
6736 InstructionList.push_back(Elt: I);
6737 break;
6738 }
6739 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6740 if (2 != Record.size())
6741 return error(Message: "Invalid fence record");
6742 AtomicOrdering Ordering = getDecodedOrdering(Val: Record[0]);
6743 if (Ordering == AtomicOrdering::NotAtomic ||
6744 Ordering == AtomicOrdering::Unordered ||
6745 Ordering == AtomicOrdering::Monotonic)
6746 return error(Message: "Invalid fence record");
6747 SyncScope::ID SSID = getDecodedSyncScopeID(Val: Record[1]);
6748 I = new FenceInst(Context, Ordering, SSID);
6749 InstructionList.push_back(Elt: I);
6750 break;
6751 }
6752 case bitc::FUNC_CODE_DEBUG_RECORD_LABEL: {
6753 // DbgLabelRecords are placed after the Instructions that they are
6754 // attached to.
6755 SeenDebugRecord = true;
6756 Instruction *Inst = getLastInstruction();
6757 if (!Inst)
6758 return error(Message: "Invalid dbg record: missing instruction");
6759 DILocation *DIL = cast<DILocation>(Val: getFnMetadataByID(ID: Record[0]));
6760 DILabel *Label = cast<DILabel>(Val: getFnMetadataByID(ID: Record[1]));
6761 Inst->getParent()->insertDbgRecordBefore(
6762 DR: new DbgLabelRecord(Label, DebugLoc(DIL)), Here: Inst->getIterator());
6763 continue; // This isn't an instruction.
6764 }
6765 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6766 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6767 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6768 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE:
6769 case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6770 // DbgVariableRecords are placed after the Instructions that they are
6771 // attached to.
6772 SeenDebugRecord = true;
6773 Instruction *Inst = getLastInstruction();
6774 if (!Inst)
6775 return error(Message: "Invalid dbg record: missing instruction");
6776
6777 // First 3 fields are common to all kinds:
6778 // DILocation, DILocalVariable, DIExpression
6779 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6780 // ..., LocationMetadata
6781 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6782 // ..., Value
6783 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6784 // ..., LocationMetadata
6785 // dbg_declare_value (FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE)
6786 // ..., LocationMetadata
6787 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6788 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6789 unsigned Slot = 0;
6790 // Common fields (0-2).
6791 DILocation *DIL = cast<DILocation>(Val: getFnMetadataByID(ID: Record[Slot++]));
6792 DILocalVariable *Var =
6793 cast<DILocalVariable>(Val: getFnMetadataByID(ID: Record[Slot++]));
6794 DIExpression *Expr =
6795 cast<DIExpression>(Val: getFnMetadataByID(ID: Record[Slot++]));
6796
6797 // Union field (3: LocationMetadata | Value).
6798 Metadata *RawLocation = nullptr;
6799 if (BitCode == bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE) {
6800 Value *V = nullptr;
6801 unsigned TyID = 0;
6802 // We never expect to see a fwd reference value here because
6803 // use-before-defs are encoded with the standard non-abbrev record
6804 // type (they'd require encoding the type too, and they're rare). As a
6805 // result, getValueTypePair only ever increments Slot by one here (once
6806 // for the value, never twice for value and type).
6807 unsigned SlotBefore = Slot;
6808 if (getValueTypePair(Record, Slot, InstNum: NextValueNo, ResVal&: V, TypeID&: TyID, ConstExprInsertBB: CurBB))
6809 return error(Message: "Invalid dbg record: invalid value");
6810 (void)SlotBefore;
6811 assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6812 RawLocation = ValueAsMetadata::get(V);
6813 } else {
6814 RawLocation = getFnMetadataByID(ID: Record[Slot++]);
6815 }
6816
6817 DbgVariableRecord *DVR = nullptr;
6818 switch (BitCode) {
6819 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6820 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6821 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6822 DbgVariableRecord::LocationType::Value);
6823 break;
6824 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6825 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6826 DbgVariableRecord::LocationType::Declare);
6827 break;
6828 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE:
6829 DVR = new DbgVariableRecord(
6830 RawLocation, Var, Expr, DIL,
6831 DbgVariableRecord::LocationType::DeclareValue);
6832 break;
6833 case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6834 DIAssignID *ID = cast<DIAssignID>(Val: getFnMetadataByID(ID: Record[Slot++]));
6835 DIExpression *AddrExpr =
6836 cast<DIExpression>(Val: getFnMetadataByID(ID: Record[Slot++]));
6837 Metadata *Addr = getFnMetadataByID(ID: Record[Slot++]);
6838 DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6839 DIL);
6840 break;
6841 }
6842 default:
6843 llvm_unreachable("Unknown DbgVariableRecord bitcode");
6844 }
6845 Inst->getParent()->insertDbgRecordBefore(DR: DVR, Here: Inst->getIterator());
6846 continue; // This isn't an instruction.
6847 }
6848 case bitc::FUNC_CODE_INST_CALL: {
6849 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6850 if (Record.size() < 3)
6851 return error(Message: "Invalid call record");
6852
6853 unsigned OpNum = 0;
6854 AttributeList PAL = getAttributes(i: Record[OpNum++]);
6855 unsigned CCInfo = Record[OpNum++];
6856
6857 FastMathFlags FMF;
6858 if ((CCInfo >> bitc::CALL_FMF) & 1) {
6859 FMF = getDecodedFastMathFlags(Val: Record[OpNum++]);
6860 if (!FMF.any())
6861 return error(Message: "Fast math flags indicator set for call with no FMF");
6862 }
6863
6864 unsigned FTyID = InvalidTypeID;
6865 FunctionType *FTy = nullptr;
6866 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6867 FTyID = Record[OpNum++];
6868 FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID));
6869 if (!FTy)
6870 return error(Message: "Explicit call type is not a function type");
6871 }
6872
6873 Value *Callee;
6874 unsigned CalleeTypeID;
6875 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Callee, TypeID&: CalleeTypeID,
6876 ConstExprInsertBB: CurBB))
6877 return error(Message: "Invalid call record");
6878
6879 PointerType *OpTy = dyn_cast<PointerType>(Val: Callee->getType());
6880 if (!OpTy)
6881 return error(Message: "Callee is not a pointer type");
6882 if (!FTy) {
6883 FTyID = getContainedTypeID(ID: CalleeTypeID);
6884 FTy = dyn_cast_or_null<FunctionType>(Val: getTypeByID(ID: FTyID));
6885 if (!FTy)
6886 return error(Message: "Callee is not of pointer to function type");
6887 }
6888 if (Record.size() < FTy->getNumParams() + OpNum)
6889 return error(Message: "Insufficient operands to call");
6890
6891 SmallVector<Value*, 16> Args;
6892 SmallVector<unsigned, 16> ArgTyIDs;
6893 // Read the fixed params.
6894 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6895 unsigned ArgTyID = getContainedTypeID(ID: FTyID, Idx: i + 1);
6896 if (FTy->getParamType(i)->isLabelTy())
6897 Args.push_back(Elt: getBasicBlock(ID: Record[OpNum]));
6898 else
6899 Args.push_back(Elt: getValue(Record, Slot: OpNum, InstNum: NextValueNo,
6900 Ty: FTy->getParamType(i), TyID: ArgTyID, ConstExprInsertBB: CurBB));
6901 ArgTyIDs.push_back(Elt: ArgTyID);
6902 if (!Args.back())
6903 return error(Message: "Invalid call record");
6904 }
6905
6906 // Read type/value pairs for varargs params.
6907 if (!FTy->isVarArg()) {
6908 if (OpNum != Record.size())
6909 return error(Message: "Invalid call record");
6910 } else {
6911 while (OpNum != Record.size()) {
6912 Value *Op;
6913 unsigned OpTypeID;
6914 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB))
6915 return error(Message: "Invalid call record");
6916 Args.push_back(Elt: Op);
6917 ArgTyIDs.push_back(Elt: OpTypeID);
6918 }
6919 }
6920
6921 // Upgrade the bundles if needed.
6922 if (!OperandBundles.empty())
6923 UpgradeOperandBundles(OperandBundles);
6924
6925 I = CallInst::Create(Ty: FTy, Func: Callee, Args, Bundles: OperandBundles);
6926 ResTypeID = getContainedTypeID(ID: FTyID);
6927 OperandBundles.clear();
6928 InstructionList.push_back(Elt: I);
6929 cast<CallInst>(Val: I)->setCallingConv(
6930 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6931 CallInst::TailCallKind TCK = CallInst::TCK_None;
6932 if (CCInfo & (1 << bitc::CALL_TAIL))
6933 TCK = CallInst::TCK_Tail;
6934 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6935 TCK = CallInst::TCK_MustTail;
6936 if (CCInfo & (1 << bitc::CALL_NOTAIL))
6937 TCK = CallInst::TCK_NoTail;
6938 cast<CallInst>(Val: I)->setTailCallKind(TCK);
6939 cast<CallInst>(Val: I)->setAttributes(PAL);
6940 if (isa<DbgInfoIntrinsic>(Val: I))
6941 SeenDebugIntrinsic = true;
6942 if (Error Err = propagateAttributeTypes(CB: cast<CallBase>(Val: I), ArgTyIDs)) {
6943 I->deleteValue();
6944 return Err;
6945 }
6946 if (FMF.any()) {
6947 if (!isa<FPMathOperator>(Val: I))
6948 return error(Message: "Fast-math-flags specified for call without "
6949 "floating-point scalar or vector return type");
6950 I->setFastMathFlags(FMF);
6951 }
6952 break;
6953 }
6954 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6955 if (Record.size() < 3)
6956 return error(Message: "Invalid va_arg record");
6957 unsigned OpTyID = Record[0];
6958 Type *OpTy = getTypeByID(ID: OpTyID);
6959 Value *Op = getValue(Record, Slot: 1, InstNum: NextValueNo, Ty: OpTy, TyID: OpTyID, ConstExprInsertBB: CurBB);
6960 ResTypeID = Record[2];
6961 Type *ResTy = getTypeByID(ID: ResTypeID);
6962 if (!OpTy || !Op || !ResTy)
6963 return error(Message: "Invalid va_arg record");
6964 I = new VAArgInst(Op, ResTy);
6965 InstructionList.push_back(Elt: I);
6966 break;
6967 }
6968
6969 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
6970 // A call or an invoke can be optionally prefixed with some variable
6971 // number of operand bundle blocks. These blocks are read into
6972 // OperandBundles and consumed at the next call or invoke instruction.
6973
6974 if (Record.empty() || Record[0] >= BundleTags.size())
6975 return error(Message: "Invalid operand bundle record");
6976
6977 std::vector<Value *> Inputs;
6978
6979 unsigned OpNum = 1;
6980 while (OpNum != Record.size()) {
6981 Value *Op;
6982 if (getValueOrMetadata(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, ConstExprInsertBB: CurBB))
6983 return error(Message: "Invalid operand bundle record");
6984 Inputs.push_back(x: Op);
6985 }
6986
6987 OperandBundles.emplace_back(args&: BundleTags[Record[0]], args: std::move(Inputs));
6988 continue;
6989 }
6990
6991 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6992 unsigned OpNum = 0;
6993 Value *Op = nullptr;
6994 unsigned OpTypeID;
6995 if (getValueTypePair(Record, Slot&: OpNum, InstNum: NextValueNo, ResVal&: Op, TypeID&: OpTypeID, ConstExprInsertBB: CurBB))
6996 return error(Message: "Invalid freeze record");
6997 if (OpNum != Record.size())
6998 return error(Message: "Invalid freeze record");
6999
7000 I = new FreezeInst(Op);
7001 ResTypeID = OpTypeID;
7002 InstructionList.push_back(Elt: I);
7003 break;
7004 }
7005 }
7006
7007 // Add instruction to end of current BB. If there is no current BB, reject
7008 // this file.
7009 if (!CurBB) {
7010 I->deleteValue();
7011 return error(Message: "Invalid instruction with no BB");
7012 }
7013 if (!OperandBundles.empty()) {
7014 I->deleteValue();
7015 return error(Message: "Operand bundles found with no consumer");
7016 }
7017 I->insertInto(ParentBB: CurBB, It: CurBB->end());
7018
7019 // If this was a terminator instruction, move to the next block.
7020 if (I->isTerminator()) {
7021 ++CurBBNo;
7022 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
7023 }
7024
7025 // Non-void values get registered in the value table for future use.
7026 if (!I->getType()->isVoidTy()) {
7027 assert(I->getType() == getTypeByID(ResTypeID) &&
7028 "Incorrect result type ID");
7029 if (Error Err = ValueList.assignValue(Idx: NextValueNo++, V: I, TypeID: ResTypeID))
7030 return Err;
7031 }
7032 }
7033
7034OutOfRecordLoop:
7035
7036 if (!OperandBundles.empty())
7037 return error(Message: "Operand bundles found with no consumer");
7038
7039 // Check the function list for unresolved values.
7040 if (Argument *A = dyn_cast<Argument>(Val: ValueList.back())) {
7041 if (!A->getParent()) {
7042 // We found at least one unresolved value. Nuke them all to avoid leaks.
7043 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
7044 if ((A = dyn_cast_or_null<Argument>(Val: ValueList[i])) && !A->getParent()) {
7045 A->replaceAllUsesWith(V: PoisonValue::get(T: A->getType()));
7046 delete A;
7047 }
7048 }
7049 return error(Message: "Never resolved value found in function");
7050 }
7051 }
7052
7053 // Unexpected unresolved metadata about to be dropped.
7054 if (MDLoader->hasFwdRefs())
7055 return error(Message: "Invalid function metadata: outgoing forward refs");
7056
7057 if (PhiConstExprBB)
7058 PhiConstExprBB->eraseFromParent();
7059
7060 for (const auto &Pair : ConstExprEdgeBBs) {
7061 BasicBlock *From = Pair.first.first;
7062 BasicBlock *To = Pair.first.second;
7063 BasicBlock *EdgeBB = Pair.second;
7064 UncondBrInst::Create(IfTrue: To, InsertBefore: EdgeBB);
7065 From->getTerminator()->replaceSuccessorWith(OldBB: To, NewBB: EdgeBB);
7066 To->replacePhiUsesWith(Old: From, New: EdgeBB);
7067 EdgeBB->moveBefore(MovePos: To);
7068 }
7069
7070 // Trim the value list down to the size it was before we parsed this function.
7071 ValueList.shrinkTo(N: ModuleValueListSize);
7072 MDLoader->shrinkTo(N: ModuleMDLoaderSize);
7073 std::vector<BasicBlock*>().swap(x&: FunctionBBs);
7074 return Error::success();
7075}
7076
7077/// Find the function body in the bitcode stream
7078Error BitcodeReader::findFunctionInStream(
7079 Function *F,
7080 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7081 while (DeferredFunctionInfoIterator->second == 0) {
7082 // This is the fallback handling for the old format bitcode that
7083 // didn't contain the function index in the VST, or when we have
7084 // an anonymous function which would not have a VST entry.
7085 // Assert that we have one of those two cases.
7086 assert(VSTOffset == 0 || !F->hasName());
7087 // Parse the next body in the stream and set its position in the
7088 // DeferredFunctionInfo map.
7089 if (Error Err = rememberAndSkipFunctionBodies())
7090 return Err;
7091 }
7092 return Error::success();
7093}
7094
7095SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
7096 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
7097 return SyncScope::ID(Val);
7098 if (Val >= SSIDs.size())
7099 return SyncScope::System; // Map unknown synchronization scopes to system.
7100 return SSIDs[Val];
7101}
7102
7103//===----------------------------------------------------------------------===//
7104// GVMaterializer implementation
7105//===----------------------------------------------------------------------===//
7106
7107Error BitcodeReader::materialize(GlobalValue *GV) {
7108 Function *F = dyn_cast<Function>(Val: GV);
7109 // If it's not a function or is already material, ignore the request.
7110 if (!F || !F->isMaterializable())
7111 return Error::success();
7112
7113 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(Val: F);
7114 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
7115 // If its position is recorded as 0, its body is somewhere in the stream
7116 // but we haven't seen it yet.
7117 if (DFII->second == 0)
7118 if (Error Err = findFunctionInStream(F, DeferredFunctionInfoIterator: DFII))
7119 return Err;
7120
7121 // Materialize metadata before parsing any function bodies.
7122 if (Error Err = materializeMetadata())
7123 return Err;
7124
7125 // Move the bit stream to the saved position of the deferred function body.
7126 if (Error JumpFailed = Stream.JumpToBit(BitNo: DFII->second))
7127 return JumpFailed;
7128
7129 if (Error Err = parseFunctionBody(F))
7130 return Err;
7131 F->setIsMaterializable(false);
7132
7133 // All parsed Functions should load into the debug info format dictated by the
7134 // Module.
7135 if (SeenDebugIntrinsic && SeenDebugRecord)
7136 return error(Message: "Mixed debug intrinsics and debug records in bitcode module!");
7137
7138 if (StripDebugInfo)
7139 stripDebugInfo(F&: *F);
7140
7141 // Finish fn->subprogram upgrade for materialized functions.
7142 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
7143 F->setSubprogram(SP);
7144
7145 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
7146 if (!MDLoader->isStrippingTBAA()) {
7147 for (auto &I : instructions(F)) {
7148 MDNode *TBAA = I.getMetadata(KindID: LLVMContext::MD_tbaa);
7149 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I: &I, MD: TBAA))
7150 continue;
7151 MDLoader->setStripTBAA(true);
7152 stripTBAA(M: F->getParent());
7153 }
7154 }
7155
7156 for (auto &I : make_early_inc_range(Range: instructions(F))) {
7157 // "Upgrade" older incorrect branch weights by dropping them.
7158 if (auto *MD = I.getMetadata(KindID: LLVMContext::MD_prof)) {
7159 if (MD->getOperand(I: 0) != nullptr && isa<MDString>(Val: MD->getOperand(I: 0))) {
7160 MDString *MDS = cast<MDString>(Val: MD->getOperand(I: 0));
7161 StringRef ProfName = MDS->getString();
7162 // Check consistency of !prof branch_weights metadata.
7163 if (ProfName != MDProfLabels::BranchWeights)
7164 continue;
7165 unsigned ExpectedNumOperands = 0;
7166 if (isa<CondBrInst>(Val: &I))
7167 ExpectedNumOperands = 2;
7168 else if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: &I))
7169 ExpectedNumOperands = SI->getNumSuccessors();
7170 else if (isa<CallInst>(Val: &I))
7171 ExpectedNumOperands = 1;
7172 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(Val: &I))
7173 ExpectedNumOperands = IBI->getNumDestinations();
7174 else if (isa<SelectInst>(Val: &I))
7175 ExpectedNumOperands = 2;
7176 else
7177 continue; // ignore and continue.
7178
7179 unsigned Offset = getBranchWeightOffset(ProfileData: MD);
7180
7181 // If branch weight doesn't match, just strip branch weight.
7182 if (MD->getNumOperands() != Offset + ExpectedNumOperands)
7183 I.setMetadata(KindID: LLVMContext::MD_prof, Node: nullptr);
7184 }
7185 }
7186
7187 if (auto *CI = dyn_cast<CallBase>(Val: &I)) {
7188 // Remove incompatible attributes on function calls.
7189 CI->removeRetAttrs(AttrsToRemove: AttributeFuncs::typeIncompatible(
7190 Ty: CI->getFunctionType()->getReturnType(), AS: CI->getRetAttributes()));
7191
7192 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7193 CI->removeParamAttrs(ArgNo, AttrsToRemove: AttributeFuncs::typeIncompatible(
7194 Ty: CI->getArgOperand(i: ArgNo)->getType(),
7195 AS: CI->getParamAttributes(ArgNo)));
7196
7197 // Upgrade intrinsics.
7198 if (Function *OldFn = CI->getCalledFunction()) {
7199 auto It = UpgradedIntrinsics.find(Val: OldFn);
7200 if (It != UpgradedIntrinsics.end())
7201 UpgradeIntrinsicCall(CB: CI, NewFn: It->second);
7202 }
7203 }
7204 }
7205
7206 // Look for functions that rely on old function attribute behavior.
7207 UpgradeFunctionAttributes(F&: *F);
7208
7209 // Bring in any functions that this function forward-referenced via
7210 // blockaddresses.
7211 return materializeForwardReferencedFunctions();
7212}
7213
7214Error BitcodeReader::materializeModule() {
7215 if (Error Err = materializeMetadata())
7216 return Err;
7217
7218 // Promise to materialize all forward references.
7219 WillMaterializeAllForwardRefs = true;
7220
7221 // Iterate over the module, deserializing any functions that are still on
7222 // disk.
7223 for (Function &F : *TheModule) {
7224 if (Error Err = materialize(GV: &F))
7225 return Err;
7226 }
7227 // At this point, if there are any function bodies, parse the rest of
7228 // the bits in the module past the last function block we have recorded
7229 // through either lazy scanning or the VST.
7230 if (LastFunctionBlockBit || NextUnreadBit)
7231 if (Error Err = parseModule(ResumeBit: LastFunctionBlockBit > NextUnreadBit
7232 ? LastFunctionBlockBit
7233 : NextUnreadBit))
7234 return Err;
7235
7236 // Check that all block address forward references got resolved (as we
7237 // promised above).
7238 if (!BasicBlockFwdRefs.empty())
7239 return error(Message: "Never resolved function from blockaddress");
7240
7241 // Upgrade any intrinsic calls that slipped through (should not happen!) and
7242 // delete the old functions to clean up. We can't do this unless the entire
7243 // module is materialized because there could always be another function body
7244 // with calls to the old function.
7245 for (auto &I : UpgradedIntrinsics) {
7246 for (auto *U : I.first->users()) {
7247 if (CallInst *CI = dyn_cast<CallInst>(Val: U))
7248 UpgradeIntrinsicCall(CB: CI, NewFn: I.second);
7249 }
7250 if (I.first != I.second) {
7251 if (!I.first->use_empty())
7252 I.first->replaceAllUsesWith(V: I.second);
7253 I.first->eraseFromParent();
7254 }
7255 }
7256 UpgradedIntrinsics.clear();
7257
7258 UpgradeDebugInfo(M&: *TheModule);
7259
7260 UpgradeModuleFlags(M&: *TheModule);
7261
7262 UpgradeNVVMAnnotations(M&: *TheModule);
7263
7264 UpgradeARCRuntime(M&: *TheModule);
7265
7266 copyModuleAttrToFunctions(M&: *TheModule);
7267
7268 return Error::success();
7269}
7270
7271std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
7272 return IdentifiedStructTypes;
7273}
7274
7275ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7276 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7277 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
7278 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
7279 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7280
7281void ModuleSummaryIndexBitcodeReader::addThisModule() {
7282 TheIndex.addModule(ModPath: ModulePath);
7283}
7284
7285ModuleSummaryIndex::ModuleInfo *
7286ModuleSummaryIndexBitcodeReader::getThisModule() {
7287 return TheIndex.getModule(ModPath: ModulePath);
7288}
7289
7290template <bool AllowNullValueInfo>
7291std::pair<ValueInfo, GlobalValue::GUID>
7292ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
7293 auto VGI = ValueIdToValueInfoMap[ValueId];
7294 // We can have a null value info in distributed ThinLTO index files:
7295 // - For memprof callsite info records when the callee function summary is not
7296 // included in the index.
7297 // - For alias summary when its aliasee summary is not included in the index.
7298 // The bitcode writer records 0 in these cases,
7299 // and the caller of this helper will set AllowNullValueInfo to true.
7300 assert(AllowNullValueInfo || std::get<0>(VGI));
7301 return VGI;
7302}
7303
7304void ModuleSummaryIndexBitcodeReader::setValueGUID(
7305 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
7306 StringRef SourceFileName) {
7307 std::string GlobalId =
7308 GlobalValue::getGlobalIdentifier(Name: ValueName, Linkage, FileName: SourceFileName);
7309 auto ValueGUID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: GlobalId);
7310 auto OriginalNameID = ValueGUID;
7311 if (GlobalValue::isLocalLinkage(Linkage))
7312 OriginalNameID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: ValueName);
7313 if (PrintSummaryGUIDs)
7314 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
7315 << ValueName << "\n";
7316
7317 // UseStrtab is false for legacy summary formats and value names are
7318 // created on stack. In that case we save the name in a string saver in
7319 // the index so that the value name can be recorded.
7320 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7321 x: TheIndex.getOrInsertValueInfo(
7322 GUID: ValueGUID, Name: UseStrtab ? ValueName : TheIndex.saveString(String: ValueName)),
7323 y&: OriginalNameID);
7324}
7325
7326// Specialized value symbol table parser used when reading module index
7327// blocks where we don't actually create global values. The parsed information
7328// is saved in the bitcode reader for use when later parsing summaries.
7329Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7330 uint64_t Offset,
7331 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7332 // With a strtab the VST is not required to parse the summary.
7333 if (UseStrtab)
7334 return Error::success();
7335
7336 assert(Offset > 0 && "Expected non-zero VST offset");
7337 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
7338 if (!MaybeCurrentBit)
7339 return MaybeCurrentBit.takeError();
7340 uint64_t CurrentBit = MaybeCurrentBit.get();
7341
7342 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::VALUE_SYMTAB_BLOCK_ID))
7343 return Err;
7344
7345 SmallVector<uint64_t, 64> Record;
7346
7347 // Read all the records for this value table.
7348 SmallString<128> ValueName;
7349
7350 while (true) {
7351 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7352 if (!MaybeEntry)
7353 return MaybeEntry.takeError();
7354 BitstreamEntry Entry = MaybeEntry.get();
7355
7356 switch (Entry.Kind) {
7357 case BitstreamEntry::SubBlock: // Handled for us already.
7358 case BitstreamEntry::Error:
7359 return error(Message: "Malformed block");
7360 case BitstreamEntry::EndBlock:
7361 // Done parsing VST, jump back to wherever we came from.
7362 if (Error JumpFailed = Stream.JumpToBit(BitNo: CurrentBit))
7363 return JumpFailed;
7364 return Error::success();
7365 case BitstreamEntry::Record:
7366 // The interesting case.
7367 break;
7368 }
7369
7370 // Read a record.
7371 Record.clear();
7372 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
7373 if (!MaybeRecord)
7374 return MaybeRecord.takeError();
7375 switch (MaybeRecord.get()) {
7376 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7377 break;
7378 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
7379 if (convertToString(Record, Idx: 1, Result&: ValueName))
7380 return error(Message: "Invalid vst_code_entry record");
7381 unsigned ValueID = Record[0];
7382 assert(!SourceFileName.empty());
7383 auto VLI = ValueIdToLinkageMap.find(Val: ValueID);
7384 assert(VLI != ValueIdToLinkageMap.end() &&
7385 "No linkage found for VST entry?");
7386 auto Linkage = VLI->second;
7387 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7388 ValueName.clear();
7389 break;
7390 }
7391 case bitc::VST_CODE_FNENTRY: {
7392 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7393 if (convertToString(Record, Idx: 2, Result&: ValueName))
7394 return error(Message: "Invalid vst_code_fnentry record");
7395 unsigned ValueID = Record[0];
7396 assert(!SourceFileName.empty());
7397 auto VLI = ValueIdToLinkageMap.find(Val: ValueID);
7398 assert(VLI != ValueIdToLinkageMap.end() &&
7399 "No linkage found for VST entry?");
7400 auto Linkage = VLI->second;
7401 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7402 ValueName.clear();
7403 break;
7404 }
7405 case bitc::VST_CODE_COMBINED_ENTRY: {
7406 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7407 unsigned ValueID = Record[0];
7408 GlobalValue::GUID RefGUID = Record[1];
7409 // The "original name", which is the second value of the pair will be
7410 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7411 ValueIdToValueInfoMap[ValueID] =
7412 std::make_pair(x: TheIndex.getOrInsertValueInfo(GUID: RefGUID), y&: RefGUID);
7413 break;
7414 }
7415 }
7416 }
7417}
7418
7419// Parse just the blocks needed for building the index out of the module.
7420// At the end of this routine the module Index is populated with a map
7421// from global value id to GlobalValueSummary objects.
7422Error ModuleSummaryIndexBitcodeReader::parseModule() {
7423 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID))
7424 return Err;
7425
7426 SmallVector<uint64_t, 64> Record;
7427 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7428 unsigned ValueId = 0;
7429
7430 // Read the index for this module.
7431 while (true) {
7432 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7433 if (!MaybeEntry)
7434 return MaybeEntry.takeError();
7435 llvm::BitstreamEntry Entry = MaybeEntry.get();
7436
7437 switch (Entry.Kind) {
7438 case BitstreamEntry::Error:
7439 return error(Message: "Malformed block");
7440 case BitstreamEntry::EndBlock:
7441 return Error::success();
7442
7443 case BitstreamEntry::SubBlock:
7444 switch (Entry.ID) {
7445 default: // Skip unknown content.
7446 if (Error Err = Stream.SkipBlock())
7447 return Err;
7448 break;
7449 case bitc::BLOCKINFO_BLOCK_ID:
7450 // Need to parse these to get abbrev ids (e.g. for VST)
7451 if (Error Err = readBlockInfo())
7452 return Err;
7453 break;
7454 case bitc::VALUE_SYMTAB_BLOCK_ID:
7455 // Should have been parsed earlier via VSTOffset, unless there
7456 // is no summary section.
7457 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7458 !SeenGlobalValSummary) &&
7459 "Expected early VST parse via VSTOffset record");
7460 if (Error Err = Stream.SkipBlock())
7461 return Err;
7462 break;
7463 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
7464 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
7465 // Add the module if it is a per-module index (has a source file name).
7466 if (!SourceFileName.empty())
7467 addThisModule();
7468 assert(!SeenValueSymbolTable &&
7469 "Already read VST when parsing summary block?");
7470 // We might not have a VST if there were no values in the
7471 // summary. An empty summary block generated when we are
7472 // performing ThinLTO compiles so we don't later invoke
7473 // the regular LTO process on them.
7474 if (VSTOffset > 0) {
7475 if (Error Err = parseValueSymbolTable(Offset: VSTOffset, ValueIdToLinkageMap))
7476 return Err;
7477 SeenValueSymbolTable = true;
7478 }
7479 SeenGlobalValSummary = true;
7480 if (Error Err = parseEntireSummary(ID: Entry.ID))
7481 return Err;
7482 break;
7483 case bitc::MODULE_STRTAB_BLOCK_ID:
7484 if (Error Err = parseModuleStringTable())
7485 return Err;
7486 break;
7487 }
7488 continue;
7489
7490 case BitstreamEntry::Record: {
7491 Record.clear();
7492 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
7493 if (!MaybeBitCode)
7494 return MaybeBitCode.takeError();
7495 switch (MaybeBitCode.get()) {
7496 default:
7497 break; // Default behavior, ignore unknown content.
7498 case bitc::MODULE_CODE_VERSION: {
7499 if (Error Err = parseVersionRecord(Record).takeError())
7500 return Err;
7501 break;
7502 }
7503 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7504 case bitc::MODULE_CODE_SOURCE_FILENAME: {
7505 SmallString<128> ValueName;
7506 if (convertToString(Record, Idx: 0, Result&: ValueName))
7507 return error(Message: "Invalid source filename record");
7508 SourceFileName = ValueName.c_str();
7509 break;
7510 }
7511 /// MODULE_CODE_HASH: [5*i32]
7512 case bitc::MODULE_CODE_HASH: {
7513 if (Record.size() != 5)
7514 return error(Message: "Invalid hash length " + Twine(Record.size()).str());
7515 auto &Hash = getThisModule()->second;
7516 int Pos = 0;
7517 for (auto &Val : Record) {
7518 assert(!(Val >> 32) && "Unexpected high bits set");
7519 Hash[Pos++] = Val;
7520 }
7521 break;
7522 }
7523 /// MODULE_CODE_VSTOFFSET: [offset]
7524 case bitc::MODULE_CODE_VSTOFFSET:
7525 if (Record.empty())
7526 return error(Message: "Invalid vstoffset record");
7527 // Note that we subtract 1 here because the offset is relative to one
7528 // word before the start of the identification or module block, which
7529 // was historically always the start of the regular bitcode header.
7530 VSTOffset = Record[0] - 1;
7531 break;
7532 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7533 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7534 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7535 // v2: [strtab offset, strtab size, v1]
7536 case bitc::MODULE_CODE_GLOBALVAR:
7537 case bitc::MODULE_CODE_FUNCTION:
7538 case bitc::MODULE_CODE_ALIAS: {
7539 StringRef Name;
7540 ArrayRef<uint64_t> GVRecord;
7541 std::tie(args&: Name, args&: GVRecord) = readNameFromStrtab(Record);
7542 if (GVRecord.size() <= 3)
7543 return error(Message: "Invalid global record");
7544 uint64_t RawLinkage = GVRecord[3];
7545 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Val: RawLinkage);
7546 if (!UseStrtab) {
7547 ValueIdToLinkageMap[ValueId++] = Linkage;
7548 break;
7549 }
7550
7551 setValueGUID(ValueID: ValueId++, ValueName: Name, Linkage, SourceFileName);
7552 break;
7553 }
7554 }
7555 }
7556 continue;
7557 }
7558 }
7559}
7560
7561SmallVector<ValueInfo, 0>
7562ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7563 SmallVector<ValueInfo, 0> Ret;
7564 Ret.reserve(N: Record.size());
7565 for (uint64_t RefValueId : Record)
7566 Ret.push_back(Elt: std::get<0>(in: getValueInfoFromValueId(ValueId: RefValueId)));
7567 return Ret;
7568}
7569
7570SmallVector<FunctionSummary::EdgeTy, 0>
7571ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7572 bool IsOldProfileFormat,
7573 bool HasProfile, bool HasRelBF) {
7574 SmallVector<FunctionSummary::EdgeTy, 0> Ret;
7575 // In the case of new profile formats, there are two Record entries per
7576 // Edge. Otherwise, conservatively reserve up to Record.size.
7577 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7578 Ret.reserve(N: Record.size() / 2);
7579 else
7580 Ret.reserve(N: Record.size());
7581
7582 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7583 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7584 bool HasTailCall = false;
7585 uint64_t RelBF = 0;
7586 ValueInfo Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record[I]));
7587 if (IsOldProfileFormat) {
7588 I += 1; // Skip old callsitecount field
7589 if (HasProfile)
7590 I += 1; // Skip old profilecount field
7591 } else if (HasProfile)
7592 std::tie(args&: Hotness, args&: HasTailCall) =
7593 getDecodedHotnessCallEdgeInfo(RawFlags: Record[++I]);
7594 // Deprecated, but still needed to read old bitcode files.
7595 else if (HasRelBF)
7596 getDecodedRelBFCallEdgeInfo(RawFlags: Record[++I], RelBF, HasTailCall);
7597 Ret.push_back(
7598 Elt: FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, HasTailCall)});
7599 }
7600 return Ret;
7601}
7602
7603static void
7604parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
7605 WholeProgramDevirtResolution &Wpd) {
7606 uint64_t ArgNum = Record[Slot++];
7607 WholeProgramDevirtResolution::ByArg &B =
7608 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7609 Slot += ArgNum;
7610
7611 B.TheKind =
7612 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
7613 B.Info = Record[Slot++];
7614 B.Byte = Record[Slot++];
7615 B.Bit = Record[Slot++];
7616}
7617
7618static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
7619 StringRef Strtab, size_t &Slot,
7620 TypeIdSummary &TypeId) {
7621 uint64_t Id = Record[Slot++];
7622 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7623
7624 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7625 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7626 static_cast<size_t>(Record[Slot + 1])};
7627 Slot += 2;
7628
7629 uint64_t ResByArgNum = Record[Slot++];
7630 for (uint64_t I = 0; I != ResByArgNum; ++I)
7631 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
7632}
7633
7634static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
7635 StringRef Strtab,
7636 ModuleSummaryIndex &TheIndex) {
7637 size_t Slot = 0;
7638 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7639 TypeId: {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7640 Slot += 2;
7641
7642 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7643 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7644 TypeId.TTRes.AlignLog2 = Record[Slot++];
7645 TypeId.TTRes.SizeM1 = Record[Slot++];
7646 TypeId.TTRes.BitMask = Record[Slot++];
7647 TypeId.TTRes.InlineBits = Record[Slot++];
7648
7649 while (Slot < Record.size())
7650 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7651}
7652
7653std::vector<FunctionSummary::ParamAccess>
7654ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7655 auto ReadRange = [&]() {
7656 APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
7657 BitcodeReader::decodeSignRotatedValue(V: Record.consume_front()));
7658 APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
7659 BitcodeReader::decodeSignRotatedValue(V: Record.consume_front()));
7660 ConstantRange Range{Lower, Upper};
7661 assert(!Range.isFullSet());
7662 assert(!Range.isUpperSignWrapped());
7663 return Range;
7664 };
7665
7666 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7667 while (!Record.empty()) {
7668 PendingParamAccesses.emplace_back();
7669 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7670 ParamAccess.ParamNo = Record.consume_front();
7671 ParamAccess.Use = ReadRange();
7672 ParamAccess.Calls.resize(new_size: Record.consume_front());
7673 for (auto &Call : ParamAccess.Calls) {
7674 Call.ParamNo = Record.consume_front();
7675 Call.Callee =
7676 std::get<0>(in: getValueInfoFromValueId(ValueId: Record.consume_front()));
7677 Call.Offsets = ReadRange();
7678 }
7679 }
7680 return PendingParamAccesses;
7681}
7682
7683void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7684 ArrayRef<uint64_t> Record, size_t &Slot,
7685 TypeIdCompatibleVtableInfo &TypeId) {
7686 uint64_t Offset = Record[Slot++];
7687 ValueInfo Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record[Slot++]));
7688 TypeId.push_back(x: {Offset, Callee});
7689}
7690
7691void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7692 ArrayRef<uint64_t> Record) {
7693 size_t Slot = 0;
7694 TypeIdCompatibleVtableInfo &TypeId =
7695 TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
7696 TypeId: {Strtab.data() + Record[Slot],
7697 static_cast<size_t>(Record[Slot + 1])});
7698 Slot += 2;
7699
7700 while (Slot < Record.size())
7701 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7702}
7703
7704SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7705 ArrayRef<uint64_t> Record, unsigned &I) {
7706 SmallVector<unsigned> StackIdList;
7707 // For backwards compatibility with old format before radix tree was
7708 // used, simply see if we found a radix tree array record (and thus if
7709 // the RadixArray is non-empty).
7710 if (RadixArray.empty()) {
7711 unsigned NumStackEntries = Record[I++];
7712 assert(Record.size() - I >= NumStackEntries);
7713 StackIdList.reserve(N: NumStackEntries);
7714 for (unsigned J = 0; J < NumStackEntries; J++) {
7715 assert(Record[I] < StackIds.size());
7716 StackIdList.push_back(Elt: getStackIdIndex(LocalIndex: Record[I++]));
7717 }
7718 } else {
7719 unsigned RadixIndex = Record[I++];
7720 // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7721 // for a detailed description of the radix tree array format. Briefly, the
7722 // first entry will be the number of frames, any negative values are the
7723 // negative of the offset of the next frame, and otherwise the frames are in
7724 // increasing linear order.
7725 assert(RadixIndex < RadixArray.size());
7726 unsigned NumStackIds = RadixArray[RadixIndex++];
7727 StackIdList.reserve(N: NumStackIds);
7728 while (NumStackIds--) {
7729 assert(RadixIndex < RadixArray.size());
7730 unsigned Elem = RadixArray[RadixIndex];
7731 if (static_cast<std::make_signed_t<unsigned>>(Elem) < 0) {
7732 RadixIndex = RadixIndex - Elem;
7733 assert(RadixIndex < RadixArray.size());
7734 Elem = RadixArray[RadixIndex];
7735 // We shouldn't encounter a second offset in a row.
7736 assert(static_cast<std::make_signed_t<unsigned>>(Elem) >= 0);
7737 }
7738 RadixIndex++;
7739 StackIdList.push_back(Elt: getStackIdIndex(LocalIndex: Elem));
7740 }
7741 }
7742 return StackIdList;
7743}
7744
7745static void setSpecialRefs(SmallVectorImpl<ValueInfo> &Refs, unsigned ROCnt,
7746 unsigned WOCnt) {
7747 // Readonly and writeonly refs are in the end of the refs list.
7748 assert(ROCnt + WOCnt <= Refs.size());
7749 unsigned FirstWORef = Refs.size() - WOCnt;
7750 unsigned RefNo = FirstWORef - ROCnt;
7751 for (; RefNo < FirstWORef; ++RefNo)
7752 Refs[RefNo].setReadOnly();
7753 for (; RefNo < Refs.size(); ++RefNo)
7754 Refs[RefNo].setWriteOnly();
7755}
7756
7757// Eagerly parse the entire summary block. This populates the GlobalValueSummary
7758// objects in the index.
7759Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7760 if (Error Err = Stream.EnterSubBlock(BlockID: ID))
7761 return Err;
7762 SmallVector<uint64_t, 64> Record;
7763
7764 // Parse version
7765 {
7766 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7767 if (!MaybeEntry)
7768 return MaybeEntry.takeError();
7769 BitstreamEntry Entry = MaybeEntry.get();
7770
7771 if (Entry.Kind != BitstreamEntry::Record)
7772 return error(Message: "Invalid Summary Block: record for version expected");
7773 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
7774 if (!MaybeRecord)
7775 return MaybeRecord.takeError();
7776 if (MaybeRecord.get() != bitc::FS_VERSION)
7777 return error(Message: "Invalid Summary Block: version expected");
7778 }
7779 const uint64_t Version = Record[0];
7780 const bool IsOldProfileFormat = Version == 1;
7781 // Starting with bitcode summary version 13, MemProf records follow the
7782 // corresponding function summary.
7783 const bool MemProfAfterFunctionSummary = Version >= 13;
7784 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
7785 return error(Message: "Invalid summary version " + Twine(Version) +
7786 ". Version should be in the range [1-" +
7787 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7788 "].");
7789 Record.clear();
7790
7791 // Keep around the last seen summary to be used when we see an optional
7792 // "OriginalName" attachement.
7793 GlobalValueSummary *LastSeenSummary = nullptr;
7794 GlobalValue::GUID LastSeenGUID = 0;
7795
7796 // Track the most recent function summary if it was prevailing, and while we
7797 // are not done processing any subsequent memprof records. Starting with
7798 // summary version 13 (tracked by MemProfAfterFunctionSummary), MemProf
7799 // records follow the function summary and we skip processing them when the
7800 // summary is not prevailing. Note that when reading a combined index we don't
7801 // know what is prevailing so this should always be set in the new format when
7802 // we encounter MemProf records.
7803 FunctionSummary *CurrentPrevailingFS = nullptr;
7804
7805 // We can expect to see any number of type ID information records before
7806 // each function summary records; these variables store the information
7807 // collected so far so that it can be used to create the summary object.
7808 std::vector<GlobalValue::GUID> PendingTypeTests;
7809 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7810 PendingTypeCheckedLoadVCalls;
7811 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7812 PendingTypeCheckedLoadConstVCalls;
7813 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7814
7815 std::vector<CallsiteInfo> PendingCallsites;
7816 std::vector<AllocInfo> PendingAllocs;
7817 std::vector<uint64_t> PendingContextIds;
7818
7819 while (true) {
7820 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7821 if (!MaybeEntry)
7822 return MaybeEntry.takeError();
7823 BitstreamEntry Entry = MaybeEntry.get();
7824
7825 switch (Entry.Kind) {
7826 case BitstreamEntry::SubBlock: // Handled for us already.
7827 case BitstreamEntry::Error:
7828 return error(Message: "Malformed block");
7829 case BitstreamEntry::EndBlock:
7830 return Error::success();
7831 case BitstreamEntry::Record:
7832 // The interesting case.
7833 break;
7834 }
7835
7836 // Read a record. The record format depends on whether this
7837 // is a per-module index or a combined index file. In the per-module
7838 // case the records contain the associated value's ID for correlation
7839 // with VST entries. In the combined index the correlation is done
7840 // via the bitcode offset of the summary records (which were saved
7841 // in the combined index VST entries). The records also contain
7842 // information used for ThinLTO renaming and importing.
7843 Record.clear();
7844 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
7845 if (!MaybeBitCode)
7846 return MaybeBitCode.takeError();
7847 unsigned BitCode = MaybeBitCode.get();
7848
7849 switch (BitCode) {
7850 default: // Default behavior: ignore.
7851 break;
7852 case bitc::FS_FLAGS: { // [flags]
7853 TheIndex.setFlags(Record[0]);
7854 break;
7855 }
7856 case bitc::FS_VALUE_GUID: { // [valueid, refguid_upper32, refguid_lower32]
7857 uint64_t ValueID = Record[0];
7858 GlobalValue::GUID RefGUID;
7859 if (Version >= 11) {
7860 RefGUID = Record[1] << 32 | Record[2];
7861 } else {
7862 RefGUID = Record[1];
7863 }
7864 ValueIdToValueInfoMap[ValueID] =
7865 std::make_pair(x: TheIndex.getOrInsertValueInfo(GUID: RefGUID), y&: RefGUID);
7866 break;
7867 }
7868 // FS_PERMODULE is legacy and does not have support for the tail call flag.
7869 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7870 // numrefs x valueid, n x (valueid)]
7871 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7872 // numrefs x valueid,
7873 // n x (valueid, hotness+tailcall flags)]
7874 // Deprecated, but still needed to read old bitcode files.
7875 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7876 // numrefs x valueid,
7877 // n x (valueid, relblockfreq+tailcall)]
7878 case bitc::FS_PERMODULE:
7879 case bitc::FS_PERMODULE_PROFILE:
7880 // Deprecated, but still needed to read old bitcode files.
7881 case bitc::FS_PERMODULE_RELBF: {
7882 unsigned ValueID = Record[0];
7883 uint64_t RawFlags = Record[1];
7884 unsigned InstCount = Record[2];
7885 uint64_t RawFunFlags = 0;
7886 unsigned NumRefs = Record[3];
7887 unsigned NumRORefs = 0, NumWORefs = 0;
7888 int RefListStartIndex = 4;
7889 if (Version >= 4) {
7890 RawFunFlags = Record[3];
7891 NumRefs = Record[4];
7892 RefListStartIndex = 5;
7893 if (Version >= 5) {
7894 NumRORefs = Record[5];
7895 RefListStartIndex = 6;
7896 if (Version >= 7) {
7897 NumWORefs = Record[6];
7898 RefListStartIndex = 7;
7899 }
7900 }
7901 }
7902
7903 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7904 // The module path string ref set in the summary must be owned by the
7905 // index's module string table. Since we don't have a module path
7906 // string table section in the per-module index, we create a single
7907 // module path string table entry with an empty (0) ID to take
7908 // ownership.
7909 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7910 assert(Record.size() >= RefListStartIndex + NumRefs &&
7911 "Record size inconsistent with number of references");
7912 SmallVector<ValueInfo, 0> Refs = makeRefList(
7913 Record: ArrayRef<uint64_t>(Record).slice(N: RefListStartIndex, M: NumRefs));
7914 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7915 // Deprecated, but still needed to read old bitcode files.
7916 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7917 SmallVector<FunctionSummary::EdgeTy, 0> Calls = makeCallList(
7918 Record: ArrayRef<uint64_t>(Record).slice(N: CallGraphEdgeStartIndex),
7919 IsOldProfileFormat, HasProfile, HasRelBF);
7920 setSpecialRefs(Refs, ROCnt: NumRORefs, WOCnt: NumWORefs);
7921 auto [VI, GUID] = getValueInfoFromValueId(ValueId: ValueID);
7922
7923 // The linker doesn't resolve local linkage values so don't check whether
7924 // those are prevailing (set IsPrevailingSym so they are always processed
7925 // and kept).
7926 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7927 bool IsPrevailingSym = !IsPrevailing || GlobalValue::isLocalLinkage(Linkage: LT) ||
7928 IsPrevailing(VI.getGUID());
7929
7930 // If this is not the prevailing copy, and the records are in the "old"
7931 // order (preceding), clear them now. They should already be empty in
7932 // the new order (following), as they are processed or skipped immediately
7933 // when they follow the summary.
7934 assert(!MemProfAfterFunctionSummary ||
7935 (PendingCallsites.empty() && PendingAllocs.empty()));
7936 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
7937 PendingCallsites.clear();
7938 PendingAllocs.clear();
7939 }
7940
7941 auto FS = std::make_unique<FunctionSummary>(
7942 args&: Flags, args&: InstCount, args: getDecodedFFlags(RawFlags: RawFunFlags), args: std::move(Refs),
7943 args: std::move(Calls), args: std::move(PendingTypeTests),
7944 args: std::move(PendingTypeTestAssumeVCalls),
7945 args: std::move(PendingTypeCheckedLoadVCalls),
7946 args: std::move(PendingTypeTestAssumeConstVCalls),
7947 args: std::move(PendingTypeCheckedLoadConstVCalls),
7948 args: std::move(PendingParamAccesses), args: std::move(PendingCallsites),
7949 args: std::move(PendingAllocs));
7950 FS->setModulePath(getThisModule()->first());
7951 FS->setOriginalName(GUID);
7952 // Set CurrentPrevailingFS only if prevailing, so subsequent MemProf
7953 // records are attached (new order) or skipped.
7954 if (MemProfAfterFunctionSummary) {
7955 if (IsPrevailingSym)
7956 CurrentPrevailingFS = FS.get();
7957 else
7958 CurrentPrevailingFS = nullptr;
7959 }
7960 TheIndex.addGlobalValueSummary(VI, Summary: std::move(FS));
7961 break;
7962 }
7963 // FS_ALIAS: [valueid, flags, valueid]
7964 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7965 // they expect all aliasee summaries to be available.
7966 case bitc::FS_ALIAS: {
7967 unsigned ValueID = Record[0];
7968 uint64_t RawFlags = Record[1];
7969 unsigned AliaseeID = Record[2];
7970 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7971 auto AS = std::make_unique<AliasSummary>(args&: Flags);
7972 // The module path string ref set in the summary must be owned by the
7973 // index's module string table. Since we don't have a module path
7974 // string table section in the per-module index, we create a single
7975 // module path string table entry with an empty (0) ID to take
7976 // ownership.
7977 AS->setModulePath(getThisModule()->first());
7978
7979 auto AliaseeVI = std::get<0>(in: getValueInfoFromValueId(ValueId: AliaseeID));
7980 auto AliaseeInModule = TheIndex.findSummaryInModule(VI: AliaseeVI, ModuleId: ModulePath);
7981 if (!AliaseeInModule)
7982 return error(Message: "Alias expects aliasee summary to be parsed");
7983 AS->setAliasee(AliaseeVI, Aliasee: AliaseeInModule);
7984
7985 auto GUID = getValueInfoFromValueId(ValueId: ValueID);
7986 AS->setOriginalName(std::get<1>(in&: GUID));
7987 TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: GUID), Summary: std::move(AS));
7988 break;
7989 }
7990 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7991 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
7992 unsigned ValueID = Record[0];
7993 uint64_t RawFlags = Record[1];
7994 unsigned RefArrayStart = 2;
7995 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7996 /* WriteOnly */ false,
7997 /* Constant */ false,
7998 GlobalObject::VCallVisibilityPublic);
7999 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8000 if (Version >= 5) {
8001 GVF = getDecodedGVarFlags(RawFlags: Record[2]);
8002 RefArrayStart = 3;
8003 }
8004 SmallVector<ValueInfo, 0> Refs =
8005 makeRefList(Record: ArrayRef<uint64_t>(Record).slice(N: RefArrayStart));
8006 auto FS =
8007 std::make_unique<GlobalVarSummary>(args&: Flags, args&: GVF, args: std::move(Refs));
8008 FS->setModulePath(getThisModule()->first());
8009 auto GUID = getValueInfoFromValueId(ValueId: ValueID);
8010 FS->setOriginalName(std::get<1>(in&: GUID));
8011 TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: GUID), Summary: std::move(FS));
8012 break;
8013 }
8014 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
8015 // numrefs, numrefs x valueid,
8016 // n x (valueid, offset)]
8017 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
8018 unsigned ValueID = Record[0];
8019 uint64_t RawFlags = Record[1];
8020 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(RawFlags: Record[2]);
8021 unsigned NumRefs = Record[3];
8022 unsigned RefListStartIndex = 4;
8023 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8024 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8025 SmallVector<ValueInfo, 0> Refs = makeRefList(
8026 Record: ArrayRef<uint64_t>(Record).slice(N: RefListStartIndex, M: NumRefs));
8027 VTableFuncList VTableFuncs;
8028 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
8029 ValueInfo Callee = std::get<0>(in: getValueInfoFromValueId(ValueId: Record[I]));
8030 uint64_t Offset = Record[++I];
8031 VTableFuncs.push_back(x: {Callee, Offset});
8032 }
8033 auto VS =
8034 std::make_unique<GlobalVarSummary>(args&: Flags, args&: GVF, args: std::move(Refs));
8035 VS->setModulePath(getThisModule()->first());
8036 VS->setVTableFuncs(VTableFuncs);
8037 auto GUID = getValueInfoFromValueId(ValueId: ValueID);
8038 VS->setOriginalName(std::get<1>(in&: GUID));
8039 TheIndex.addGlobalValueSummary(VI: std::get<0>(in&: GUID), Summary: std::move(VS));
8040 break;
8041 }
8042 // FS_COMBINED is legacy and does not have support for the tail call flag.
8043 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
8044 // numrefs x valueid, n x (valueid)]
8045 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
8046 // numrefs x valueid,
8047 // n x (valueid, hotness+tailcall flags)]
8048 case bitc::FS_COMBINED:
8049 case bitc::FS_COMBINED_PROFILE: {
8050 unsigned ValueID = Record[0];
8051 uint64_t ModuleId = Record[1];
8052 uint64_t RawFlags = Record[2];
8053 unsigned InstCount = Record[3];
8054 uint64_t RawFunFlags = 0;
8055 unsigned NumRefs = Record[4];
8056 unsigned NumRORefs = 0, NumWORefs = 0;
8057 int RefListStartIndex = 5;
8058
8059 if (Version >= 4) {
8060 RawFunFlags = Record[4];
8061 RefListStartIndex = 6;
8062 size_t NumRefsIndex = 5;
8063 if (Version >= 5) {
8064 unsigned NumRORefsOffset = 1;
8065 RefListStartIndex = 7;
8066 if (Version >= 6) {
8067 NumRefsIndex = 6;
8068 RefListStartIndex = 8;
8069 if (Version >= 7) {
8070 RefListStartIndex = 9;
8071 NumWORefs = Record[8];
8072 NumRORefsOffset = 2;
8073 }
8074 }
8075 NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
8076 }
8077 NumRefs = Record[NumRefsIndex];
8078 }
8079
8080 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8081 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8082 assert(Record.size() >= RefListStartIndex + NumRefs &&
8083 "Record size inconsistent with number of references");
8084 SmallVector<ValueInfo, 0> Refs = makeRefList(
8085 Record: ArrayRef<uint64_t>(Record).slice(N: RefListStartIndex, M: NumRefs));
8086 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
8087 SmallVector<FunctionSummary::EdgeTy, 0> Edges = makeCallList(
8088 Record: ArrayRef<uint64_t>(Record).slice(N: CallGraphEdgeStartIndex),
8089 IsOldProfileFormat, HasProfile, HasRelBF: false);
8090 ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID));
8091 setSpecialRefs(Refs, ROCnt: NumRORefs, WOCnt: NumWORefs);
8092 auto FS = std::make_unique<FunctionSummary>(
8093 args&: Flags, args&: InstCount, args: getDecodedFFlags(RawFlags: RawFunFlags), args: std::move(Refs),
8094 args: std::move(Edges), args: std::move(PendingTypeTests),
8095 args: std::move(PendingTypeTestAssumeVCalls),
8096 args: std::move(PendingTypeCheckedLoadVCalls),
8097 args: std::move(PendingTypeTestAssumeConstVCalls),
8098 args: std::move(PendingTypeCheckedLoadConstVCalls),
8099 args: std::move(PendingParamAccesses), args: std::move(PendingCallsites),
8100 args: std::move(PendingAllocs));
8101 LastSeenSummary = FS.get();
8102 if (MemProfAfterFunctionSummary)
8103 CurrentPrevailingFS = FS.get();
8104 LastSeenGUID = VI.getGUID();
8105 FS->setModulePath(ModuleIdMap[ModuleId]);
8106 TheIndex.addGlobalValueSummary(VI, Summary: std::move(FS));
8107 break;
8108 }
8109 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
8110 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
8111 // they expect all aliasee summaries to be available.
8112 case bitc::FS_COMBINED_ALIAS: {
8113 unsigned ValueID = Record[0];
8114 uint64_t ModuleId = Record[1];
8115 uint64_t RawFlags = Record[2];
8116 unsigned AliaseeValueId = Record[3];
8117 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8118 auto AS = std::make_unique<AliasSummary>(args&: Flags);
8119 LastSeenSummary = AS.get();
8120 AS->setModulePath(ModuleIdMap[ModuleId]);
8121
8122 auto AliaseeVI = std::get<0>(
8123 in: getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueId: AliaseeValueId));
8124 if (AliaseeVI) {
8125 auto AliaseeInModule =
8126 TheIndex.findSummaryInModule(VI: AliaseeVI, ModuleId: AS->modulePath());
8127 AS->setAliasee(AliaseeVI, Aliasee: AliaseeInModule);
8128 }
8129 ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID));
8130 LastSeenGUID = VI.getGUID();
8131 TheIndex.addGlobalValueSummary(VI, Summary: std::move(AS));
8132 break;
8133 }
8134 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
8135 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
8136 unsigned ValueID = Record[0];
8137 uint64_t ModuleId = Record[1];
8138 uint64_t RawFlags = Record[2];
8139 unsigned RefArrayStart = 3;
8140 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
8141 /* WriteOnly */ false,
8142 /* Constant */ false,
8143 GlobalObject::VCallVisibilityPublic);
8144 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8145 if (Version >= 5) {
8146 GVF = getDecodedGVarFlags(RawFlags: Record[3]);
8147 RefArrayStart = 4;
8148 }
8149 SmallVector<ValueInfo, 0> Refs =
8150 makeRefList(Record: ArrayRef<uint64_t>(Record).slice(N: RefArrayStart));
8151 auto FS =
8152 std::make_unique<GlobalVarSummary>(args&: Flags, args&: GVF, args: std::move(Refs));
8153 LastSeenSummary = FS.get();
8154 FS->setModulePath(ModuleIdMap[ModuleId]);
8155 ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID));
8156 LastSeenGUID = VI.getGUID();
8157 TheIndex.addGlobalValueSummary(VI, Summary: std::move(FS));
8158 break;
8159 }
8160 // FS_COMBINED_ORIGINAL_NAME: [original_name]
8161 case bitc::FS_COMBINED_ORIGINAL_NAME: {
8162 uint64_t OriginalName = Record[0];
8163 if (!LastSeenSummary)
8164 return error(Message: "Name attachment that does not follow a combined record");
8165 LastSeenSummary->setOriginalName(OriginalName);
8166 TheIndex.addOriginalName(ValueGUID: LastSeenGUID, OrigGUID: OriginalName);
8167 // Reset the LastSeenSummary
8168 LastSeenSummary = nullptr;
8169 LastSeenGUID = 0;
8170 break;
8171 }
8172 case bitc::FS_TYPE_TESTS:
8173 assert(PendingTypeTests.empty());
8174 llvm::append_range(C&: PendingTypeTests, R&: Record);
8175 break;
8176
8177 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
8178 assert(PendingTypeTestAssumeVCalls.empty());
8179 for (unsigned I = 0; I != Record.size(); I += 2)
8180 PendingTypeTestAssumeVCalls.push_back(x: {.GUID: Record[I], .Offset: Record[I+1]});
8181 break;
8182
8183 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
8184 assert(PendingTypeCheckedLoadVCalls.empty());
8185 for (unsigned I = 0; I != Record.size(); I += 2)
8186 PendingTypeCheckedLoadVCalls.push_back(x: {.GUID: Record[I], .Offset: Record[I+1]});
8187 break;
8188
8189 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
8190 PendingTypeTestAssumeConstVCalls.push_back(
8191 x: {.VFunc: {.GUID: Record[0], .Offset: Record[1]}, .Args: {Record.begin() + 2, Record.end()}});
8192 break;
8193
8194 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
8195 PendingTypeCheckedLoadConstVCalls.push_back(
8196 x: {.VFunc: {.GUID: Record[0], .Offset: Record[1]}, .Args: {Record.begin() + 2, Record.end()}});
8197 break;
8198
8199 case bitc::FS_CFI_FUNCTION_DEFS: {
8200 auto &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
8201 for (unsigned I = 0; I != Record.size(); I += 2)
8202 CfiFunctionDefs.emplace(A: Strtab.data() + Record[I],
8203 A: static_cast<size_t>(Record[I + 1]));
8204 break;
8205 }
8206
8207 case bitc::FS_CFI_FUNCTION_DECLS: {
8208 auto &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
8209 for (unsigned I = 0; I != Record.size(); I += 2)
8210 CfiFunctionDecls.emplace(A: Strtab.data() + Record[I],
8211 A: static_cast<size_t>(Record[I + 1]));
8212 break;
8213 }
8214
8215 case bitc::FS_TYPE_ID:
8216 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
8217 break;
8218
8219 case bitc::FS_TYPE_ID_METADATA:
8220 parseTypeIdCompatibleVtableSummaryRecord(Record);
8221 break;
8222
8223 case bitc::FS_BLOCK_COUNT:
8224 TheIndex.addBlockCount(C: Record[0]);
8225 break;
8226
8227 case bitc::FS_PARAM_ACCESS: {
8228 PendingParamAccesses = parseParamAccesses(Record);
8229 break;
8230 }
8231
8232 case bitc::FS_STACK_IDS: { // [n x stackid]
8233 // Save stack ids in the reader to consult when adding stack ids from the
8234 // lists in the stack node and alloc node entries.
8235 assert(StackIds.empty());
8236 if (Version <= 11) {
8237 StackIds = ArrayRef<uint64_t>(Record);
8238 } else {
8239 // This is an array of 32-bit fixed-width values, holding each 64-bit
8240 // context id as a pair of adjacent (most significant first) 32-bit
8241 // words.
8242 assert(Record.size() % 2 == 0);
8243 StackIds.reserve(n: Record.size() / 2);
8244 for (auto R = Record.begin(); R != Record.end(); R += 2)
8245 StackIds.push_back(x: *R << 32 | *(R + 1));
8246 }
8247 assert(StackIdToIndex.empty());
8248 // Initialize with a marker to support lazy population.
8249 StackIdToIndex.resize(new_size: StackIds.size(), x: UninitializedStackIdIndex);
8250 break;
8251 }
8252
8253 case bitc::FS_CONTEXT_RADIX_TREE_ARRAY: { // [n x entry]
8254 RadixArray = ArrayRef<uint64_t>(Record);
8255 break;
8256 }
8257
8258 case bitc::FS_PERMODULE_CALLSITE_INFO: {
8259 // If they are in the new order (following), they are skipped when they
8260 // follow a non-prevailing summary (CurrentPrevailingFS will be null).
8261 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8262 break;
8263 unsigned ValueID = Record[0];
8264 SmallVector<unsigned> StackIdList;
8265 for (uint64_t R : drop_begin(RangeOrContainer&: Record)) {
8266 assert(R < StackIds.size());
8267 StackIdList.push_back(Elt: getStackIdIndex(LocalIndex: R));
8268 }
8269 ValueInfo VI = std::get<0>(in: getValueInfoFromValueId(ValueId: ValueID));
8270 if (MemProfAfterFunctionSummary)
8271 CurrentPrevailingFS->addCallsite(
8272 Callsite: CallsiteInfo({VI, std::move(StackIdList)}));
8273 else
8274 PendingCallsites.push_back(x: CallsiteInfo({VI, std::move(StackIdList)}));
8275 break;
8276 }
8277
8278 case bitc::FS_COMBINED_CALLSITE_INFO: {
8279 // In the combined index case we don't have a prevailing check,
8280 // so we should always have a CurrentPrevailingFS.
8281 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8282 auto RecordIter = Record.begin();
8283 unsigned ValueID = *RecordIter++;
8284 unsigned NumStackIds = *RecordIter++;
8285 unsigned NumVersions = *RecordIter++;
8286 assert(Record.size() == 3 + NumStackIds + NumVersions);
8287 SmallVector<unsigned> StackIdList;
8288 for (unsigned J = 0; J < NumStackIds; J++) {
8289 assert(*RecordIter < StackIds.size());
8290 StackIdList.push_back(Elt: getStackIdIndex(LocalIndex: *RecordIter++));
8291 }
8292 SmallVector<unsigned> Versions;
8293 for (unsigned J = 0; J < NumVersions; J++)
8294 Versions.push_back(Elt: *RecordIter++);
8295 ValueInfo VI = std::get<0>(
8296 in: getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueId: ValueID));
8297 if (MemProfAfterFunctionSummary)
8298 CurrentPrevailingFS->addCallsite(
8299 Callsite: CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8300 else
8301 PendingCallsites.push_back(
8302 x: CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8303 break;
8304 }
8305
8306 case bitc::FS_ALLOC_CONTEXT_IDS: {
8307 // If they are in the new order (following), they are skipped when they
8308 // follow a non-prevailing summary (CurrentPrevailingFS will be null).
8309 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8310 break;
8311 // This is an array of 32-bit fixed-width values, holding each 64-bit
8312 // context id as a pair of adjacent (most significant first) 32-bit words.
8313 assert(Record.size() % 2 == 0);
8314 PendingContextIds.reserve(n: Record.size() / 2);
8315 for (auto R = Record.begin(); R != Record.end(); R += 2)
8316 PendingContextIds.push_back(x: *R << 32 | *(R + 1));
8317 break;
8318 }
8319
8320 case bitc::FS_PERMODULE_ALLOC_INFO: {
8321 // If they are in the new order (following), they are skipped when they
8322 // follow a non-prevailing summary (CurrentPrevailingFS will be null).
8323 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8324 PendingContextIds.clear();
8325 break;
8326 }
8327 unsigned I = 0;
8328 std::vector<MIBInfo> MIBs;
8329 unsigned NumMIBs = 0;
8330 if (Version >= 10)
8331 NumMIBs = Record[I++];
8332 unsigned MIBsRead = 0;
8333 while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8334 (Version < 10 && I < Record.size())) {
8335 assert(Record.size() - I >= 2);
8336 AllocationType AllocType = (AllocationType)Record[I++];
8337 auto StackIdList = parseAllocInfoContext(Record, I);
8338 MIBs.push_back(x: MIBInfo(AllocType, std::move(StackIdList)));
8339 }
8340 // We either have nothing left or at least NumMIBs context size info
8341 // indices left (for the total sizes included when reporting of hinted
8342 // bytes is enabled).
8343 assert(I == Record.size() || Record.size() - I >= NumMIBs);
8344 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8345 if (I < Record.size()) {
8346 assert(!PendingContextIds.empty() &&
8347 "Missing context ids for alloc sizes");
8348 unsigned ContextIdIndex = 0;
8349 MIBsRead = 0;
8350 // The sizes are a linearized array of sizes, where for each MIB there
8351 // is 1 or more sizes (due to context trimming, each MIB in the metadata
8352 // and summarized here can correspond to more than one original context
8353 // from the profile).
8354 while (MIBsRead++ < NumMIBs) {
8355 // First read the number of contexts recorded for this MIB.
8356 unsigned NumContextSizeInfoEntries = Record[I++];
8357 assert(Record.size() - I >= NumContextSizeInfoEntries);
8358 std::vector<ContextTotalSize> ContextSizes;
8359 ContextSizes.reserve(n: NumContextSizeInfoEntries);
8360 for (unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8361 assert(ContextIdIndex < PendingContextIds.size());
8362 // Skip any 0 entries for MIBs without the context size info.
8363 if (PendingContextIds[ContextIdIndex] == 0) {
8364 // The size should also be 0 if the context was 0.
8365 assert(!Record[I]);
8366 ContextIdIndex++;
8367 I++;
8368 continue;
8369 }
8370 // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8371 // should be in the same order as the total sizes.
8372 ContextSizes.push_back(
8373 x: {.FullStackId: PendingContextIds[ContextIdIndex++], .TotalSize: Record[I++]});
8374 }
8375 AllContextSizes.push_back(x: std::move(ContextSizes));
8376 }
8377 PendingContextIds.clear();
8378 }
8379 AllocInfo AI(std::move(MIBs));
8380 if (!AllContextSizes.empty()) {
8381 assert(AI.MIBs.size() == AllContextSizes.size());
8382 AI.ContextSizeInfos = std::move(AllContextSizes);
8383 }
8384
8385 if (MemProfAfterFunctionSummary)
8386 CurrentPrevailingFS->addAlloc(Alloc: std::move(AI));
8387 else
8388 PendingAllocs.push_back(x: std::move(AI));
8389 break;
8390 }
8391
8392 case bitc::FS_COMBINED_ALLOC_INFO:
8393 case bitc::FS_COMBINED_ALLOC_INFO_NO_CONTEXT: {
8394 // In the combined index case we don't have a prevailing check,
8395 // so we should always have a CurrentPrevailingFS.
8396 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8397 unsigned I = 0;
8398 std::vector<MIBInfo> MIBs;
8399 unsigned NumMIBs = Record[I++];
8400 unsigned NumVersions = Record[I++];
8401 unsigned MIBsRead = 0;
8402 while (MIBsRead++ < NumMIBs) {
8403 assert(Record.size() - I >= 2);
8404 AllocationType AllocType = (AllocationType)Record[I++];
8405 SmallVector<unsigned> StackIdList;
8406 if (BitCode == bitc::FS_COMBINED_ALLOC_INFO)
8407 StackIdList = parseAllocInfoContext(Record, I);
8408 MIBs.push_back(x: MIBInfo(AllocType, std::move(StackIdList)));
8409 }
8410 assert(Record.size() - I >= NumVersions);
8411 SmallVector<uint8_t> Versions;
8412 for (unsigned J = 0; J < NumVersions; J++)
8413 Versions.push_back(Elt: Record[I++]);
8414 assert(I == Record.size());
8415 AllocInfo AI(std::move(Versions), std::move(MIBs));
8416 if (MemProfAfterFunctionSummary)
8417 CurrentPrevailingFS->addAlloc(Alloc: std::move(AI));
8418 else
8419 PendingAllocs.push_back(x: std::move(AI));
8420 break;
8421 }
8422 }
8423 }
8424 llvm_unreachable("Exit infinite loop");
8425}
8426
8427// Parse the module string table block into the Index.
8428// This populates the ModulePathStringTable map in the index.
8429Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8430 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_STRTAB_BLOCK_ID))
8431 return Err;
8432
8433 SmallVector<uint64_t, 64> Record;
8434
8435 SmallString<128> ModulePath;
8436 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
8437
8438 while (true) {
8439 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8440 if (!MaybeEntry)
8441 return MaybeEntry.takeError();
8442 BitstreamEntry Entry = MaybeEntry.get();
8443
8444 switch (Entry.Kind) {
8445 case BitstreamEntry::SubBlock: // Handled for us already.
8446 case BitstreamEntry::Error:
8447 return error(Message: "Malformed block");
8448 case BitstreamEntry::EndBlock:
8449 return Error::success();
8450 case BitstreamEntry::Record:
8451 // The interesting case.
8452 break;
8453 }
8454
8455 Record.clear();
8456 Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
8457 if (!MaybeRecord)
8458 return MaybeRecord.takeError();
8459 switch (MaybeRecord.get()) {
8460 default: // Default behavior: ignore.
8461 break;
8462 case bitc::MST_CODE_ENTRY: {
8463 // MST_ENTRY: [modid, namechar x N]
8464 uint64_t ModuleId = Record[0];
8465
8466 if (convertToString(Record, Idx: 1, Result&: ModulePath))
8467 return error(Message: "Invalid code_entry record");
8468
8469 LastSeenModule = TheIndex.addModule(ModPath: ModulePath);
8470 ModuleIdMap[ModuleId] = LastSeenModule->first();
8471
8472 ModulePath.clear();
8473 break;
8474 }
8475 /// MST_CODE_HASH: [5*i32]
8476 case bitc::MST_CODE_HASH: {
8477 if (Record.size() != 5)
8478 return error(Message: "Invalid hash length " + Twine(Record.size()).str());
8479 if (!LastSeenModule)
8480 return error(Message: "Invalid hash that does not follow a module path");
8481 int Pos = 0;
8482 for (auto &Val : Record) {
8483 assert(!(Val >> 32) && "Unexpected high bits set");
8484 LastSeenModule->second[Pos++] = Val;
8485 }
8486 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8487 LastSeenModule = nullptr;
8488 break;
8489 }
8490 }
8491 }
8492 llvm_unreachable("Exit infinite loop");
8493}
8494
8495namespace {
8496
8497// FIXME: This class is only here to support the transition to llvm::Error. It
8498// will be removed once this transition is complete. Clients should prefer to
8499// deal with the Error value directly, rather than converting to error_code.
8500class BitcodeErrorCategoryType : public std::error_category {
8501 const char *name() const noexcept override {
8502 return "llvm.bitcode";
8503 }
8504
8505 std::string message(int IE) const override {
8506 BitcodeError E = static_cast<BitcodeError>(IE);
8507 switch (E) {
8508 case BitcodeError::CorruptedBitcode:
8509 return "Corrupted bitcode";
8510 }
8511 llvm_unreachable("Unknown error type!");
8512 }
8513};
8514
8515} // end anonymous namespace
8516
8517const std::error_category &llvm::BitcodeErrorCategory() {
8518 static BitcodeErrorCategoryType ErrorCategory;
8519 return ErrorCategory;
8520}
8521
8522static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
8523 unsigned Block, unsigned RecordID) {
8524 if (Error Err = Stream.EnterSubBlock(BlockID: Block))
8525 return std::move(Err);
8526
8527 StringRef Strtab;
8528 while (true) {
8529 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8530 if (!MaybeEntry)
8531 return MaybeEntry.takeError();
8532 llvm::BitstreamEntry Entry = MaybeEntry.get();
8533
8534 switch (Entry.Kind) {
8535 case BitstreamEntry::EndBlock:
8536 return Strtab;
8537
8538 case BitstreamEntry::Error:
8539 return error(Message: "Malformed block");
8540
8541 case BitstreamEntry::SubBlock:
8542 if (Error Err = Stream.SkipBlock())
8543 return std::move(Err);
8544 break;
8545
8546 case BitstreamEntry::Record:
8547 StringRef Blob;
8548 SmallVector<uint64_t, 1> Record;
8549 Expected<unsigned> MaybeRecord =
8550 Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob);
8551 if (!MaybeRecord)
8552 return MaybeRecord.takeError();
8553 if (MaybeRecord.get() == RecordID)
8554 Strtab = Blob;
8555 break;
8556 }
8557 }
8558}
8559
8560//===----------------------------------------------------------------------===//
8561// External interface
8562//===----------------------------------------------------------------------===//
8563
8564Expected<std::vector<BitcodeModule>>
8565llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
8566 auto FOrErr = getBitcodeFileContents(Buffer);
8567 if (!FOrErr)
8568 return FOrErr.takeError();
8569 return std::move(FOrErr->Mods);
8570}
8571
8572Expected<BitcodeFileContents>
8573llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
8574 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8575 if (!StreamOrErr)
8576 return StreamOrErr.takeError();
8577 BitstreamCursor &Stream = *StreamOrErr;
8578
8579 BitcodeFileContents F;
8580 while (true) {
8581 uint64_t BCBegin = Stream.getCurrentByteNo();
8582
8583 // We may be consuming bitcode from a client that leaves garbage at the end
8584 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8585 // the end that there cannot possibly be another module, stop looking.
8586 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
8587 return F;
8588
8589 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8590 if (!MaybeEntry)
8591 return MaybeEntry.takeError();
8592 llvm::BitstreamEntry Entry = MaybeEntry.get();
8593
8594 switch (Entry.Kind) {
8595 case BitstreamEntry::EndBlock:
8596 case BitstreamEntry::Error:
8597 return error(Message: "Malformed block");
8598
8599 case BitstreamEntry::SubBlock: {
8600 uint64_t IdentificationBit = -1ull;
8601 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
8602 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8603 if (Error Err = Stream.SkipBlock())
8604 return std::move(Err);
8605
8606 {
8607 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8608 if (!MaybeEntry)
8609 return MaybeEntry.takeError();
8610 Entry = MaybeEntry.get();
8611 }
8612
8613 if (Entry.Kind != BitstreamEntry::SubBlock ||
8614 Entry.ID != bitc::MODULE_BLOCK_ID)
8615 return error(Message: "Malformed block");
8616 }
8617
8618 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
8619 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8620 if (Error Err = Stream.SkipBlock())
8621 return std::move(Err);
8622
8623 F.Mods.push_back(x: {Stream.getBitcodeBytes().slice(
8624 N: BCBegin, M: Stream.getCurrentByteNo() - BCBegin),
8625 Buffer.getBufferIdentifier(), IdentificationBit,
8626 ModuleBit});
8627 continue;
8628 }
8629
8630 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
8631 Expected<StringRef> Strtab =
8632 readBlobInRecord(Stream, Block: bitc::STRTAB_BLOCK_ID, RecordID: bitc::STRTAB_BLOB);
8633 if (!Strtab)
8634 return Strtab.takeError();
8635 // This string table is used by every preceding bitcode module that does
8636 // not have its own string table. A bitcode file may have multiple
8637 // string tables if it was created by binary concatenation, for example
8638 // with "llvm-cat -b".
8639 for (BitcodeModule &I : llvm::reverse(C&: F.Mods)) {
8640 if (!I.Strtab.empty())
8641 break;
8642 I.Strtab = *Strtab;
8643 }
8644 // Similarly, the string table is used by every preceding symbol table;
8645 // normally there will be just one unless the bitcode file was created
8646 // by binary concatenation.
8647 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
8648 F.StrtabForSymtab = *Strtab;
8649 continue;
8650 }
8651
8652 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
8653 Expected<StringRef> SymtabOrErr =
8654 readBlobInRecord(Stream, Block: bitc::SYMTAB_BLOCK_ID, RecordID: bitc::SYMTAB_BLOB);
8655 if (!SymtabOrErr)
8656 return SymtabOrErr.takeError();
8657
8658 // We can expect the bitcode file to have multiple symbol tables if it
8659 // was created by binary concatenation. In that case we silently
8660 // ignore any subsequent symbol tables, which is fine because this is a
8661 // low level function. The client is expected to notice that the number
8662 // of modules in the symbol table does not match the number of modules
8663 // in the input file and regenerate the symbol table.
8664 if (F.Symtab.empty())
8665 F.Symtab = *SymtabOrErr;
8666 continue;
8667 }
8668
8669 if (Error Err = Stream.SkipBlock())
8670 return std::move(Err);
8671 continue;
8672 }
8673 case BitstreamEntry::Record:
8674 if (Error E = Stream.skipRecord(AbbrevID: Entry.ID).takeError())
8675 return std::move(E);
8676 continue;
8677 }
8678 }
8679}
8680
8681/// Get a lazy one-at-time loading module from bitcode.
8682///
8683/// This isn't always used in a lazy context. In particular, it's also used by
8684/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
8685/// in forward-referenced functions from block address references.
8686///
8687/// \param[in] MaterializeAll Set to \c true if we should materialize
8688/// everything.
8689Expected<std::unique_ptr<Module>>
8690BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
8691 bool ShouldLazyLoadMetadata, bool IsImporting,
8692 ParserCallbacks Callbacks) {
8693 BitstreamCursor Stream(Buffer);
8694
8695 std::string ProducerIdentification;
8696 if (IdentificationBit != -1ull) {
8697 if (Error JumpFailed = Stream.JumpToBit(BitNo: IdentificationBit))
8698 return std::move(JumpFailed);
8699 if (Error E =
8700 readIdentificationBlock(Stream).moveInto(Value&: ProducerIdentification))
8701 return std::move(E);
8702 }
8703
8704 if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit))
8705 return std::move(JumpFailed);
8706 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8707 Context);
8708
8709 std::unique_ptr<Module> M =
8710 std::make_unique<Module>(args&: ModuleIdentifier, args&: Context);
8711 M->setMaterializer(R);
8712
8713 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8714 if (Error Err = R->parseBitcodeInto(M: M.get(), ShouldLazyLoadMetadata,
8715 IsImporting, Callbacks))
8716 return std::move(Err);
8717
8718 if (MaterializeAll) {
8719 // Read in the entire module, and destroy the BitcodeReader.
8720 if (Error Err = M->materializeAll())
8721 return std::move(Err);
8722 } else {
8723 // Resolve forward references from blockaddresses.
8724 if (Error Err = R->materializeForwardReferencedFunctions())
8725 return std::move(Err);
8726 }
8727
8728 return std::move(M);
8729}
8730
8731Expected<std::unique_ptr<Module>>
8732BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8733 bool IsImporting, ParserCallbacks Callbacks) {
8734 return getModuleImpl(Context, MaterializeAll: false, ShouldLazyLoadMetadata, IsImporting,
8735 Callbacks);
8736}
8737
8738// Parse the specified bitcode buffer and merge the index into CombinedIndex.
8739// We don't use ModuleIdentifier here because the client may need to control the
8740// module path used in the combined summary (e.g. when reading summaries for
8741// regular LTO modules).
8742Error BitcodeModule::readSummary(
8743 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8744 std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8745 BitstreamCursor Stream(Buffer);
8746 if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit))
8747 return JumpFailed;
8748
8749 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8750 ModulePath, IsPrevailing);
8751 return R.parseModule();
8752}
8753
8754// Parse the specified bitcode buffer, returning the function info index.
8755Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
8756 BitstreamCursor Stream(Buffer);
8757 if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit))
8758 return std::move(JumpFailed);
8759
8760 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/args: false);
8761 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8762 ModuleIdentifier, 0);
8763
8764 if (Error Err = R.parseModule())
8765 return std::move(Err);
8766
8767 return std::move(Index);
8768}
8769
8770static Expected<std::pair<bool, bool>>
8771getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID) {
8772 if (Error Err = Stream.EnterSubBlock(BlockID: ID))
8773 return std::move(Err);
8774
8775 SmallVector<uint64_t, 64> Record;
8776 while (true) {
8777 BitstreamEntry Entry;
8778 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Value&: Entry))
8779 return std::move(E);
8780
8781 switch (Entry.Kind) {
8782 case BitstreamEntry::SubBlock: // Handled for us already.
8783 case BitstreamEntry::Error:
8784 return error(Message: "Malformed block");
8785 case BitstreamEntry::EndBlock: {
8786 // If no flags record found, return both flags as false.
8787 return std::make_pair(x: false, y: false);
8788 }
8789 case BitstreamEntry::Record:
8790 // The interesting case.
8791 break;
8792 }
8793
8794 // Look for the FS_FLAGS record.
8795 Record.clear();
8796 Expected<unsigned> MaybeBitCode = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record);
8797 if (!MaybeBitCode)
8798 return MaybeBitCode.takeError();
8799 switch (MaybeBitCode.get()) {
8800 default: // Default behavior: ignore.
8801 break;
8802 case bitc::FS_FLAGS: { // [flags]
8803 uint64_t Flags = Record[0];
8804 // Scan flags.
8805 assert(Flags <= 0x7ff && "Unexpected bits in flag");
8806
8807 bool EnableSplitLTOUnit = Flags & 0x8;
8808 bool UnifiedLTO = Flags & 0x200;
8809 return std::make_pair(x&: EnableSplitLTOUnit, y&: UnifiedLTO);
8810 }
8811 }
8812 }
8813 llvm_unreachable("Exit infinite loop");
8814}
8815
8816// Check if the given bitcode buffer contains a global value summary block.
8817Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
8818 BitstreamCursor Stream(Buffer);
8819 if (Error JumpFailed = Stream.JumpToBit(BitNo: ModuleBit))
8820 return std::move(JumpFailed);
8821
8822 if (Error Err = Stream.EnterSubBlock(BlockID: bitc::MODULE_BLOCK_ID))
8823 return std::move(Err);
8824
8825 while (true) {
8826 llvm::BitstreamEntry Entry;
8827 if (Error E = Stream.advance().moveInto(Value&: Entry))
8828 return std::move(E);
8829
8830 switch (Entry.Kind) {
8831 case BitstreamEntry::Error:
8832 return error(Message: "Malformed block");
8833 case BitstreamEntry::EndBlock:
8834 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8835 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8836
8837 case BitstreamEntry::SubBlock:
8838 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID ||
8839 Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
8840 Expected<std::pair<bool, bool>> Flags =
8841 getEnableSplitLTOUnitAndUnifiedFlag(Stream, ID: Entry.ID);
8842 if (!Flags)
8843 return Flags.takeError();
8844 BitcodeLTOInfo LTOInfo;
8845 std::tie(args&: LTOInfo.EnableSplitLTOUnit, args&: LTOInfo.UnifiedLTO) = Flags.get();
8846 LTOInfo.IsThinLTO = (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID);
8847 LTOInfo.HasSummary = true;
8848 return LTOInfo;
8849 }
8850
8851 // Ignore other sub-blocks.
8852 if (Error Err = Stream.SkipBlock())
8853 return std::move(Err);
8854 continue;
8855
8856 case BitstreamEntry::Record:
8857 if (Expected<unsigned> StreamFailed = Stream.skipRecord(AbbrevID: Entry.ID))
8858 continue;
8859 else
8860 return StreamFailed.takeError();
8861 }
8862 }
8863}
8864
8865static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
8866 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
8867 if (!MsOrErr)
8868 return MsOrErr.takeError();
8869
8870 if (MsOrErr->size() != 1)
8871 return error(Message: "Expected a single module");
8872
8873 return (*MsOrErr)[0];
8874}
8875
8876Expected<std::unique_ptr<Module>>
8877llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8878 bool ShouldLazyLoadMetadata, bool IsImporting,
8879 ParserCallbacks Callbacks) {
8880 Expected<BitcodeModule> BM = getSingleModule(Buffer);
8881 if (!BM)
8882 return BM.takeError();
8883
8884 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8885 Callbacks);
8886}
8887
8888Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
8889 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8890 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8891 auto MOrErr = getLazyBitcodeModule(Buffer: *Buffer, Context, ShouldLazyLoadMetadata,
8892 IsImporting, Callbacks);
8893 if (MOrErr)
8894 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8895 return MOrErr;
8896}
8897
8898Expected<std::unique_ptr<Module>>
8899BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8900 return getModuleImpl(Context, MaterializeAll: true, ShouldLazyLoadMetadata: false, IsImporting: false, Callbacks);
8901 // TODO: Restore the use-lists to the in-memory state when the bitcode was
8902 // written. We must defer until the Module has been fully materialized.
8903}
8904
8905Expected<std::unique_ptr<Module>>
8906llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8907 ParserCallbacks Callbacks) {
8908 Expected<BitcodeModule> BM = getSingleModule(Buffer);
8909 if (!BM)
8910 return BM.takeError();
8911
8912 return BM->parseModule(Context, Callbacks);
8913}
8914
8915Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
8916 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8917 if (!StreamOrErr)
8918 return StreamOrErr.takeError();
8919
8920 return readTriple(Stream&: *StreamOrErr);
8921}
8922
8923Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
8924 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8925 if (!StreamOrErr)
8926 return StreamOrErr.takeError();
8927
8928 return hasObjCCategory(Stream&: *StreamOrErr);
8929}
8930
8931Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
8932 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8933 if (!StreamOrErr)
8934 return StreamOrErr.takeError();
8935
8936 return readIdentificationCode(Stream&: *StreamOrErr);
8937}
8938
8939Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8940 ModuleSummaryIndex &CombinedIndex) {
8941 Expected<BitcodeModule> BM = getSingleModule(Buffer);
8942 if (!BM)
8943 return BM.takeError();
8944
8945 return BM->readSummary(CombinedIndex, ModulePath: BM->getModuleIdentifier());
8946}
8947
8948Expected<std::unique_ptr<ModuleSummaryIndex>>
8949llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
8950 Expected<BitcodeModule> BM = getSingleModule(Buffer);
8951 if (!BM)
8952 return BM.takeError();
8953
8954 return BM->getSummary();
8955}
8956
8957Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
8958 Expected<BitcodeModule> BM = getSingleModule(Buffer);
8959 if (!BM)
8960 return BM.takeError();
8961
8962 return BM->getLTOInfo();
8963}
8964
8965Expected<std::unique_ptr<ModuleSummaryIndex>>
8966llvm::getModuleSummaryIndexForFile(StringRef Path,
8967 bool IgnoreEmptyThinLTOIndexFile) {
8968 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
8969 MemoryBuffer::getFileOrSTDIN(Filename: Path);
8970 if (!FileOrErr)
8971 return errorCodeToError(EC: FileOrErr.getError());
8972 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8973 return nullptr;
8974 return getModuleSummaryIndex(Buffer: **FileOrErr);
8975}
8976