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