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