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