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