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