1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
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
7 //===----------------------------------------------------------------------===//
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"
88 #include <system_error>
95 static cl::opt
<bool> PrintSummaryGUIDs(
96 "print-summary-global-ids", cl::init(false), cl::Hidden
,
98 "Print the global id for each value when reading the module summary"));
100 static cl::opt
<bool> ExpandConstantExprs(
101 "expand-constant-exprs", cl::Hidden
,
103 "Expand constant expressions to instructions for testing purposes"));
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.
109 cl::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)"));
113 extern cl::opt
<bool> UseNewDbgInfoFormat
;
114 extern cl::opt
<cl::boolOrDefault
> PreserveInputDbgFormat
;
115 extern bool WriteNewDbgInfoFormatToBitcode
;
116 extern cl::opt
<bool> WriteNewDbgInfoFormat
;
121 SWITCH_INST_MAGIC
= 0x4B5 // May 2012 => 1205 => Hex
124 } // end anonymous namespace
126 static Error
error(const Twine
&Message
) {
127 return make_error
<StringError
>(
128 Message
, make_error_code(BitcodeError::CorruptedBitcode
));
131 static Error
hasInvalidBitcodeHeader(BitstreamCursor
&Stream
) {
132 if (!Stream
.canSkipToPos(4))
133 return createStringError(std::errc::illegal_byte_sequence
,
134 "file too small to contain bitcode header");
135 for (unsigned C
: {'B', 'C'})
136 if (Expected
<SimpleBitstreamCursor::word_t
> Res
= Stream
.Read(8)) {
138 return createStringError(std::errc::illegal_byte_sequence
,
139 "file doesn't start with bitcode header");
141 return Res
.takeError();
142 for (unsigned C
: {0x0, 0xC, 0xE, 0xD})
143 if (Expected
<SimpleBitstreamCursor::word_t
> Res
= Stream
.Read(4)) {
145 return createStringError(std::errc::illegal_byte_sequence
,
146 "file doesn't start with bitcode header");
148 return Res
.takeError();
149 return Error::success();
152 static Expected
<BitstreamCursor
> initStream(MemoryBufferRef Buffer
) {
153 const unsigned char *BufPtr
= (const unsigned char *)Buffer
.getBufferStart();
154 const unsigned char *BufEnd
= BufPtr
+ Buffer
.getBufferSize();
156 if (Buffer
.getBufferSize() & 3)
157 return error("Invalid bitcode signature");
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
, true))
163 return error("Invalid bitcode wrapper header");
165 BitstreamCursor
Stream(ArrayRef
<uint8_t>(BufPtr
, BufEnd
));
166 if (Error Err
= hasInvalidBitcodeHeader(Stream
))
167 return std::move(Err
);
169 return std::move(Stream
);
172 /// Convert a string from a record into an std::string, return true on failure.
173 template <typename StrTy
>
174 static bool convertToString(ArrayRef
<uint64_t> Record
, unsigned Idx
,
176 if (Idx
> Record
.size())
179 Result
.append(Record
.begin() + Idx
, Record
.end());
183 // Strip all the TBAA attachment for the module.
184 static void stripTBAA(Module
*M
) {
186 if (F
.isMaterializable())
188 for (auto &I
: instructions(F
))
189 I
.setMetadata(LLVMContext::MD_tbaa
, nullptr);
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.
195 static Expected
<std::string
> readIdentificationBlock(BitstreamCursor
&Stream
) {
196 if (Error Err
= Stream
.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID
))
197 return std::move(Err
);
199 // Read all the records.
200 SmallVector
<uint64_t, 64> Record
;
202 std::string ProducerIdentification
;
205 BitstreamEntry Entry
;
206 if (Error E
= Stream
.advance().moveInto(Entry
))
209 switch (Entry
.Kind
) {
211 case BitstreamEntry::Error
:
212 return error("Malformed block");
213 case BitstreamEntry::EndBlock
:
214 return ProducerIdentification
;
215 case BitstreamEntry::Record
:
216 // The interesting case.
222 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
224 return MaybeBitCode
.takeError();
225 switch (MaybeBitCode
.get()) {
226 default: // Default behavior: reject
227 return error("Invalid value");
228 case bitc::IDENTIFICATION_CODE_STRING
: // IDENTIFICATION: [strchr x N]
229 convertToString(Record
, 0, ProducerIdentification
);
231 case bitc::IDENTIFICATION_CODE_EPOCH
: { // EPOCH: [epoch#]
232 unsigned epoch
= (unsigned)Record
[0];
233 if (epoch
!= bitc::BITCODE_CURRENT_EPOCH
) {
235 Twine("Incompatible epoch: Bitcode '") + Twine(epoch
) +
236 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH
) + "'");
243 static 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.
247 if (Stream
.AtEndOfStream())
250 BitstreamEntry Entry
;
251 if (Error E
= Stream
.advance().moveInto(Entry
))
254 switch (Entry
.Kind
) {
255 case BitstreamEntry::EndBlock
:
256 case BitstreamEntry::Error
:
257 return error("Malformed block");
259 case BitstreamEntry::SubBlock
:
260 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
)
261 return readIdentificationBlock(Stream
);
263 // Ignore other sub-blocks.
264 if (Error Err
= Stream
.SkipBlock())
265 return std::move(Err
);
267 case BitstreamEntry::Record
:
268 if (Error E
= Stream
.skipRecord(Entry
.ID
).takeError())
275 static Expected
<bool> hasObjCCategoryInModule(BitstreamCursor
&Stream
) {
276 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
277 return std::move(Err
);
279 SmallVector
<uint64_t, 64> Record
;
280 // Read all the records for this module.
283 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
285 return MaybeEntry
.takeError();
286 BitstreamEntry Entry
= MaybeEntry
.get();
288 switch (Entry
.Kind
) {
289 case BitstreamEntry::SubBlock
: // Handled for us already.
290 case BitstreamEntry::Error
:
291 return error("Malformed block");
292 case BitstreamEntry::EndBlock
:
294 case BitstreamEntry::Record
:
295 // The interesting case.
300 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
302 return MaybeRecord
.takeError();
303 switch (MaybeRecord
.get()) {
305 break; // Default behavior, ignore unknown content.
306 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
308 if (convertToString(Record
, 0, S
))
309 return error("Invalid section name record");
310 // Check for the i386 and other (x86_64, ARM) conventions
311 if (S
.find("__DATA,__objc_catlist") != std::string::npos
||
312 S
.find("__OBJC,__category") != std::string::npos
||
313 S
.find("__TEXT,__swift") != std::string::npos
)
320 llvm_unreachable("Exit infinite loop");
323 static 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.
327 BitstreamEntry Entry
;
328 if (Error E
= Stream
.advance().moveInto(Entry
))
331 switch (Entry
.Kind
) {
332 case BitstreamEntry::Error
:
333 return error("Malformed block");
334 case BitstreamEntry::EndBlock
:
337 case BitstreamEntry::SubBlock
:
338 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
339 return hasObjCCategoryInModule(Stream
);
341 // Ignore other sub-blocks.
342 if (Error Err
= Stream
.SkipBlock())
343 return std::move(Err
);
346 case BitstreamEntry::Record
:
347 if (Error E
= Stream
.skipRecord(Entry
.ID
).takeError())
354 static Expected
<std::string
> readModuleTriple(BitstreamCursor
&Stream
) {
355 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
356 return std::move(Err
);
358 SmallVector
<uint64_t, 64> Record
;
362 // Read all the records for this module.
364 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
366 return MaybeEntry
.takeError();
367 BitstreamEntry Entry
= MaybeEntry
.get();
369 switch (Entry
.Kind
) {
370 case BitstreamEntry::SubBlock
: // Handled for us already.
371 case BitstreamEntry::Error
:
372 return error("Malformed block");
373 case BitstreamEntry::EndBlock
:
375 case BitstreamEntry::Record
:
376 // The interesting case.
381 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
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]
388 if (convertToString(Record
, 0, S
))
389 return error("Invalid triple record");
396 llvm_unreachable("Exit infinite loop");
399 static 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.
403 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advance();
405 return MaybeEntry
.takeError();
406 BitstreamEntry Entry
= MaybeEntry
.get();
408 switch (Entry
.Kind
) {
409 case BitstreamEntry::Error
:
410 return error("Malformed block");
411 case BitstreamEntry::EndBlock
:
414 case BitstreamEntry::SubBlock
:
415 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
416 return readModuleTriple(Stream
);
418 // Ignore other sub-blocks.
419 if (Error Err
= Stream
.SkipBlock())
420 return std::move(Err
);
423 case BitstreamEntry::Record
:
424 if (llvm::Expected
<unsigned> Skipped
= Stream
.skipRecord(Entry
.ID
))
427 return Skipped
.takeError();
434 class BitcodeReaderBase
{
436 BitcodeReaderBase(BitstreamCursor Stream
, StringRef Strtab
)
437 : Stream(std::move(Stream
)), Strtab(Strtab
) {
438 this->Stream
.setBlockInfo(&BlockInfo
);
441 BitstreamBlockInfo BlockInfo
;
442 BitstreamCursor Stream
;
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;
449 Expected
<unsigned> parseVersionRecord(ArrayRef
<uint64_t> Record
);
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
);
457 Error
readBlockInfo();
459 // Contains an arbitrary and optional string identifying the bitcode producer
460 std::string ProducerIdentification
;
462 Error
error(const Twine
&Message
);
465 } // end anonymous namespace
467 Error
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(FullMsg
);
476 BitcodeReaderBase::parseVersionRecord(ArrayRef
<uint64_t> Record
) {
478 return error("Invalid version record");
479 unsigned ModuleVersion
= Record
[0];
480 if (ModuleVersion
> 2)
481 return error("Invalid value");
482 UseStrtab
= ModuleVersion
>= 2;
483 return ModuleVersion
;
486 std::pair
<StringRef
, ArrayRef
<uint64_t>>
487 BitcodeReaderBase::readNameFromStrtab(ArrayRef
<uint64_t> Record
) {
490 // Invalid reference. Let the caller complain about the record being empty.
491 if (Record
[0] + Record
[1] > Strtab
.size())
493 return {StringRef(Strtab
.data() + Record
[0], Record
[1]), Record
.slice(2)};
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.
504 class BitcodeConstant final
: public Value
,
505 TrailingObjects
<BitcodeConstant
, unsigned> {
506 friend TrailingObjects
;
508 // Value subclass ID: Pick largest possible value to avoid any clashes.
509 static constexpr uint8_t SubclassID
= 255;
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
;
526 // Separate struct to make passing different number of parameters to
527 // BitcodeConstant::create() more convenient.
531 unsigned BlockAddressBB
= 0;
532 Type
*SrcElemTy
= nullptr;
533 std::optional
<ConstantRange
> InRange
;
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
)) {}
540 ExtraInfo(uint8_t Opcode
, uint8_t Flags
, unsigned BlockAddressBB
)
541 : Opcode(Opcode
), Flags(Flags
), BlockAddressBB(BlockAddressBB
) {}
546 unsigned NumOperands
;
547 unsigned BlockAddressBB
;
548 Type
*SrcElemTy
; // GEP source element type.
549 std::optional
<ConstantRange
> InRange
; // GEP inrange attribute.
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(OpIDs
.begin(), OpIDs
.end(),
557 getTrailingObjects
<unsigned>());
560 BitcodeConstant
&operator=(const BitcodeConstant
&) = delete;
563 static BitcodeConstant
*create(BumpPtrAllocator
&A
, Type
*Ty
,
564 const ExtraInfo
&Info
,
565 ArrayRef
<unsigned> OpIDs
) {
566 void *Mem
= A
.Allocate(totalSizeToAlloc
<unsigned>(OpIDs
.size()),
567 alignof(BitcodeConstant
));
568 return new (Mem
) BitcodeConstant(Ty
, Info
, OpIDs
);
571 static bool classof(const Value
*V
) { return V
->getValueID() == SubclassID
; }
573 ArrayRef
<unsigned> getOperandIDs() const {
574 return ArrayRef(getTrailingObjects
<unsigned>(), NumOperands
);
577 std::optional
<ConstantRange
> getInRange() const {
578 assert(Opcode
== Instruction::GetElementPtr
);
582 const char *getOpcodeName() const {
583 return Instruction::getOpcodeName(Opcode
);
587 class 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;
597 std::vector
<std::string
> SectionTable
;
598 std::vector
<std::string
> GCTable
;
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
;
623 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInits
;
624 std::vector
<std::pair
<GlobalValue
*, unsigned>> IndirectSymbolInits
;
626 struct FunctionOperandInfo
{
628 unsigned PersonalityFn
;
632 std::vector
<FunctionOperandInfo
> FunctionOperands
;
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
;
638 /// The set of attribute groups.
639 std::map
<unsigned, AttributeList
> MAttributeGroups
;
641 /// While parsing a function body, this is a list of the basic blocks for the
643 std::vector
<BasicBlock
*> FunctionBBs
;
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
;
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
;
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;
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
;
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
;
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
;
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
;
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;
689 /// True if all functions will be materialized, negating the need to process
690 /// (e.g.) blockaddress forward references.
691 bool WillMaterializeAllForwardRefs
= false;
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;
698 bool StripDebugInfo
= false;
699 TBAAVerifier TBAAVerifyHelper
;
701 std::vector
<std::string
> BundleTags
;
702 SmallVector
<SyncScope::ID
, 8> SSIDs
;
704 std::optional
<ValueTypeCallbackTy
> ValueTypeCallback
;
707 BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
708 StringRef ProducerIdentification
, LLVMContext
&Context
);
710 Error
materializeForwardReferencedFunctions();
712 Error
materialize(GlobalValue
*GV
) override
;
713 Error
materializeModule() override
;
714 std::vector
<StructType
*> getIdentifiedStructTypes() const override
;
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
= {});
721 static uint64_t decodeSignRotatedValue(uint64_t V
);
723 /// Materialize any deferred Metadata block.
724 Error
materializeMetadata() override
;
726 void setStripDebugInfo() override
;
729 std::vector
<StructType
*> IdentifiedStructTypes
;
730 StructType
*createIdentifiedStructType(LLVMContext
&Context
, StringRef Name
);
731 StructType
*createIdentifiedStructType(LLVMContext
&Context
);
733 static constexpr unsigned InvalidTypeID
= ~0u;
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
= {});
740 void callValueTypeCallback(Value
*F
, unsigned TypeID
);
741 Expected
<Value
*> materializeValue(unsigned ValID
, BasicBlock
*InsertBB
);
742 Expected
<Constant
*> getValueForInitializer(unsigned ID
);
744 Value
*getFnValueByID(unsigned ID
, Type
*Ty
, unsigned TyID
,
745 BasicBlock
*ConstExprInsertBB
) {
746 if (Ty
&& Ty
->isMetadataTy())
747 return MetadataAsValue::get(Ty
->getContext(), getFnMetadataByID(ID
));
748 return ValueList
.getValueFwdRef(ID
, Ty
, TyID
, ConstExprInsertBB
);
751 Metadata
*getFnMetadataByID(unsigned ID
) {
752 return MDLoader
->getMetadataFwdRefOrLoad(ID
);
755 BasicBlock
*getBasicBlock(unsigned ID
) const {
756 if (ID
>= FunctionBBs
.size()) return nullptr; // Invalid ID
757 return FunctionBBs
[ID
];
760 AttributeList
getAttributes(unsigned i
) const {
761 if (i
-1 < MAttributes
.size())
762 return MAttributes
[i
-1];
763 return AttributeList();
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
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.
776 ValNo
= InstNum
- ValNo
;
777 if (ValNo
< InstNum
) {
778 // If this is not a forward reference, just return the value we already
780 TypeID
= ValueList
.getTypeID(ValNo
);
781 ResVal
= getFnValueByID(ValNo
, nullptr, TypeID
, ConstExprInsertBB
);
782 assert((!ResVal
|| ResVal
->getType() == getTypeByID(TypeID
)) &&
783 "Incorrect type ID stored for value");
784 return ResVal
== nullptr;
786 if (Slot
== Record
.size())
789 TypeID
= (unsigned)Record
[Slot
++];
790 ResVal
= getFnValueByID(ValNo
, getTypeByID(TypeID
), TypeID
,
792 return ResVal
== nullptr;
795 bool getValueOrMetadata(const SmallVectorImpl
<uint64_t> &Record
,
796 unsigned &Slot
, unsigned InstNum
, Value
*&ResVal
,
797 BasicBlock
*ConstExprInsertBB
) {
798 if (Slot
== Record
.size())
800 unsigned ValID
= Record
[Slot
++];
801 if (ValID
!= static_cast<unsigned>(bitc::OB_METADATA
)) {
803 return getValueTypePair(Record
, --Slot
, InstNum
, ResVal
, TypeId
,
806 if (Slot
== Record
.size())
808 unsigned ValNo
= InstNum
- (unsigned)Record
[Slot
++];
809 ResVal
= MetadataAsValue::get(Context
, getFnMetadataByID(ValNo
));
813 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
814 /// past the number of slots used by the value in the record. Return true if
815 /// there is an error.
816 bool popValue(const SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
817 unsigned InstNum
, Type
*Ty
, unsigned TyID
, Value
*&ResVal
,
818 BasicBlock
*ConstExprInsertBB
) {
819 if (getValue(Record
, Slot
, InstNum
, Ty
, TyID
, ResVal
, ConstExprInsertBB
))
821 // All values currently take a single record slot.
826 /// Like popValue, but does not increment the Slot number.
827 bool getValue(const SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
828 unsigned InstNum
, Type
*Ty
, unsigned TyID
, Value
*&ResVal
,
829 BasicBlock
*ConstExprInsertBB
) {
830 ResVal
= getValue(Record
, Slot
, InstNum
, Ty
, TyID
, ConstExprInsertBB
);
831 return ResVal
== nullptr;
834 /// Version of getValue that returns ResVal directly, or 0 if there is an
836 Value
*getValue(const SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
837 unsigned InstNum
, Type
*Ty
, unsigned TyID
,
838 BasicBlock
*ConstExprInsertBB
) {
839 if (Slot
== Record
.size()) return nullptr;
840 unsigned ValNo
= (unsigned)Record
[Slot
];
841 // Adjust the ValNo, if it was encoded relative to the InstNum.
843 ValNo
= InstNum
- ValNo
;
844 return getFnValueByID(ValNo
, Ty
, TyID
, ConstExprInsertBB
);
847 /// Like getValue, but decodes signed VBRs.
848 Value
*getValueSigned(const SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
849 unsigned InstNum
, Type
*Ty
, unsigned TyID
,
850 BasicBlock
*ConstExprInsertBB
) {
851 if (Slot
== Record
.size()) return nullptr;
852 unsigned ValNo
= (unsigned)decodeSignRotatedValue(Record
[Slot
]);
853 // Adjust the ValNo, if it was encoded relative to the InstNum.
855 ValNo
= InstNum
- ValNo
;
856 return getFnValueByID(ValNo
, Ty
, TyID
, ConstExprInsertBB
);
859 Expected
<ConstantRange
> readConstantRange(ArrayRef
<uint64_t> Record
,
862 if (Record
.size() - OpNum
< 2)
863 return error("Too few records for range");
865 unsigned LowerActiveWords
= Record
[OpNum
];
866 unsigned UpperActiveWords
= Record
[OpNum
++] >> 32;
867 if (Record
.size() - OpNum
< LowerActiveWords
+ UpperActiveWords
)
868 return error("Too few records for range");
870 readWideAPInt(ArrayRef(&Record
[OpNum
], LowerActiveWords
), BitWidth
);
871 OpNum
+= LowerActiveWords
;
873 readWideAPInt(ArrayRef(&Record
[OpNum
], UpperActiveWords
), BitWidth
);
874 OpNum
+= UpperActiveWords
;
875 return ConstantRange(Lower
, Upper
);
877 int64_t Start
= BitcodeReader::decodeSignRotatedValue(Record
[OpNum
++]);
878 int64_t End
= BitcodeReader::decodeSignRotatedValue(Record
[OpNum
++]);
879 return ConstantRange(APInt(BitWidth
, Start
, true),
880 APInt(BitWidth
, End
, true));
884 Expected
<ConstantRange
>
885 readBitWidthAndConstantRange(ArrayRef
<uint64_t> Record
, unsigned &OpNum
) {
886 if (Record
.size() - OpNum
< 1)
887 return error("Too few records for range");
888 unsigned BitWidth
= Record
[OpNum
++];
889 return readConstantRange(Record
, OpNum
, BitWidth
);
892 /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
893 /// corresponding argument's pointee type. Also upgrades intrinsics that now
894 /// require an elementtype attribute.
895 Error
propagateAttributeTypes(CallBase
*CB
, ArrayRef
<unsigned> ArgsTys
);
897 /// Converts alignment exponent (i.e. power of two (or zero)) to the
898 /// corresponding alignment to use. If alignment is too large, returns
899 /// a corresponding error code.
900 Error
parseAlignmentValue(uint64_t Exponent
, MaybeAlign
&Alignment
);
901 Error
parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
);
902 Error
parseModule(uint64_t ResumeBit
, bool ShouldLazyLoadMetadata
= false,
903 ParserCallbacks Callbacks
= {});
905 Error
parseComdatRecord(ArrayRef
<uint64_t> Record
);
906 Error
parseGlobalVarRecord(ArrayRef
<uint64_t> Record
);
907 Error
parseFunctionRecord(ArrayRef
<uint64_t> Record
);
908 Error
parseGlobalIndirectSymbolRecord(unsigned BitCode
,
909 ArrayRef
<uint64_t> Record
);
911 Error
parseAttributeBlock();
912 Error
parseAttributeGroupBlock();
913 Error
parseTypeTable();
914 Error
parseTypeTableBody();
915 Error
parseOperandBundleTags();
916 Error
parseSyncScopeNames();
918 Expected
<Value
*> recordValue(SmallVectorImpl
<uint64_t> &Record
,
919 unsigned NameIndex
, Triple
&TT
);
920 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
, Function
*F
,
921 ArrayRef
<uint64_t> Record
);
922 Error
parseValueSymbolTable(uint64_t Offset
= 0);
923 Error
parseGlobalValueSymbolTable();
924 Error
parseConstants();
925 Error
rememberAndSkipFunctionBodies();
926 Error
rememberAndSkipFunctionBody();
927 /// Save the positions of the Metadata blocks and skip parsing the blocks.
928 Error
rememberAndSkipMetadata();
929 Error
typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
);
930 Error
parseFunctionBody(Function
*F
);
931 Error
globalCleanup();
932 Error
resolveGlobalAndIndirectSymbolInits();
933 Error
parseUseLists();
934 Error
findFunctionInStream(
936 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
);
938 SyncScope::ID
getDecodedSyncScopeID(unsigned Val
);
941 /// Class to manage reading and parsing function summary index bitcode
943 class ModuleSummaryIndexBitcodeReader
: public BitcodeReaderBase
{
944 /// The module index built during parsing.
945 ModuleSummaryIndex
&TheIndex
;
947 /// Indicates whether we have encountered a global value summary section
948 /// yet during parsing.
949 bool SeenGlobalValSummary
= false;
951 /// Indicates whether we have already parsed the VST, used for error checking.
952 bool SeenValueSymbolTable
= false;
954 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
955 /// Used to enable on-demand parsing of the VST.
956 uint64_t VSTOffset
= 0;
958 // Map to save ValueId to ValueInfo association that was recorded in the
959 // ValueSymbolTable. It is used after the VST is parsed to convert
960 // call graph edges read from the function summary from referencing
961 // callees by their ValueId to using the ValueInfo instead, which is how
962 // they are recorded in the summary index being built.
963 // We save a GUID which refers to the same global as the ValueInfo, but
964 // ignoring the linkage, i.e. for values other than local linkage they are
965 // identical (this is the second member). ValueInfo has the real GUID.
966 DenseMap
<unsigned, std::pair
<ValueInfo
, GlobalValue::GUID
>>
967 ValueIdToValueInfoMap
;
969 /// Map populated during module path string table parsing, from the
970 /// module ID to a string reference owned by the index's module
971 /// path string table, used to correlate with combined index
973 DenseMap
<uint64_t, StringRef
> ModuleIdMap
;
975 /// Original source file name recorded in a bitcode record.
976 std::string SourceFileName
;
978 /// The string identifier given to this module by the client, normally the
979 /// path to the bitcode file.
980 StringRef ModulePath
;
982 /// Callback to ask whether a symbol is the prevailing copy when invoked
983 /// during combined index building.
984 std::function
<bool(GlobalValue::GUID
)> IsPrevailing
;
986 /// Saves the stack ids from the STACK_IDS record to consult when adding stack
987 /// ids from the lists in the callsite and alloc entries to the index.
988 std::vector
<uint64_t> StackIds
;
990 /// Linearized radix tree of allocation contexts. See the description above
991 /// the CallStackRadixTreeBuilder class in ProfileData/MemProf.h for format.
992 std::vector
<uint64_t> RadixArray
;
995 ModuleSummaryIndexBitcodeReader(
996 BitstreamCursor Stream
, StringRef Strtab
, ModuleSummaryIndex
&TheIndex
,
997 StringRef ModulePath
,
998 std::function
<bool(GlobalValue::GUID
)> IsPrevailing
= nullptr);
1000 Error
parseModule();
1003 void setValueGUID(uint64_t ValueID
, StringRef ValueName
,
1004 GlobalValue::LinkageTypes Linkage
,
1005 StringRef SourceFileName
);
1006 Error
parseValueSymbolTable(
1008 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
);
1009 SmallVector
<ValueInfo
, 0> makeRefList(ArrayRef
<uint64_t> Record
);
1010 SmallVector
<FunctionSummary::EdgeTy
, 0>
1011 makeCallList(ArrayRef
<uint64_t> Record
, bool IsOldProfileFormat
,
1012 bool HasProfile
, bool HasRelBF
);
1013 Error
parseEntireSummary(unsigned ID
);
1014 Error
parseModuleStringTable();
1015 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef
<uint64_t> Record
);
1016 void parseTypeIdCompatibleVtableInfo(ArrayRef
<uint64_t> Record
, size_t &Slot
,
1017 TypeIdCompatibleVtableInfo
&TypeId
);
1018 std::vector
<FunctionSummary::ParamAccess
>
1019 parseParamAccesses(ArrayRef
<uint64_t> Record
);
1020 SmallVector
<unsigned> parseAllocInfoContext(ArrayRef
<uint64_t> Record
,
1023 template <bool AllowNullValueInfo
= false>
1024 std::pair
<ValueInfo
, GlobalValue::GUID
>
1025 getValueInfoFromValueId(unsigned ValueId
);
1027 void addThisModule();
1028 ModuleSummaryIndex::ModuleInfo
*getThisModule();
1031 } // end anonymous namespace
1033 std::error_code
llvm::errorToErrorCodeAndEmitErrors(LLVMContext
&Ctx
,
1037 handleAllErrors(std::move(Err
), [&](ErrorInfoBase
&EIB
) {
1038 EC
= EIB
.convertToErrorCode();
1039 Ctx
.emitError(EIB
.message());
1043 return std::error_code();
1046 BitcodeReader::BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
1047 StringRef ProducerIdentification
,
1048 LLVMContext
&Context
)
1049 : BitcodeReaderBase(std::move(Stream
), Strtab
), Context(Context
),
1050 ValueList(this->Stream
.SizeInBytes(),
1051 [this](unsigned ValID
, BasicBlock
*InsertBB
) {
1052 return materializeValue(ValID
, InsertBB
);
1054 this->ProducerIdentification
= std::string(ProducerIdentification
);
1057 Error
BitcodeReader::materializeForwardReferencedFunctions() {
1058 if (WillMaterializeAllForwardRefs
)
1059 return Error::success();
1061 // Prevent recursion.
1062 WillMaterializeAllForwardRefs
= true;
1064 while (!BasicBlockFwdRefQueue
.empty()) {
1065 Function
*F
= BasicBlockFwdRefQueue
.front();
1066 BasicBlockFwdRefQueue
.pop_front();
1067 assert(F
&& "Expected valid function");
1068 if (!BasicBlockFwdRefs
.count(F
))
1069 // Already materialized.
1072 // Check for a function that isn't materializable to prevent an infinite
1073 // loop. When parsing a blockaddress stored in a global variable, there
1074 // isn't a trivial way to check if a function will have a body without a
1075 // linear search through FunctionsWithBodies, so just check it here.
1076 if (!F
->isMaterializable())
1077 return error("Never resolved function from blockaddress");
1079 // Try to materialize F.
1080 if (Error Err
= materialize(F
))
1083 assert(BasicBlockFwdRefs
.empty() && "Function missing from queue");
1085 for (Function
*F
: BackwardRefFunctions
)
1086 if (Error Err
= materialize(F
))
1088 BackwardRefFunctions
.clear();
1091 WillMaterializeAllForwardRefs
= false;
1092 return Error::success();
1095 //===----------------------------------------------------------------------===//
1096 // Helper functions to implement forward reference resolution, etc.
1097 //===----------------------------------------------------------------------===//
1099 static bool hasImplicitComdat(size_t Val
) {
1103 case 1: // Old WeakAnyLinkage
1104 case 4: // Old LinkOnceAnyLinkage
1105 case 10: // Old WeakODRLinkage
1106 case 11: // Old LinkOnceODRLinkage
1111 static GlobalValue::LinkageTypes
getDecodedLinkage(unsigned Val
) {
1113 default: // Map unknown/new linkages to external
1115 return GlobalValue::ExternalLinkage
;
1117 return GlobalValue::AppendingLinkage
;
1119 return GlobalValue::InternalLinkage
;
1121 return GlobalValue::ExternalLinkage
; // Obsolete DLLImportLinkage
1123 return GlobalValue::ExternalLinkage
; // Obsolete DLLExportLinkage
1125 return GlobalValue::ExternalWeakLinkage
;
1127 return GlobalValue::CommonLinkage
;
1129 return GlobalValue::PrivateLinkage
;
1131 return GlobalValue::AvailableExternallyLinkage
;
1133 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateLinkage
1135 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateWeakLinkage
1137 return GlobalValue::ExternalLinkage
; // Obsolete LinkOnceODRAutoHideLinkage
1138 case 1: // Old value with implicit comdat.
1140 return GlobalValue::WeakAnyLinkage
;
1141 case 10: // Old value with implicit comdat.
1143 return GlobalValue::WeakODRLinkage
;
1144 case 4: // Old value with implicit comdat.
1146 return GlobalValue::LinkOnceAnyLinkage
;
1147 case 11: // Old value with implicit comdat.
1149 return GlobalValue::LinkOnceODRLinkage
;
1153 static FunctionSummary::FFlags
getDecodedFFlags(uint64_t RawFlags
) {
1154 FunctionSummary::FFlags Flags
;
1155 Flags
.ReadNone
= RawFlags
& 0x1;
1156 Flags
.ReadOnly
= (RawFlags
>> 1) & 0x1;
1157 Flags
.NoRecurse
= (RawFlags
>> 2) & 0x1;
1158 Flags
.ReturnDoesNotAlias
= (RawFlags
>> 3) & 0x1;
1159 Flags
.NoInline
= (RawFlags
>> 4) & 0x1;
1160 Flags
.AlwaysInline
= (RawFlags
>> 5) & 0x1;
1161 Flags
.NoUnwind
= (RawFlags
>> 6) & 0x1;
1162 Flags
.MayThrow
= (RawFlags
>> 7) & 0x1;
1163 Flags
.HasUnknownCall
= (RawFlags
>> 8) & 0x1;
1164 Flags
.MustBeUnreachable
= (RawFlags
>> 9) & 0x1;
1168 // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1170 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1171 // visibility: [8, 10).
1172 static GlobalValueSummary::GVFlags
getDecodedGVSummaryFlags(uint64_t RawFlags
,
1174 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1175 // like getDecodedLinkage() above. Any future change to the linkage enum and
1176 // to getDecodedLinkage() will need to be taken into account here as above.
1177 auto Linkage
= GlobalValue::LinkageTypes(RawFlags
& 0xF); // 4 bits
1178 auto Visibility
= GlobalValue::VisibilityTypes((RawFlags
>> 8) & 3); // 2 bits
1179 auto IK
= GlobalValueSummary::ImportKind((RawFlags
>> 10) & 1); // 1 bit
1180 RawFlags
= RawFlags
>> 4;
1181 bool NotEligibleToImport
= (RawFlags
& 0x1) || Version
< 3;
1182 // The Live flag wasn't introduced until version 3. For dead stripping
1183 // to work correctly on earlier versions, we must conservatively treat all
1185 bool Live
= (RawFlags
& 0x2) || Version
< 3;
1186 bool Local
= (RawFlags
& 0x4);
1187 bool AutoHide
= (RawFlags
& 0x8);
1189 return GlobalValueSummary::GVFlags(Linkage
, Visibility
, NotEligibleToImport
,
1190 Live
, Local
, AutoHide
, IK
);
1193 // Decode the flags for GlobalVariable in the summary
1194 static GlobalVarSummary::GVarFlags
getDecodedGVarFlags(uint64_t RawFlags
) {
1195 return GlobalVarSummary::GVarFlags(
1196 (RawFlags
& 0x1) ? true : false, (RawFlags
& 0x2) ? true : false,
1197 (RawFlags
& 0x4) ? true : false,
1198 (GlobalObject::VCallVisibility
)(RawFlags
>> 3));
1201 static std::pair
<CalleeInfo::HotnessType
, bool>
1202 getDecodedHotnessCallEdgeInfo(uint64_t RawFlags
) {
1203 CalleeInfo::HotnessType Hotness
=
1204 static_cast<CalleeInfo::HotnessType
>(RawFlags
& 0x7); // 3 bits
1205 bool HasTailCall
= (RawFlags
& 0x8); // 1 bit
1206 return {Hotness
, HasTailCall
};
1209 static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags
, uint64_t &RelBF
,
1210 bool &HasTailCall
) {
1211 static constexpr uint64_t RelBlockFreqMask
=
1212 (1 << CalleeInfo::RelBlockFreqBits
) - 1;
1213 RelBF
= RawFlags
& RelBlockFreqMask
; // RelBlockFreqBits bits
1214 HasTailCall
= (RawFlags
& (1 << CalleeInfo::RelBlockFreqBits
)); // 1 bit
1217 static GlobalValue::VisibilityTypes
getDecodedVisibility(unsigned Val
) {
1219 default: // Map unknown visibilities to default.
1220 case 0: return GlobalValue::DefaultVisibility
;
1221 case 1: return GlobalValue::HiddenVisibility
;
1222 case 2: return GlobalValue::ProtectedVisibility
;
1226 static GlobalValue::DLLStorageClassTypes
1227 getDecodedDLLStorageClass(unsigned Val
) {
1229 default: // Map unknown values to default.
1230 case 0: return GlobalValue::DefaultStorageClass
;
1231 case 1: return GlobalValue::DLLImportStorageClass
;
1232 case 2: return GlobalValue::DLLExportStorageClass
;
1236 static bool getDecodedDSOLocal(unsigned Val
) {
1238 default: // Map unknown values to preemptable.
1239 case 0: return false;
1240 case 1: return true;
1244 static std::optional
<CodeModel::Model
> getDecodedCodeModel(unsigned Val
) {
1247 return CodeModel::Tiny
;
1249 return CodeModel::Small
;
1251 return CodeModel::Kernel
;
1253 return CodeModel::Medium
;
1255 return CodeModel::Large
;
1261 static GlobalVariable::ThreadLocalMode
getDecodedThreadLocalMode(unsigned Val
) {
1263 case 0: return GlobalVariable::NotThreadLocal
;
1264 default: // Map unknown non-zero value to general dynamic.
1265 case 1: return GlobalVariable::GeneralDynamicTLSModel
;
1266 case 2: return GlobalVariable::LocalDynamicTLSModel
;
1267 case 3: return GlobalVariable::InitialExecTLSModel
;
1268 case 4: return GlobalVariable::LocalExecTLSModel
;
1272 static GlobalVariable::UnnamedAddr
getDecodedUnnamedAddrType(unsigned Val
) {
1274 default: // Map unknown to UnnamedAddr::None.
1275 case 0: return GlobalVariable::UnnamedAddr::None
;
1276 case 1: return GlobalVariable::UnnamedAddr::Global
;
1277 case 2: return GlobalVariable::UnnamedAddr::Local
;
1281 static int getDecodedCastOpcode(unsigned Val
) {
1284 case bitc::CAST_TRUNC
: return Instruction::Trunc
;
1285 case bitc::CAST_ZEXT
: return Instruction::ZExt
;
1286 case bitc::CAST_SEXT
: return Instruction::SExt
;
1287 case bitc::CAST_FPTOUI
: return Instruction::FPToUI
;
1288 case bitc::CAST_FPTOSI
: return Instruction::FPToSI
;
1289 case bitc::CAST_UITOFP
: return Instruction::UIToFP
;
1290 case bitc::CAST_SITOFP
: return Instruction::SIToFP
;
1291 case bitc::CAST_FPTRUNC
: return Instruction::FPTrunc
;
1292 case bitc::CAST_FPEXT
: return Instruction::FPExt
;
1293 case bitc::CAST_PTRTOINT
: return Instruction::PtrToInt
;
1294 case bitc::CAST_INTTOPTR
: return Instruction::IntToPtr
;
1295 case bitc::CAST_BITCAST
: return Instruction::BitCast
;
1296 case bitc::CAST_ADDRSPACECAST
: return Instruction::AddrSpaceCast
;
1300 static int getDecodedUnaryOpcode(unsigned Val
, Type
*Ty
) {
1301 bool IsFP
= Ty
->isFPOrFPVectorTy();
1302 // UnOps are only valid for int/fp or vector of int/fp types
1303 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
1309 case bitc::UNOP_FNEG
:
1310 return IsFP
? Instruction::FNeg
: -1;
1314 static int getDecodedBinaryOpcode(unsigned Val
, Type
*Ty
) {
1315 bool IsFP
= Ty
->isFPOrFPVectorTy();
1316 // BinOps are only valid for int/fp or vector of int/fp types
1317 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
1323 case bitc::BINOP_ADD
:
1324 return IsFP
? Instruction::FAdd
: Instruction::Add
;
1325 case bitc::BINOP_SUB
:
1326 return IsFP
? Instruction::FSub
: Instruction::Sub
;
1327 case bitc::BINOP_MUL
:
1328 return IsFP
? Instruction::FMul
: Instruction::Mul
;
1329 case bitc::BINOP_UDIV
:
1330 return IsFP
? -1 : Instruction::UDiv
;
1331 case bitc::BINOP_SDIV
:
1332 return IsFP
? Instruction::FDiv
: Instruction::SDiv
;
1333 case bitc::BINOP_UREM
:
1334 return IsFP
? -1 : Instruction::URem
;
1335 case bitc::BINOP_SREM
:
1336 return IsFP
? Instruction::FRem
: Instruction::SRem
;
1337 case bitc::BINOP_SHL
:
1338 return IsFP
? -1 : Instruction::Shl
;
1339 case bitc::BINOP_LSHR
:
1340 return IsFP
? -1 : Instruction::LShr
;
1341 case bitc::BINOP_ASHR
:
1342 return IsFP
? -1 : Instruction::AShr
;
1343 case bitc::BINOP_AND
:
1344 return IsFP
? -1 : Instruction::And
;
1345 case bitc::BINOP_OR
:
1346 return IsFP
? -1 : Instruction::Or
;
1347 case bitc::BINOP_XOR
:
1348 return IsFP
? -1 : Instruction::Xor
;
1352 static AtomicRMWInst::BinOp
getDecodedRMWOperation(unsigned Val
) {
1354 default: return AtomicRMWInst::BAD_BINOP
;
1355 case bitc::RMW_XCHG
: return AtomicRMWInst::Xchg
;
1356 case bitc::RMW_ADD
: return AtomicRMWInst::Add
;
1357 case bitc::RMW_SUB
: return AtomicRMWInst::Sub
;
1358 case bitc::RMW_AND
: return AtomicRMWInst::And
;
1359 case bitc::RMW_NAND
: return AtomicRMWInst::Nand
;
1360 case bitc::RMW_OR
: return AtomicRMWInst::Or
;
1361 case bitc::RMW_XOR
: return AtomicRMWInst::Xor
;
1362 case bitc::RMW_MAX
: return AtomicRMWInst::Max
;
1363 case bitc::RMW_MIN
: return AtomicRMWInst::Min
;
1364 case bitc::RMW_UMAX
: return AtomicRMWInst::UMax
;
1365 case bitc::RMW_UMIN
: return AtomicRMWInst::UMin
;
1366 case bitc::RMW_FADD
: return AtomicRMWInst::FAdd
;
1367 case bitc::RMW_FSUB
: return AtomicRMWInst::FSub
;
1368 case bitc::RMW_FMAX
: return AtomicRMWInst::FMax
;
1369 case bitc::RMW_FMIN
: return AtomicRMWInst::FMin
;
1370 case bitc::RMW_UINC_WRAP
:
1371 return AtomicRMWInst::UIncWrap
;
1372 case bitc::RMW_UDEC_WRAP
:
1373 return AtomicRMWInst::UDecWrap
;
1374 case bitc::RMW_USUB_COND
:
1375 return AtomicRMWInst::USubCond
;
1376 case bitc::RMW_USUB_SAT
:
1377 return AtomicRMWInst::USubSat
;
1381 static AtomicOrdering
getDecodedOrdering(unsigned Val
) {
1383 case bitc::ORDERING_NOTATOMIC
: return AtomicOrdering::NotAtomic
;
1384 case bitc::ORDERING_UNORDERED
: return AtomicOrdering::Unordered
;
1385 case bitc::ORDERING_MONOTONIC
: return AtomicOrdering::Monotonic
;
1386 case bitc::ORDERING_ACQUIRE
: return AtomicOrdering::Acquire
;
1387 case bitc::ORDERING_RELEASE
: return AtomicOrdering::Release
;
1388 case bitc::ORDERING_ACQREL
: return AtomicOrdering::AcquireRelease
;
1389 default: // Map unknown orderings to sequentially-consistent.
1390 case bitc::ORDERING_SEQCST
: return AtomicOrdering::SequentiallyConsistent
;
1394 static Comdat::SelectionKind
getDecodedComdatSelectionKind(unsigned Val
) {
1396 default: // Map unknown selection kinds to any.
1397 case bitc::COMDAT_SELECTION_KIND_ANY
:
1399 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH
:
1400 return Comdat::ExactMatch
;
1401 case bitc::COMDAT_SELECTION_KIND_LARGEST
:
1402 return Comdat::Largest
;
1403 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES
:
1404 return Comdat::NoDeduplicate
;
1405 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE
:
1406 return Comdat::SameSize
;
1410 static FastMathFlags
getDecodedFastMathFlags(unsigned Val
) {
1412 if (0 != (Val
& bitc::UnsafeAlgebra
))
1414 if (0 != (Val
& bitc::AllowReassoc
))
1415 FMF
.setAllowReassoc();
1416 if (0 != (Val
& bitc::NoNaNs
))
1418 if (0 != (Val
& bitc::NoInfs
))
1420 if (0 != (Val
& bitc::NoSignedZeros
))
1421 FMF
.setNoSignedZeros();
1422 if (0 != (Val
& bitc::AllowReciprocal
))
1423 FMF
.setAllowReciprocal();
1424 if (0 != (Val
& bitc::AllowContract
))
1425 FMF
.setAllowContract(true);
1426 if (0 != (Val
& bitc::ApproxFunc
))
1427 FMF
.setApproxFunc();
1431 static void upgradeDLLImportExportLinkage(GlobalValue
*GV
, unsigned Val
) {
1432 // A GlobalValue with local linkage cannot have a DLL storage class.
1433 if (GV
->hasLocalLinkage())
1436 case 5: GV
->setDLLStorageClass(GlobalValue::DLLImportStorageClass
); break;
1437 case 6: GV
->setDLLStorageClass(GlobalValue::DLLExportStorageClass
); break;
1441 Type
*BitcodeReader::getTypeByID(unsigned ID
) {
1442 // The type table size is always specified correctly.
1443 if (ID
>= TypeList
.size())
1446 if (Type
*Ty
= TypeList
[ID
])
1449 // If we have a forward reference, the only possible case is when it is to a
1450 // named struct. Just create a placeholder for now.
1451 return TypeList
[ID
] = createIdentifiedStructType(Context
);
1454 unsigned BitcodeReader::getContainedTypeID(unsigned ID
, unsigned Idx
) {
1455 auto It
= ContainedTypeIDs
.find(ID
);
1456 if (It
== ContainedTypeIDs
.end())
1457 return InvalidTypeID
;
1459 if (Idx
>= It
->second
.size())
1460 return InvalidTypeID
;
1462 return It
->second
[Idx
];
1465 Type
*BitcodeReader::getPtrElementTypeByID(unsigned ID
) {
1466 if (ID
>= TypeList
.size())
1469 Type
*Ty
= TypeList
[ID
];
1470 if (!Ty
->isPointerTy())
1473 return getTypeByID(getContainedTypeID(ID
, 0));
1476 unsigned BitcodeReader::getVirtualTypeID(Type
*Ty
,
1477 ArrayRef
<unsigned> ChildTypeIDs
) {
1478 unsigned ChildTypeID
= ChildTypeIDs
.empty() ? InvalidTypeID
: ChildTypeIDs
[0];
1479 auto CacheKey
= std::make_pair(Ty
, ChildTypeID
);
1480 auto It
= VirtualTypeIDs
.find(CacheKey
);
1481 if (It
!= VirtualTypeIDs
.end()) {
1482 // The cmpxchg return value is the only place we need more than one
1483 // contained type ID, however the second one will always be the same (i1),
1484 // so we don't need to include it in the cache key. This asserts that the
1485 // contained types are indeed as expected and there are no collisions.
1486 assert((ChildTypeIDs
.empty() ||
1487 ContainedTypeIDs
[It
->second
] == ChildTypeIDs
) &&
1488 "Incorrect cached contained type IDs");
1492 unsigned TypeID
= TypeList
.size();
1493 TypeList
.push_back(Ty
);
1494 if (!ChildTypeIDs
.empty())
1495 append_range(ContainedTypeIDs
[TypeID
], ChildTypeIDs
);
1496 VirtualTypeIDs
.insert({CacheKey
, TypeID
});
1500 static GEPNoWrapFlags
toGEPNoWrapFlags(uint64_t Flags
) {
1502 if (Flags
& (1 << bitc::GEP_INBOUNDS
))
1503 NW
|= GEPNoWrapFlags::inBounds();
1504 if (Flags
& (1 << bitc::GEP_NUSW
))
1505 NW
|= GEPNoWrapFlags::noUnsignedSignedWrap();
1506 if (Flags
& (1 << bitc::GEP_NUW
))
1507 NW
|= GEPNoWrapFlags::noUnsignedWrap();
1511 static bool isConstExprSupported(const BitcodeConstant
*BC
) {
1512 uint8_t Opcode
= BC
->Opcode
;
1514 // These are not real constant expressions, always consider them supported.
1515 if (Opcode
>= BitcodeConstant::FirstSpecialOpcode
)
1518 // If -expand-constant-exprs is set, we want to consider all expressions
1520 if (ExpandConstantExprs
)
1523 if (Instruction::isBinaryOp(Opcode
))
1524 return ConstantExpr::isSupportedBinOp(Opcode
);
1526 if (Instruction::isCast(Opcode
))
1527 return ConstantExpr::isSupportedCastOp(Opcode
);
1529 if (Opcode
== Instruction::GetElementPtr
)
1530 return ConstantExpr::isSupportedGetElementPtr(BC
->SrcElemTy
);
1533 case Instruction::FNeg
:
1534 case Instruction::Select
:
1535 case Instruction::ICmp
:
1536 case Instruction::FCmp
:
1543 Expected
<Value
*> BitcodeReader::materializeValue(unsigned StartValID
,
1544 BasicBlock
*InsertBB
) {
1545 // Quickly handle the case where there is no BitcodeConstant to resolve.
1546 if (StartValID
< ValueList
.size() && ValueList
[StartValID
] &&
1547 !isa
<BitcodeConstant
>(ValueList
[StartValID
]))
1548 return ValueList
[StartValID
];
1550 SmallDenseMap
<unsigned, Value
*> MaterializedValues
;
1551 SmallVector
<unsigned> Worklist
;
1552 Worklist
.push_back(StartValID
);
1553 while (!Worklist
.empty()) {
1554 unsigned ValID
= Worklist
.back();
1555 if (MaterializedValues
.count(ValID
)) {
1556 // Duplicate expression that was already handled.
1557 Worklist
.pop_back();
1561 if (ValID
>= ValueList
.size() || !ValueList
[ValID
])
1562 return error("Invalid value ID");
1564 Value
*V
= ValueList
[ValID
];
1565 auto *BC
= dyn_cast
<BitcodeConstant
>(V
);
1567 MaterializedValues
.insert({ValID
, V
});
1568 Worklist
.pop_back();
1572 // Iterate in reverse, so values will get popped from the worklist in
1574 SmallVector
<Value
*> Ops
;
1575 for (unsigned OpID
: reverse(BC
->getOperandIDs())) {
1576 auto It
= MaterializedValues
.find(OpID
);
1577 if (It
!= MaterializedValues
.end())
1578 Ops
.push_back(It
->second
);
1580 Worklist
.push_back(OpID
);
1583 // Some expressions have not been resolved yet, handle them first and then
1584 // revisit this one.
1585 if (Ops
.size() != BC
->getOperandIDs().size())
1587 std::reverse(Ops
.begin(), Ops
.end());
1589 SmallVector
<Constant
*> ConstOps
;
1590 for (Value
*Op
: Ops
)
1591 if (auto *C
= dyn_cast
<Constant
>(Op
))
1592 ConstOps
.push_back(C
);
1594 // Materialize as constant expression if possible.
1595 if (isConstExprSupported(BC
) && ConstOps
.size() == Ops
.size()) {
1597 if (Instruction::isCast(BC
->Opcode
)) {
1598 C
= UpgradeBitCastExpr(BC
->Opcode
, ConstOps
[0], BC
->getType());
1600 C
= ConstantExpr::getCast(BC
->Opcode
, ConstOps
[0], BC
->getType());
1601 } else if (Instruction::isBinaryOp(BC
->Opcode
)) {
1602 C
= ConstantExpr::get(BC
->Opcode
, ConstOps
[0], ConstOps
[1], BC
->Flags
);
1604 switch (BC
->Opcode
) {
1605 case BitcodeConstant::ConstantPtrAuthOpcode
: {
1606 auto *Key
= dyn_cast
<ConstantInt
>(ConstOps
[1]);
1608 return error("ptrauth key operand must be ConstantInt");
1610 auto *Disc
= dyn_cast
<ConstantInt
>(ConstOps
[2]);
1612 return error("ptrauth disc operand must be ConstantInt");
1614 C
= ConstantPtrAuth::get(ConstOps
[0], Key
, Disc
, ConstOps
[3]);
1617 case BitcodeConstant::NoCFIOpcode
: {
1618 auto *GV
= dyn_cast
<GlobalValue
>(ConstOps
[0]);
1620 return error("no_cfi operand must be GlobalValue");
1621 C
= NoCFIValue::get(GV
);
1624 case BitcodeConstant::DSOLocalEquivalentOpcode
: {
1625 auto *GV
= dyn_cast
<GlobalValue
>(ConstOps
[0]);
1627 return error("dso_local operand must be GlobalValue");
1628 C
= DSOLocalEquivalent::get(GV
);
1631 case BitcodeConstant::BlockAddressOpcode
: {
1632 Function
*Fn
= dyn_cast
<Function
>(ConstOps
[0]);
1634 return error("blockaddress operand must be a function");
1636 // If the function is already parsed we can insert the block address
1639 unsigned BBID
= BC
->BlockAddressBB
;
1641 // Invalid reference to entry block.
1642 return error("Invalid ID");
1644 Function::iterator BBI
= Fn
->begin(), BBE
= Fn
->end();
1645 for (size_t I
= 0, E
= BBID
; I
!= E
; ++I
) {
1647 return error("Invalid ID");
1652 // Otherwise insert a placeholder and remember it so it can be
1653 // inserted when the function is parsed.
1654 auto &FwdBBs
= BasicBlockFwdRefs
[Fn
];
1656 BasicBlockFwdRefQueue
.push_back(Fn
);
1657 if (FwdBBs
.size() < BBID
+ 1)
1658 FwdBBs
.resize(BBID
+ 1);
1660 FwdBBs
[BBID
] = BasicBlock::Create(Context
);
1663 C
= BlockAddress::get(Fn
, BB
);
1666 case BitcodeConstant::ConstantStructOpcode
: {
1667 auto *ST
= cast
<StructType
>(BC
->getType());
1668 if (ST
->getNumElements() != ConstOps
.size())
1669 return error("Invalid number of elements in struct initializer");
1671 for (const auto [Ty
, Op
] : zip(ST
->elements(), ConstOps
))
1672 if (Op
->getType() != Ty
)
1673 return error("Incorrect type in struct initializer");
1675 C
= ConstantStruct::get(ST
, ConstOps
);
1678 case BitcodeConstant::ConstantArrayOpcode
: {
1679 auto *AT
= cast
<ArrayType
>(BC
->getType());
1680 if (AT
->getNumElements() != ConstOps
.size())
1681 return error("Invalid number of elements in array initializer");
1683 for (Constant
*Op
: ConstOps
)
1684 if (Op
->getType() != AT
->getElementType())
1685 return error("Incorrect type in array initializer");
1687 C
= ConstantArray::get(AT
, ConstOps
);
1690 case BitcodeConstant::ConstantVectorOpcode
: {
1691 auto *VT
= cast
<FixedVectorType
>(BC
->getType());
1692 if (VT
->getNumElements() != ConstOps
.size())
1693 return error("Invalid number of elements in vector initializer");
1695 for (Constant
*Op
: ConstOps
)
1696 if (Op
->getType() != VT
->getElementType())
1697 return error("Incorrect type in vector initializer");
1699 C
= ConstantVector::get(ConstOps
);
1702 case Instruction::GetElementPtr
:
1703 C
= ConstantExpr::getGetElementPtr(
1704 BC
->SrcElemTy
, ConstOps
[0], ArrayRef(ConstOps
).drop_front(),
1705 toGEPNoWrapFlags(BC
->Flags
), BC
->getInRange());
1707 case Instruction::ExtractElement
:
1708 C
= ConstantExpr::getExtractElement(ConstOps
[0], ConstOps
[1]);
1710 case Instruction::InsertElement
:
1711 C
= ConstantExpr::getInsertElement(ConstOps
[0], ConstOps
[1],
1714 case Instruction::ShuffleVector
: {
1715 SmallVector
<int, 16> Mask
;
1716 ShuffleVectorInst::getShuffleMask(ConstOps
[2], Mask
);
1717 C
= ConstantExpr::getShuffleVector(ConstOps
[0], ConstOps
[1], Mask
);
1721 llvm_unreachable("Unhandled bitcode constant");
1725 // Cache resolved constant.
1726 ValueList
.replaceValueWithoutRAUW(ValID
, C
);
1727 MaterializedValues
.insert({ValID
, C
});
1728 Worklist
.pop_back();
1733 return error(Twine("Value referenced by initializer is an unsupported "
1734 "constant expression of type ") +
1735 BC
->getOpcodeName());
1737 // Materialize as instructions if necessary.
1739 if (Instruction::isCast(BC
->Opcode
)) {
1740 I
= CastInst::Create((Instruction::CastOps
)BC
->Opcode
, Ops
[0],
1741 BC
->getType(), "constexpr", InsertBB
);
1742 } else if (Instruction::isUnaryOp(BC
->Opcode
)) {
1743 I
= UnaryOperator::Create((Instruction::UnaryOps
)BC
->Opcode
, Ops
[0],
1744 "constexpr", InsertBB
);
1745 } else if (Instruction::isBinaryOp(BC
->Opcode
)) {
1746 I
= BinaryOperator::Create((Instruction::BinaryOps
)BC
->Opcode
, Ops
[0],
1747 Ops
[1], "constexpr", InsertBB
);
1748 if (isa
<OverflowingBinaryOperator
>(I
)) {
1749 if (BC
->Flags
& OverflowingBinaryOperator::NoSignedWrap
)
1750 I
->setHasNoSignedWrap();
1751 if (BC
->Flags
& OverflowingBinaryOperator::NoUnsignedWrap
)
1752 I
->setHasNoUnsignedWrap();
1754 if (isa
<PossiblyExactOperator
>(I
) &&
1755 (BC
->Flags
& PossiblyExactOperator::IsExact
))
1758 switch (BC
->Opcode
) {
1759 case BitcodeConstant::ConstantVectorOpcode
: {
1760 Type
*IdxTy
= Type::getInt32Ty(BC
->getContext());
1761 Value
*V
= PoisonValue::get(BC
->getType());
1762 for (auto Pair
: enumerate(Ops
)) {
1763 Value
*Idx
= ConstantInt::get(IdxTy
, Pair
.index());
1764 V
= InsertElementInst::Create(V
, Pair
.value(), Idx
, "constexpr.ins",
1767 I
= cast
<Instruction
>(V
);
1770 case BitcodeConstant::ConstantStructOpcode
:
1771 case BitcodeConstant::ConstantArrayOpcode
: {
1772 Value
*V
= PoisonValue::get(BC
->getType());
1773 for (auto Pair
: enumerate(Ops
))
1774 V
= InsertValueInst::Create(V
, Pair
.value(), Pair
.index(),
1775 "constexpr.ins", InsertBB
);
1776 I
= cast
<Instruction
>(V
);
1779 case Instruction::ICmp
:
1780 case Instruction::FCmp
:
1781 I
= CmpInst::Create((Instruction::OtherOps
)BC
->Opcode
,
1782 (CmpInst::Predicate
)BC
->Flags
, Ops
[0], Ops
[1],
1783 "constexpr", InsertBB
);
1785 case Instruction::GetElementPtr
:
1786 I
= GetElementPtrInst::Create(BC
->SrcElemTy
, Ops
[0],
1787 ArrayRef(Ops
).drop_front(), "constexpr",
1789 cast
<GetElementPtrInst
>(I
)->setNoWrapFlags(toGEPNoWrapFlags(BC
->Flags
));
1791 case Instruction::Select
:
1792 I
= SelectInst::Create(Ops
[0], Ops
[1], Ops
[2], "constexpr", InsertBB
);
1794 case Instruction::ExtractElement
:
1795 I
= ExtractElementInst::Create(Ops
[0], Ops
[1], "constexpr", InsertBB
);
1797 case Instruction::InsertElement
:
1798 I
= InsertElementInst::Create(Ops
[0], Ops
[1], Ops
[2], "constexpr",
1801 case Instruction::ShuffleVector
:
1802 I
= new ShuffleVectorInst(Ops
[0], Ops
[1], Ops
[2], "constexpr",
1806 llvm_unreachable("Unhandled bitcode constant");
1810 MaterializedValues
.insert({ValID
, I
});
1811 Worklist
.pop_back();
1814 return MaterializedValues
[StartValID
];
1817 Expected
<Constant
*> BitcodeReader::getValueForInitializer(unsigned ID
) {
1818 Expected
<Value
*> MaybeV
= materializeValue(ID
, /* InsertBB */ nullptr);
1820 return MaybeV
.takeError();
1822 // Result must be Constant if InsertBB is nullptr.
1823 return cast
<Constant
>(MaybeV
.get());
1826 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
,
1828 auto *Ret
= StructType::create(Context
, Name
);
1829 IdentifiedStructTypes
.push_back(Ret
);
1833 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
) {
1834 auto *Ret
= StructType::create(Context
);
1835 IdentifiedStructTypes
.push_back(Ret
);
1839 //===----------------------------------------------------------------------===//
1840 // Functions for parsing blocks from the bitcode file
1841 //===----------------------------------------------------------------------===//
1843 static uint64_t getRawAttributeMask(Attribute::AttrKind Val
) {
1845 case Attribute::EndAttrKinds
:
1846 case Attribute::EmptyKey
:
1847 case Attribute::TombstoneKey
:
1848 llvm_unreachable("Synthetic enumerators which should never get here");
1850 case Attribute::None
: return 0;
1851 case Attribute::ZExt
: return 1 << 0;
1852 case Attribute::SExt
: return 1 << 1;
1853 case Attribute::NoReturn
: return 1 << 2;
1854 case Attribute::InReg
: return 1 << 3;
1855 case Attribute::StructRet
: return 1 << 4;
1856 case Attribute::NoUnwind
: return 1 << 5;
1857 case Attribute::NoAlias
: return 1 << 6;
1858 case Attribute::ByVal
: return 1 << 7;
1859 case Attribute::Nest
: return 1 << 8;
1860 case Attribute::ReadNone
: return 1 << 9;
1861 case Attribute::ReadOnly
: return 1 << 10;
1862 case Attribute::NoInline
: return 1 << 11;
1863 case Attribute::AlwaysInline
: return 1 << 12;
1864 case Attribute::OptimizeForSize
: return 1 << 13;
1865 case Attribute::StackProtect
: return 1 << 14;
1866 case Attribute::StackProtectReq
: return 1 << 15;
1867 case Attribute::Alignment
: return 31 << 16;
1868 case Attribute::NoCapture
: return 1 << 21;
1869 case Attribute::NoRedZone
: return 1 << 22;
1870 case Attribute::NoImplicitFloat
: return 1 << 23;
1871 case Attribute::Naked
: return 1 << 24;
1872 case Attribute::InlineHint
: return 1 << 25;
1873 case Attribute::StackAlignment
: return 7 << 26;
1874 case Attribute::ReturnsTwice
: return 1 << 29;
1875 case Attribute::UWTable
: return 1 << 30;
1876 case Attribute::NonLazyBind
: return 1U << 31;
1877 case Attribute::SanitizeAddress
: return 1ULL << 32;
1878 case Attribute::MinSize
: return 1ULL << 33;
1879 case Attribute::NoDuplicate
: return 1ULL << 34;
1880 case Attribute::StackProtectStrong
: return 1ULL << 35;
1881 case Attribute::SanitizeThread
: return 1ULL << 36;
1882 case Attribute::SanitizeMemory
: return 1ULL << 37;
1883 case Attribute::NoBuiltin
: return 1ULL << 38;
1884 case Attribute::Returned
: return 1ULL << 39;
1885 case Attribute::Cold
: return 1ULL << 40;
1886 case Attribute::Builtin
: return 1ULL << 41;
1887 case Attribute::OptimizeNone
: return 1ULL << 42;
1888 case Attribute::InAlloca
: return 1ULL << 43;
1889 case Attribute::NonNull
: return 1ULL << 44;
1890 case Attribute::JumpTable
: return 1ULL << 45;
1891 case Attribute::Convergent
: return 1ULL << 46;
1892 case Attribute::SafeStack
: return 1ULL << 47;
1893 case Attribute::NoRecurse
: return 1ULL << 48;
1894 // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1895 // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
1896 case Attribute::SwiftSelf
: return 1ULL << 51;
1897 case Attribute::SwiftError
: return 1ULL << 52;
1898 case Attribute::WriteOnly
: return 1ULL << 53;
1899 case Attribute::Speculatable
: return 1ULL << 54;
1900 case Attribute::StrictFP
: return 1ULL << 55;
1901 case Attribute::SanitizeHWAddress
: return 1ULL << 56;
1902 case Attribute::NoCfCheck
: return 1ULL << 57;
1903 case Attribute::OptForFuzzing
: return 1ULL << 58;
1904 case Attribute::ShadowCallStack
: return 1ULL << 59;
1905 case Attribute::SpeculativeLoadHardening
:
1907 case Attribute::ImmArg
:
1909 case Attribute::WillReturn
:
1911 case Attribute::NoFree
:
1914 // Other attributes are not supported in the raw format,
1915 // as we ran out of space.
1918 llvm_unreachable("Unsupported attribute type");
1921 static void addRawAttributeValue(AttrBuilder
&B
, uint64_t Val
) {
1924 for (Attribute::AttrKind I
= Attribute::None
; I
!= Attribute::EndAttrKinds
;
1925 I
= Attribute::AttrKind(I
+ 1)) {
1926 if (uint64_t A
= (Val
& getRawAttributeMask(I
))) {
1927 if (I
== Attribute::Alignment
)
1928 B
.addAlignmentAttr(1ULL << ((A
>> 16) - 1));
1929 else if (I
== Attribute::StackAlignment
)
1930 B
.addStackAlignmentAttr(1ULL << ((A
>> 26)-1));
1931 else if (Attribute::isTypeAttrKind(I
))
1932 B
.addTypeAttr(I
, nullptr); // Type will be auto-upgraded.
1939 /// This fills an AttrBuilder object with the LLVM attributes that have
1940 /// been decoded from the given integer. This function must stay in sync with
1941 /// 'encodeLLVMAttributesForBitcode'.
1942 static void decodeLLVMAttributesForBitcode(AttrBuilder
&B
,
1943 uint64_t EncodedAttrs
,
1945 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1946 // the bits above 31 down by 11 bits.
1947 unsigned Alignment
= (EncodedAttrs
& (0xffffULL
<< 16)) >> 16;
1948 assert((!Alignment
|| isPowerOf2_32(Alignment
)) &&
1949 "Alignment must be a power of two.");
1952 B
.addAlignmentAttr(Alignment
);
1954 uint64_t Attrs
= ((EncodedAttrs
& (0xfffffULL
<< 32)) >> 11) |
1955 (EncodedAttrs
& 0xffff);
1957 if (AttrIdx
== AttributeList::FunctionIndex
) {
1958 // Upgrade old memory attributes.
1959 MemoryEffects ME
= MemoryEffects::unknown();
1960 if (Attrs
& (1ULL << 9)) {
1962 Attrs
&= ~(1ULL << 9);
1963 ME
&= MemoryEffects::none();
1965 if (Attrs
& (1ULL << 10)) {
1967 Attrs
&= ~(1ULL << 10);
1968 ME
&= MemoryEffects::readOnly();
1970 if (Attrs
& (1ULL << 49)) {
1971 // InaccessibleMemOnly
1972 Attrs
&= ~(1ULL << 49);
1973 ME
&= MemoryEffects::inaccessibleMemOnly();
1975 if (Attrs
& (1ULL << 50)) {
1976 // InaccessibleMemOrArgMemOnly
1977 Attrs
&= ~(1ULL << 50);
1978 ME
&= MemoryEffects::inaccessibleOrArgMemOnly();
1980 if (Attrs
& (1ULL << 53)) {
1982 Attrs
&= ~(1ULL << 53);
1983 ME
&= MemoryEffects::writeOnly();
1985 if (ME
!= MemoryEffects::unknown())
1986 B
.addMemoryAttr(ME
);
1989 addRawAttributeValue(B
, Attrs
);
1992 Error
BitcodeReader::parseAttributeBlock() {
1993 if (Error Err
= Stream
.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID
))
1996 if (!MAttributes
.empty())
1997 return error("Invalid multiple blocks");
1999 SmallVector
<uint64_t, 64> Record
;
2001 SmallVector
<AttributeList
, 8> Attrs
;
2003 // Read all the records.
2005 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2007 return MaybeEntry
.takeError();
2008 BitstreamEntry Entry
= MaybeEntry
.get();
2010 switch (Entry
.Kind
) {
2011 case BitstreamEntry::SubBlock
: // Handled for us already.
2012 case BitstreamEntry::Error
:
2013 return error("Malformed block");
2014 case BitstreamEntry::EndBlock
:
2015 return Error::success();
2016 case BitstreamEntry::Record
:
2017 // The interesting case.
2023 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2025 return MaybeRecord
.takeError();
2026 switch (MaybeRecord
.get()) {
2027 default: // Default behavior: ignore.
2029 case bitc::PARAMATTR_CODE_ENTRY_OLD
: // ENTRY: [paramidx0, attr0, ...]
2030 // Deprecated, but still needed to read old bitcode files.
2031 if (Record
.size() & 1)
2032 return error("Invalid parameter attribute record");
2034 for (unsigned i
= 0, e
= Record
.size(); i
!= e
; i
+= 2) {
2035 AttrBuilder
B(Context
);
2036 decodeLLVMAttributesForBitcode(B
, Record
[i
+1], Record
[i
]);
2037 Attrs
.push_back(AttributeList::get(Context
, Record
[i
], B
));
2040 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
2043 case bitc::PARAMATTR_CODE_ENTRY
: // ENTRY: [attrgrp0, attrgrp1, ...]
2044 for (uint64_t Val
: Record
)
2045 Attrs
.push_back(MAttributeGroups
[Val
]);
2047 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
2054 // Returns Attribute::None on unrecognized codes.
2055 static Attribute::AttrKind
getAttrFromCode(uint64_t Code
) {
2058 return Attribute::None
;
2059 case bitc::ATTR_KIND_ALIGNMENT
:
2060 return Attribute::Alignment
;
2061 case bitc::ATTR_KIND_ALWAYS_INLINE
:
2062 return Attribute::AlwaysInline
;
2063 case bitc::ATTR_KIND_BUILTIN
:
2064 return Attribute::Builtin
;
2065 case bitc::ATTR_KIND_BY_VAL
:
2066 return Attribute::ByVal
;
2067 case bitc::ATTR_KIND_IN_ALLOCA
:
2068 return Attribute::InAlloca
;
2069 case bitc::ATTR_KIND_COLD
:
2070 return Attribute::Cold
;
2071 case bitc::ATTR_KIND_CONVERGENT
:
2072 return Attribute::Convergent
;
2073 case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
:
2074 return Attribute::DisableSanitizerInstrumentation
;
2075 case bitc::ATTR_KIND_ELEMENTTYPE
:
2076 return Attribute::ElementType
;
2077 case bitc::ATTR_KIND_FNRETTHUNK_EXTERN
:
2078 return Attribute::FnRetThunkExtern
;
2079 case bitc::ATTR_KIND_INLINE_HINT
:
2080 return Attribute::InlineHint
;
2081 case bitc::ATTR_KIND_IN_REG
:
2082 return Attribute::InReg
;
2083 case bitc::ATTR_KIND_JUMP_TABLE
:
2084 return Attribute::JumpTable
;
2085 case bitc::ATTR_KIND_MEMORY
:
2086 return Attribute::Memory
;
2087 case bitc::ATTR_KIND_NOFPCLASS
:
2088 return Attribute::NoFPClass
;
2089 case bitc::ATTR_KIND_MIN_SIZE
:
2090 return Attribute::MinSize
;
2091 case bitc::ATTR_KIND_NAKED
:
2092 return Attribute::Naked
;
2093 case bitc::ATTR_KIND_NEST
:
2094 return Attribute::Nest
;
2095 case bitc::ATTR_KIND_NO_ALIAS
:
2096 return Attribute::NoAlias
;
2097 case bitc::ATTR_KIND_NO_BUILTIN
:
2098 return Attribute::NoBuiltin
;
2099 case bitc::ATTR_KIND_NO_CALLBACK
:
2100 return Attribute::NoCallback
;
2101 case bitc::ATTR_KIND_NO_CAPTURE
:
2102 return Attribute::NoCapture
;
2103 case bitc::ATTR_KIND_NO_DIVERGENCE_SOURCE
:
2104 return Attribute::NoDivergenceSource
;
2105 case bitc::ATTR_KIND_NO_DUPLICATE
:
2106 return Attribute::NoDuplicate
;
2107 case bitc::ATTR_KIND_NOFREE
:
2108 return Attribute::NoFree
;
2109 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT
:
2110 return Attribute::NoImplicitFloat
;
2111 case bitc::ATTR_KIND_NO_INLINE
:
2112 return Attribute::NoInline
;
2113 case bitc::ATTR_KIND_NO_RECURSE
:
2114 return Attribute::NoRecurse
;
2115 case bitc::ATTR_KIND_NO_MERGE
:
2116 return Attribute::NoMerge
;
2117 case bitc::ATTR_KIND_NON_LAZY_BIND
:
2118 return Attribute::NonLazyBind
;
2119 case bitc::ATTR_KIND_NON_NULL
:
2120 return Attribute::NonNull
;
2121 case bitc::ATTR_KIND_DEREFERENCEABLE
:
2122 return Attribute::Dereferenceable
;
2123 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL
:
2124 return Attribute::DereferenceableOrNull
;
2125 case bitc::ATTR_KIND_ALLOC_ALIGN
:
2126 return Attribute::AllocAlign
;
2127 case bitc::ATTR_KIND_ALLOC_KIND
:
2128 return Attribute::AllocKind
;
2129 case bitc::ATTR_KIND_ALLOC_SIZE
:
2130 return Attribute::AllocSize
;
2131 case bitc::ATTR_KIND_ALLOCATED_POINTER
:
2132 return Attribute::AllocatedPointer
;
2133 case bitc::ATTR_KIND_NO_RED_ZONE
:
2134 return Attribute::NoRedZone
;
2135 case bitc::ATTR_KIND_NO_RETURN
:
2136 return Attribute::NoReturn
;
2137 case bitc::ATTR_KIND_NOSYNC
:
2138 return Attribute::NoSync
;
2139 case bitc::ATTR_KIND_NOCF_CHECK
:
2140 return Attribute::NoCfCheck
;
2141 case bitc::ATTR_KIND_NO_PROFILE
:
2142 return Attribute::NoProfile
;
2143 case bitc::ATTR_KIND_SKIP_PROFILE
:
2144 return Attribute::SkipProfile
;
2145 case bitc::ATTR_KIND_NO_UNWIND
:
2146 return Attribute::NoUnwind
;
2147 case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS
:
2148 return Attribute::NoSanitizeBounds
;
2149 case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE
:
2150 return Attribute::NoSanitizeCoverage
;
2151 case bitc::ATTR_KIND_NULL_POINTER_IS_VALID
:
2152 return Attribute::NullPointerIsValid
;
2153 case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
:
2154 return Attribute::OptimizeForDebugging
;
2155 case bitc::ATTR_KIND_OPT_FOR_FUZZING
:
2156 return Attribute::OptForFuzzing
;
2157 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE
:
2158 return Attribute::OptimizeForSize
;
2159 case bitc::ATTR_KIND_OPTIMIZE_NONE
:
2160 return Attribute::OptimizeNone
;
2161 case bitc::ATTR_KIND_READ_NONE
:
2162 return Attribute::ReadNone
;
2163 case bitc::ATTR_KIND_READ_ONLY
:
2164 return Attribute::ReadOnly
;
2165 case bitc::ATTR_KIND_RETURNED
:
2166 return Attribute::Returned
;
2167 case bitc::ATTR_KIND_RETURNS_TWICE
:
2168 return Attribute::ReturnsTwice
;
2169 case bitc::ATTR_KIND_S_EXT
:
2170 return Attribute::SExt
;
2171 case bitc::ATTR_KIND_SPECULATABLE
:
2172 return Attribute::Speculatable
;
2173 case bitc::ATTR_KIND_STACK_ALIGNMENT
:
2174 return Attribute::StackAlignment
;
2175 case bitc::ATTR_KIND_STACK_PROTECT
:
2176 return Attribute::StackProtect
;
2177 case bitc::ATTR_KIND_STACK_PROTECT_REQ
:
2178 return Attribute::StackProtectReq
;
2179 case bitc::ATTR_KIND_STACK_PROTECT_STRONG
:
2180 return Attribute::StackProtectStrong
;
2181 case bitc::ATTR_KIND_SAFESTACK
:
2182 return Attribute::SafeStack
;
2183 case bitc::ATTR_KIND_SHADOWCALLSTACK
:
2184 return Attribute::ShadowCallStack
;
2185 case bitc::ATTR_KIND_STRICT_FP
:
2186 return Attribute::StrictFP
;
2187 case bitc::ATTR_KIND_STRUCT_RET
:
2188 return Attribute::StructRet
;
2189 case bitc::ATTR_KIND_SANITIZE_ADDRESS
:
2190 return Attribute::SanitizeAddress
;
2191 case bitc::ATTR_KIND_SANITIZE_HWADDRESS
:
2192 return Attribute::SanitizeHWAddress
;
2193 case bitc::ATTR_KIND_SANITIZE_THREAD
:
2194 return Attribute::SanitizeThread
;
2195 case bitc::ATTR_KIND_SANITIZE_TYPE
:
2196 return Attribute::SanitizeType
;
2197 case bitc::ATTR_KIND_SANITIZE_MEMORY
:
2198 return Attribute::SanitizeMemory
;
2199 case bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
:
2200 return Attribute::SanitizeNumericalStability
;
2201 case bitc::ATTR_KIND_SANITIZE_REALTIME
:
2202 return Attribute::SanitizeRealtime
;
2203 case bitc::ATTR_KIND_SANITIZE_REALTIME_BLOCKING
:
2204 return Attribute::SanitizeRealtimeBlocking
;
2205 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING
:
2206 return Attribute::SpeculativeLoadHardening
;
2207 case bitc::ATTR_KIND_SWIFT_ERROR
:
2208 return Attribute::SwiftError
;
2209 case bitc::ATTR_KIND_SWIFT_SELF
:
2210 return Attribute::SwiftSelf
;
2211 case bitc::ATTR_KIND_SWIFT_ASYNC
:
2212 return Attribute::SwiftAsync
;
2213 case bitc::ATTR_KIND_UW_TABLE
:
2214 return Attribute::UWTable
;
2215 case bitc::ATTR_KIND_VSCALE_RANGE
:
2216 return Attribute::VScaleRange
;
2217 case bitc::ATTR_KIND_WILLRETURN
:
2218 return Attribute::WillReturn
;
2219 case bitc::ATTR_KIND_WRITEONLY
:
2220 return Attribute::WriteOnly
;
2221 case bitc::ATTR_KIND_Z_EXT
:
2222 return Attribute::ZExt
;
2223 case bitc::ATTR_KIND_IMMARG
:
2224 return Attribute::ImmArg
;
2225 case bitc::ATTR_KIND_SANITIZE_MEMTAG
:
2226 return Attribute::SanitizeMemTag
;
2227 case bitc::ATTR_KIND_PREALLOCATED
:
2228 return Attribute::Preallocated
;
2229 case bitc::ATTR_KIND_NOUNDEF
:
2230 return Attribute::NoUndef
;
2231 case bitc::ATTR_KIND_BYREF
:
2232 return Attribute::ByRef
;
2233 case bitc::ATTR_KIND_MUSTPROGRESS
:
2234 return Attribute::MustProgress
;
2235 case bitc::ATTR_KIND_HOT
:
2236 return Attribute::Hot
;
2237 case bitc::ATTR_KIND_PRESPLIT_COROUTINE
:
2238 return Attribute::PresplitCoroutine
;
2239 case bitc::ATTR_KIND_WRITABLE
:
2240 return Attribute::Writable
;
2241 case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
:
2242 return Attribute::CoroDestroyOnlyWhenComplete
;
2243 case bitc::ATTR_KIND_DEAD_ON_UNWIND
:
2244 return Attribute::DeadOnUnwind
;
2245 case bitc::ATTR_KIND_RANGE
:
2246 return Attribute::Range
;
2247 case bitc::ATTR_KIND_INITIALIZES
:
2248 return Attribute::Initializes
;
2249 case bitc::ATTR_KIND_CORO_ELIDE_SAFE
:
2250 return Attribute::CoroElideSafe
;
2251 case bitc::ATTR_KIND_NO_EXT
:
2252 return Attribute::NoExt
;
2253 case bitc::ATTR_KIND_CAPTURES
:
2254 return Attribute::Captures
;
2258 Error
BitcodeReader::parseAlignmentValue(uint64_t Exponent
,
2259 MaybeAlign
&Alignment
) {
2260 // Note: Alignment in bitcode files is incremented by 1, so that zero
2261 // can be used for default alignment.
2262 if (Exponent
> Value::MaxAlignmentExponent
+ 1)
2263 return error("Invalid alignment value");
2264 Alignment
= decodeMaybeAlign(Exponent
);
2265 return Error::success();
2268 Error
BitcodeReader::parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
) {
2269 *Kind
= getAttrFromCode(Code
);
2270 if (*Kind
== Attribute::None
)
2271 return error("Unknown attribute kind (" + Twine(Code
) + ")");
2272 return Error::success();
2275 static bool upgradeOldMemoryAttribute(MemoryEffects
&ME
, uint64_t EncodedKind
) {
2276 switch (EncodedKind
) {
2277 case bitc::ATTR_KIND_READ_NONE
:
2278 ME
&= MemoryEffects::none();
2280 case bitc::ATTR_KIND_READ_ONLY
:
2281 ME
&= MemoryEffects::readOnly();
2283 case bitc::ATTR_KIND_WRITEONLY
:
2284 ME
&= MemoryEffects::writeOnly();
2286 case bitc::ATTR_KIND_ARGMEMONLY
:
2287 ME
&= MemoryEffects::argMemOnly();
2289 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY
:
2290 ME
&= MemoryEffects::inaccessibleMemOnly();
2292 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
:
2293 ME
&= MemoryEffects::inaccessibleOrArgMemOnly();
2300 Error
BitcodeReader::parseAttributeGroupBlock() {
2301 if (Error Err
= Stream
.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID
))
2304 if (!MAttributeGroups
.empty())
2305 return error("Invalid multiple blocks");
2307 SmallVector
<uint64_t, 64> Record
;
2309 // Read all the records.
2311 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2313 return MaybeEntry
.takeError();
2314 BitstreamEntry Entry
= MaybeEntry
.get();
2316 switch (Entry
.Kind
) {
2317 case BitstreamEntry::SubBlock
: // Handled for us already.
2318 case BitstreamEntry::Error
:
2319 return error("Malformed block");
2320 case BitstreamEntry::EndBlock
:
2321 return Error::success();
2322 case BitstreamEntry::Record
:
2323 // The interesting case.
2329 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2331 return MaybeRecord
.takeError();
2332 switch (MaybeRecord
.get()) {
2333 default: // Default behavior: ignore.
2335 case bitc::PARAMATTR_GRP_CODE_ENTRY
: { // ENTRY: [grpid, idx, a0, a1, ...]
2336 if (Record
.size() < 3)
2337 return error("Invalid grp record");
2339 uint64_t GrpID
= Record
[0];
2340 uint64_t Idx
= Record
[1]; // Index of the object this attribute refers to.
2342 AttrBuilder
B(Context
);
2343 MemoryEffects ME
= MemoryEffects::unknown();
2344 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
2345 if (Record
[i
] == 0) { // Enum attribute
2346 Attribute::AttrKind Kind
;
2347 uint64_t EncodedKind
= Record
[++i
];
2348 if (Idx
== AttributeList::FunctionIndex
&&
2349 upgradeOldMemoryAttribute(ME
, EncodedKind
))
2352 if (Error Err
= parseAttrKind(EncodedKind
, &Kind
))
2355 // Upgrade old-style byval attribute to one with a type, even if it's
2356 // nullptr. We will have to insert the real type when we associate
2357 // this AttributeList with a function.
2358 if (Kind
== Attribute::ByVal
)
2359 B
.addByValAttr(nullptr);
2360 else if (Kind
== Attribute::StructRet
)
2361 B
.addStructRetAttr(nullptr);
2362 else if (Kind
== Attribute::InAlloca
)
2363 B
.addInAllocaAttr(nullptr);
2364 else if (Kind
== Attribute::UWTable
)
2365 B
.addUWTableAttr(UWTableKind::Default
);
2366 else if (Attribute::isEnumAttrKind(Kind
))
2367 B
.addAttribute(Kind
);
2369 return error("Not an enum attribute");
2370 } else if (Record
[i
] == 1) { // Integer attribute
2371 Attribute::AttrKind Kind
;
2372 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
2374 if (!Attribute::isIntAttrKind(Kind
))
2375 return error("Not an int attribute");
2376 if (Kind
== Attribute::Alignment
)
2377 B
.addAlignmentAttr(Record
[++i
]);
2378 else if (Kind
== Attribute::StackAlignment
)
2379 B
.addStackAlignmentAttr(Record
[++i
]);
2380 else if (Kind
== Attribute::Dereferenceable
)
2381 B
.addDereferenceableAttr(Record
[++i
]);
2382 else if (Kind
== Attribute::DereferenceableOrNull
)
2383 B
.addDereferenceableOrNullAttr(Record
[++i
]);
2384 else if (Kind
== Attribute::AllocSize
)
2385 B
.addAllocSizeAttrFromRawRepr(Record
[++i
]);
2386 else if (Kind
== Attribute::VScaleRange
)
2387 B
.addVScaleRangeAttrFromRawRepr(Record
[++i
]);
2388 else if (Kind
== Attribute::UWTable
)
2389 B
.addUWTableAttr(UWTableKind(Record
[++i
]));
2390 else if (Kind
== Attribute::AllocKind
)
2391 B
.addAllocKindAttr(static_cast<AllocFnKind
>(Record
[++i
]));
2392 else if (Kind
== Attribute::Memory
)
2393 B
.addMemoryAttr(MemoryEffects::createFromIntValue(Record
[++i
]));
2394 else if (Kind
== Attribute::Captures
)
2395 B
.addCapturesAttr(CaptureInfo::createFromIntValue(Record
[++i
]));
2396 else if (Kind
== Attribute::NoFPClass
)
2398 static_cast<FPClassTest
>(Record
[++i
] & fcAllFlags
));
2399 } else if (Record
[i
] == 3 || Record
[i
] == 4) { // String attribute
2400 bool HasValue
= (Record
[i
++] == 4);
2401 SmallString
<64> KindStr
;
2402 SmallString
<64> ValStr
;
2404 while (Record
[i
] != 0 && i
!= e
)
2405 KindStr
+= Record
[i
++];
2406 assert(Record
[i
] == 0 && "Kind string not null terminated");
2409 // Has a value associated with it.
2410 ++i
; // Skip the '0' that terminates the "kind" string.
2411 while (Record
[i
] != 0 && i
!= e
)
2412 ValStr
+= Record
[i
++];
2413 assert(Record
[i
] == 0 && "Value string not null terminated");
2416 B
.addAttribute(KindStr
.str(), ValStr
.str());
2417 } else if (Record
[i
] == 5 || Record
[i
] == 6) {
2418 bool HasType
= Record
[i
] == 6;
2419 Attribute::AttrKind Kind
;
2420 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
2422 if (!Attribute::isTypeAttrKind(Kind
))
2423 return error("Not a type attribute");
2425 B
.addTypeAttr(Kind
, HasType
? getTypeByID(Record
[++i
]) : nullptr);
2426 } else if (Record
[i
] == 7) {
2427 Attribute::AttrKind Kind
;
2430 if (Error Err
= parseAttrKind(Record
[i
++], &Kind
))
2432 if (!Attribute::isConstantRangeAttrKind(Kind
))
2433 return error("Not a ConstantRange attribute");
2435 Expected
<ConstantRange
> MaybeCR
=
2436 readBitWidthAndConstantRange(Record
, i
);
2438 return MaybeCR
.takeError();
2441 B
.addConstantRangeAttr(Kind
, MaybeCR
.get());
2442 } else if (Record
[i
] == 8) {
2443 Attribute::AttrKind Kind
;
2446 if (Error Err
= parseAttrKind(Record
[i
++], &Kind
))
2448 if (!Attribute::isConstantRangeListAttrKind(Kind
))
2449 return error("Not a constant range list attribute");
2451 SmallVector
<ConstantRange
, 2> Val
;
2453 return error("Too few records for constant range list");
2454 unsigned RangeSize
= Record
[i
++];
2455 unsigned BitWidth
= Record
[i
++];
2456 for (unsigned Idx
= 0; Idx
< RangeSize
; ++Idx
) {
2457 Expected
<ConstantRange
> MaybeCR
=
2458 readConstantRange(Record
, i
, BitWidth
);
2460 return MaybeCR
.takeError();
2461 Val
.push_back(MaybeCR
.get());
2465 if (!ConstantRangeList::isOrderedRanges(Val
))
2466 return error("Invalid (unordered or overlapping) range list");
2467 B
.addConstantRangeListAttr(Kind
, Val
);
2469 return error("Invalid attribute group entry");
2473 if (ME
!= MemoryEffects::unknown())
2474 B
.addMemoryAttr(ME
);
2476 UpgradeAttributes(B
);
2477 MAttributeGroups
[GrpID
] = AttributeList::get(Context
, Idx
, B
);
2484 Error
BitcodeReader::parseTypeTable() {
2485 if (Error Err
= Stream
.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW
))
2488 return parseTypeTableBody();
2491 Error
BitcodeReader::parseTypeTableBody() {
2492 if (!TypeList
.empty())
2493 return error("Invalid multiple blocks");
2495 SmallVector
<uint64_t, 64> Record
;
2496 unsigned NumRecords
= 0;
2498 SmallString
<64> TypeName
;
2500 // Read all the records for this type table.
2502 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2504 return MaybeEntry
.takeError();
2505 BitstreamEntry Entry
= MaybeEntry
.get();
2507 switch (Entry
.Kind
) {
2508 case BitstreamEntry::SubBlock
: // Handled for us already.
2509 case BitstreamEntry::Error
:
2510 return error("Malformed block");
2511 case BitstreamEntry::EndBlock
:
2512 if (NumRecords
!= TypeList
.size())
2513 return error("Malformed block");
2514 return Error::success();
2515 case BitstreamEntry::Record
:
2516 // The interesting case.
2522 Type
*ResultTy
= nullptr;
2523 SmallVector
<unsigned> ContainedIDs
;
2524 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2526 return MaybeRecord
.takeError();
2527 switch (MaybeRecord
.get()) {
2529 return error("Invalid value");
2530 case bitc::TYPE_CODE_NUMENTRY
: // TYPE_CODE_NUMENTRY: [numentries]
2531 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2532 // type list. This allows us to reserve space.
2534 return error("Invalid numentry record");
2535 TypeList
.resize(Record
[0]);
2537 case bitc::TYPE_CODE_VOID
: // VOID
2538 ResultTy
= Type::getVoidTy(Context
);
2540 case bitc::TYPE_CODE_HALF
: // HALF
2541 ResultTy
= Type::getHalfTy(Context
);
2543 case bitc::TYPE_CODE_BFLOAT
: // BFLOAT
2544 ResultTy
= Type::getBFloatTy(Context
);
2546 case bitc::TYPE_CODE_FLOAT
: // FLOAT
2547 ResultTy
= Type::getFloatTy(Context
);
2549 case bitc::TYPE_CODE_DOUBLE
: // DOUBLE
2550 ResultTy
= Type::getDoubleTy(Context
);
2552 case bitc::TYPE_CODE_X86_FP80
: // X86_FP80
2553 ResultTy
= Type::getX86_FP80Ty(Context
);
2555 case bitc::TYPE_CODE_FP128
: // FP128
2556 ResultTy
= Type::getFP128Ty(Context
);
2558 case bitc::TYPE_CODE_PPC_FP128
: // PPC_FP128
2559 ResultTy
= Type::getPPC_FP128Ty(Context
);
2561 case bitc::TYPE_CODE_LABEL
: // LABEL
2562 ResultTy
= Type::getLabelTy(Context
);
2564 case bitc::TYPE_CODE_METADATA
: // METADATA
2565 ResultTy
= Type::getMetadataTy(Context
);
2567 case bitc::TYPE_CODE_X86_MMX
: // X86_MMX
2568 // Deprecated: decodes as <1 x i64>
2570 llvm::FixedVectorType::get(llvm::IntegerType::get(Context
, 64), 1);
2572 case bitc::TYPE_CODE_X86_AMX
: // X86_AMX
2573 ResultTy
= Type::getX86_AMXTy(Context
);
2575 case bitc::TYPE_CODE_TOKEN
: // TOKEN
2576 ResultTy
= Type::getTokenTy(Context
);
2578 case bitc::TYPE_CODE_INTEGER
: { // INTEGER: [width]
2580 return error("Invalid integer record");
2582 uint64_t NumBits
= Record
[0];
2583 if (NumBits
< IntegerType::MIN_INT_BITS
||
2584 NumBits
> IntegerType::MAX_INT_BITS
)
2585 return error("Bitwidth for integer type out of range");
2586 ResultTy
= IntegerType::get(Context
, NumBits
);
2589 case bitc::TYPE_CODE_POINTER
: { // POINTER: [pointee type] or
2590 // [pointee type, address space]
2592 return error("Invalid pointer record");
2593 unsigned AddressSpace
= 0;
2594 if (Record
.size() == 2)
2595 AddressSpace
= Record
[1];
2596 ResultTy
= getTypeByID(Record
[0]);
2598 !PointerType::isValidElementType(ResultTy
))
2599 return error("Invalid type");
2600 ContainedIDs
.push_back(Record
[0]);
2601 ResultTy
= PointerType::get(ResultTy
, AddressSpace
);
2604 case bitc::TYPE_CODE_OPAQUE_POINTER
: { // OPAQUE_POINTER: [addrspace]
2605 if (Record
.size() != 1)
2606 return error("Invalid opaque pointer record");
2607 unsigned AddressSpace
= Record
[0];
2608 ResultTy
= PointerType::get(Context
, AddressSpace
);
2611 case bitc::TYPE_CODE_FUNCTION_OLD
: {
2612 // Deprecated, but still needed to read old bitcode files.
2613 // FUNCTION: [vararg, attrid, retty, paramty x N]
2614 if (Record
.size() < 3)
2615 return error("Invalid function record");
2616 SmallVector
<Type
*, 8> ArgTys
;
2617 for (unsigned i
= 3, e
= Record
.size(); i
!= e
; ++i
) {
2618 if (Type
*T
= getTypeByID(Record
[i
]))
2619 ArgTys
.push_back(T
);
2624 ResultTy
= getTypeByID(Record
[2]);
2625 if (!ResultTy
|| ArgTys
.size() < Record
.size()-3)
2626 return error("Invalid type");
2628 ContainedIDs
.append(Record
.begin() + 2, Record
.end());
2629 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
2632 case bitc::TYPE_CODE_FUNCTION
: {
2633 // FUNCTION: [vararg, retty, paramty x N]
2634 if (Record
.size() < 2)
2635 return error("Invalid function record");
2636 SmallVector
<Type
*, 8> ArgTys
;
2637 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
2638 if (Type
*T
= getTypeByID(Record
[i
])) {
2639 if (!FunctionType::isValidArgumentType(T
))
2640 return error("Invalid function argument type");
2641 ArgTys
.push_back(T
);
2647 ResultTy
= getTypeByID(Record
[1]);
2648 if (!ResultTy
|| ArgTys
.size() < Record
.size()-2)
2649 return error("Invalid type");
2651 ContainedIDs
.append(Record
.begin() + 1, Record
.end());
2652 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
2655 case bitc::TYPE_CODE_STRUCT_ANON
: { // STRUCT: [ispacked, eltty x N]
2657 return error("Invalid anon struct record");
2658 SmallVector
<Type
*, 8> EltTys
;
2659 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
2660 if (Type
*T
= getTypeByID(Record
[i
]))
2661 EltTys
.push_back(T
);
2665 if (EltTys
.size() != Record
.size()-1)
2666 return error("Invalid type");
2667 ContainedIDs
.append(Record
.begin() + 1, Record
.end());
2668 ResultTy
= StructType::get(Context
, EltTys
, Record
[0]);
2671 case bitc::TYPE_CODE_STRUCT_NAME
: // STRUCT_NAME: [strchr x N]
2672 if (convertToString(Record
, 0, TypeName
))
2673 return error("Invalid struct name record");
2676 case bitc::TYPE_CODE_STRUCT_NAMED
: { // STRUCT: [ispacked, eltty x N]
2678 return error("Invalid named struct record");
2680 if (NumRecords
>= TypeList
.size())
2681 return error("Invalid TYPE table");
2683 // Check to see if this was forward referenced, if so fill in the temp.
2684 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
2686 Res
->setName(TypeName
);
2687 TypeList
[NumRecords
] = nullptr;
2688 } else // Otherwise, create a new struct.
2689 Res
= createIdentifiedStructType(Context
, TypeName
);
2692 SmallVector
<Type
*, 8> EltTys
;
2693 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
2694 if (Type
*T
= getTypeByID(Record
[i
]))
2695 EltTys
.push_back(T
);
2699 if (EltTys
.size() != Record
.size()-1)
2700 return error("Invalid named struct record");
2701 if (auto E
= Res
->setBodyOrError(EltTys
, Record
[0]))
2703 ContainedIDs
.append(Record
.begin() + 1, Record
.end());
2707 case bitc::TYPE_CODE_OPAQUE
: { // OPAQUE: []
2708 if (Record
.size() != 1)
2709 return error("Invalid opaque type record");
2711 if (NumRecords
>= TypeList
.size())
2712 return error("Invalid TYPE table");
2714 // Check to see if this was forward referenced, if so fill in the temp.
2715 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
2717 Res
->setName(TypeName
);
2718 TypeList
[NumRecords
] = nullptr;
2719 } else // Otherwise, create a new struct with no body.
2720 Res
= createIdentifiedStructType(Context
, TypeName
);
2725 case bitc::TYPE_CODE_TARGET_TYPE
: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2726 if (Record
.size() < 1)
2727 return error("Invalid target extension type record");
2729 if (NumRecords
>= TypeList
.size())
2730 return error("Invalid TYPE table");
2732 if (Record
[0] >= Record
.size())
2733 return error("Too many type parameters");
2735 unsigned NumTys
= Record
[0];
2736 SmallVector
<Type
*, 4> TypeParams
;
2737 SmallVector
<unsigned, 8> IntParams
;
2738 for (unsigned i
= 0; i
< NumTys
; i
++) {
2739 if (Type
*T
= getTypeByID(Record
[i
+ 1]))
2740 TypeParams
.push_back(T
);
2742 return error("Invalid type");
2745 for (unsigned i
= NumTys
+ 1, e
= Record
.size(); i
< e
; i
++) {
2746 if (Record
[i
] > UINT_MAX
)
2747 return error("Integer parameter too large");
2748 IntParams
.push_back(Record
[i
]);
2751 TargetExtType::getOrError(Context
, TypeName
, TypeParams
, IntParams
);
2752 if (auto E
= TTy
.takeError())
2758 case bitc::TYPE_CODE_ARRAY
: // ARRAY: [numelts, eltty]
2759 if (Record
.size() < 2)
2760 return error("Invalid array type record");
2761 ResultTy
= getTypeByID(Record
[1]);
2762 if (!ResultTy
|| !ArrayType::isValidElementType(ResultTy
))
2763 return error("Invalid type");
2764 ContainedIDs
.push_back(Record
[1]);
2765 ResultTy
= ArrayType::get(ResultTy
, Record
[0]);
2767 case bitc::TYPE_CODE_VECTOR
: // VECTOR: [numelts, eltty] or
2768 // [numelts, eltty, scalable]
2769 if (Record
.size() < 2)
2770 return error("Invalid vector type record");
2772 return error("Invalid vector length");
2773 ResultTy
= getTypeByID(Record
[1]);
2774 if (!ResultTy
|| !VectorType::isValidElementType(ResultTy
))
2775 return error("Invalid type");
2776 bool Scalable
= Record
.size() > 2 ? Record
[2] : false;
2777 ContainedIDs
.push_back(Record
[1]);
2778 ResultTy
= VectorType::get(ResultTy
, Record
[0], Scalable
);
2782 if (NumRecords
>= TypeList
.size())
2783 return error("Invalid TYPE table");
2784 if (TypeList
[NumRecords
])
2786 "Invalid TYPE table: Only named structs can be forward referenced");
2787 assert(ResultTy
&& "Didn't read a type?");
2788 TypeList
[NumRecords
] = ResultTy
;
2789 if (!ContainedIDs
.empty())
2790 ContainedTypeIDs
[NumRecords
] = std::move(ContainedIDs
);
2795 Error
BitcodeReader::parseOperandBundleTags() {
2796 if (Error Err
= Stream
.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
))
2799 if (!BundleTags
.empty())
2800 return error("Invalid multiple blocks");
2802 SmallVector
<uint64_t, 64> Record
;
2805 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2807 return MaybeEntry
.takeError();
2808 BitstreamEntry Entry
= MaybeEntry
.get();
2810 switch (Entry
.Kind
) {
2811 case BitstreamEntry::SubBlock
: // Handled for us already.
2812 case BitstreamEntry::Error
:
2813 return error("Malformed block");
2814 case BitstreamEntry::EndBlock
:
2815 return Error::success();
2816 case BitstreamEntry::Record
:
2817 // The interesting case.
2821 // Tags are implicitly mapped to integers by their order.
2823 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2825 return MaybeRecord
.takeError();
2826 if (MaybeRecord
.get() != bitc::OPERAND_BUNDLE_TAG
)
2827 return error("Invalid operand bundle record");
2829 // OPERAND_BUNDLE_TAG: [strchr x N]
2830 BundleTags
.emplace_back();
2831 if (convertToString(Record
, 0, BundleTags
.back()))
2832 return error("Invalid operand bundle record");
2837 Error
BitcodeReader::parseSyncScopeNames() {
2838 if (Error Err
= Stream
.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID
))
2842 return error("Invalid multiple synchronization scope names blocks");
2844 SmallVector
<uint64_t, 64> Record
;
2846 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2848 return MaybeEntry
.takeError();
2849 BitstreamEntry Entry
= MaybeEntry
.get();
2851 switch (Entry
.Kind
) {
2852 case BitstreamEntry::SubBlock
: // Handled for us already.
2853 case BitstreamEntry::Error
:
2854 return error("Malformed block");
2855 case BitstreamEntry::EndBlock
:
2857 return error("Invalid empty synchronization scope names block");
2858 return Error::success();
2859 case BitstreamEntry::Record
:
2860 // The interesting case.
2864 // Synchronization scope names are implicitly mapped to synchronization
2865 // scope IDs by their order.
2867 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2869 return MaybeRecord
.takeError();
2870 if (MaybeRecord
.get() != bitc::SYNC_SCOPE_NAME
)
2871 return error("Invalid sync scope record");
2873 SmallString
<16> SSN
;
2874 if (convertToString(Record
, 0, SSN
))
2875 return error("Invalid sync scope record");
2877 SSIDs
.push_back(Context
.getOrInsertSyncScopeID(SSN
));
2882 /// Associate a value with its name from the given index in the provided record.
2883 Expected
<Value
*> BitcodeReader::recordValue(SmallVectorImpl
<uint64_t> &Record
,
2884 unsigned NameIndex
, Triple
&TT
) {
2885 SmallString
<128> ValueName
;
2886 if (convertToString(Record
, NameIndex
, ValueName
))
2887 return error("Invalid record");
2888 unsigned ValueID
= Record
[0];
2889 if (ValueID
>= ValueList
.size() || !ValueList
[ValueID
])
2890 return error("Invalid record");
2891 Value
*V
= ValueList
[ValueID
];
2893 StringRef
NameStr(ValueName
.data(), ValueName
.size());
2894 if (NameStr
.contains(0))
2895 return error("Invalid value name");
2896 V
->setName(NameStr
);
2897 auto *GO
= dyn_cast
<GlobalObject
>(V
);
2898 if (GO
&& ImplicitComdatObjects
.contains(GO
) && TT
.supportsCOMDAT())
2899 GO
->setComdat(TheModule
->getOrInsertComdat(V
->getName()));
2903 /// Helper to note and return the current location, and jump to the given
2905 static Expected
<uint64_t> jumpToValueSymbolTable(uint64_t Offset
,
2906 BitstreamCursor
&Stream
) {
2907 // Save the current parsing location so we can jump back at the end
2909 uint64_t CurrentBit
= Stream
.GetCurrentBitNo();
2910 if (Error JumpFailed
= Stream
.JumpToBit(Offset
* 32))
2911 return std::move(JumpFailed
);
2912 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advance();
2914 return MaybeEntry
.takeError();
2915 if (MaybeEntry
.get().Kind
!= BitstreamEntry::SubBlock
||
2916 MaybeEntry
.get().ID
!= bitc::VALUE_SYMTAB_BLOCK_ID
)
2917 return error("Expected value symbol table subblock");
2921 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
,
2923 ArrayRef
<uint64_t> Record
) {
2924 // Note that we subtract 1 here because the offset is relative to one word
2925 // before the start of the identification or module block, which was
2926 // historically always the start of the regular bitcode header.
2927 uint64_t FuncWordOffset
= Record
[1] - 1;
2928 uint64_t FuncBitOffset
= FuncWordOffset
* 32;
2929 DeferredFunctionInfo
[F
] = FuncBitOffset
+ FuncBitcodeOffsetDelta
;
2930 // Set the LastFunctionBlockBit to point to the last function block.
2931 // Later when parsing is resumed after function materialization,
2932 // we can simply skip that last function block.
2933 if (FuncBitOffset
> LastFunctionBlockBit
)
2934 LastFunctionBlockBit
= FuncBitOffset
;
2937 /// Read a new-style GlobalValue symbol table.
2938 Error
BitcodeReader::parseGlobalValueSymbolTable() {
2939 unsigned FuncBitcodeOffsetDelta
=
2940 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
2942 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
2945 SmallVector
<uint64_t, 64> Record
;
2947 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2949 return MaybeEntry
.takeError();
2950 BitstreamEntry Entry
= MaybeEntry
.get();
2952 switch (Entry
.Kind
) {
2953 case BitstreamEntry::SubBlock
:
2954 case BitstreamEntry::Error
:
2955 return error("Malformed block");
2956 case BitstreamEntry::EndBlock
:
2957 return Error::success();
2958 case BitstreamEntry::Record
:
2963 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2965 return MaybeRecord
.takeError();
2966 switch (MaybeRecord
.get()) {
2967 case bitc::VST_CODE_FNENTRY
: { // [valueid, offset]
2968 unsigned ValueID
= Record
[0];
2969 if (ValueID
>= ValueList
.size() || !ValueList
[ValueID
])
2970 return error("Invalid value reference in symbol table");
2971 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
,
2972 cast
<Function
>(ValueList
[ValueID
]), Record
);
2979 /// Parse the value symbol table at either the current parsing location or
2980 /// at the given bit offset if provided.
2981 Error
BitcodeReader::parseValueSymbolTable(uint64_t Offset
) {
2982 uint64_t CurrentBit
;
2983 // Pass in the Offset to distinguish between calling for the module-level
2984 // VST (where we want to jump to the VST offset) and the function-level
2985 // VST (where we don't).
2987 Expected
<uint64_t> MaybeCurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
2988 if (!MaybeCurrentBit
)
2989 return MaybeCurrentBit
.takeError();
2990 CurrentBit
= MaybeCurrentBit
.get();
2991 // If this module uses a string table, read this as a module-level VST.
2993 if (Error Err
= parseGlobalValueSymbolTable())
2995 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
2997 return Error::success();
2999 // Otherwise, the VST will be in a similar format to a function-level VST,
3000 // and will contain symbol names.
3003 // Compute the delta between the bitcode indices in the VST (the word offset
3004 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
3005 // expected by the lazy reader. The reader's EnterSubBlock expects to have
3006 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
3007 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
3008 // just before entering the VST subblock because: 1) the EnterSubBlock
3009 // changes the AbbrevID width; 2) the VST block is nested within the same
3010 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
3011 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
3012 // jump to the FUNCTION_BLOCK using this offset later, we don't want
3013 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
3014 unsigned FuncBitcodeOffsetDelta
=
3015 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
3017 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
3020 SmallVector
<uint64_t, 64> Record
;
3022 Triple
TT(TheModule
->getTargetTriple());
3024 // Read all the records for this value table.
3025 SmallString
<128> ValueName
;
3028 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
3030 return MaybeEntry
.takeError();
3031 BitstreamEntry Entry
= MaybeEntry
.get();
3033 switch (Entry
.Kind
) {
3034 case BitstreamEntry::SubBlock
: // Handled for us already.
3035 case BitstreamEntry::Error
:
3036 return error("Malformed block");
3037 case BitstreamEntry::EndBlock
:
3039 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
3041 return Error::success();
3042 case BitstreamEntry::Record
:
3043 // The interesting case.
3049 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
3051 return MaybeRecord
.takeError();
3052 switch (MaybeRecord
.get()) {
3053 default: // Default behavior: unknown type.
3055 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
3056 Expected
<Value
*> ValOrErr
= recordValue(Record
, 1, TT
);
3057 if (Error Err
= ValOrErr
.takeError())
3062 case bitc::VST_CODE_FNENTRY
: {
3063 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
3064 Expected
<Value
*> ValOrErr
= recordValue(Record
, 2, TT
);
3065 if (Error Err
= ValOrErr
.takeError())
3067 Value
*V
= ValOrErr
.get();
3069 // Ignore function offsets emitted for aliases of functions in older
3070 // versions of LLVM.
3071 if (auto *F
= dyn_cast
<Function
>(V
))
3072 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
, F
, Record
);
3075 case bitc::VST_CODE_BBENTRY
: {
3076 if (convertToString(Record
, 1, ValueName
))
3077 return error("Invalid bbentry record");
3078 BasicBlock
*BB
= getBasicBlock(Record
[0]);
3080 return error("Invalid bbentry record");
3082 BB
->setName(ValueName
.str());
3090 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
3092 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V
) {
3097 // There is no such thing as -0 with integers. "-0" really means MININT.
3101 /// Resolve all of the initializers for global values and aliases that we can.
3102 Error
BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3103 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInitWorklist
;
3104 std::vector
<std::pair
<GlobalValue
*, unsigned>> IndirectSymbolInitWorklist
;
3105 std::vector
<FunctionOperandInfo
> FunctionOperandWorklist
;
3107 GlobalInitWorklist
.swap(GlobalInits
);
3108 IndirectSymbolInitWorklist
.swap(IndirectSymbolInits
);
3109 FunctionOperandWorklist
.swap(FunctionOperands
);
3111 while (!GlobalInitWorklist
.empty()) {
3112 unsigned ValID
= GlobalInitWorklist
.back().second
;
3113 if (ValID
>= ValueList
.size()) {
3114 // Not ready to resolve this yet, it requires something later in the file.
3115 GlobalInits
.push_back(GlobalInitWorklist
.back());
3117 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3119 return MaybeC
.takeError();
3120 GlobalInitWorklist
.back().first
->setInitializer(MaybeC
.get());
3122 GlobalInitWorklist
.pop_back();
3125 while (!IndirectSymbolInitWorklist
.empty()) {
3126 unsigned ValID
= IndirectSymbolInitWorklist
.back().second
;
3127 if (ValID
>= ValueList
.size()) {
3128 IndirectSymbolInits
.push_back(IndirectSymbolInitWorklist
.back());
3130 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3132 return MaybeC
.takeError();
3133 Constant
*C
= MaybeC
.get();
3134 GlobalValue
*GV
= IndirectSymbolInitWorklist
.back().first
;
3135 if (auto *GA
= dyn_cast
<GlobalAlias
>(GV
)) {
3136 if (C
->getType() != GV
->getType())
3137 return error("Alias and aliasee types don't match");
3139 } else if (auto *GI
= dyn_cast
<GlobalIFunc
>(GV
)) {
3142 return error("Expected an alias or an ifunc");
3145 IndirectSymbolInitWorklist
.pop_back();
3148 while (!FunctionOperandWorklist
.empty()) {
3149 FunctionOperandInfo
&Info
= FunctionOperandWorklist
.back();
3150 if (Info
.PersonalityFn
) {
3151 unsigned ValID
= Info
.PersonalityFn
- 1;
3152 if (ValID
< ValueList
.size()) {
3153 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3155 return MaybeC
.takeError();
3156 Info
.F
->setPersonalityFn(MaybeC
.get());
3157 Info
.PersonalityFn
= 0;
3161 unsigned ValID
= Info
.Prefix
- 1;
3162 if (ValID
< ValueList
.size()) {
3163 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3165 return MaybeC
.takeError();
3166 Info
.F
->setPrefixData(MaybeC
.get());
3170 if (Info
.Prologue
) {
3171 unsigned ValID
= Info
.Prologue
- 1;
3172 if (ValID
< ValueList
.size()) {
3173 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3175 return MaybeC
.takeError();
3176 Info
.F
->setPrologueData(MaybeC
.get());
3180 if (Info
.PersonalityFn
|| Info
.Prefix
|| Info
.Prologue
)
3181 FunctionOperands
.push_back(Info
);
3182 FunctionOperandWorklist
.pop_back();
3185 return Error::success();
3188 APInt
llvm::readWideAPInt(ArrayRef
<uint64_t> Vals
, unsigned TypeBits
) {
3189 SmallVector
<uint64_t, 8> Words(Vals
.size());
3190 transform(Vals
, Words
.begin(),
3191 BitcodeReader::decodeSignRotatedValue
);
3193 return APInt(TypeBits
, Words
);
3196 Error
BitcodeReader::parseConstants() {
3197 if (Error Err
= Stream
.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID
))
3200 SmallVector
<uint64_t, 64> Record
;
3202 // Read all the records for this value table.
3203 Type
*CurTy
= Type::getInt32Ty(Context
);
3204 unsigned Int32TyID
= getVirtualTypeID(CurTy
);
3205 unsigned CurTyID
= Int32TyID
;
3206 Type
*CurElemTy
= nullptr;
3207 unsigned NextCstNo
= ValueList
.size();
3210 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
3212 return MaybeEntry
.takeError();
3213 BitstreamEntry Entry
= MaybeEntry
.get();
3215 switch (Entry
.Kind
) {
3216 case BitstreamEntry::SubBlock
: // Handled for us already.
3217 case BitstreamEntry::Error
:
3218 return error("Malformed block");
3219 case BitstreamEntry::EndBlock
:
3220 if (NextCstNo
!= ValueList
.size())
3221 return error("Invalid constant reference");
3222 return Error::success();
3223 case BitstreamEntry::Record
:
3224 // The interesting case.
3230 Type
*VoidType
= Type::getVoidTy(Context
);
3232 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
3234 return MaybeBitCode
.takeError();
3235 switch (unsigned BitCode
= MaybeBitCode
.get()) {
3236 default: // Default behavior: unknown constant
3237 case bitc::CST_CODE_UNDEF
: // UNDEF
3238 V
= UndefValue::get(CurTy
);
3240 case bitc::CST_CODE_POISON
: // POISON
3241 V
= PoisonValue::get(CurTy
);
3243 case bitc::CST_CODE_SETTYPE
: // SETTYPE: [typeid]
3245 return error("Invalid settype record");
3246 if (Record
[0] >= TypeList
.size() || !TypeList
[Record
[0]])
3247 return error("Invalid settype record");
3248 if (TypeList
[Record
[0]] == VoidType
)
3249 return error("Invalid constant type");
3250 CurTyID
= Record
[0];
3251 CurTy
= TypeList
[CurTyID
];
3252 CurElemTy
= getPtrElementTypeByID(CurTyID
);
3253 continue; // Skip the ValueList manipulation.
3254 case bitc::CST_CODE_NULL
: // NULL
3255 if (CurTy
->isVoidTy() || CurTy
->isFunctionTy() || CurTy
->isLabelTy())
3256 return error("Invalid type for a constant null value");
3257 if (auto *TETy
= dyn_cast
<TargetExtType
>(CurTy
))
3258 if (!TETy
->hasProperty(TargetExtType::HasZeroInit
))
3259 return error("Invalid type for a constant null value");
3260 V
= Constant::getNullValue(CurTy
);
3262 case bitc::CST_CODE_INTEGER
: // INTEGER: [intval]
3263 if (!CurTy
->isIntOrIntVectorTy() || Record
.empty())
3264 return error("Invalid integer const record");
3265 V
= ConstantInt::get(CurTy
, decodeSignRotatedValue(Record
[0]));
3267 case bitc::CST_CODE_WIDE_INTEGER
: {// WIDE_INTEGER: [n x intval]
3268 if (!CurTy
->isIntOrIntVectorTy() || Record
.empty())
3269 return error("Invalid wide integer const record");
3271 auto *ScalarTy
= cast
<IntegerType
>(CurTy
->getScalarType());
3272 APInt VInt
= readWideAPInt(Record
, ScalarTy
->getBitWidth());
3273 V
= ConstantInt::get(CurTy
, VInt
);
3276 case bitc::CST_CODE_FLOAT
: { // FLOAT: [fpval]
3278 return error("Invalid float const record");
3280 auto *ScalarTy
= CurTy
->getScalarType();
3281 if (ScalarTy
->isHalfTy())
3282 V
= ConstantFP::get(CurTy
, APFloat(APFloat::IEEEhalf(),
3283 APInt(16, (uint16_t)Record
[0])));
3284 else if (ScalarTy
->isBFloatTy())
3285 V
= ConstantFP::get(
3286 CurTy
, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record
[0])));
3287 else if (ScalarTy
->isFloatTy())
3288 V
= ConstantFP::get(CurTy
, APFloat(APFloat::IEEEsingle(),
3289 APInt(32, (uint32_t)Record
[0])));
3290 else if (ScalarTy
->isDoubleTy())
3291 V
= ConstantFP::get(
3292 CurTy
, APFloat(APFloat::IEEEdouble(), APInt(64, Record
[0])));
3293 else if (ScalarTy
->isX86_FP80Ty()) {
3294 // Bits are not stored the same way as a normal i80 APInt, compensate.
3295 uint64_t Rearrange
[2];
3296 Rearrange
[0] = (Record
[1] & 0xffffLL
) | (Record
[0] << 16);
3297 Rearrange
[1] = Record
[0] >> 48;
3298 V
= ConstantFP::get(
3299 CurTy
, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange
)));
3300 } else if (ScalarTy
->isFP128Ty())
3301 V
= ConstantFP::get(CurTy
,
3302 APFloat(APFloat::IEEEquad(), APInt(128, Record
)));
3303 else if (ScalarTy
->isPPC_FP128Ty())
3304 V
= ConstantFP::get(
3305 CurTy
, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record
)));
3307 V
= PoisonValue::get(CurTy
);
3311 case bitc::CST_CODE_AGGREGATE
: {// AGGREGATE: [n x value number]
3313 return error("Invalid aggregate record");
3315 unsigned Size
= Record
.size();
3316 SmallVector
<unsigned, 16> Elts
;
3317 for (unsigned i
= 0; i
!= Size
; ++i
)
3318 Elts
.push_back(Record
[i
]);
3320 if (isa
<StructType
>(CurTy
)) {
3321 V
= BitcodeConstant::create(
3322 Alloc
, CurTy
, BitcodeConstant::ConstantStructOpcode
, Elts
);
3323 } else if (isa
<ArrayType
>(CurTy
)) {
3324 V
= BitcodeConstant::create(Alloc
, CurTy
,
3325 BitcodeConstant::ConstantArrayOpcode
, Elts
);
3326 } else if (isa
<VectorType
>(CurTy
)) {
3327 V
= BitcodeConstant::create(
3328 Alloc
, CurTy
, BitcodeConstant::ConstantVectorOpcode
, Elts
);
3330 V
= PoisonValue::get(CurTy
);
3334 case bitc::CST_CODE_STRING
: // STRING: [values]
3335 case bitc::CST_CODE_CSTRING
: { // CSTRING: [values]
3337 return error("Invalid string record");
3339 SmallString
<16> Elts(Record
.begin(), Record
.end());
3340 V
= ConstantDataArray::getString(Context
, Elts
,
3341 BitCode
== bitc::CST_CODE_CSTRING
);
3344 case bitc::CST_CODE_DATA
: {// DATA: [n x value]
3346 return error("Invalid data record");
3349 if (auto *Array
= dyn_cast
<ArrayType
>(CurTy
))
3350 EltTy
= Array
->getElementType();
3352 EltTy
= cast
<VectorType
>(CurTy
)->getElementType();
3353 if (EltTy
->isIntegerTy(8)) {
3354 SmallVector
<uint8_t, 16> Elts(Record
.begin(), Record
.end());
3355 if (isa
<VectorType
>(CurTy
))
3356 V
= ConstantDataVector::get(Context
, Elts
);
3358 V
= ConstantDataArray::get(Context
, Elts
);
3359 } else if (EltTy
->isIntegerTy(16)) {
3360 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
3361 if (isa
<VectorType
>(CurTy
))
3362 V
= ConstantDataVector::get(Context
, Elts
);
3364 V
= ConstantDataArray::get(Context
, Elts
);
3365 } else if (EltTy
->isIntegerTy(32)) {
3366 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
3367 if (isa
<VectorType
>(CurTy
))
3368 V
= ConstantDataVector::get(Context
, Elts
);
3370 V
= ConstantDataArray::get(Context
, Elts
);
3371 } else if (EltTy
->isIntegerTy(64)) {
3372 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
3373 if (isa
<VectorType
>(CurTy
))
3374 V
= ConstantDataVector::get(Context
, Elts
);
3376 V
= ConstantDataArray::get(Context
, Elts
);
3377 } else if (EltTy
->isHalfTy()) {
3378 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
3379 if (isa
<VectorType
>(CurTy
))
3380 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3382 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3383 } else if (EltTy
->isBFloatTy()) {
3384 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
3385 if (isa
<VectorType
>(CurTy
))
3386 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3388 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3389 } else if (EltTy
->isFloatTy()) {
3390 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
3391 if (isa
<VectorType
>(CurTy
))
3392 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3394 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3395 } else if (EltTy
->isDoubleTy()) {
3396 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
3397 if (isa
<VectorType
>(CurTy
))
3398 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3400 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3402 return error("Invalid type for value");
3406 case bitc::CST_CODE_CE_UNOP
: { // CE_UNOP: [opcode, opval]
3407 if (Record
.size() < 2)
3408 return error("Invalid unary op constexpr record");
3409 int Opc
= getDecodedUnaryOpcode(Record
[0], CurTy
);
3411 V
= PoisonValue::get(CurTy
); // Unknown unop.
3413 V
= BitcodeConstant::create(Alloc
, CurTy
, Opc
, (unsigned)Record
[1]);
3417 case bitc::CST_CODE_CE_BINOP
: { // CE_BINOP: [opcode, opval, opval]
3418 if (Record
.size() < 3)
3419 return error("Invalid binary op constexpr record");
3420 int Opc
= getDecodedBinaryOpcode(Record
[0], CurTy
);
3422 V
= PoisonValue::get(CurTy
); // Unknown binop.
3425 if (Record
.size() >= 4) {
3426 if (Opc
== Instruction::Add
||
3427 Opc
== Instruction::Sub
||
3428 Opc
== Instruction::Mul
||
3429 Opc
== Instruction::Shl
) {
3430 if (Record
[3] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
3431 Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3432 if (Record
[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
3433 Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3434 } else if (Opc
== Instruction::SDiv
||
3435 Opc
== Instruction::UDiv
||
3436 Opc
== Instruction::LShr
||
3437 Opc
== Instruction::AShr
) {
3438 if (Record
[3] & (1 << bitc::PEO_EXACT
))
3439 Flags
|= PossiblyExactOperator::IsExact
;
3442 V
= BitcodeConstant::create(Alloc
, CurTy
, {(uint8_t)Opc
, Flags
},
3443 {(unsigned)Record
[1], (unsigned)Record
[2]});
3447 case bitc::CST_CODE_CE_CAST
: { // CE_CAST: [opcode, opty, opval]
3448 if (Record
.size() < 3)
3449 return error("Invalid cast constexpr record");
3450 int Opc
= getDecodedCastOpcode(Record
[0]);
3452 V
= PoisonValue::get(CurTy
); // Unknown cast.
3454 unsigned OpTyID
= Record
[1];
3455 Type
*OpTy
= getTypeByID(OpTyID
);
3457 return error("Invalid cast constexpr record");
3458 V
= BitcodeConstant::create(Alloc
, CurTy
, Opc
, (unsigned)Record
[2]);
3462 case bitc::CST_CODE_CE_INBOUNDS_GEP
: // [ty, n x operands]
3463 case bitc::CST_CODE_CE_GEP_OLD
: // [ty, n x operands]
3464 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
: // [ty, flags, n x
3466 case bitc::CST_CODE_CE_GEP
: // [ty, flags, n x operands]
3467 case bitc::CST_CODE_CE_GEP_WITH_INRANGE
: { // [ty, flags, start, end, n x
3469 if (Record
.size() < 2)
3470 return error("Constant GEP record must have at least two elements");
3472 Type
*PointeeType
= nullptr;
3473 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
||
3474 BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE
||
3475 BitCode
== bitc::CST_CODE_CE_GEP
|| Record
.size() % 2)
3476 PointeeType
= getTypeByID(Record
[OpNum
++]);
3479 std::optional
<ConstantRange
> InRange
;
3480 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
) {
3481 uint64_t Op
= Record
[OpNum
++];
3482 Flags
= Op
& 1; // inbounds
3483 unsigned InRangeIndex
= Op
>> 1;
3484 // "Upgrade" inrange by dropping it. The feature is too niche to
3487 } else if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE
) {
3488 Flags
= Record
[OpNum
++];
3489 Expected
<ConstantRange
> MaybeInRange
=
3490 readBitWidthAndConstantRange(Record
, OpNum
);
3492 return MaybeInRange
.takeError();
3493 InRange
= MaybeInRange
.get();
3494 } else if (BitCode
== bitc::CST_CODE_CE_GEP
) {
3495 Flags
= Record
[OpNum
++];
3496 } else if (BitCode
== bitc::CST_CODE_CE_INBOUNDS_GEP
)
3497 Flags
= (1 << bitc::GEP_INBOUNDS
);
3499 SmallVector
<unsigned, 16> Elts
;
3500 unsigned BaseTypeID
= Record
[OpNum
];
3501 while (OpNum
!= Record
.size()) {
3502 unsigned ElTyID
= Record
[OpNum
++];
3503 Type
*ElTy
= getTypeByID(ElTyID
);
3505 return error("Invalid getelementptr constexpr record");
3506 Elts
.push_back(Record
[OpNum
++]);
3509 if (Elts
.size() < 1)
3510 return error("Invalid gep with no operands");
3512 Type
*BaseType
= getTypeByID(BaseTypeID
);
3513 if (isa
<VectorType
>(BaseType
)) {
3514 BaseTypeID
= getContainedTypeID(BaseTypeID
, 0);
3515 BaseType
= getTypeByID(BaseTypeID
);
3518 PointerType
*OrigPtrTy
= dyn_cast_or_null
<PointerType
>(BaseType
);
3520 return error("GEP base operand must be pointer or vector of pointer");
3523 PointeeType
= getPtrElementTypeByID(BaseTypeID
);
3525 return error("Missing element type for old-style constant GEP");
3528 V
= BitcodeConstant::create(
3530 {Instruction::GetElementPtr
, uint8_t(Flags
), PointeeType
, InRange
},
3534 case bitc::CST_CODE_CE_SELECT
: { // CE_SELECT: [opval#, opval#, opval#]
3535 if (Record
.size() < 3)
3536 return error("Invalid select constexpr record");
3538 V
= BitcodeConstant::create(
3539 Alloc
, CurTy
, Instruction::Select
,
3540 {(unsigned)Record
[0], (unsigned)Record
[1], (unsigned)Record
[2]});
3543 case bitc::CST_CODE_CE_EXTRACTELT
3544 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3545 if (Record
.size() < 3)
3546 return error("Invalid extractelement constexpr record");
3547 unsigned OpTyID
= Record
[0];
3549 dyn_cast_or_null
<VectorType
>(getTypeByID(OpTyID
));
3551 return error("Invalid extractelement constexpr record");
3553 if (Record
.size() == 4) {
3554 unsigned IdxTyID
= Record
[2];
3555 Type
*IdxTy
= getTypeByID(IdxTyID
);
3557 return error("Invalid extractelement constexpr record");
3558 IdxRecord
= Record
[3];
3560 // Deprecated, but still needed to read old bitcode files.
3561 IdxRecord
= Record
[2];
3563 V
= BitcodeConstant::create(Alloc
, CurTy
, Instruction::ExtractElement
,
3564 {(unsigned)Record
[1], IdxRecord
});
3567 case bitc::CST_CODE_CE_INSERTELT
3568 : { // CE_INSERTELT: [opval, opval, opty, opval]
3569 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
3570 if (Record
.size() < 3 || !OpTy
)
3571 return error("Invalid insertelement constexpr record");
3573 if (Record
.size() == 4) {
3574 unsigned IdxTyID
= Record
[2];
3575 Type
*IdxTy
= getTypeByID(IdxTyID
);
3577 return error("Invalid insertelement constexpr record");
3578 IdxRecord
= Record
[3];
3580 // Deprecated, but still needed to read old bitcode files.
3581 IdxRecord
= Record
[2];
3583 V
= BitcodeConstant::create(
3584 Alloc
, CurTy
, Instruction::InsertElement
,
3585 {(unsigned)Record
[0], (unsigned)Record
[1], IdxRecord
});
3588 case bitc::CST_CODE_CE_SHUFFLEVEC
: { // CE_SHUFFLEVEC: [opval, opval, opval]
3589 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
3590 if (Record
.size() < 3 || !OpTy
)
3591 return error("Invalid shufflevector constexpr record");
3592 V
= BitcodeConstant::create(
3593 Alloc
, CurTy
, Instruction::ShuffleVector
,
3594 {(unsigned)Record
[0], (unsigned)Record
[1], (unsigned)Record
[2]});
3597 case bitc::CST_CODE_CE_SHUFVEC_EX
: { // [opty, opval, opval, opval]
3598 VectorType
*RTy
= dyn_cast
<VectorType
>(CurTy
);
3600 dyn_cast_or_null
<VectorType
>(getTypeByID(Record
[0]));
3601 if (Record
.size() < 4 || !RTy
|| !OpTy
)
3602 return error("Invalid shufflevector constexpr record");
3603 V
= BitcodeConstant::create(
3604 Alloc
, CurTy
, Instruction::ShuffleVector
,
3605 {(unsigned)Record
[1], (unsigned)Record
[2], (unsigned)Record
[3]});
3608 case bitc::CST_CODE_CE_CMP
: { // CE_CMP: [opty, opval, opval, pred]
3609 if (Record
.size() < 4)
3610 return error("Invalid cmp constexpt record");
3611 unsigned OpTyID
= Record
[0];
3612 Type
*OpTy
= getTypeByID(OpTyID
);
3614 return error("Invalid cmp constexpr record");
3615 V
= BitcodeConstant::create(
3617 {(uint8_t)(OpTy
->isFPOrFPVectorTy() ? Instruction::FCmp
3618 : Instruction::ICmp
),
3619 (uint8_t)Record
[3]},
3620 {(unsigned)Record
[1], (unsigned)Record
[2]});
3623 // This maintains backward compatibility, pre-asm dialect keywords.
3624 // Deprecated, but still needed to read old bitcode files.
3625 case bitc::CST_CODE_INLINEASM_OLD
: {
3626 if (Record
.size() < 2)
3627 return error("Invalid inlineasm record");
3628 std::string AsmStr
, ConstrStr
;
3629 bool HasSideEffects
= Record
[0] & 1;
3630 bool IsAlignStack
= Record
[0] >> 1;
3631 unsigned AsmStrSize
= Record
[1];
3632 if (2+AsmStrSize
>= Record
.size())
3633 return error("Invalid inlineasm record");
3634 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
3635 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
3636 return error("Invalid inlineasm record");
3638 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3639 AsmStr
+= (char)Record
[2+i
];
3640 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3641 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
3642 UpgradeInlineAsmString(&AsmStr
);
3644 return error("Missing element type for old-style inlineasm");
3645 V
= InlineAsm::get(cast
<FunctionType
>(CurElemTy
), AsmStr
, ConstrStr
,
3646 HasSideEffects
, IsAlignStack
);
3649 // This version adds support for the asm dialect keywords (e.g.,
3651 case bitc::CST_CODE_INLINEASM_OLD2
: {
3652 if (Record
.size() < 2)
3653 return error("Invalid inlineasm record");
3654 std::string AsmStr
, ConstrStr
;
3655 bool HasSideEffects
= Record
[0] & 1;
3656 bool IsAlignStack
= (Record
[0] >> 1) & 1;
3657 unsigned AsmDialect
= Record
[0] >> 2;
3658 unsigned AsmStrSize
= Record
[1];
3659 if (2+AsmStrSize
>= Record
.size())
3660 return error("Invalid inlineasm record");
3661 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
3662 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
3663 return error("Invalid inlineasm record");
3665 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3666 AsmStr
+= (char)Record
[2+i
];
3667 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3668 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
3669 UpgradeInlineAsmString(&AsmStr
);
3671 return error("Missing element type for old-style inlineasm");
3672 V
= InlineAsm::get(cast
<FunctionType
>(CurElemTy
), AsmStr
, ConstrStr
,
3673 HasSideEffects
, IsAlignStack
,
3674 InlineAsm::AsmDialect(AsmDialect
));
3677 // This version adds support for the unwind keyword.
3678 case bitc::CST_CODE_INLINEASM_OLD3
: {
3679 if (Record
.size() < 2)
3680 return error("Invalid inlineasm record");
3682 std::string AsmStr
, ConstrStr
;
3683 bool HasSideEffects
= Record
[OpNum
] & 1;
3684 bool IsAlignStack
= (Record
[OpNum
] >> 1) & 1;
3685 unsigned AsmDialect
= (Record
[OpNum
] >> 2) & 1;
3686 bool CanThrow
= (Record
[OpNum
] >> 3) & 1;
3688 unsigned AsmStrSize
= Record
[OpNum
];
3690 if (OpNum
+ AsmStrSize
>= Record
.size())
3691 return error("Invalid inlineasm record");
3692 unsigned ConstStrSize
= Record
[OpNum
+ AsmStrSize
];
3693 if (OpNum
+ 1 + AsmStrSize
+ ConstStrSize
> Record
.size())
3694 return error("Invalid inlineasm record");
3696 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3697 AsmStr
+= (char)Record
[OpNum
+ i
];
3699 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3700 ConstrStr
+= (char)Record
[OpNum
+ AsmStrSize
+ i
];
3701 UpgradeInlineAsmString(&AsmStr
);
3703 return error("Missing element type for old-style inlineasm");
3704 V
= InlineAsm::get(cast
<FunctionType
>(CurElemTy
), AsmStr
, ConstrStr
,
3705 HasSideEffects
, IsAlignStack
,
3706 InlineAsm::AsmDialect(AsmDialect
), CanThrow
);
3709 // This version adds explicit function type.
3710 case bitc::CST_CODE_INLINEASM
: {
3711 if (Record
.size() < 3)
3712 return error("Invalid inlineasm record");
3714 auto *FnTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(Record
[OpNum
]));
3717 return error("Invalid inlineasm record");
3718 std::string AsmStr
, ConstrStr
;
3719 bool HasSideEffects
= Record
[OpNum
] & 1;
3720 bool IsAlignStack
= (Record
[OpNum
] >> 1) & 1;
3721 unsigned AsmDialect
= (Record
[OpNum
] >> 2) & 1;
3722 bool CanThrow
= (Record
[OpNum
] >> 3) & 1;
3724 unsigned AsmStrSize
= Record
[OpNum
];
3726 if (OpNum
+ AsmStrSize
>= Record
.size())
3727 return error("Invalid inlineasm record");
3728 unsigned ConstStrSize
= Record
[OpNum
+ AsmStrSize
];
3729 if (OpNum
+ 1 + AsmStrSize
+ ConstStrSize
> Record
.size())
3730 return error("Invalid inlineasm record");
3732 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3733 AsmStr
+= (char)Record
[OpNum
+ i
];
3735 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3736 ConstrStr
+= (char)Record
[OpNum
+ AsmStrSize
+ i
];
3737 UpgradeInlineAsmString(&AsmStr
);
3738 V
= InlineAsm::get(FnTy
, AsmStr
, ConstrStr
, HasSideEffects
, IsAlignStack
,
3739 InlineAsm::AsmDialect(AsmDialect
), CanThrow
);
3742 case bitc::CST_CODE_BLOCKADDRESS
:{
3743 if (Record
.size() < 3)
3744 return error("Invalid blockaddress record");
3745 unsigned FnTyID
= Record
[0];
3746 Type
*FnTy
= getTypeByID(FnTyID
);
3748 return error("Invalid blockaddress record");
3749 V
= BitcodeConstant::create(
3751 {BitcodeConstant::BlockAddressOpcode
, 0, (unsigned)Record
[2]},
3755 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT
: {
3756 if (Record
.size() < 2)
3757 return error("Invalid dso_local record");
3758 unsigned GVTyID
= Record
[0];
3759 Type
*GVTy
= getTypeByID(GVTyID
);
3761 return error("Invalid dso_local record");
3762 V
= BitcodeConstant::create(
3763 Alloc
, CurTy
, BitcodeConstant::DSOLocalEquivalentOpcode
, Record
[1]);
3766 case bitc::CST_CODE_NO_CFI_VALUE
: {
3767 if (Record
.size() < 2)
3768 return error("Invalid no_cfi record");
3769 unsigned GVTyID
= Record
[0];
3770 Type
*GVTy
= getTypeByID(GVTyID
);
3772 return error("Invalid no_cfi record");
3773 V
= BitcodeConstant::create(Alloc
, CurTy
, BitcodeConstant::NoCFIOpcode
,
3777 case bitc::CST_CODE_PTRAUTH
: {
3778 if (Record
.size() < 4)
3779 return error("Invalid ptrauth record");
3780 // Ptr, Key, Disc, AddrDisc
3781 V
= BitcodeConstant::create(Alloc
, CurTy
,
3782 BitcodeConstant::ConstantPtrAuthOpcode
,
3783 {(unsigned)Record
[0], (unsigned)Record
[1],
3784 (unsigned)Record
[2], (unsigned)Record
[3]});
3789 assert(V
->getType() == getTypeByID(CurTyID
) && "Incorrect result type ID");
3790 if (Error Err
= ValueList
.assignValue(NextCstNo
, V
, CurTyID
))
3796 Error
BitcodeReader::parseUseLists() {
3797 if (Error Err
= Stream
.EnterSubBlock(bitc::USELIST_BLOCK_ID
))
3800 // Read all the records.
3801 SmallVector
<uint64_t, 64> Record
;
3804 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
3806 return MaybeEntry
.takeError();
3807 BitstreamEntry Entry
= MaybeEntry
.get();
3809 switch (Entry
.Kind
) {
3810 case BitstreamEntry::SubBlock
: // Handled for us already.
3811 case BitstreamEntry::Error
:
3812 return error("Malformed block");
3813 case BitstreamEntry::EndBlock
:
3814 return Error::success();
3815 case BitstreamEntry::Record
:
3816 // The interesting case.
3820 // Read a use list record.
3823 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
3825 return MaybeRecord
.takeError();
3826 switch (MaybeRecord
.get()) {
3827 default: // Default behavior: unknown type.
3829 case bitc::USELIST_CODE_BB
:
3832 case bitc::USELIST_CODE_DEFAULT
: {
3833 unsigned RecordLength
= Record
.size();
3834 if (RecordLength
< 3)
3835 // Records should have at least an ID and two indexes.
3836 return error("Invalid record");
3837 unsigned ID
= Record
.pop_back_val();
3841 assert(ID
< FunctionBBs
.size() && "Basic block not found");
3842 V
= FunctionBBs
[ID
];
3845 unsigned NumUses
= 0;
3846 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
3847 for (const Use
&U
: V
->materialized_uses()) {
3848 if (++NumUses
> Record
.size())
3850 Order
[&U
] = Record
[NumUses
- 1];
3852 if (Order
.size() != Record
.size() || NumUses
> Record
.size())
3853 // Mismatches can happen if the functions are being materialized lazily
3854 // (out-of-order), or a value has been upgraded.
3857 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
3858 return Order
.lookup(&L
) < Order
.lookup(&R
);
3866 /// When we see the block for metadata, remember where it is and then skip it.
3867 /// This lets us lazily deserialize the metadata.
3868 Error
BitcodeReader::rememberAndSkipMetadata() {
3869 // Save the current stream state.
3870 uint64_t CurBit
= Stream
.GetCurrentBitNo();
3871 DeferredMetadataInfo
.push_back(CurBit
);
3873 // Skip over the block for now.
3874 if (Error Err
= Stream
.SkipBlock())
3876 return Error::success();
3879 Error
BitcodeReader::materializeMetadata() {
3880 for (uint64_t BitPos
: DeferredMetadataInfo
) {
3881 // Move the bit stream to the saved position.
3882 if (Error JumpFailed
= Stream
.JumpToBit(BitPos
))
3884 if (Error Err
= MDLoader
->parseModuleMetadata())
3888 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3889 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3891 if (!TheModule
->getNamedMetadata("llvm.linker.options")) {
3892 if (Metadata
*Val
= TheModule
->getModuleFlag("Linker Options")) {
3893 NamedMDNode
*LinkerOpts
=
3894 TheModule
->getOrInsertNamedMetadata("llvm.linker.options");
3895 for (const MDOperand
&MDOptions
: cast
<MDNode
>(Val
)->operands())
3896 LinkerOpts
->addOperand(cast
<MDNode
>(MDOptions
));
3900 DeferredMetadataInfo
.clear();
3901 return Error::success();
3904 void BitcodeReader::setStripDebugInfo() { StripDebugInfo
= true; }
3906 /// When we see the block for a function body, remember where it is and then
3907 /// skip it. This lets us lazily deserialize the functions.
3908 Error
BitcodeReader::rememberAndSkipFunctionBody() {
3909 // Get the function we are talking about.
3910 if (FunctionsWithBodies
.empty())
3911 return error("Insufficient function protos");
3913 Function
*Fn
= FunctionsWithBodies
.back();
3914 FunctionsWithBodies
.pop_back();
3916 // Save the current stream state.
3917 uint64_t CurBit
= Stream
.GetCurrentBitNo();
3919 (DeferredFunctionInfo
[Fn
] == 0 || DeferredFunctionInfo
[Fn
] == CurBit
) &&
3920 "Mismatch between VST and scanned function offsets");
3921 DeferredFunctionInfo
[Fn
] = CurBit
;
3923 // Skip over the function block for now.
3924 if (Error Err
= Stream
.SkipBlock())
3926 return Error::success();
3929 Error
BitcodeReader::globalCleanup() {
3930 // Patch the initializers for globals and aliases up.
3931 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
3933 if (!GlobalInits
.empty() || !IndirectSymbolInits
.empty())
3934 return error("Malformed global initializer set");
3936 // Look for intrinsic functions which need to be upgraded at some point
3937 // and functions that need to have their function attributes upgraded.
3938 for (Function
&F
: *TheModule
) {
3939 MDLoader
->upgradeDebugIntrinsics(F
);
3941 // If PreserveInputDbgFormat=true, then we don't know whether we want
3942 // intrinsics or records, and we won't perform any conversions in either
3943 // case, so don't upgrade intrinsics to records.
3944 if (UpgradeIntrinsicFunction(
3945 &F
, NewFn
, PreserveInputDbgFormat
!= cl::boolOrDefault::BOU_TRUE
))
3946 UpgradedIntrinsics
[&F
] = NewFn
;
3947 // Look for functions that rely on old function attribute behavior.
3948 UpgradeFunctionAttributes(F
);
3951 // Look for global variables which need to be renamed.
3952 std::vector
<std::pair
<GlobalVariable
*, GlobalVariable
*>> UpgradedVariables
;
3953 for (GlobalVariable
&GV
: TheModule
->globals())
3954 if (GlobalVariable
*Upgraded
= UpgradeGlobalVariable(&GV
))
3955 UpgradedVariables
.emplace_back(&GV
, Upgraded
);
3956 for (auto &Pair
: UpgradedVariables
) {
3957 Pair
.first
->eraseFromParent();
3958 TheModule
->insertGlobalVariable(Pair
.second
);
3961 // Force deallocation of memory for these vectors to favor the client that
3962 // want lazy deserialization.
3963 std::vector
<std::pair
<GlobalVariable
*, unsigned>>().swap(GlobalInits
);
3964 std::vector
<std::pair
<GlobalValue
*, unsigned>>().swap(IndirectSymbolInits
);
3965 return Error::success();
3968 /// Support for lazy parsing of function bodies. This is required if we
3969 /// either have an old bitcode file without a VST forward declaration record,
3970 /// or if we have an anonymous function being materialized, since anonymous
3971 /// functions do not have a name and are therefore not in the VST.
3972 Error
BitcodeReader::rememberAndSkipFunctionBodies() {
3973 if (Error JumpFailed
= Stream
.JumpToBit(NextUnreadBit
))
3976 if (Stream
.AtEndOfStream())
3977 return error("Could not find function in stream");
3979 if (!SeenFirstFunctionBody
)
3980 return error("Trying to materialize functions before seeing function blocks");
3982 // An old bitcode file with the symbol table at the end would have
3983 // finished the parse greedily.
3984 assert(SeenValueSymbolTable
);
3986 SmallVector
<uint64_t, 64> Record
;
3989 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
3991 return MaybeEntry
.takeError();
3992 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
3994 switch (Entry
.Kind
) {
3996 return error("Expect SubBlock");
3997 case BitstreamEntry::SubBlock
:
4000 return error("Expect function block");
4001 case bitc::FUNCTION_BLOCK_ID
:
4002 if (Error Err
= rememberAndSkipFunctionBody())
4004 NextUnreadBit
= Stream
.GetCurrentBitNo();
4005 return Error::success();
4011 Error
BitcodeReaderBase::readBlockInfo() {
4012 Expected
<std::optional
<BitstreamBlockInfo
>> MaybeNewBlockInfo
=
4013 Stream
.ReadBlockInfoBlock();
4014 if (!MaybeNewBlockInfo
)
4015 return MaybeNewBlockInfo
.takeError();
4016 std::optional
<BitstreamBlockInfo
> NewBlockInfo
=
4017 std::move(MaybeNewBlockInfo
.get());
4019 return error("Malformed block");
4020 BlockInfo
= std::move(*NewBlockInfo
);
4021 return Error::success();
4024 Error
BitcodeReader::parseComdatRecord(ArrayRef
<uint64_t> Record
) {
4025 // v1: [selection_kind, name]
4026 // v2: [strtab_offset, strtab_size, selection_kind]
4028 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4031 return error("Invalid record");
4032 Comdat::SelectionKind SK
= getDecodedComdatSelectionKind(Record
[0]);
4033 std::string OldFormatName
;
4035 if (Record
.size() < 2)
4036 return error("Invalid record");
4037 unsigned ComdatNameSize
= Record
[1];
4038 if (ComdatNameSize
> Record
.size() - 2)
4039 return error("Comdat name size too large");
4040 OldFormatName
.reserve(ComdatNameSize
);
4041 for (unsigned i
= 0; i
!= ComdatNameSize
; ++i
)
4042 OldFormatName
+= (char)Record
[2 + i
];
4043 Name
= OldFormatName
;
4045 Comdat
*C
= TheModule
->getOrInsertComdat(Name
);
4046 C
->setSelectionKind(SK
);
4047 ComdatList
.push_back(C
);
4048 return Error::success();
4051 static void inferDSOLocal(GlobalValue
*GV
) {
4052 // infer dso_local from linkage and visibility if it is not encoded.
4053 if (GV
->hasLocalLinkage() ||
4054 (!GV
->hasDefaultVisibility() && !GV
->hasExternalWeakLinkage()))
4055 GV
->setDSOLocal(true);
4058 GlobalValue::SanitizerMetadata
deserializeSanitizerMetadata(unsigned V
) {
4059 GlobalValue::SanitizerMetadata Meta
;
4061 Meta
.NoAddress
= true;
4063 Meta
.NoHWAddress
= true;
4067 Meta
.IsDynInit
= true;
4071 Error
BitcodeReader::parseGlobalVarRecord(ArrayRef
<uint64_t> Record
) {
4072 // v1: [pointer type, isconst, initid, linkage, alignment, section,
4073 // visibility, threadlocal, unnamed_addr, externally_initialized,
4074 // dllstorageclass, comdat, attributes, preemption specifier,
4075 // partition strtab offset, partition strtab size] (name in VST)
4076 // v2: [strtab_offset, strtab_size, v1]
4077 // v3: [v2, code_model]
4079 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4081 if (Record
.size() < 6)
4082 return error("Invalid record");
4083 unsigned TyID
= Record
[0];
4084 Type
*Ty
= getTypeByID(TyID
);
4086 return error("Invalid record");
4087 bool isConstant
= Record
[1] & 1;
4088 bool explicitType
= Record
[1] & 2;
4089 unsigned AddressSpace
;
4091 AddressSpace
= Record
[1] >> 2;
4093 if (!Ty
->isPointerTy())
4094 return error("Invalid type for value");
4095 AddressSpace
= cast
<PointerType
>(Ty
)->getAddressSpace();
4096 TyID
= getContainedTypeID(TyID
);
4097 Ty
= getTypeByID(TyID
);
4099 return error("Missing element type for old-style global");
4102 uint64_t RawLinkage
= Record
[3];
4103 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
4104 MaybeAlign Alignment
;
4105 if (Error Err
= parseAlignmentValue(Record
[4], Alignment
))
4107 std::string Section
;
4109 if (Record
[5] - 1 >= SectionTable
.size())
4110 return error("Invalid ID");
4111 Section
= SectionTable
[Record
[5] - 1];
4113 GlobalValue::VisibilityTypes Visibility
= GlobalValue::DefaultVisibility
;
4114 // Local linkage must have default visibility.
4115 // auto-upgrade `hidden` and `protected` for old bitcode.
4116 if (Record
.size() > 6 && !GlobalValue::isLocalLinkage(Linkage
))
4117 Visibility
= getDecodedVisibility(Record
[6]);
4119 GlobalVariable::ThreadLocalMode TLM
= GlobalVariable::NotThreadLocal
;
4120 if (Record
.size() > 7)
4121 TLM
= getDecodedThreadLocalMode(Record
[7]);
4123 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
4124 if (Record
.size() > 8)
4125 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[8]);
4127 bool ExternallyInitialized
= false;
4128 if (Record
.size() > 9)
4129 ExternallyInitialized
= Record
[9];
4131 GlobalVariable
*NewGV
=
4132 new GlobalVariable(*TheModule
, Ty
, isConstant
, Linkage
, nullptr, Name
,
4133 nullptr, TLM
, AddressSpace
, ExternallyInitialized
);
4135 NewGV
->setAlignment(*Alignment
);
4136 if (!Section
.empty())
4137 NewGV
->setSection(Section
);
4138 NewGV
->setVisibility(Visibility
);
4139 NewGV
->setUnnamedAddr(UnnamedAddr
);
4141 if (Record
.size() > 10) {
4142 // A GlobalValue with local linkage cannot have a DLL storage class.
4143 if (!NewGV
->hasLocalLinkage()) {
4144 NewGV
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[10]));
4147 upgradeDLLImportExportLinkage(NewGV
, RawLinkage
);
4150 ValueList
.push_back(NewGV
, getVirtualTypeID(NewGV
->getType(), TyID
));
4152 // Remember which value to use for the global initializer.
4153 if (unsigned InitID
= Record
[2])
4154 GlobalInits
.push_back(std::make_pair(NewGV
, InitID
- 1));
4156 if (Record
.size() > 11) {
4157 if (unsigned ComdatID
= Record
[11]) {
4158 if (ComdatID
> ComdatList
.size())
4159 return error("Invalid global variable comdat ID");
4160 NewGV
->setComdat(ComdatList
[ComdatID
- 1]);
4162 } else if (hasImplicitComdat(RawLinkage
)) {
4163 ImplicitComdatObjects
.insert(NewGV
);
4166 if (Record
.size() > 12) {
4167 auto AS
= getAttributes(Record
[12]).getFnAttrs();
4168 NewGV
->setAttributes(AS
);
4171 if (Record
.size() > 13) {
4172 NewGV
->setDSOLocal(getDecodedDSOLocal(Record
[13]));
4174 inferDSOLocal(NewGV
);
4176 // Check whether we have enough values to read a partition name.
4177 if (Record
.size() > 15)
4178 NewGV
->setPartition(StringRef(Strtab
.data() + Record
[14], Record
[15]));
4180 if (Record
.size() > 16 && Record
[16]) {
4181 llvm::GlobalValue::SanitizerMetadata Meta
=
4182 deserializeSanitizerMetadata(Record
[16]);
4183 NewGV
->setSanitizerMetadata(Meta
);
4186 if (Record
.size() > 17 && Record
[17]) {
4187 if (auto CM
= getDecodedCodeModel(Record
[17]))
4188 NewGV
->setCodeModel(*CM
);
4190 return error("Invalid global variable code model");
4193 return Error::success();
4196 void BitcodeReader::callValueTypeCallback(Value
*F
, unsigned TypeID
) {
4197 if (ValueTypeCallback
) {
4198 (*ValueTypeCallback
)(
4199 F
, TypeID
, [this](unsigned I
) { return getTypeByID(I
); },
4200 [this](unsigned I
, unsigned J
) { return getContainedTypeID(I
, J
); });
4204 Error
BitcodeReader::parseFunctionRecord(ArrayRef
<uint64_t> Record
) {
4205 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
4206 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
4207 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
4208 // v2: [strtab_offset, strtab_size, v1]
4210 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4212 if (Record
.size() < 8)
4213 return error("Invalid record");
4214 unsigned FTyID
= Record
[0];
4215 Type
*FTy
= getTypeByID(FTyID
);
4217 return error("Invalid record");
4218 if (isa
<PointerType
>(FTy
)) {
4219 FTyID
= getContainedTypeID(FTyID
, 0);
4220 FTy
= getTypeByID(FTyID
);
4222 return error("Missing element type for old-style function");
4225 if (!isa
<FunctionType
>(FTy
))
4226 return error("Invalid type for value");
4227 auto CC
= static_cast<CallingConv::ID
>(Record
[1]);
4228 if (CC
& ~CallingConv::MaxID
)
4229 return error("Invalid calling convention ID");
4231 unsigned AddrSpace
= TheModule
->getDataLayout().getProgramAddressSpace();
4232 if (Record
.size() > 16)
4233 AddrSpace
= Record
[16];
4236 Function::Create(cast
<FunctionType
>(FTy
), GlobalValue::ExternalLinkage
,
4237 AddrSpace
, Name
, TheModule
);
4239 assert(Func
->getFunctionType() == FTy
&&
4240 "Incorrect fully specified type provided for function");
4241 FunctionTypeIDs
[Func
] = FTyID
;
4243 Func
->setCallingConv(CC
);
4244 bool isProto
= Record
[2];
4245 uint64_t RawLinkage
= Record
[3];
4246 Func
->setLinkage(getDecodedLinkage(RawLinkage
));
4247 Func
->setAttributes(getAttributes(Record
[4]));
4248 callValueTypeCallback(Func
, FTyID
);
4250 // Upgrade any old-style byval or sret without a type by propagating the
4251 // argument's pointee type. There should be no opaque pointers where the byval
4252 // type is implicit.
4253 for (unsigned i
= 0; i
!= Func
->arg_size(); ++i
) {
4254 for (Attribute::AttrKind Kind
: {Attribute::ByVal
, Attribute::StructRet
,
4255 Attribute::InAlloca
}) {
4256 if (!Func
->hasParamAttribute(i
, Kind
))
4259 if (Func
->getParamAttribute(i
, Kind
).getValueAsType())
4262 Func
->removeParamAttr(i
, Kind
);
4264 unsigned ParamTypeID
= getContainedTypeID(FTyID
, i
+ 1);
4265 Type
*PtrEltTy
= getPtrElementTypeByID(ParamTypeID
);
4267 return error("Missing param element type for attribute upgrade");
4271 case Attribute::ByVal
:
4272 NewAttr
= Attribute::getWithByValType(Context
, PtrEltTy
);
4274 case Attribute::StructRet
:
4275 NewAttr
= Attribute::getWithStructRetType(Context
, PtrEltTy
);
4277 case Attribute::InAlloca
:
4278 NewAttr
= Attribute::getWithInAllocaType(Context
, PtrEltTy
);
4281 llvm_unreachable("not an upgraded type attribute");
4284 Func
->addParamAttr(i
, NewAttr
);
4288 if (Func
->getCallingConv() == CallingConv::X86_INTR
&&
4289 !Func
->arg_empty() && !Func
->hasParamAttribute(0, Attribute::ByVal
)) {
4290 unsigned ParamTypeID
= getContainedTypeID(FTyID
, 1);
4291 Type
*ByValTy
= getPtrElementTypeByID(ParamTypeID
);
4293 return error("Missing param element type for x86_intrcc upgrade");
4294 Attribute NewAttr
= Attribute::getWithByValType(Context
, ByValTy
);
4295 Func
->addParamAttr(0, NewAttr
);
4298 MaybeAlign Alignment
;
4299 if (Error Err
= parseAlignmentValue(Record
[5], Alignment
))
4302 Func
->setAlignment(*Alignment
);
4304 if (Record
[6] - 1 >= SectionTable
.size())
4305 return error("Invalid ID");
4306 Func
->setSection(SectionTable
[Record
[6] - 1]);
4308 // Local linkage must have default visibility.
4309 // auto-upgrade `hidden` and `protected` for old bitcode.
4310 if (!Func
->hasLocalLinkage())
4311 Func
->setVisibility(getDecodedVisibility(Record
[7]));
4312 if (Record
.size() > 8 && Record
[8]) {
4313 if (Record
[8] - 1 >= GCTable
.size())
4314 return error("Invalid ID");
4315 Func
->setGC(GCTable
[Record
[8] - 1]);
4317 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
4318 if (Record
.size() > 9)
4319 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[9]);
4320 Func
->setUnnamedAddr(UnnamedAddr
);
4322 FunctionOperandInfo OperandInfo
= {Func
, 0, 0, 0};
4323 if (Record
.size() > 10)
4324 OperandInfo
.Prologue
= Record
[10];
4326 if (Record
.size() > 11) {
4327 // A GlobalValue with local linkage cannot have a DLL storage class.
4328 if (!Func
->hasLocalLinkage()) {
4329 Func
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[11]));
4332 upgradeDLLImportExportLinkage(Func
, RawLinkage
);
4335 if (Record
.size() > 12) {
4336 if (unsigned ComdatID
= Record
[12]) {
4337 if (ComdatID
> ComdatList
.size())
4338 return error("Invalid function comdat ID");
4339 Func
->setComdat(ComdatList
[ComdatID
- 1]);
4341 } else if (hasImplicitComdat(RawLinkage
)) {
4342 ImplicitComdatObjects
.insert(Func
);
4345 if (Record
.size() > 13)
4346 OperandInfo
.Prefix
= Record
[13];
4348 if (Record
.size() > 14)
4349 OperandInfo
.PersonalityFn
= Record
[14];
4351 if (Record
.size() > 15) {
4352 Func
->setDSOLocal(getDecodedDSOLocal(Record
[15]));
4354 inferDSOLocal(Func
);
4356 // Record[16] is the address space number.
4358 // Check whether we have enough values to read a partition name. Also make
4359 // sure Strtab has enough values.
4360 if (Record
.size() > 18 && Strtab
.data() &&
4361 Record
[17] + Record
[18] <= Strtab
.size()) {
4362 Func
->setPartition(StringRef(Strtab
.data() + Record
[17], Record
[18]));
4365 ValueList
.push_back(Func
, getVirtualTypeID(Func
->getType(), FTyID
));
4367 if (OperandInfo
.PersonalityFn
|| OperandInfo
.Prefix
|| OperandInfo
.Prologue
)
4368 FunctionOperands
.push_back(OperandInfo
);
4370 // If this is a function with a body, remember the prototype we are
4371 // creating now, so that we can match up the body with them later.
4373 Func
->setIsMaterializable(true);
4374 FunctionsWithBodies
.push_back(Func
);
4375 DeferredFunctionInfo
[Func
] = 0;
4377 return Error::success();
4380 Error
BitcodeReader::parseGlobalIndirectSymbolRecord(
4381 unsigned BitCode
, ArrayRef
<uint64_t> Record
) {
4382 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4383 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4384 // dllstorageclass, threadlocal, unnamed_addr,
4385 // preemption specifier] (name in VST)
4386 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4387 // visibility, dllstorageclass, threadlocal, unnamed_addr,
4388 // preemption specifier] (name in VST)
4389 // v2: [strtab_offset, strtab_size, v1]
4391 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4393 bool NewRecord
= BitCode
!= bitc::MODULE_CODE_ALIAS_OLD
;
4394 if (Record
.size() < (3 + (unsigned)NewRecord
))
4395 return error("Invalid record");
4397 unsigned TypeID
= Record
[OpNum
++];
4398 Type
*Ty
= getTypeByID(TypeID
);
4400 return error("Invalid record");
4404 auto *PTy
= dyn_cast
<PointerType
>(Ty
);
4406 return error("Invalid type for value");
4407 AddrSpace
= PTy
->getAddressSpace();
4408 TypeID
= getContainedTypeID(TypeID
);
4409 Ty
= getTypeByID(TypeID
);
4411 return error("Missing element type for old-style indirect symbol");
4413 AddrSpace
= Record
[OpNum
++];
4416 auto Val
= Record
[OpNum
++];
4417 auto Linkage
= Record
[OpNum
++];
4419 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
4420 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
)
4421 NewGA
= GlobalAlias::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
4424 NewGA
= GlobalIFunc::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
4425 nullptr, TheModule
);
4427 // Local linkage must have default visibility.
4428 // auto-upgrade `hidden` and `protected` for old bitcode.
4429 if (OpNum
!= Record
.size()) {
4430 auto VisInd
= OpNum
++;
4431 if (!NewGA
->hasLocalLinkage())
4432 NewGA
->setVisibility(getDecodedVisibility(Record
[VisInd
]));
4434 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
4435 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
) {
4436 if (OpNum
!= Record
.size()) {
4437 auto S
= Record
[OpNum
++];
4438 // A GlobalValue with local linkage cannot have a DLL storage class.
4439 if (!NewGA
->hasLocalLinkage())
4440 NewGA
->setDLLStorageClass(getDecodedDLLStorageClass(S
));
4443 upgradeDLLImportExportLinkage(NewGA
, Linkage
);
4444 if (OpNum
!= Record
.size())
4445 NewGA
->setThreadLocalMode(getDecodedThreadLocalMode(Record
[OpNum
++]));
4446 if (OpNum
!= Record
.size())
4447 NewGA
->setUnnamedAddr(getDecodedUnnamedAddrType(Record
[OpNum
++]));
4449 if (OpNum
!= Record
.size())
4450 NewGA
->setDSOLocal(getDecodedDSOLocal(Record
[OpNum
++]));
4451 inferDSOLocal(NewGA
);
4453 // Check whether we have enough values to read a partition name.
4454 if (OpNum
+ 1 < Record
.size()) {
4455 // Check Strtab has enough values for the partition.
4456 if (Record
[OpNum
] + Record
[OpNum
+ 1] > Strtab
.size())
4457 return error("Malformed partition, too large.");
4458 NewGA
->setPartition(
4459 StringRef(Strtab
.data() + Record
[OpNum
], Record
[OpNum
+ 1]));
4462 ValueList
.push_back(NewGA
, getVirtualTypeID(NewGA
->getType(), TypeID
));
4463 IndirectSymbolInits
.push_back(std::make_pair(NewGA
, Val
));
4464 return Error::success();
4467 Error
BitcodeReader::parseModule(uint64_t ResumeBit
,
4468 bool ShouldLazyLoadMetadata
,
4469 ParserCallbacks Callbacks
) {
4470 // Load directly into RemoveDIs format if LoadBitcodeIntoNewDbgInfoFormat
4471 // has been set to true and we aren't attempting to preserve the existing
4472 // format in the bitcode (default action: load into the old debug format).
4473 if (PreserveInputDbgFormat
!= cl::boolOrDefault::BOU_TRUE
) {
4474 TheModule
->IsNewDbgInfoFormat
=
4475 UseNewDbgInfoFormat
&&
4476 LoadBitcodeIntoNewDbgInfoFormat
!= cl::boolOrDefault::BOU_FALSE
;
4479 this->ValueTypeCallback
= std::move(Callbacks
.ValueType
);
4481 if (Error JumpFailed
= Stream
.JumpToBit(ResumeBit
))
4483 } else if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
4486 SmallVector
<uint64_t, 64> Record
;
4488 // Parts of bitcode parsing depend on the datalayout. Make sure we
4489 // finalize the datalayout before we run any of that code.
4490 bool ResolvedDataLayout
= false;
4491 // In order to support importing modules with illegal data layout strings,
4492 // delay parsing the data layout string until after upgrades and overrides
4493 // have been applied, allowing to fix illegal data layout strings.
4494 // Initialize to the current module's layout string in case none is specified.
4495 std::string TentativeDataLayoutStr
= TheModule
->getDataLayoutStr();
4497 auto ResolveDataLayout
= [&]() -> Error
{
4498 if (ResolvedDataLayout
)
4499 return Error::success();
4501 // Datalayout and triple can't be parsed after this point.
4502 ResolvedDataLayout
= true;
4504 // Auto-upgrade the layout string
4505 TentativeDataLayoutStr
= llvm::UpgradeDataLayoutString(
4506 TentativeDataLayoutStr
, TheModule
->getTargetTriple());
4509 if (Callbacks
.DataLayout
) {
4510 if (auto LayoutOverride
= (*Callbacks
.DataLayout
)(
4511 TheModule
->getTargetTriple(), TentativeDataLayoutStr
))
4512 TentativeDataLayoutStr
= *LayoutOverride
;
4515 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4516 Expected
<DataLayout
> MaybeDL
= DataLayout::parse(TentativeDataLayoutStr
);
4518 return MaybeDL
.takeError();
4520 TheModule
->setDataLayout(MaybeDL
.get());
4521 return Error::success();
4524 // Read all the records for this module.
4526 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
4528 return MaybeEntry
.takeError();
4529 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
4531 switch (Entry
.Kind
) {
4532 case BitstreamEntry::Error
:
4533 return error("Malformed block");
4534 case BitstreamEntry::EndBlock
:
4535 if (Error Err
= ResolveDataLayout())
4537 return globalCleanup();
4539 case BitstreamEntry::SubBlock
:
4541 default: // Skip unknown content.
4542 if (Error Err
= Stream
.SkipBlock())
4545 case bitc::BLOCKINFO_BLOCK_ID
:
4546 if (Error Err
= readBlockInfo())
4549 case bitc::PARAMATTR_BLOCK_ID
:
4550 if (Error Err
= parseAttributeBlock())
4553 case bitc::PARAMATTR_GROUP_BLOCK_ID
:
4554 if (Error Err
= parseAttributeGroupBlock())
4557 case bitc::TYPE_BLOCK_ID_NEW
:
4558 if (Error Err
= parseTypeTable())
4561 case bitc::VALUE_SYMTAB_BLOCK_ID
:
4562 if (!SeenValueSymbolTable
) {
4563 // Either this is an old form VST without function index and an
4564 // associated VST forward declaration record (which would have caused
4565 // the VST to be jumped to and parsed before it was encountered
4566 // normally in the stream), or there were no function blocks to
4567 // trigger an earlier parsing of the VST.
4568 assert(VSTOffset
== 0 || FunctionsWithBodies
.empty());
4569 if (Error Err
= parseValueSymbolTable())
4571 SeenValueSymbolTable
= true;
4573 // We must have had a VST forward declaration record, which caused
4574 // the parser to jump to and parse the VST earlier.
4575 assert(VSTOffset
> 0);
4576 if (Error Err
= Stream
.SkipBlock())
4580 case bitc::CONSTANTS_BLOCK_ID
:
4581 if (Error Err
= parseConstants())
4583 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
4586 case bitc::METADATA_BLOCK_ID
:
4587 if (ShouldLazyLoadMetadata
) {
4588 if (Error Err
= rememberAndSkipMetadata())
4592 assert(DeferredMetadataInfo
.empty() && "Unexpected deferred metadata");
4593 if (Error Err
= MDLoader
->parseModuleMetadata())
4596 case bitc::METADATA_KIND_BLOCK_ID
:
4597 if (Error Err
= MDLoader
->parseMetadataKinds())
4600 case bitc::FUNCTION_BLOCK_ID
:
4601 if (Error Err
= ResolveDataLayout())
4604 // If this is the first function body we've seen, reverse the
4605 // FunctionsWithBodies list.
4606 if (!SeenFirstFunctionBody
) {
4607 std::reverse(FunctionsWithBodies
.begin(), FunctionsWithBodies
.end());
4608 if (Error Err
= globalCleanup())
4610 SeenFirstFunctionBody
= true;
4613 if (VSTOffset
> 0) {
4614 // If we have a VST forward declaration record, make sure we
4615 // parse the VST now if we haven't already. It is needed to
4616 // set up the DeferredFunctionInfo vector for lazy reading.
4617 if (!SeenValueSymbolTable
) {
4618 if (Error Err
= BitcodeReader::parseValueSymbolTable(VSTOffset
))
4620 SeenValueSymbolTable
= true;
4621 // Fall through so that we record the NextUnreadBit below.
4622 // This is necessary in case we have an anonymous function that
4623 // is later materialized. Since it will not have a VST entry we
4624 // need to fall back to the lazy parse to find its offset.
4626 // If we have a VST forward declaration record, but have already
4627 // parsed the VST (just above, when the first function body was
4628 // encountered here), then we are resuming the parse after
4629 // materializing functions. The ResumeBit points to the
4630 // start of the last function block recorded in the
4631 // DeferredFunctionInfo map. Skip it.
4632 if (Error Err
= Stream
.SkipBlock())
4638 // Support older bitcode files that did not have the function
4639 // index in the VST, nor a VST forward declaration record, as
4640 // well as anonymous functions that do not have VST entries.
4641 // Build the DeferredFunctionInfo vector on the fly.
4642 if (Error Err
= rememberAndSkipFunctionBody())
4645 // Suspend parsing when we reach the function bodies. Subsequent
4646 // materialization calls will resume it when necessary. If the bitcode
4647 // file is old, the symbol table will be at the end instead and will not
4648 // have been seen yet. In this case, just finish the parse now.
4649 if (SeenValueSymbolTable
) {
4650 NextUnreadBit
= Stream
.GetCurrentBitNo();
4651 // After the VST has been parsed, we need to make sure intrinsic name
4652 // are auto-upgraded.
4653 return globalCleanup();
4656 case bitc::USELIST_BLOCK_ID
:
4657 if (Error Err
= parseUseLists())
4660 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
:
4661 if (Error Err
= parseOperandBundleTags())
4664 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID
:
4665 if (Error Err
= parseSyncScopeNames())
4671 case BitstreamEntry::Record
:
4672 // The interesting case.
4677 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
4679 return MaybeBitCode
.takeError();
4680 switch (unsigned BitCode
= MaybeBitCode
.get()) {
4681 default: break; // Default behavior, ignore unknown content.
4682 case bitc::MODULE_CODE_VERSION
: {
4683 Expected
<unsigned> VersionOrErr
= parseVersionRecord(Record
);
4685 return VersionOrErr
.takeError();
4686 UseRelativeIDs
= *VersionOrErr
>= 1;
4689 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
4690 if (ResolvedDataLayout
)
4691 return error("target triple too late in module");
4693 if (convertToString(Record
, 0, S
))
4694 return error("Invalid record");
4695 TheModule
->setTargetTriple(S
);
4698 case bitc::MODULE_CODE_DATALAYOUT
: { // DATALAYOUT: [strchr x N]
4699 if (ResolvedDataLayout
)
4700 return error("datalayout too late in module");
4701 if (convertToString(Record
, 0, TentativeDataLayoutStr
))
4702 return error("Invalid record");
4705 case bitc::MODULE_CODE_ASM
: { // ASM: [strchr x N]
4707 if (convertToString(Record
, 0, S
))
4708 return error("Invalid record");
4709 TheModule
->setModuleInlineAsm(S
);
4712 case bitc::MODULE_CODE_DEPLIB
: { // DEPLIB: [strchr x N]
4713 // Deprecated, but still needed to read old bitcode files.
4715 if (convertToString(Record
, 0, S
))
4716 return error("Invalid record");
4720 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
4722 if (convertToString(Record
, 0, S
))
4723 return error("Invalid record");
4724 SectionTable
.push_back(S
);
4727 case bitc::MODULE_CODE_GCNAME
: { // SECTIONNAME: [strchr x N]
4729 if (convertToString(Record
, 0, S
))
4730 return error("Invalid record");
4731 GCTable
.push_back(S
);
4734 case bitc::MODULE_CODE_COMDAT
:
4735 if (Error Err
= parseComdatRecord(Record
))
4738 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4739 // written by ThinLinkBitcodeWriter. See
4740 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4742 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4743 case bitc::MODULE_CODE_GLOBALVAR
:
4744 if (Error Err
= parseGlobalVarRecord(Record
))
4747 case bitc::MODULE_CODE_FUNCTION
:
4748 if (Error Err
= ResolveDataLayout())
4750 if (Error Err
= parseFunctionRecord(Record
))
4753 case bitc::MODULE_CODE_IFUNC
:
4754 case bitc::MODULE_CODE_ALIAS
:
4755 case bitc::MODULE_CODE_ALIAS_OLD
:
4756 if (Error Err
= parseGlobalIndirectSymbolRecord(BitCode
, Record
))
4759 /// MODULE_CODE_VSTOFFSET: [offset]
4760 case bitc::MODULE_CODE_VSTOFFSET
:
4762 return error("Invalid record");
4763 // Note that we subtract 1 here because the offset is relative to one word
4764 // before the start of the identification or module block, which was
4765 // historically always the start of the regular bitcode header.
4766 VSTOffset
= Record
[0] - 1;
4768 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4769 case bitc::MODULE_CODE_SOURCE_FILENAME
:
4770 SmallString
<128> ValueName
;
4771 if (convertToString(Record
, 0, ValueName
))
4772 return error("Invalid record");
4773 TheModule
->setSourceFileName(ValueName
);
4778 this->ValueTypeCallback
= std::nullopt
;
4779 return Error::success();
4782 Error
BitcodeReader::parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
,
4784 ParserCallbacks Callbacks
) {
4786 MetadataLoaderCallbacks MDCallbacks
;
4787 MDCallbacks
.GetTypeByID
= [&](unsigned ID
) { return getTypeByID(ID
); };
4788 MDCallbacks
.GetContainedTypeID
= [&](unsigned I
, unsigned J
) {
4789 return getContainedTypeID(I
, J
);
4791 MDCallbacks
.MDType
= Callbacks
.MDType
;
4792 MDLoader
= MetadataLoader(Stream
, *M
, ValueList
, IsImporting
, MDCallbacks
);
4793 return parseModule(0, ShouldLazyLoadMetadata
, Callbacks
);
4796 Error
BitcodeReader::typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
) {
4797 if (!isa
<PointerType
>(PtrType
))
4798 return error("Load/Store operand is not a pointer type");
4799 if (!PointerType::isLoadableOrStorableType(ValType
))
4800 return error("Cannot load/store from pointer");
4801 return Error::success();
4804 Error
BitcodeReader::propagateAttributeTypes(CallBase
*CB
,
4805 ArrayRef
<unsigned> ArgTyIDs
) {
4806 AttributeList Attrs
= CB
->getAttributes();
4807 for (unsigned i
= 0; i
!= CB
->arg_size(); ++i
) {
4808 for (Attribute::AttrKind Kind
: {Attribute::ByVal
, Attribute::StructRet
,
4809 Attribute::InAlloca
}) {
4810 if (!Attrs
.hasParamAttr(i
, Kind
) ||
4811 Attrs
.getParamAttr(i
, Kind
).getValueAsType())
4814 Type
*PtrEltTy
= getPtrElementTypeByID(ArgTyIDs
[i
]);
4816 return error("Missing element type for typed attribute upgrade");
4820 case Attribute::ByVal
:
4821 NewAttr
= Attribute::getWithByValType(Context
, PtrEltTy
);
4823 case Attribute::StructRet
:
4824 NewAttr
= Attribute::getWithStructRetType(Context
, PtrEltTy
);
4826 case Attribute::InAlloca
:
4827 NewAttr
= Attribute::getWithInAllocaType(Context
, PtrEltTy
);
4830 llvm_unreachable("not an upgraded type attribute");
4833 Attrs
= Attrs
.addParamAttribute(Context
, i
, NewAttr
);
4837 if (CB
->isInlineAsm()) {
4838 const InlineAsm
*IA
= cast
<InlineAsm
>(CB
->getCalledOperand());
4840 for (const InlineAsm::ConstraintInfo
&CI
: IA
->ParseConstraints()) {
4844 if (CI
.isIndirect
&& !Attrs
.getParamElementType(ArgNo
)) {
4845 Type
*ElemTy
= getPtrElementTypeByID(ArgTyIDs
[ArgNo
]);
4847 return error("Missing element type for inline asm upgrade");
4848 Attrs
= Attrs
.addParamAttribute(
4850 Attribute::get(Context
, Attribute::ElementType
, ElemTy
));
4857 switch (CB
->getIntrinsicID()) {
4858 case Intrinsic::preserve_array_access_index
:
4859 case Intrinsic::preserve_struct_access_index
:
4860 case Intrinsic::aarch64_ldaxr
:
4861 case Intrinsic::aarch64_ldxr
:
4862 case Intrinsic::aarch64_stlxr
:
4863 case Intrinsic::aarch64_stxr
:
4864 case Intrinsic::arm_ldaex
:
4865 case Intrinsic::arm_ldrex
:
4866 case Intrinsic::arm_stlex
:
4867 case Intrinsic::arm_strex
: {
4869 switch (CB
->getIntrinsicID()) {
4870 case Intrinsic::aarch64_stlxr
:
4871 case Intrinsic::aarch64_stxr
:
4872 case Intrinsic::arm_stlex
:
4873 case Intrinsic::arm_strex
:
4880 if (!Attrs
.getParamElementType(ArgNo
)) {
4881 Type
*ElTy
= getPtrElementTypeByID(ArgTyIDs
[ArgNo
]);
4883 return error("Missing element type for elementtype upgrade");
4884 Attribute NewAttr
= Attribute::get(Context
, Attribute::ElementType
, ElTy
);
4885 Attrs
= Attrs
.addParamAttribute(Context
, ArgNo
, NewAttr
);
4893 CB
->setAttributes(Attrs
);
4894 return Error::success();
4897 /// Lazily parse the specified function body block.
4898 Error
BitcodeReader::parseFunctionBody(Function
*F
) {
4899 if (Error Err
= Stream
.EnterSubBlock(bitc::FUNCTION_BLOCK_ID
))
4902 // Unexpected unresolved metadata when parsing function.
4903 if (MDLoader
->hasFwdRefs())
4904 return error("Invalid function metadata: incoming forward references");
4906 InstructionList
.clear();
4907 unsigned ModuleValueListSize
= ValueList
.size();
4908 unsigned ModuleMDLoaderSize
= MDLoader
->size();
4910 // Add all the function arguments to the value table.
4912 unsigned FTyID
= FunctionTypeIDs
[F
];
4913 for (Argument
&I
: F
->args()) {
4914 unsigned ArgTyID
= getContainedTypeID(FTyID
, ArgNo
+ 1);
4915 assert(I
.getType() == getTypeByID(ArgTyID
) &&
4916 "Incorrect fully specified type for Function Argument");
4917 ValueList
.push_back(&I
, ArgTyID
);
4920 unsigned NextValueNo
= ValueList
.size();
4921 BasicBlock
*CurBB
= nullptr;
4922 unsigned CurBBNo
= 0;
4923 // Block into which constant expressions from phi nodes are materialized.
4924 BasicBlock
*PhiConstExprBB
= nullptr;
4925 // Edge blocks for phi nodes into which constant expressions have been
4927 SmallMapVector
<std::pair
<BasicBlock
*, BasicBlock
*>, BasicBlock
*, 4>
4931 auto getLastInstruction
= [&]() -> Instruction
* {
4932 if (CurBB
&& !CurBB
->empty())
4933 return &CurBB
->back();
4934 else if (CurBBNo
&& FunctionBBs
[CurBBNo
- 1] &&
4935 !FunctionBBs
[CurBBNo
- 1]->empty())
4936 return &FunctionBBs
[CurBBNo
- 1]->back();
4940 std::vector
<OperandBundleDef
> OperandBundles
;
4942 // Read all the records.
4943 SmallVector
<uint64_t, 64> Record
;
4946 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
4948 return MaybeEntry
.takeError();
4949 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
4951 switch (Entry
.Kind
) {
4952 case BitstreamEntry::Error
:
4953 return error("Malformed block");
4954 case BitstreamEntry::EndBlock
:
4955 goto OutOfRecordLoop
;
4957 case BitstreamEntry::SubBlock
:
4959 default: // Skip unknown content.
4960 if (Error Err
= Stream
.SkipBlock())
4963 case bitc::CONSTANTS_BLOCK_ID
:
4964 if (Error Err
= parseConstants())
4966 NextValueNo
= ValueList
.size();
4968 case bitc::VALUE_SYMTAB_BLOCK_ID
:
4969 if (Error Err
= parseValueSymbolTable())
4972 case bitc::METADATA_ATTACHMENT_ID
:
4973 if (Error Err
= MDLoader
->parseMetadataAttachment(*F
, InstructionList
))
4976 case bitc::METADATA_BLOCK_ID
:
4977 assert(DeferredMetadataInfo
.empty() &&
4978 "Must read all module-level metadata before function-level");
4979 if (Error Err
= MDLoader
->parseFunctionMetadata())
4982 case bitc::USELIST_BLOCK_ID
:
4983 if (Error Err
= parseUseLists())
4989 case BitstreamEntry::Record
:
4990 // The interesting case.
4996 Instruction
*I
= nullptr;
4997 unsigned ResTypeID
= InvalidTypeID
;
4998 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
5000 return MaybeBitCode
.takeError();
5001 switch (unsigned BitCode
= MaybeBitCode
.get()) {
5002 default: // Default behavior: reject
5003 return error("Invalid value");
5004 case bitc::FUNC_CODE_DECLAREBLOCKS
: { // DECLAREBLOCKS: [nblocks]
5005 if (Record
.empty() || Record
[0] == 0)
5006 return error("Invalid record");
5007 // Create all the basic blocks for the function.
5008 FunctionBBs
.resize(Record
[0]);
5010 // See if anything took the address of blocks in this function.
5011 auto BBFRI
= BasicBlockFwdRefs
.find(F
);
5012 if (BBFRI
== BasicBlockFwdRefs
.end()) {
5013 for (BasicBlock
*&BB
: FunctionBBs
)
5014 BB
= BasicBlock::Create(Context
, "", F
);
5016 auto &BBRefs
= BBFRI
->second
;
5017 // Check for invalid basic block references.
5018 if (BBRefs
.size() > FunctionBBs
.size())
5019 return error("Invalid ID");
5020 assert(!BBRefs
.empty() && "Unexpected empty array");
5021 assert(!BBRefs
.front() && "Invalid reference to entry block");
5022 for (unsigned I
= 0, E
= FunctionBBs
.size(), RE
= BBRefs
.size(); I
!= E
;
5024 if (I
< RE
&& BBRefs
[I
]) {
5025 BBRefs
[I
]->insertInto(F
);
5026 FunctionBBs
[I
] = BBRefs
[I
];
5028 FunctionBBs
[I
] = BasicBlock::Create(Context
, "", F
);
5031 // Erase from the table.
5032 BasicBlockFwdRefs
.erase(BBFRI
);
5035 CurBB
= FunctionBBs
[0];
5039 case bitc::FUNC_CODE_BLOCKADDR_USERS
: // BLOCKADDR_USERS: [vals...]
5040 // The record should not be emitted if it's an empty list.
5042 return error("Invalid record");
5043 // When we have the RARE case of a BlockAddress Constant that is not
5044 // scoped to the Function it refers to, we need to conservatively
5045 // materialize the referred to Function, regardless of whether or not
5046 // that Function will ultimately be linked, otherwise users of
5047 // BitcodeReader might start splicing out Function bodies such that we
5048 // might no longer be able to materialize the BlockAddress since the
5049 // BasicBlock (and entire body of the Function) the BlockAddress refers
5050 // to may have been moved. In the case that the user of BitcodeReader
5051 // decides ultimately not to link the Function body, materializing here
5052 // could be considered wasteful, but it's better than a deserialization
5053 // failure as described. This keeps BitcodeReader unaware of complex
5054 // linkage policy decisions such as those use by LTO, leaving those
5055 // decisions "one layer up."
5056 for (uint64_t ValID
: Record
)
5057 if (auto *F
= dyn_cast
<Function
>(ValueList
[ValID
]))
5058 BackwardRefFunctions
.push_back(F
);
5060 return error("Invalid record");
5064 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN
: // DEBUG_LOC_AGAIN
5065 // This record indicates that the last instruction is at the same
5066 // location as the previous instruction with a location.
5067 I
= getLastInstruction();
5070 return error("Invalid record");
5071 I
->setDebugLoc(LastLoc
);
5075 case bitc::FUNC_CODE_DEBUG_LOC
: { // DEBUG_LOC: [line, col, scope, ia]
5076 I
= getLastInstruction();
5077 if (!I
|| Record
.size() < 4)
5078 return error("Invalid record");
5080 unsigned Line
= Record
[0], Col
= Record
[1];
5081 unsigned ScopeID
= Record
[2], IAID
= Record
[3];
5082 bool isImplicitCode
= Record
.size() == 5 && Record
[4];
5084 MDNode
*Scope
= nullptr, *IA
= nullptr;
5086 Scope
= dyn_cast_or_null
<MDNode
>(
5087 MDLoader
->getMetadataFwdRefOrLoad(ScopeID
- 1));
5089 return error("Invalid record");
5092 IA
= dyn_cast_or_null
<MDNode
>(
5093 MDLoader
->getMetadataFwdRefOrLoad(IAID
- 1));
5095 return error("Invalid record");
5097 LastLoc
= DILocation::get(Scope
->getContext(), Line
, Col
, Scope
, IA
,
5099 I
->setDebugLoc(LastLoc
);
5103 case bitc::FUNC_CODE_INST_UNOP
: { // UNOP: [opval, ty, opcode]
5107 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
, TypeID
, CurBB
) ||
5108 OpNum
+1 > Record
.size())
5109 return error("Invalid record");
5111 int Opc
= getDecodedUnaryOpcode(Record
[OpNum
++], LHS
->getType());
5113 return error("Invalid record");
5114 I
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
5116 InstructionList
.push_back(I
);
5117 if (OpNum
< Record
.size()) {
5118 if (isa
<FPMathOperator
>(I
)) {
5119 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5121 I
->setFastMathFlags(FMF
);
5126 case bitc::FUNC_CODE_INST_BINOP
: { // BINOP: [opval, ty, opval, opcode]
5130 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
, TypeID
, CurBB
) ||
5131 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), TypeID
, RHS
,
5133 OpNum
+1 > Record
.size())
5134 return error("Invalid record");
5136 int Opc
= getDecodedBinaryOpcode(Record
[OpNum
++], LHS
->getType());
5138 return error("Invalid record");
5139 I
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
5141 InstructionList
.push_back(I
);
5142 if (OpNum
< Record
.size()) {
5143 if (Opc
== Instruction::Add
||
5144 Opc
== Instruction::Sub
||
5145 Opc
== Instruction::Mul
||
5146 Opc
== Instruction::Shl
) {
5147 if (Record
[OpNum
] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
5148 cast
<BinaryOperator
>(I
)->setHasNoSignedWrap(true);
5149 if (Record
[OpNum
] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
5150 cast
<BinaryOperator
>(I
)->setHasNoUnsignedWrap(true);
5151 } else if (Opc
== Instruction::SDiv
||
5152 Opc
== Instruction::UDiv
||
5153 Opc
== Instruction::LShr
||
5154 Opc
== Instruction::AShr
) {
5155 if (Record
[OpNum
] & (1 << bitc::PEO_EXACT
))
5156 cast
<BinaryOperator
>(I
)->setIsExact(true);
5157 } else if (Opc
== Instruction::Or
) {
5158 if (Record
[OpNum
] & (1 << bitc::PDI_DISJOINT
))
5159 cast
<PossiblyDisjointInst
>(I
)->setIsDisjoint(true);
5160 } else if (isa
<FPMathOperator
>(I
)) {
5161 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5163 I
->setFastMathFlags(FMF
);
5168 case bitc::FUNC_CODE_INST_CAST
: { // CAST: [opval, opty, destty, castopc]
5172 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
) ||
5173 OpNum
+ 1 > Record
.size())
5174 return error("Invalid record");
5176 ResTypeID
= Record
[OpNum
++];
5177 Type
*ResTy
= getTypeByID(ResTypeID
);
5178 int Opc
= getDecodedCastOpcode(Record
[OpNum
++]);
5180 if (Opc
== -1 || !ResTy
)
5181 return error("Invalid record");
5182 Instruction
*Temp
= nullptr;
5183 if ((I
= UpgradeBitCastInst(Opc
, Op
, ResTy
, Temp
))) {
5185 InstructionList
.push_back(Temp
);
5186 assert(CurBB
&& "No current BB?");
5187 Temp
->insertInto(CurBB
, CurBB
->end());
5190 auto CastOp
= (Instruction::CastOps
)Opc
;
5191 if (!CastInst::castIsValid(CastOp
, Op
, ResTy
))
5192 return error("Invalid cast");
5193 I
= CastInst::Create(CastOp
, Op
, ResTy
);
5196 if (OpNum
< Record
.size()) {
5197 if (Opc
== Instruction::ZExt
|| Opc
== Instruction::UIToFP
) {
5198 if (Record
[OpNum
] & (1 << bitc::PNNI_NON_NEG
))
5199 cast
<PossiblyNonNegInst
>(I
)->setNonNeg(true);
5200 } else if (Opc
== Instruction::Trunc
) {
5201 if (Record
[OpNum
] & (1 << bitc::TIO_NO_UNSIGNED_WRAP
))
5202 cast
<TruncInst
>(I
)->setHasNoUnsignedWrap(true);
5203 if (Record
[OpNum
] & (1 << bitc::TIO_NO_SIGNED_WRAP
))
5204 cast
<TruncInst
>(I
)->setHasNoSignedWrap(true);
5206 if (isa
<FPMathOperator
>(I
)) {
5207 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5209 I
->setFastMathFlags(FMF
);
5213 InstructionList
.push_back(I
);
5216 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
:
5217 case bitc::FUNC_CODE_INST_GEP_OLD
:
5218 case bitc::FUNC_CODE_INST_GEP
: { // GEP: type, [n x operands]
5225 if (BitCode
== bitc::FUNC_CODE_INST_GEP
) {
5226 NW
= toGEPNoWrapFlags(Record
[OpNum
++]);
5227 TyID
= Record
[OpNum
++];
5228 Ty
= getTypeByID(TyID
);
5230 if (BitCode
== bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
)
5231 NW
= GEPNoWrapFlags::inBounds();
5232 TyID
= InvalidTypeID
;
5237 unsigned BasePtrTypeID
;
5238 if (getValueTypePair(Record
, OpNum
, NextValueNo
, BasePtr
, BasePtrTypeID
,
5240 return error("Invalid record");
5243 TyID
= getContainedTypeID(BasePtrTypeID
);
5244 if (BasePtr
->getType()->isVectorTy())
5245 TyID
= getContainedTypeID(TyID
);
5246 Ty
= getTypeByID(TyID
);
5249 SmallVector
<Value
*, 16> GEPIdx
;
5250 while (OpNum
!= Record
.size()) {
5253 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5254 return error("Invalid record");
5255 GEPIdx
.push_back(Op
);
5258 auto *GEP
= GetElementPtrInst::Create(Ty
, BasePtr
, GEPIdx
);
5262 if (cast
<GEPOperator
>(I
)->getNumIndices() != 0) {
5263 auto GTI
= std::next(gep_type_begin(I
));
5264 for (Value
*Idx
: drop_begin(cast
<GEPOperator
>(I
)->indices())) {
5265 unsigned SubType
= 0;
5266 if (GTI
.isStruct()) {
5268 Idx
->getType()->isVectorTy()
5269 ? cast
<ConstantInt
>(cast
<Constant
>(Idx
)->getSplatValue())
5270 : cast
<ConstantInt
>(Idx
);
5271 SubType
= IdxC
->getZExtValue();
5273 ResTypeID
= getContainedTypeID(ResTypeID
, SubType
);
5278 // At this point ResTypeID is the result element type. We need a pointer
5279 // or vector of pointer to it.
5280 ResTypeID
= getVirtualTypeID(I
->getType()->getScalarType(), ResTypeID
);
5281 if (I
->getType()->isVectorTy())
5282 ResTypeID
= getVirtualTypeID(I
->getType(), ResTypeID
);
5284 InstructionList
.push_back(I
);
5285 GEP
->setNoWrapFlags(NW
);
5289 case bitc::FUNC_CODE_INST_EXTRACTVAL
: {
5290 // EXTRACTVAL: [opty, opval, n x indices]
5294 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
, AggTypeID
, CurBB
))
5295 return error("Invalid record");
5296 Type
*Ty
= Agg
->getType();
5298 unsigned RecSize
= Record
.size();
5299 if (OpNum
== RecSize
)
5300 return error("EXTRACTVAL: Invalid instruction with 0 indices");
5302 SmallVector
<unsigned, 4> EXTRACTVALIdx
;
5303 ResTypeID
= AggTypeID
;
5304 for (; OpNum
!= RecSize
; ++OpNum
) {
5305 bool IsArray
= Ty
->isArrayTy();
5306 bool IsStruct
= Ty
->isStructTy();
5307 uint64_t Index
= Record
[OpNum
];
5309 if (!IsStruct
&& !IsArray
)
5310 return error("EXTRACTVAL: Invalid type");
5311 if ((unsigned)Index
!= Index
)
5312 return error("Invalid value");
5313 if (IsStruct
&& Index
>= Ty
->getStructNumElements())
5314 return error("EXTRACTVAL: Invalid struct index");
5315 if (IsArray
&& Index
>= Ty
->getArrayNumElements())
5316 return error("EXTRACTVAL: Invalid array index");
5317 EXTRACTVALIdx
.push_back((unsigned)Index
);
5320 Ty
= Ty
->getStructElementType(Index
);
5321 ResTypeID
= getContainedTypeID(ResTypeID
, Index
);
5323 Ty
= Ty
->getArrayElementType();
5324 ResTypeID
= getContainedTypeID(ResTypeID
);
5328 I
= ExtractValueInst::Create(Agg
, EXTRACTVALIdx
);
5329 InstructionList
.push_back(I
);
5333 case bitc::FUNC_CODE_INST_INSERTVAL
: {
5334 // INSERTVAL: [opty, opval, opty, opval, n x indices]
5338 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
, AggTypeID
, CurBB
))
5339 return error("Invalid record");
5342 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
5343 return error("Invalid record");
5345 unsigned RecSize
= Record
.size();
5346 if (OpNum
== RecSize
)
5347 return error("INSERTVAL: Invalid instruction with 0 indices");
5349 SmallVector
<unsigned, 4> INSERTVALIdx
;
5350 Type
*CurTy
= Agg
->getType();
5351 for (; OpNum
!= RecSize
; ++OpNum
) {
5352 bool IsArray
= CurTy
->isArrayTy();
5353 bool IsStruct
= CurTy
->isStructTy();
5354 uint64_t Index
= Record
[OpNum
];
5356 if (!IsStruct
&& !IsArray
)
5357 return error("INSERTVAL: Invalid type");
5358 if ((unsigned)Index
!= Index
)
5359 return error("Invalid value");
5360 if (IsStruct
&& Index
>= CurTy
->getStructNumElements())
5361 return error("INSERTVAL: Invalid struct index");
5362 if (IsArray
&& Index
>= CurTy
->getArrayNumElements())
5363 return error("INSERTVAL: Invalid array index");
5365 INSERTVALIdx
.push_back((unsigned)Index
);
5367 CurTy
= CurTy
->getStructElementType(Index
);
5369 CurTy
= CurTy
->getArrayElementType();
5372 if (CurTy
!= Val
->getType())
5373 return error("Inserted value type doesn't match aggregate type");
5375 I
= InsertValueInst::Create(Agg
, Val
, INSERTVALIdx
);
5376 ResTypeID
= AggTypeID
;
5377 InstructionList
.push_back(I
);
5381 case bitc::FUNC_CODE_INST_SELECT
: { // SELECT: [opval, ty, opval, opval]
5382 // obsolete form of select
5383 // handles select i1 ... in old bitcode
5385 Value
*TrueVal
, *FalseVal
, *Cond
;
5387 Type
*CondType
= Type::getInt1Ty(Context
);
5388 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
, TypeID
,
5390 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), TypeID
,
5392 popValue(Record
, OpNum
, NextValueNo
, CondType
,
5393 getVirtualTypeID(CondType
), Cond
, CurBB
))
5394 return error("Invalid record");
5396 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
5398 InstructionList
.push_back(I
);
5402 case bitc::FUNC_CODE_INST_VSELECT
: {// VSELECT: [ty,opval,opval,predty,pred]
5403 // new form of select
5404 // handles select i1 or select [N x i1]
5406 Value
*TrueVal
, *FalseVal
, *Cond
;
5407 unsigned ValTypeID
, CondTypeID
;
5408 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
, ValTypeID
,
5410 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), ValTypeID
,
5412 getValueTypePair(Record
, OpNum
, NextValueNo
, Cond
, CondTypeID
, CurBB
))
5413 return error("Invalid record");
5415 // select condition can be either i1 or [N x i1]
5416 if (VectorType
* vector_type
=
5417 dyn_cast
<VectorType
>(Cond
->getType())) {
5419 if (vector_type
->getElementType() != Type::getInt1Ty(Context
))
5420 return error("Invalid type for value");
5423 if (Cond
->getType() != Type::getInt1Ty(Context
))
5424 return error("Invalid type for value");
5427 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
5428 ResTypeID
= ValTypeID
;
5429 InstructionList
.push_back(I
);
5430 if (OpNum
< Record
.size() && isa
<FPMathOperator
>(I
)) {
5431 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5433 I
->setFastMathFlags(FMF
);
5438 case bitc::FUNC_CODE_INST_EXTRACTELT
: { // EXTRACTELT: [opty, opval, opval]
5441 unsigned VecTypeID
, IdxTypeID
;
5442 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
, VecTypeID
, CurBB
) ||
5443 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
, IdxTypeID
, CurBB
))
5444 return error("Invalid record");
5445 if (!Vec
->getType()->isVectorTy())
5446 return error("Invalid type for value");
5447 I
= ExtractElementInst::Create(Vec
, Idx
);
5448 ResTypeID
= getContainedTypeID(VecTypeID
);
5449 InstructionList
.push_back(I
);
5453 case bitc::FUNC_CODE_INST_INSERTELT
: { // INSERTELT: [ty, opval,opval,opval]
5455 Value
*Vec
, *Elt
, *Idx
;
5456 unsigned VecTypeID
, IdxTypeID
;
5457 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
, VecTypeID
, CurBB
))
5458 return error("Invalid record");
5459 if (!Vec
->getType()->isVectorTy())
5460 return error("Invalid type for value");
5461 if (popValue(Record
, OpNum
, NextValueNo
,
5462 cast
<VectorType
>(Vec
->getType())->getElementType(),
5463 getContainedTypeID(VecTypeID
), Elt
, CurBB
) ||
5464 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
, IdxTypeID
, CurBB
))
5465 return error("Invalid record");
5466 I
= InsertElementInst::Create(Vec
, Elt
, Idx
);
5467 ResTypeID
= VecTypeID
;
5468 InstructionList
.push_back(I
);
5472 case bitc::FUNC_CODE_INST_SHUFFLEVEC
: {// SHUFFLEVEC: [opval,ty,opval,opval]
5474 Value
*Vec1
, *Vec2
, *Mask
;
5475 unsigned Vec1TypeID
;
5476 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec1
, Vec1TypeID
,
5478 popValue(Record
, OpNum
, NextValueNo
, Vec1
->getType(), Vec1TypeID
,
5480 return error("Invalid record");
5482 unsigned MaskTypeID
;
5483 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Mask
, MaskTypeID
, CurBB
))
5484 return error("Invalid record");
5485 if (!Vec1
->getType()->isVectorTy() || !Vec2
->getType()->isVectorTy())
5486 return error("Invalid type for value");
5488 I
= new ShuffleVectorInst(Vec1
, Vec2
, Mask
);
5490 getVirtualTypeID(I
->getType(), getContainedTypeID(Vec1TypeID
));
5491 InstructionList
.push_back(I
);
5495 case bitc::FUNC_CODE_INST_CMP
: // CMP: [opty, opval, opval, pred]
5496 // Old form of ICmp/FCmp returning bool
5497 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5498 // both legal on vectors but had different behaviour.
5499 case bitc::FUNC_CODE_INST_CMP2
: { // CMP2: [opty, opval, opval, pred]
5500 // FCmp/ICmp returning bool or vector of bool
5505 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
, LHSTypeID
, CurBB
) ||
5506 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), LHSTypeID
, RHS
,
5508 return error("Invalid record");
5510 if (OpNum
>= Record
.size())
5512 "Invalid record: operand number exceeded available operands");
5514 CmpInst::Predicate PredVal
= CmpInst::Predicate(Record
[OpNum
]);
5515 bool IsFP
= LHS
->getType()->isFPOrFPVectorTy();
5517 if (IsFP
&& Record
.size() > OpNum
+1)
5518 FMF
= getDecodedFastMathFlags(Record
[++OpNum
]);
5521 if (!CmpInst::isFPPredicate(PredVal
))
5522 return error("Invalid fcmp predicate");
5523 I
= new FCmpInst(PredVal
, LHS
, RHS
);
5525 if (!CmpInst::isIntPredicate(PredVal
))
5526 return error("Invalid icmp predicate");
5527 I
= new ICmpInst(PredVal
, LHS
, RHS
);
5528 if (Record
.size() > OpNum
+ 1 &&
5529 (Record
[++OpNum
] & (1 << bitc::ICMP_SAME_SIGN
)))
5530 cast
<ICmpInst
>(I
)->setSameSign();
5533 if (OpNum
+ 1 != Record
.size())
5534 return error("Invalid record");
5536 ResTypeID
= getVirtualTypeID(I
->getType()->getScalarType());
5537 if (LHS
->getType()->isVectorTy())
5538 ResTypeID
= getVirtualTypeID(I
->getType(), ResTypeID
);
5541 I
->setFastMathFlags(FMF
);
5542 InstructionList
.push_back(I
);
5546 case bitc::FUNC_CODE_INST_RET
: // RET: [opty,opval<optional>]
5548 unsigned Size
= Record
.size();
5550 I
= ReturnInst::Create(Context
);
5551 InstructionList
.push_back(I
);
5556 Value
*Op
= nullptr;
5558 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5559 return error("Invalid record");
5560 if (OpNum
!= Record
.size())
5561 return error("Invalid record");
5563 I
= ReturnInst::Create(Context
, Op
);
5564 InstructionList
.push_back(I
);
5567 case bitc::FUNC_CODE_INST_BR
: { // BR: [bb#, bb#, opval] or [bb#]
5568 if (Record
.size() != 1 && Record
.size() != 3)
5569 return error("Invalid record");
5570 BasicBlock
*TrueDest
= getBasicBlock(Record
[0]);
5572 return error("Invalid record");
5574 if (Record
.size() == 1) {
5575 I
= BranchInst::Create(TrueDest
);
5576 InstructionList
.push_back(I
);
5579 BasicBlock
*FalseDest
= getBasicBlock(Record
[1]);
5580 Type
*CondType
= Type::getInt1Ty(Context
);
5581 Value
*Cond
= getValue(Record
, 2, NextValueNo
, CondType
,
5582 getVirtualTypeID(CondType
), CurBB
);
5583 if (!FalseDest
|| !Cond
)
5584 return error("Invalid record");
5585 I
= BranchInst::Create(TrueDest
, FalseDest
, Cond
);
5586 InstructionList
.push_back(I
);
5590 case bitc::FUNC_CODE_INST_CLEANUPRET
: { // CLEANUPRET: [val] or [val,bb#]
5591 if (Record
.size() != 1 && Record
.size() != 2)
5592 return error("Invalid record");
5594 Type
*TokenTy
= Type::getTokenTy(Context
);
5595 Value
*CleanupPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5596 getVirtualTypeID(TokenTy
), CurBB
);
5598 return error("Invalid record");
5599 BasicBlock
*UnwindDest
= nullptr;
5600 if (Record
.size() == 2) {
5601 UnwindDest
= getBasicBlock(Record
[Idx
++]);
5603 return error("Invalid record");
5606 I
= CleanupReturnInst::Create(CleanupPad
, UnwindDest
);
5607 InstructionList
.push_back(I
);
5610 case bitc::FUNC_CODE_INST_CATCHRET
: { // CATCHRET: [val,bb#]
5611 if (Record
.size() != 2)
5612 return error("Invalid record");
5614 Type
*TokenTy
= Type::getTokenTy(Context
);
5615 Value
*CatchPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5616 getVirtualTypeID(TokenTy
), CurBB
);
5618 return error("Invalid record");
5619 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
5621 return error("Invalid record");
5623 I
= CatchReturnInst::Create(CatchPad
, BB
);
5624 InstructionList
.push_back(I
);
5627 case bitc::FUNC_CODE_INST_CATCHSWITCH
: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5628 // We must have, at minimum, the outer scope and the number of arguments.
5629 if (Record
.size() < 2)
5630 return error("Invalid record");
5634 Type
*TokenTy
= Type::getTokenTy(Context
);
5635 Value
*ParentPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5636 getVirtualTypeID(TokenTy
), CurBB
);
5638 return error("Invalid record");
5640 unsigned NumHandlers
= Record
[Idx
++];
5642 SmallVector
<BasicBlock
*, 2> Handlers
;
5643 for (unsigned Op
= 0; Op
!= NumHandlers
; ++Op
) {
5644 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
5646 return error("Invalid record");
5647 Handlers
.push_back(BB
);
5650 BasicBlock
*UnwindDest
= nullptr;
5651 if (Idx
+ 1 == Record
.size()) {
5652 UnwindDest
= getBasicBlock(Record
[Idx
++]);
5654 return error("Invalid record");
5657 if (Record
.size() != Idx
)
5658 return error("Invalid record");
5661 CatchSwitchInst::Create(ParentPad
, UnwindDest
, NumHandlers
);
5662 for (BasicBlock
*Handler
: Handlers
)
5663 CatchSwitch
->addHandler(Handler
);
5665 ResTypeID
= getVirtualTypeID(I
->getType());
5666 InstructionList
.push_back(I
);
5669 case bitc::FUNC_CODE_INST_CATCHPAD
:
5670 case bitc::FUNC_CODE_INST_CLEANUPPAD
: { // [tok,num,(ty,val)*]
5671 // We must have, at minimum, the outer scope and the number of arguments.
5672 if (Record
.size() < 2)
5673 return error("Invalid record");
5677 Type
*TokenTy
= Type::getTokenTy(Context
);
5678 Value
*ParentPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5679 getVirtualTypeID(TokenTy
), CurBB
);
5681 return error("Invald record");
5683 unsigned NumArgOperands
= Record
[Idx
++];
5685 SmallVector
<Value
*, 2> Args
;
5686 for (unsigned Op
= 0; Op
!= NumArgOperands
; ++Op
) {
5689 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
, ValTypeID
, nullptr))
5690 return error("Invalid record");
5691 Args
.push_back(Val
);
5694 if (Record
.size() != Idx
)
5695 return error("Invalid record");
5697 if (BitCode
== bitc::FUNC_CODE_INST_CLEANUPPAD
)
5698 I
= CleanupPadInst::Create(ParentPad
, Args
);
5700 I
= CatchPadInst::Create(ParentPad
, Args
);
5701 ResTypeID
= getVirtualTypeID(I
->getType());
5702 InstructionList
.push_back(I
);
5705 case bitc::FUNC_CODE_INST_SWITCH
: { // SWITCH: [opty, op0, op1, ...]
5707 if ((Record
[0] >> 16) == SWITCH_INST_MAGIC
) {
5708 // "New" SwitchInst format with case ranges. The changes to write this
5709 // format were reverted but we still recognize bitcode that uses it.
5710 // Hopefully someday we will have support for case ranges and can use
5711 // this format again.
5713 unsigned OpTyID
= Record
[1];
5714 Type
*OpTy
= getTypeByID(OpTyID
);
5715 unsigned ValueBitWidth
= cast
<IntegerType
>(OpTy
)->getBitWidth();
5717 Value
*Cond
= getValue(Record
, 2, NextValueNo
, OpTy
, OpTyID
, CurBB
);
5718 BasicBlock
*Default
= getBasicBlock(Record
[3]);
5719 if (!OpTy
|| !Cond
|| !Default
)
5720 return error("Invalid record");
5722 unsigned NumCases
= Record
[4];
5724 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
5725 InstructionList
.push_back(SI
);
5727 unsigned CurIdx
= 5;
5728 for (unsigned i
= 0; i
!= NumCases
; ++i
) {
5729 SmallVector
<ConstantInt
*, 1> CaseVals
;
5730 unsigned NumItems
= Record
[CurIdx
++];
5731 for (unsigned ci
= 0; ci
!= NumItems
; ++ci
) {
5732 bool isSingleNumber
= Record
[CurIdx
++];
5735 unsigned ActiveWords
= 1;
5736 if (ValueBitWidth
> 64)
5737 ActiveWords
= Record
[CurIdx
++];
5738 Low
= readWideAPInt(ArrayRef(&Record
[CurIdx
], ActiveWords
),
5740 CurIdx
+= ActiveWords
;
5742 if (!isSingleNumber
) {
5744 if (ValueBitWidth
> 64)
5745 ActiveWords
= Record
[CurIdx
++];
5746 APInt High
= readWideAPInt(ArrayRef(&Record
[CurIdx
], ActiveWords
),
5748 CurIdx
+= ActiveWords
;
5750 // FIXME: It is not clear whether values in the range should be
5751 // compared as signed or unsigned values. The partially
5752 // implemented changes that used this format in the past used
5753 // unsigned comparisons.
5754 for ( ; Low
.ule(High
); ++Low
)
5755 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
5757 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
5759 BasicBlock
*DestBB
= getBasicBlock(Record
[CurIdx
++]);
5760 for (ConstantInt
*Cst
: CaseVals
)
5761 SI
->addCase(Cst
, DestBB
);
5767 // Old SwitchInst format without case ranges.
5769 if (Record
.size() < 3 || (Record
.size() & 1) == 0)
5770 return error("Invalid record");
5771 unsigned OpTyID
= Record
[0];
5772 Type
*OpTy
= getTypeByID(OpTyID
);
5773 Value
*Cond
= getValue(Record
, 1, NextValueNo
, OpTy
, OpTyID
, CurBB
);
5774 BasicBlock
*Default
= getBasicBlock(Record
[2]);
5775 if (!OpTy
|| !Cond
|| !Default
)
5776 return error("Invalid record");
5777 unsigned NumCases
= (Record
.size()-3)/2;
5778 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
5779 InstructionList
.push_back(SI
);
5780 for (unsigned i
= 0, e
= NumCases
; i
!= e
; ++i
) {
5781 ConstantInt
*CaseVal
= dyn_cast_or_null
<ConstantInt
>(
5782 getFnValueByID(Record
[3+i
*2], OpTy
, OpTyID
, nullptr));
5783 BasicBlock
*DestBB
= getBasicBlock(Record
[1+3+i
*2]);
5784 if (!CaseVal
|| !DestBB
) {
5786 return error("Invalid record");
5788 SI
->addCase(CaseVal
, DestBB
);
5793 case bitc::FUNC_CODE_INST_INDIRECTBR
: { // INDIRECTBR: [opty, op0, op1, ...]
5794 if (Record
.size() < 2)
5795 return error("Invalid record");
5796 unsigned OpTyID
= Record
[0];
5797 Type
*OpTy
= getTypeByID(OpTyID
);
5798 Value
*Address
= getValue(Record
, 1, NextValueNo
, OpTy
, OpTyID
, CurBB
);
5799 if (!OpTy
|| !Address
)
5800 return error("Invalid record");
5801 unsigned NumDests
= Record
.size()-2;
5802 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, NumDests
);
5803 InstructionList
.push_back(IBI
);
5804 for (unsigned i
= 0, e
= NumDests
; i
!= e
; ++i
) {
5805 if (BasicBlock
*DestBB
= getBasicBlock(Record
[2+i
])) {
5806 IBI
->addDestination(DestBB
);
5809 return error("Invalid record");
5816 case bitc::FUNC_CODE_INST_INVOKE
: {
5817 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5818 if (Record
.size() < 4)
5819 return error("Invalid record");
5821 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
5822 unsigned CCInfo
= Record
[OpNum
++];
5823 BasicBlock
*NormalBB
= getBasicBlock(Record
[OpNum
++]);
5824 BasicBlock
*UnwindBB
= getBasicBlock(Record
[OpNum
++]);
5826 unsigned FTyID
= InvalidTypeID
;
5827 FunctionType
*FTy
= nullptr;
5828 if ((CCInfo
>> 13) & 1) {
5829 FTyID
= Record
[OpNum
++];
5830 FTy
= dyn_cast
<FunctionType
>(getTypeByID(FTyID
));
5832 return error("Explicit invoke type is not a function type");
5836 unsigned CalleeTypeID
;
5837 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, CalleeTypeID
,
5839 return error("Invalid record");
5841 PointerType
*CalleeTy
= dyn_cast
<PointerType
>(Callee
->getType());
5843 return error("Callee is not a pointer");
5845 FTyID
= getContainedTypeID(CalleeTypeID
);
5846 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
5848 return error("Callee is not of pointer to function type");
5850 if (Record
.size() < FTy
->getNumParams() + OpNum
)
5851 return error("Insufficient operands to call");
5853 SmallVector
<Value
*, 16> Ops
;
5854 SmallVector
<unsigned, 16> ArgTyIDs
;
5855 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
5856 unsigned ArgTyID
= getContainedTypeID(FTyID
, i
+ 1);
5857 Ops
.push_back(getValue(Record
, OpNum
, NextValueNo
, FTy
->getParamType(i
),
5859 ArgTyIDs
.push_back(ArgTyID
);
5861 return error("Invalid record");
5864 if (!FTy
->isVarArg()) {
5865 if (Record
.size() != OpNum
)
5866 return error("Invalid record");
5868 // Read type/value pairs for varargs params.
5869 while (OpNum
!= Record
.size()) {
5872 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5873 return error("Invalid record");
5875 ArgTyIDs
.push_back(OpTypeID
);
5879 // Upgrade the bundles if needed.
5880 if (!OperandBundles
.empty())
5881 UpgradeOperandBundles(OperandBundles
);
5883 I
= InvokeInst::Create(FTy
, Callee
, NormalBB
, UnwindBB
, Ops
,
5885 ResTypeID
= getContainedTypeID(FTyID
);
5886 OperandBundles
.clear();
5887 InstructionList
.push_back(I
);
5888 cast
<InvokeInst
>(I
)->setCallingConv(
5889 static_cast<CallingConv::ID
>(CallingConv::MaxID
& CCInfo
));
5890 cast
<InvokeInst
>(I
)->setAttributes(PAL
);
5891 if (Error Err
= propagateAttributeTypes(cast
<CallBase
>(I
), ArgTyIDs
)) {
5898 case bitc::FUNC_CODE_INST_RESUME
: { // RESUME: [opval]
5900 Value
*Val
= nullptr;
5902 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
, ValTypeID
, CurBB
))
5903 return error("Invalid record");
5904 I
= ResumeInst::Create(Val
);
5905 InstructionList
.push_back(I
);
5908 case bitc::FUNC_CODE_INST_CALLBR
: {
5909 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5911 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
5912 unsigned CCInfo
= Record
[OpNum
++];
5914 BasicBlock
*DefaultDest
= getBasicBlock(Record
[OpNum
++]);
5915 unsigned NumIndirectDests
= Record
[OpNum
++];
5916 SmallVector
<BasicBlock
*, 16> IndirectDests
;
5917 for (unsigned i
= 0, e
= NumIndirectDests
; i
!= e
; ++i
)
5918 IndirectDests
.push_back(getBasicBlock(Record
[OpNum
++]));
5920 unsigned FTyID
= InvalidTypeID
;
5921 FunctionType
*FTy
= nullptr;
5922 if ((CCInfo
>> bitc::CALL_EXPLICIT_TYPE
) & 1) {
5923 FTyID
= Record
[OpNum
++];
5924 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
5926 return error("Explicit call type is not a function type");
5930 unsigned CalleeTypeID
;
5931 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, CalleeTypeID
,
5933 return error("Invalid record");
5935 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
5937 return error("Callee is not a pointer type");
5939 FTyID
= getContainedTypeID(CalleeTypeID
);
5940 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
5942 return error("Callee is not of pointer to function type");
5944 if (Record
.size() < FTy
->getNumParams() + OpNum
)
5945 return error("Insufficient operands to call");
5947 SmallVector
<Value
*, 16> Args
;
5948 SmallVector
<unsigned, 16> ArgTyIDs
;
5949 // Read the fixed params.
5950 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
5952 unsigned ArgTyID
= getContainedTypeID(FTyID
, i
+ 1);
5953 if (FTy
->getParamType(i
)->isLabelTy())
5954 Arg
= getBasicBlock(Record
[OpNum
]);
5956 Arg
= getValue(Record
, OpNum
, NextValueNo
, FTy
->getParamType(i
),
5959 return error("Invalid record");
5960 Args
.push_back(Arg
);
5961 ArgTyIDs
.push_back(ArgTyID
);
5964 // Read type/value pairs for varargs params.
5965 if (!FTy
->isVarArg()) {
5966 if (OpNum
!= Record
.size())
5967 return error("Invalid record");
5969 while (OpNum
!= Record
.size()) {
5972 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5973 return error("Invalid record");
5975 ArgTyIDs
.push_back(OpTypeID
);
5979 // Upgrade the bundles if needed.
5980 if (!OperandBundles
.empty())
5981 UpgradeOperandBundles(OperandBundles
);
5983 if (auto *IA
= dyn_cast
<InlineAsm
>(Callee
)) {
5984 InlineAsm::ConstraintInfoVector ConstraintInfo
= IA
->ParseConstraints();
5985 auto IsLabelConstraint
= [](const InlineAsm::ConstraintInfo
&CI
) {
5986 return CI
.Type
== InlineAsm::isLabel
;
5988 if (none_of(ConstraintInfo
, IsLabelConstraint
)) {
5989 // Upgrade explicit blockaddress arguments to label constraints.
5990 // Verify that the last arguments are blockaddress arguments that
5991 // match the indirect destinations. Clang always generates callbr
5992 // in this form. We could support reordering with more effort.
5993 unsigned FirstBlockArg
= Args
.size() - IndirectDests
.size();
5994 for (unsigned ArgNo
= FirstBlockArg
; ArgNo
< Args
.size(); ++ArgNo
) {
5995 unsigned LabelNo
= ArgNo
- FirstBlockArg
;
5996 auto *BA
= dyn_cast
<BlockAddress
>(Args
[ArgNo
]);
5997 if (!BA
|| BA
->getFunction() != F
||
5998 LabelNo
> IndirectDests
.size() ||
5999 BA
->getBasicBlock() != IndirectDests
[LabelNo
])
6000 return error("callbr argument does not match indirect dest");
6003 // Remove blockaddress arguments.
6004 Args
.erase(Args
.begin() + FirstBlockArg
, Args
.end());
6005 ArgTyIDs
.erase(ArgTyIDs
.begin() + FirstBlockArg
, ArgTyIDs
.end());
6007 // Recreate the function type with less arguments.
6008 SmallVector
<Type
*> ArgTys
;
6009 for (Value
*Arg
: Args
)
6010 ArgTys
.push_back(Arg
->getType());
6012 FunctionType::get(FTy
->getReturnType(), ArgTys
, FTy
->isVarArg());
6014 // Update constraint string to use label constraints.
6015 std::string Constraints
= IA
->getConstraintString();
6018 for (const auto &CI
: ConstraintInfo
) {
6020 if (ArgNo
>= FirstBlockArg
)
6021 Constraints
.insert(Pos
, "!");
6025 // Go to next constraint in string.
6026 Pos
= Constraints
.find(',', Pos
);
6027 if (Pos
== std::string::npos
)
6032 Callee
= InlineAsm::get(FTy
, IA
->getAsmString(), Constraints
,
6033 IA
->hasSideEffects(), IA
->isAlignStack(),
6034 IA
->getDialect(), IA
->canThrow());
6038 I
= CallBrInst::Create(FTy
, Callee
, DefaultDest
, IndirectDests
, Args
,
6040 ResTypeID
= getContainedTypeID(FTyID
);
6041 OperandBundles
.clear();
6042 InstructionList
.push_back(I
);
6043 cast
<CallBrInst
>(I
)->setCallingConv(
6044 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
6045 cast
<CallBrInst
>(I
)->setAttributes(PAL
);
6046 if (Error Err
= propagateAttributeTypes(cast
<CallBase
>(I
), ArgTyIDs
)) {
6052 case bitc::FUNC_CODE_INST_UNREACHABLE
: // UNREACHABLE
6053 I
= new UnreachableInst(Context
);
6054 InstructionList
.push_back(I
);
6056 case bitc::FUNC_CODE_INST_PHI
: { // PHI: [ty, val0,bb0, ...]
6058 return error("Invalid phi record");
6059 // The first record specifies the type.
6060 unsigned TyID
= Record
[0];
6061 Type
*Ty
= getTypeByID(TyID
);
6063 return error("Invalid phi record");
6065 // Phi arguments are pairs of records of [value, basic block].
6066 // There is an optional final record for fast-math-flags if this phi has a
6067 // floating-point type.
6068 size_t NumArgs
= (Record
.size() - 1) / 2;
6069 PHINode
*PN
= PHINode::Create(Ty
, NumArgs
);
6070 if ((Record
.size() - 1) % 2 == 1 && !isa
<FPMathOperator
>(PN
)) {
6072 return error("Invalid phi record");
6074 InstructionList
.push_back(PN
);
6076 SmallDenseMap
<BasicBlock
*, Value
*> Args
;
6077 for (unsigned i
= 0; i
!= NumArgs
; i
++) {
6078 BasicBlock
*BB
= getBasicBlock(Record
[i
* 2 + 2]);
6081 return error("Invalid phi BB");
6084 // Phi nodes may contain the same predecessor multiple times, in which
6085 // case the incoming value must be identical. Directly reuse the already
6086 // seen value here, to avoid expanding a constant expression multiple
6088 auto It
= Args
.find(BB
);
6089 if (It
!= Args
.end()) {
6090 PN
->addIncoming(It
->second
, BB
);
6094 // If there already is a block for this edge (from a different phi),
6096 BasicBlock
*EdgeBB
= ConstExprEdgeBBs
.lookup({BB
, CurBB
});
6098 // Otherwise, use a temporary block (that we will discard if it
6099 // turns out to be unnecessary).
6100 if (!PhiConstExprBB
)
6101 PhiConstExprBB
= BasicBlock::Create(Context
, "phi.constexpr", F
);
6102 EdgeBB
= PhiConstExprBB
;
6105 // With the new function encoding, it is possible that operands have
6106 // negative IDs (for forward references). Use a signed VBR
6107 // representation to keep the encoding small.
6110 V
= getValueSigned(Record
, i
* 2 + 1, NextValueNo
, Ty
, TyID
, EdgeBB
);
6112 V
= getValue(Record
, i
* 2 + 1, NextValueNo
, Ty
, TyID
, EdgeBB
);
6115 PhiConstExprBB
->eraseFromParent();
6116 return error("Invalid phi record");
6119 if (EdgeBB
== PhiConstExprBB
&& !EdgeBB
->empty()) {
6120 ConstExprEdgeBBs
.insert({{BB
, CurBB
}, EdgeBB
});
6121 PhiConstExprBB
= nullptr;
6123 PN
->addIncoming(V
, BB
);
6124 Args
.insert({BB
, V
});
6129 // If there are an even number of records, the final record must be FMF.
6130 if (Record
.size() % 2 == 0) {
6131 assert(isa
<FPMathOperator
>(I
) && "Unexpected phi type");
6132 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[Record
.size() - 1]);
6134 I
->setFastMathFlags(FMF
);
6140 case bitc::FUNC_CODE_INST_LANDINGPAD
:
6141 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD
: {
6142 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6144 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD
) {
6145 if (Record
.size() < 3)
6146 return error("Invalid record");
6148 assert(BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
);
6149 if (Record
.size() < 4)
6150 return error("Invalid record");
6152 ResTypeID
= Record
[Idx
++];
6153 Type
*Ty
= getTypeByID(ResTypeID
);
6155 return error("Invalid record");
6156 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
) {
6157 Value
*PersFn
= nullptr;
6158 unsigned PersFnTypeID
;
6159 if (getValueTypePair(Record
, Idx
, NextValueNo
, PersFn
, PersFnTypeID
,
6161 return error("Invalid record");
6163 if (!F
->hasPersonalityFn())
6164 F
->setPersonalityFn(cast
<Constant
>(PersFn
));
6165 else if (F
->getPersonalityFn() != cast
<Constant
>(PersFn
))
6166 return error("Personality function mismatch");
6169 bool IsCleanup
= !!Record
[Idx
++];
6170 unsigned NumClauses
= Record
[Idx
++];
6171 LandingPadInst
*LP
= LandingPadInst::Create(Ty
, NumClauses
);
6172 LP
->setCleanup(IsCleanup
);
6173 for (unsigned J
= 0; J
!= NumClauses
; ++J
) {
6174 LandingPadInst::ClauseType CT
=
6175 LandingPadInst::ClauseType(Record
[Idx
++]); (void)CT
;
6179 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
, ValTypeID
,
6182 return error("Invalid record");
6185 assert((CT
!= LandingPadInst::Catch
||
6186 !isa
<ArrayType
>(Val
->getType())) &&
6187 "Catch clause has a invalid type!");
6188 assert((CT
!= LandingPadInst::Filter
||
6189 isa
<ArrayType
>(Val
->getType())) &&
6190 "Filter clause has invalid type!");
6191 LP
->addClause(cast
<Constant
>(Val
));
6195 InstructionList
.push_back(I
);
6199 case bitc::FUNC_CODE_INST_ALLOCA
: { // ALLOCA: [instty, opty, op, align]
6200 if (Record
.size() != 4 && Record
.size() != 5)
6201 return error("Invalid record");
6202 using APV
= AllocaPackedValues
;
6203 const uint64_t Rec
= Record
[3];
6204 const bool InAlloca
= Bitfield::get
<APV::UsedWithInAlloca
>(Rec
);
6205 const bool SwiftError
= Bitfield::get
<APV::SwiftError
>(Rec
);
6206 unsigned TyID
= Record
[0];
6207 Type
*Ty
= getTypeByID(TyID
);
6208 if (!Bitfield::get
<APV::ExplicitType
>(Rec
)) {
6209 TyID
= getContainedTypeID(TyID
);
6210 Ty
= getTypeByID(TyID
);
6212 return error("Missing element type for old-style alloca");
6214 unsigned OpTyID
= Record
[1];
6215 Type
*OpTy
= getTypeByID(OpTyID
);
6216 Value
*Size
= getFnValueByID(Record
[2], OpTy
, OpTyID
, CurBB
);
6219 Bitfield::get
<APV::AlignLower
>(Rec
) |
6220 (Bitfield::get
<APV::AlignUpper
>(Rec
) << APV::AlignLower::Bits
);
6221 if (Error Err
= parseAlignmentValue(AlignExp
, Align
)) {
6225 return error("Invalid record");
6227 const DataLayout
&DL
= TheModule
->getDataLayout();
6228 unsigned AS
= Record
.size() == 5 ? Record
[4] : DL
.getAllocaAddrSpace();
6230 SmallPtrSet
<Type
*, 4> Visited
;
6231 if (!Align
&& !Ty
->isSized(&Visited
))
6232 return error("alloca of unsized type");
6234 Align
= DL
.getPrefTypeAlign(Ty
);
6236 if (!Size
->getType()->isIntegerTy())
6237 return error("alloca element count must have integer type");
6239 AllocaInst
*AI
= new AllocaInst(Ty
, AS
, Size
, *Align
);
6240 AI
->setUsedWithInAlloca(InAlloca
);
6241 AI
->setSwiftError(SwiftError
);
6243 ResTypeID
= getVirtualTypeID(AI
->getType(), TyID
);
6244 InstructionList
.push_back(I
);
6247 case bitc::FUNC_CODE_INST_LOAD
: { // LOAD: [opty, op, align, vol]
6251 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
) ||
6252 (OpNum
+ 2 != Record
.size() && OpNum
+ 3 != Record
.size()))
6253 return error("Invalid record");
6255 if (!isa
<PointerType
>(Op
->getType()))
6256 return error("Load operand is not a pointer type");
6259 if (OpNum
+ 3 == Record
.size()) {
6260 ResTypeID
= Record
[OpNum
++];
6261 Ty
= getTypeByID(ResTypeID
);
6263 ResTypeID
= getContainedTypeID(OpTypeID
);
6264 Ty
= getTypeByID(ResTypeID
);
6268 return error("Missing load type");
6270 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
6274 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6276 SmallPtrSet
<Type
*, 4> Visited
;
6277 if (!Align
&& !Ty
->isSized(&Visited
))
6278 return error("load of unsized type");
6280 Align
= TheModule
->getDataLayout().getABITypeAlign(Ty
);
6281 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], *Align
);
6282 InstructionList
.push_back(I
);
6285 case bitc::FUNC_CODE_INST_LOADATOMIC
: {
6286 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6290 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
) ||
6291 (OpNum
+ 4 != Record
.size() && OpNum
+ 5 != Record
.size()))
6292 return error("Invalid record");
6294 if (!isa
<PointerType
>(Op
->getType()))
6295 return error("Load operand is not a pointer type");
6298 if (OpNum
+ 5 == Record
.size()) {
6299 ResTypeID
= Record
[OpNum
++];
6300 Ty
= getTypeByID(ResTypeID
);
6302 ResTypeID
= getContainedTypeID(OpTypeID
);
6303 Ty
= getTypeByID(ResTypeID
);
6307 return error("Missing atomic load type");
6309 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
6312 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
6313 if (Ordering
== AtomicOrdering::NotAtomic
||
6314 Ordering
== AtomicOrdering::Release
||
6315 Ordering
== AtomicOrdering::AcquireRelease
)
6316 return error("Invalid record");
6317 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
6318 return error("Invalid record");
6319 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
6322 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6325 return error("Alignment missing from atomic load");
6326 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], *Align
, Ordering
, SSID
);
6327 InstructionList
.push_back(I
);
6330 case bitc::FUNC_CODE_INST_STORE
:
6331 case bitc::FUNC_CODE_INST_STORE_OLD
: { // STORE2:[ptrty, ptr, val, align, vol]
6334 unsigned PtrTypeID
, ValTypeID
;
6335 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6336 return error("Invalid record");
6338 if (BitCode
== bitc::FUNC_CODE_INST_STORE
) {
6339 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
6340 return error("Invalid record");
6342 ValTypeID
= getContainedTypeID(PtrTypeID
);
6343 if (popValue(Record
, OpNum
, NextValueNo
, getTypeByID(ValTypeID
),
6344 ValTypeID
, Val
, CurBB
))
6345 return error("Invalid record");
6348 if (OpNum
+ 2 != Record
.size())
6349 return error("Invalid record");
6351 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
6354 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6356 SmallPtrSet
<Type
*, 4> Visited
;
6357 if (!Align
&& !Val
->getType()->isSized(&Visited
))
6358 return error("store of unsized type");
6360 Align
= TheModule
->getDataLayout().getABITypeAlign(Val
->getType());
6361 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+ 1], *Align
);
6362 InstructionList
.push_back(I
);
6365 case bitc::FUNC_CODE_INST_STOREATOMIC
:
6366 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD
: {
6367 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6370 unsigned PtrTypeID
, ValTypeID
;
6371 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
) ||
6372 !isa
<PointerType
>(Ptr
->getType()))
6373 return error("Invalid record");
6374 if (BitCode
== bitc::FUNC_CODE_INST_STOREATOMIC
) {
6375 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
6376 return error("Invalid record");
6378 ValTypeID
= getContainedTypeID(PtrTypeID
);
6379 if (popValue(Record
, OpNum
, NextValueNo
, getTypeByID(ValTypeID
),
6380 ValTypeID
, Val
, CurBB
))
6381 return error("Invalid record");
6384 if (OpNum
+ 4 != Record
.size())
6385 return error("Invalid record");
6387 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
6389 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
6390 if (Ordering
== AtomicOrdering::NotAtomic
||
6391 Ordering
== AtomicOrdering::Acquire
||
6392 Ordering
== AtomicOrdering::AcquireRelease
)
6393 return error("Invalid record");
6394 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
6395 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
6396 return error("Invalid record");
6399 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6402 return error("Alignment missing from atomic store");
6403 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+ 1], *Align
, Ordering
, SSID
);
6404 InstructionList
.push_back(I
);
6407 case bitc::FUNC_CODE_INST_CMPXCHG_OLD
: {
6408 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6409 // failure_ordering?, weak?]
6410 const size_t NumRecords
= Record
.size();
6412 Value
*Ptr
= nullptr;
6414 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6415 return error("Invalid record");
6417 if (!isa
<PointerType
>(Ptr
->getType()))
6418 return error("Cmpxchg operand is not a pointer type");
6420 Value
*Cmp
= nullptr;
6421 unsigned CmpTypeID
= getContainedTypeID(PtrTypeID
);
6422 if (popValue(Record
, OpNum
, NextValueNo
, getTypeByID(CmpTypeID
),
6423 CmpTypeID
, Cmp
, CurBB
))
6424 return error("Invalid record");
6426 Value
*New
= nullptr;
6427 if (popValue(Record
, OpNum
, NextValueNo
, Cmp
->getType(), CmpTypeID
,
6429 NumRecords
< OpNum
+ 3 || NumRecords
> OpNum
+ 5)
6430 return error("Invalid record");
6432 const AtomicOrdering SuccessOrdering
=
6433 getDecodedOrdering(Record
[OpNum
+ 1]);
6434 if (SuccessOrdering
== AtomicOrdering::NotAtomic
||
6435 SuccessOrdering
== AtomicOrdering::Unordered
)
6436 return error("Invalid record");
6438 const SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 2]);
6440 if (Error Err
= typeCheckLoadStoreInst(Cmp
->getType(), Ptr
->getType()))
6443 const AtomicOrdering FailureOrdering
=
6445 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering
)
6446 : getDecodedOrdering(Record
[OpNum
+ 3]);
6448 if (FailureOrdering
== AtomicOrdering::NotAtomic
||
6449 FailureOrdering
== AtomicOrdering::Unordered
)
6450 return error("Invalid record");
6452 const Align
Alignment(
6453 TheModule
->getDataLayout().getTypeStoreSize(Cmp
->getType()));
6455 I
= new AtomicCmpXchgInst(Ptr
, Cmp
, New
, Alignment
, SuccessOrdering
,
6456 FailureOrdering
, SSID
);
6457 cast
<AtomicCmpXchgInst
>(I
)->setVolatile(Record
[OpNum
]);
6459 if (NumRecords
< 8) {
6460 // Before weak cmpxchgs existed, the instruction simply returned the
6461 // value loaded from memory, so bitcode files from that era will be
6462 // expecting the first component of a modern cmpxchg.
6463 I
->insertInto(CurBB
, CurBB
->end());
6464 I
= ExtractValueInst::Create(I
, 0);
6465 ResTypeID
= CmpTypeID
;
6467 cast
<AtomicCmpXchgInst
>(I
)->setWeak(Record
[OpNum
+ 4]);
6468 unsigned I1TypeID
= getVirtualTypeID(Type::getInt1Ty(Context
));
6469 ResTypeID
= getVirtualTypeID(I
->getType(), {CmpTypeID
, I1TypeID
});
6472 InstructionList
.push_back(I
);
6475 case bitc::FUNC_CODE_INST_CMPXCHG
: {
6476 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6477 // failure_ordering, weak, align?]
6478 const size_t NumRecords
= Record
.size();
6480 Value
*Ptr
= nullptr;
6482 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6483 return error("Invalid record");
6485 if (!isa
<PointerType
>(Ptr
->getType()))
6486 return error("Cmpxchg operand is not a pointer type");
6488 Value
*Cmp
= nullptr;
6490 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Cmp
, CmpTypeID
, CurBB
))
6491 return error("Invalid record");
6493 Value
*Val
= nullptr;
6494 if (popValue(Record
, OpNum
, NextValueNo
, Cmp
->getType(), CmpTypeID
, Val
,
6496 return error("Invalid record");
6498 if (NumRecords
< OpNum
+ 3 || NumRecords
> OpNum
+ 6)
6499 return error("Invalid record");
6501 const bool IsVol
= Record
[OpNum
];
6503 const AtomicOrdering SuccessOrdering
=
6504 getDecodedOrdering(Record
[OpNum
+ 1]);
6505 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering
))
6506 return error("Invalid cmpxchg success ordering");
6508 const SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 2]);
6510 if (Error Err
= typeCheckLoadStoreInst(Cmp
->getType(), Ptr
->getType()))
6513 const AtomicOrdering FailureOrdering
=
6514 getDecodedOrdering(Record
[OpNum
+ 3]);
6515 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering
))
6516 return error("Invalid cmpxchg failure ordering");
6518 const bool IsWeak
= Record
[OpNum
+ 4];
6520 MaybeAlign Alignment
;
6522 if (NumRecords
== (OpNum
+ 6)) {
6523 if (Error Err
= parseAlignmentValue(Record
[OpNum
+ 5], Alignment
))
6528 Align(TheModule
->getDataLayout().getTypeStoreSize(Cmp
->getType()));
6530 I
= new AtomicCmpXchgInst(Ptr
, Cmp
, Val
, *Alignment
, SuccessOrdering
,
6531 FailureOrdering
, SSID
);
6532 cast
<AtomicCmpXchgInst
>(I
)->setVolatile(IsVol
);
6533 cast
<AtomicCmpXchgInst
>(I
)->setWeak(IsWeak
);
6535 unsigned I1TypeID
= getVirtualTypeID(Type::getInt1Ty(Context
));
6536 ResTypeID
= getVirtualTypeID(I
->getType(), {CmpTypeID
, I1TypeID
});
6538 InstructionList
.push_back(I
);
6541 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD
:
6542 case bitc::FUNC_CODE_INST_ATOMICRMW
: {
6543 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6544 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6545 const size_t NumRecords
= Record
.size();
6548 Value
*Ptr
= nullptr;
6550 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6551 return error("Invalid record");
6553 if (!isa
<PointerType
>(Ptr
->getType()))
6554 return error("Invalid record");
6556 Value
*Val
= nullptr;
6557 unsigned ValTypeID
= InvalidTypeID
;
6558 if (BitCode
== bitc::FUNC_CODE_INST_ATOMICRMW_OLD
) {
6559 ValTypeID
= getContainedTypeID(PtrTypeID
);
6560 if (popValue(Record
, OpNum
, NextValueNo
,
6561 getTypeByID(ValTypeID
), ValTypeID
, Val
, CurBB
))
6562 return error("Invalid record");
6564 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
6565 return error("Invalid record");
6568 if (!(NumRecords
== (OpNum
+ 4) || NumRecords
== (OpNum
+ 5)))
6569 return error("Invalid record");
6571 const AtomicRMWInst::BinOp Operation
=
6572 getDecodedRMWOperation(Record
[OpNum
]);
6573 if (Operation
< AtomicRMWInst::FIRST_BINOP
||
6574 Operation
> AtomicRMWInst::LAST_BINOP
)
6575 return error("Invalid record");
6577 const bool IsVol
= Record
[OpNum
+ 1];
6579 const AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
6580 if (Ordering
== AtomicOrdering::NotAtomic
||
6581 Ordering
== AtomicOrdering::Unordered
)
6582 return error("Invalid record");
6584 const SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
6586 MaybeAlign Alignment
;
6588 if (NumRecords
== (OpNum
+ 5)) {
6589 if (Error Err
= parseAlignmentValue(Record
[OpNum
+ 4], Alignment
))
6595 Align(TheModule
->getDataLayout().getTypeStoreSize(Val
->getType()));
6597 I
= new AtomicRMWInst(Operation
, Ptr
, Val
, *Alignment
, Ordering
, SSID
);
6598 ResTypeID
= ValTypeID
;
6599 cast
<AtomicRMWInst
>(I
)->setVolatile(IsVol
);
6601 InstructionList
.push_back(I
);
6604 case bitc::FUNC_CODE_INST_FENCE
: { // FENCE:[ordering, ssid]
6605 if (2 != Record
.size())
6606 return error("Invalid record");
6607 AtomicOrdering Ordering
= getDecodedOrdering(Record
[0]);
6608 if (Ordering
== AtomicOrdering::NotAtomic
||
6609 Ordering
== AtomicOrdering::Unordered
||
6610 Ordering
== AtomicOrdering::Monotonic
)
6611 return error("Invalid record");
6612 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[1]);
6613 I
= new FenceInst(Context
, Ordering
, SSID
);
6614 InstructionList
.push_back(I
);
6617 case bitc::FUNC_CODE_DEBUG_RECORD_LABEL
: {
6618 // DbgLabelRecords are placed after the Instructions that they are
6620 SeenDebugRecord
= true;
6621 Instruction
*Inst
= getLastInstruction();
6623 return error("Invalid dbg record: missing instruction");
6624 DILocation
*DIL
= cast
<DILocation
>(getFnMetadataByID(Record
[0]));
6625 DILabel
*Label
= cast
<DILabel
>(getFnMetadataByID(Record
[1]));
6626 Inst
->getParent()->insertDbgRecordBefore(
6627 new DbgLabelRecord(Label
, DebugLoc(DIL
)), Inst
->getIterator());
6628 continue; // This isn't an instruction.
6630 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
:
6631 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE
:
6632 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE
:
6633 case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN
: {
6634 // DbgVariableRecords are placed after the Instructions that they are
6636 SeenDebugRecord
= true;
6637 Instruction
*Inst
= getLastInstruction();
6639 return error("Invalid dbg record: missing instruction");
6641 // First 3 fields are common to all kinds:
6642 // DILocation, DILocalVariable, DIExpression
6643 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6644 // ..., LocationMetadata
6645 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6647 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6648 // ..., LocationMetadata
6649 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6650 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6652 // Common fields (0-2).
6653 DILocation
*DIL
= cast
<DILocation
>(getFnMetadataByID(Record
[Slot
++]));
6654 DILocalVariable
*Var
=
6655 cast
<DILocalVariable
>(getFnMetadataByID(Record
[Slot
++]));
6656 DIExpression
*Expr
=
6657 cast
<DIExpression
>(getFnMetadataByID(Record
[Slot
++]));
6659 // Union field (3: LocationMetadata | Value).
6660 Metadata
*RawLocation
= nullptr;
6661 if (BitCode
== bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
) {
6664 // We never expect to see a fwd reference value here because
6665 // use-before-defs are encoded with the standard non-abbrev record
6666 // type (they'd require encoding the type too, and they're rare). As a
6667 // result, getValueTypePair only ever increments Slot by one here (once
6668 // for the value, never twice for value and type).
6669 unsigned SlotBefore
= Slot
;
6670 if (getValueTypePair(Record
, Slot
, NextValueNo
, V
, TyID
, CurBB
))
6671 return error("Invalid dbg record: invalid value");
6673 assert((SlotBefore
== Slot
- 1) && "unexpected fwd ref");
6674 RawLocation
= ValueAsMetadata::get(V
);
6676 RawLocation
= getFnMetadataByID(Record
[Slot
++]);
6679 DbgVariableRecord
*DVR
= nullptr;
6681 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE
:
6682 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
:
6683 DVR
= new DbgVariableRecord(RawLocation
, Var
, Expr
, DIL
,
6684 DbgVariableRecord::LocationType::Value
);
6686 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE
:
6687 DVR
= new DbgVariableRecord(RawLocation
, Var
, Expr
, DIL
,
6688 DbgVariableRecord::LocationType::Declare
);
6690 case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN
: {
6691 DIAssignID
*ID
= cast
<DIAssignID
>(getFnMetadataByID(Record
[Slot
++]));
6692 DIExpression
*AddrExpr
=
6693 cast
<DIExpression
>(getFnMetadataByID(Record
[Slot
++]));
6694 Metadata
*Addr
= getFnMetadataByID(Record
[Slot
++]);
6695 DVR
= new DbgVariableRecord(RawLocation
, Var
, Expr
, ID
, Addr
, AddrExpr
,
6700 llvm_unreachable("Unknown DbgVariableRecord bitcode");
6702 Inst
->getParent()->insertDbgRecordBefore(DVR
, Inst
->getIterator());
6703 continue; // This isn't an instruction.
6705 case bitc::FUNC_CODE_INST_CALL
: {
6706 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6707 if (Record
.size() < 3)
6708 return error("Invalid record");
6711 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
6712 unsigned CCInfo
= Record
[OpNum
++];
6715 if ((CCInfo
>> bitc::CALL_FMF
) & 1) {
6716 FMF
= getDecodedFastMathFlags(Record
[OpNum
++]);
6718 return error("Fast math flags indicator set for call with no FMF");
6721 unsigned FTyID
= InvalidTypeID
;
6722 FunctionType
*FTy
= nullptr;
6723 if ((CCInfo
>> bitc::CALL_EXPLICIT_TYPE
) & 1) {
6724 FTyID
= Record
[OpNum
++];
6725 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
6727 return error("Explicit call type is not a function type");
6731 unsigned CalleeTypeID
;
6732 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, CalleeTypeID
,
6734 return error("Invalid record");
6736 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
6738 return error("Callee is not a pointer type");
6740 FTyID
= getContainedTypeID(CalleeTypeID
);
6741 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
6743 return error("Callee is not of pointer to function type");
6745 if (Record
.size() < FTy
->getNumParams() + OpNum
)
6746 return error("Insufficient operands to call");
6748 SmallVector
<Value
*, 16> Args
;
6749 SmallVector
<unsigned, 16> ArgTyIDs
;
6750 // Read the fixed params.
6751 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
6752 unsigned ArgTyID
= getContainedTypeID(FTyID
, i
+ 1);
6753 if (FTy
->getParamType(i
)->isLabelTy())
6754 Args
.push_back(getBasicBlock(Record
[OpNum
]));
6756 Args
.push_back(getValue(Record
, OpNum
, NextValueNo
,
6757 FTy
->getParamType(i
), ArgTyID
, CurBB
));
6758 ArgTyIDs
.push_back(ArgTyID
);
6760 return error("Invalid record");
6763 // Read type/value pairs for varargs params.
6764 if (!FTy
->isVarArg()) {
6765 if (OpNum
!= Record
.size())
6766 return error("Invalid record");
6768 while (OpNum
!= Record
.size()) {
6771 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
6772 return error("Invalid record");
6774 ArgTyIDs
.push_back(OpTypeID
);
6778 // Upgrade the bundles if needed.
6779 if (!OperandBundles
.empty())
6780 UpgradeOperandBundles(OperandBundles
);
6782 I
= CallInst::Create(FTy
, Callee
, Args
, OperandBundles
);
6783 ResTypeID
= getContainedTypeID(FTyID
);
6784 OperandBundles
.clear();
6785 InstructionList
.push_back(I
);
6786 cast
<CallInst
>(I
)->setCallingConv(
6787 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
6788 CallInst::TailCallKind TCK
= CallInst::TCK_None
;
6789 if (CCInfo
& (1 << bitc::CALL_TAIL
))
6790 TCK
= CallInst::TCK_Tail
;
6791 if (CCInfo
& (1 << bitc::CALL_MUSTTAIL
))
6792 TCK
= CallInst::TCK_MustTail
;
6793 if (CCInfo
& (1 << bitc::CALL_NOTAIL
))
6794 TCK
= CallInst::TCK_NoTail
;
6795 cast
<CallInst
>(I
)->setTailCallKind(TCK
);
6796 cast
<CallInst
>(I
)->setAttributes(PAL
);
6797 if (isa
<DbgInfoIntrinsic
>(I
))
6798 SeenDebugIntrinsic
= true;
6799 if (Error Err
= propagateAttributeTypes(cast
<CallBase
>(I
), ArgTyIDs
)) {
6804 if (!isa
<FPMathOperator
>(I
))
6805 return error("Fast-math-flags specified for call without "
6806 "floating-point scalar or vector return type");
6807 I
->setFastMathFlags(FMF
);
6811 case bitc::FUNC_CODE_INST_VAARG
: { // VAARG: [valistty, valist, instty]
6812 if (Record
.size() < 3)
6813 return error("Invalid record");
6814 unsigned OpTyID
= Record
[0];
6815 Type
*OpTy
= getTypeByID(OpTyID
);
6816 Value
*Op
= getValue(Record
, 1, NextValueNo
, OpTy
, OpTyID
, CurBB
);
6817 ResTypeID
= Record
[2];
6818 Type
*ResTy
= getTypeByID(ResTypeID
);
6819 if (!OpTy
|| !Op
|| !ResTy
)
6820 return error("Invalid record");
6821 I
= new VAArgInst(Op
, ResTy
);
6822 InstructionList
.push_back(I
);
6826 case bitc::FUNC_CODE_OPERAND_BUNDLE
: {
6827 // A call or an invoke can be optionally prefixed with some variable
6828 // number of operand bundle blocks. These blocks are read into
6829 // OperandBundles and consumed at the next call or invoke instruction.
6831 if (Record
.empty() || Record
[0] >= BundleTags
.size())
6832 return error("Invalid record");
6834 std::vector
<Value
*> Inputs
;
6837 while (OpNum
!= Record
.size()) {
6839 if (getValueOrMetadata(Record
, OpNum
, NextValueNo
, Op
, CurBB
))
6840 return error("Invalid record");
6841 Inputs
.push_back(Op
);
6844 OperandBundles
.emplace_back(BundleTags
[Record
[0]], std::move(Inputs
));
6848 case bitc::FUNC_CODE_INST_FREEZE
: { // FREEZE: [opty,opval]
6850 Value
*Op
= nullptr;
6852 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
6853 return error("Invalid record");
6854 if (OpNum
!= Record
.size())
6855 return error("Invalid record");
6857 I
= new FreezeInst(Op
);
6858 ResTypeID
= OpTypeID
;
6859 InstructionList
.push_back(I
);
6864 // Add instruction to end of current BB. If there is no current BB, reject
6868 return error("Invalid instruction with no BB");
6870 if (!OperandBundles
.empty()) {
6872 return error("Operand bundles found with no consumer");
6874 I
->insertInto(CurBB
, CurBB
->end());
6876 // If this was a terminator instruction, move to the next block.
6877 if (I
->isTerminator()) {
6879 CurBB
= CurBBNo
< FunctionBBs
.size() ? FunctionBBs
[CurBBNo
] : nullptr;
6882 // Non-void values get registered in the value table for future use.
6883 if (!I
->getType()->isVoidTy()) {
6884 assert(I
->getType() == getTypeByID(ResTypeID
) &&
6885 "Incorrect result type ID");
6886 if (Error Err
= ValueList
.assignValue(NextValueNo
++, I
, ResTypeID
))
6893 if (!OperandBundles
.empty())
6894 return error("Operand bundles found with no consumer");
6896 // Check the function list for unresolved values.
6897 if (Argument
*A
= dyn_cast
<Argument
>(ValueList
.back())) {
6898 if (!A
->getParent()) {
6899 // We found at least one unresolved value. Nuke them all to avoid leaks.
6900 for (unsigned i
= ModuleValueListSize
, e
= ValueList
.size(); i
!= e
; ++i
){
6901 if ((A
= dyn_cast_or_null
<Argument
>(ValueList
[i
])) && !A
->getParent()) {
6902 A
->replaceAllUsesWith(PoisonValue::get(A
->getType()));
6906 return error("Never resolved value found in function");
6910 // Unexpected unresolved metadata about to be dropped.
6911 if (MDLoader
->hasFwdRefs())
6912 return error("Invalid function metadata: outgoing forward refs");
6915 PhiConstExprBB
->eraseFromParent();
6917 for (const auto &Pair
: ConstExprEdgeBBs
) {
6918 BasicBlock
*From
= Pair
.first
.first
;
6919 BasicBlock
*To
= Pair
.first
.second
;
6920 BasicBlock
*EdgeBB
= Pair
.second
;
6921 BranchInst::Create(To
, EdgeBB
);
6922 From
->getTerminator()->replaceSuccessorWith(To
, EdgeBB
);
6923 To
->replacePhiUsesWith(From
, EdgeBB
);
6924 EdgeBB
->moveBefore(To
);
6927 // Trim the value list down to the size it was before we parsed this function.
6928 ValueList
.shrinkTo(ModuleValueListSize
);
6929 MDLoader
->shrinkTo(ModuleMDLoaderSize
);
6930 std::vector
<BasicBlock
*>().swap(FunctionBBs
);
6931 return Error::success();
6934 /// Find the function body in the bitcode stream
6935 Error
BitcodeReader::findFunctionInStream(
6937 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
) {
6938 while (DeferredFunctionInfoIterator
->second
== 0) {
6939 // This is the fallback handling for the old format bitcode that
6940 // didn't contain the function index in the VST, or when we have
6941 // an anonymous function which would not have a VST entry.
6942 // Assert that we have one of those two cases.
6943 assert(VSTOffset
== 0 || !F
->hasName());
6944 // Parse the next body in the stream and set its position in the
6945 // DeferredFunctionInfo map.
6946 if (Error Err
= rememberAndSkipFunctionBodies())
6949 return Error::success();
6952 SyncScope::ID
BitcodeReader::getDecodedSyncScopeID(unsigned Val
) {
6953 if (Val
== SyncScope::SingleThread
|| Val
== SyncScope::System
)
6954 return SyncScope::ID(Val
);
6955 if (Val
>= SSIDs
.size())
6956 return SyncScope::System
; // Map unknown synchronization scopes to system.
6960 //===----------------------------------------------------------------------===//
6961 // GVMaterializer implementation
6962 //===----------------------------------------------------------------------===//
6964 Error
BitcodeReader::materialize(GlobalValue
*GV
) {
6965 Function
*F
= dyn_cast
<Function
>(GV
);
6966 // If it's not a function or is already material, ignore the request.
6967 if (!F
|| !F
->isMaterializable())
6968 return Error::success();
6970 DenseMap
<Function
*, uint64_t>::iterator DFII
= DeferredFunctionInfo
.find(F
);
6971 assert(DFII
!= DeferredFunctionInfo
.end() && "Deferred function not found!");
6972 // If its position is recorded as 0, its body is somewhere in the stream
6973 // but we haven't seen it yet.
6974 if (DFII
->second
== 0)
6975 if (Error Err
= findFunctionInStream(F
, DFII
))
6978 // Materialize metadata before parsing any function bodies.
6979 if (Error Err
= materializeMetadata())
6982 // Move the bit stream to the saved position of the deferred function body.
6983 if (Error JumpFailed
= Stream
.JumpToBit(DFII
->second
))
6986 // Regardless of the debug info format we want to end up in, we need
6987 // IsNewDbgInfoFormat=true to construct any debug records seen in the bitcode.
6988 F
->IsNewDbgInfoFormat
= true;
6990 if (Error Err
= parseFunctionBody(F
))
6992 F
->setIsMaterializable(false);
6994 // All parsed Functions should load into the debug info format dictated by the
6995 // Module, unless we're attempting to preserve the input debug info format.
6996 if (SeenDebugIntrinsic
&& SeenDebugRecord
)
6997 return error("Mixed debug intrinsics and debug records in bitcode module!");
6998 if (PreserveInputDbgFormat
== cl::boolOrDefault::BOU_TRUE
) {
6999 bool SeenAnyDebugInfo
= SeenDebugIntrinsic
|| SeenDebugRecord
;
7000 bool NewDbgInfoFormatDesired
=
7001 SeenAnyDebugInfo
? SeenDebugRecord
: F
->getParent()->IsNewDbgInfoFormat
;
7002 if (SeenAnyDebugInfo
) {
7003 UseNewDbgInfoFormat
= SeenDebugRecord
;
7004 WriteNewDbgInfoFormatToBitcode
= SeenDebugRecord
;
7005 WriteNewDbgInfoFormat
= SeenDebugRecord
;
7007 // If the module's debug info format doesn't match the observed input
7008 // format, then set its format now; we don't need to call the conversion
7009 // function because there must be no existing intrinsics to convert.
7010 // Otherwise, just set the format on this function now.
7011 if (NewDbgInfoFormatDesired
!= F
->getParent()->IsNewDbgInfoFormat
)
7012 F
->getParent()->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired
);
7014 F
->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired
);
7016 // If we aren't preserving formats, we use the Module flag to get our
7017 // desired format instead of reading flags, in case we are lazy-loading and
7018 // the format of the module has been changed since it was set by the flags.
7019 // We only need to convert debug info here if we have debug records but
7020 // desire the intrinsic format; everything else is a no-op or handled by the
7022 bool ModuleIsNewDbgInfoFormat
= F
->getParent()->IsNewDbgInfoFormat
;
7023 if (ModuleIsNewDbgInfoFormat
|| !SeenDebugRecord
)
7024 F
->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat
);
7026 F
->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat
);
7032 // Upgrade any old intrinsic calls in the function.
7033 for (auto &I
: UpgradedIntrinsics
) {
7034 for (User
*U
: llvm::make_early_inc_range(I
.first
->materialized_users()))
7035 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
7036 UpgradeIntrinsicCall(CI
, I
.second
);
7039 // Finish fn->subprogram upgrade for materialized functions.
7040 if (DISubprogram
*SP
= MDLoader
->lookupSubprogramForFunction(F
))
7041 F
->setSubprogram(SP
);
7043 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
7044 if (!MDLoader
->isStrippingTBAA()) {
7045 for (auto &I
: instructions(F
)) {
7046 MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
);
7047 if (!TBAA
|| TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
))
7049 MDLoader
->setStripTBAA(true);
7050 stripTBAA(F
->getParent());
7054 for (auto &I
: instructions(F
)) {
7055 // "Upgrade" older incorrect branch weights by dropping them.
7056 if (auto *MD
= I
.getMetadata(LLVMContext::MD_prof
)) {
7057 if (MD
->getOperand(0) != nullptr && isa
<MDString
>(MD
->getOperand(0))) {
7058 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
7059 StringRef ProfName
= MDS
->getString();
7060 // Check consistency of !prof branch_weights metadata.
7061 if (ProfName
!= "branch_weights")
7063 unsigned ExpectedNumOperands
= 0;
7064 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(&I
))
7065 ExpectedNumOperands
= BI
->getNumSuccessors();
7066 else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(&I
))
7067 ExpectedNumOperands
= SI
->getNumSuccessors();
7068 else if (isa
<CallInst
>(&I
))
7069 ExpectedNumOperands
= 1;
7070 else if (IndirectBrInst
*IBI
= dyn_cast
<IndirectBrInst
>(&I
))
7071 ExpectedNumOperands
= IBI
->getNumDestinations();
7072 else if (isa
<SelectInst
>(&I
))
7073 ExpectedNumOperands
= 2;
7075 continue; // ignore and continue.
7077 unsigned Offset
= getBranchWeightOffset(MD
);
7079 // If branch weight doesn't match, just strip branch weight.
7080 if (MD
->getNumOperands() != Offset
+ ExpectedNumOperands
)
7081 I
.setMetadata(LLVMContext::MD_prof
, nullptr);
7085 // Remove incompatible attributes on function calls.
7086 if (auto *CI
= dyn_cast
<CallBase
>(&I
)) {
7087 CI
->removeRetAttrs(AttributeFuncs::typeIncompatible(
7088 CI
->getFunctionType()->getReturnType(), CI
->getRetAttributes()));
7090 for (unsigned ArgNo
= 0; ArgNo
< CI
->arg_size(); ++ArgNo
)
7091 CI
->removeParamAttrs(ArgNo
, AttributeFuncs::typeIncompatible(
7092 CI
->getArgOperand(ArgNo
)->getType(),
7093 CI
->getParamAttributes(ArgNo
)));
7097 // Look for functions that rely on old function attribute behavior.
7098 UpgradeFunctionAttributes(*F
);
7100 // Bring in any functions that this function forward-referenced via
7102 return materializeForwardReferencedFunctions();
7105 Error
BitcodeReader::materializeModule() {
7106 if (Error Err
= materializeMetadata())
7109 // Promise to materialize all forward references.
7110 WillMaterializeAllForwardRefs
= true;
7112 // Iterate over the module, deserializing any functions that are still on
7114 for (Function
&F
: *TheModule
) {
7115 if (Error Err
= materialize(&F
))
7118 // At this point, if there are any function bodies, parse the rest of
7119 // the bits in the module past the last function block we have recorded
7120 // through either lazy scanning or the VST.
7121 if (LastFunctionBlockBit
|| NextUnreadBit
)
7122 if (Error Err
= parseModule(LastFunctionBlockBit
> NextUnreadBit
7123 ? LastFunctionBlockBit
7127 // Check that all block address forward references got resolved (as we
7129 if (!BasicBlockFwdRefs
.empty())
7130 return error("Never resolved function from blockaddress");
7132 // Upgrade any intrinsic calls that slipped through (should not happen!) and
7133 // delete the old functions to clean up. We can't do this unless the entire
7134 // module is materialized because there could always be another function body
7135 // with calls to the old function.
7136 for (auto &I
: UpgradedIntrinsics
) {
7137 for (auto *U
: I
.first
->users()) {
7138 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
7139 UpgradeIntrinsicCall(CI
, I
.second
);
7141 if (!I
.first
->use_empty())
7142 I
.first
->replaceAllUsesWith(I
.second
);
7143 I
.first
->eraseFromParent();
7145 UpgradedIntrinsics
.clear();
7147 UpgradeDebugInfo(*TheModule
);
7149 UpgradeModuleFlags(*TheModule
);
7151 UpgradeARCRuntime(*TheModule
);
7153 return Error::success();
7156 std::vector
<StructType
*> BitcodeReader::getIdentifiedStructTypes() const {
7157 return IdentifiedStructTypes
;
7160 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7161 BitstreamCursor Cursor
, StringRef Strtab
, ModuleSummaryIndex
&TheIndex
,
7162 StringRef ModulePath
, std::function
<bool(GlobalValue::GUID
)> IsPrevailing
)
7163 : BitcodeReaderBase(std::move(Cursor
), Strtab
), TheIndex(TheIndex
),
7164 ModulePath(ModulePath
), IsPrevailing(IsPrevailing
) {}
7166 void ModuleSummaryIndexBitcodeReader::addThisModule() {
7167 TheIndex
.addModule(ModulePath
);
7170 ModuleSummaryIndex::ModuleInfo
*
7171 ModuleSummaryIndexBitcodeReader::getThisModule() {
7172 return TheIndex
.getModule(ModulePath
);
7175 template <bool AllowNullValueInfo
>
7176 std::pair
<ValueInfo
, GlobalValue::GUID
>
7177 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId
) {
7178 auto VGI
= ValueIdToValueInfoMap
[ValueId
];
7179 // We can have a null value info for memprof callsite info records in
7180 // distributed ThinLTO index files when the callee function summary is not
7181 // included in the index. The bitcode writer records 0 in that case,
7182 // and the caller of this helper will set AllowNullValueInfo to true.
7183 assert(AllowNullValueInfo
|| std::get
<0>(VGI
));
7187 void ModuleSummaryIndexBitcodeReader::setValueGUID(
7188 uint64_t ValueID
, StringRef ValueName
, GlobalValue::LinkageTypes Linkage
,
7189 StringRef SourceFileName
) {
7190 std::string GlobalId
=
7191 GlobalValue::getGlobalIdentifier(ValueName
, Linkage
, SourceFileName
);
7192 auto ValueGUID
= GlobalValue::getGUID(GlobalId
);
7193 auto OriginalNameID
= ValueGUID
;
7194 if (GlobalValue::isLocalLinkage(Linkage
))
7195 OriginalNameID
= GlobalValue::getGUID(ValueName
);
7196 if (PrintSummaryGUIDs
)
7197 dbgs() << "GUID " << ValueGUID
<< "(" << OriginalNameID
<< ") is "
7198 << ValueName
<< "\n";
7200 // UseStrtab is false for legacy summary formats and value names are
7201 // created on stack. In that case we save the name in a string saver in
7202 // the index so that the value name can be recorded.
7203 ValueIdToValueInfoMap
[ValueID
] = std::make_pair(
7204 TheIndex
.getOrInsertValueInfo(
7205 ValueGUID
, UseStrtab
? ValueName
: TheIndex
.saveString(ValueName
)),
7209 // Specialized value symbol table parser used when reading module index
7210 // blocks where we don't actually create global values. The parsed information
7211 // is saved in the bitcode reader for use when later parsing summaries.
7212 Error
ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7214 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
) {
7215 // With a strtab the VST is not required to parse the summary.
7217 return Error::success();
7219 assert(Offset
> 0 && "Expected non-zero VST offset");
7220 Expected
<uint64_t> MaybeCurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
7221 if (!MaybeCurrentBit
)
7222 return MaybeCurrentBit
.takeError();
7223 uint64_t CurrentBit
= MaybeCurrentBit
.get();
7225 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
7228 SmallVector
<uint64_t, 64> Record
;
7230 // Read all the records for this value table.
7231 SmallString
<128> ValueName
;
7234 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
7236 return MaybeEntry
.takeError();
7237 BitstreamEntry Entry
= MaybeEntry
.get();
7239 switch (Entry
.Kind
) {
7240 case BitstreamEntry::SubBlock
: // Handled for us already.
7241 case BitstreamEntry::Error
:
7242 return error("Malformed block");
7243 case BitstreamEntry::EndBlock
:
7244 // Done parsing VST, jump back to wherever we came from.
7245 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
7247 return Error::success();
7248 case BitstreamEntry::Record
:
7249 // The interesting case.
7255 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
7257 return MaybeRecord
.takeError();
7258 switch (MaybeRecord
.get()) {
7259 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7261 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
7262 if (convertToString(Record
, 1, ValueName
))
7263 return error("Invalid record");
7264 unsigned ValueID
= Record
[0];
7265 assert(!SourceFileName
.empty());
7266 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
7267 assert(VLI
!= ValueIdToLinkageMap
.end() &&
7268 "No linkage found for VST entry?");
7269 auto Linkage
= VLI
->second
;
7270 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
7274 case bitc::VST_CODE_FNENTRY
: {
7275 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7276 if (convertToString(Record
, 2, ValueName
))
7277 return error("Invalid record");
7278 unsigned ValueID
= Record
[0];
7279 assert(!SourceFileName
.empty());
7280 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
7281 assert(VLI
!= ValueIdToLinkageMap
.end() &&
7282 "No linkage found for VST entry?");
7283 auto Linkage
= VLI
->second
;
7284 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
7288 case bitc::VST_CODE_COMBINED_ENTRY
: {
7289 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7290 unsigned ValueID
= Record
[0];
7291 GlobalValue::GUID RefGUID
= Record
[1];
7292 // The "original name", which is the second value of the pair will be
7293 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7294 ValueIdToValueInfoMap
[ValueID
] =
7295 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
7302 // Parse just the blocks needed for building the index out of the module.
7303 // At the end of this routine the module Index is populated with a map
7304 // from global value id to GlobalValueSummary objects.
7305 Error
ModuleSummaryIndexBitcodeReader::parseModule() {
7306 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
7309 SmallVector
<uint64_t, 64> Record
;
7310 DenseMap
<unsigned, GlobalValue::LinkageTypes
> ValueIdToLinkageMap
;
7311 unsigned ValueId
= 0;
7313 // Read the index for this module.
7315 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
7317 return MaybeEntry
.takeError();
7318 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
7320 switch (Entry
.Kind
) {
7321 case BitstreamEntry::Error
:
7322 return error("Malformed block");
7323 case BitstreamEntry::EndBlock
:
7324 return Error::success();
7326 case BitstreamEntry::SubBlock
:
7328 default: // Skip unknown content.
7329 if (Error Err
= Stream
.SkipBlock())
7332 case bitc::BLOCKINFO_BLOCK_ID
:
7333 // Need to parse these to get abbrev ids (e.g. for VST)
7334 if (Error Err
= readBlockInfo())
7337 case bitc::VALUE_SYMTAB_BLOCK_ID
:
7338 // Should have been parsed earlier via VSTOffset, unless there
7339 // is no summary section.
7340 assert(((SeenValueSymbolTable
&& VSTOffset
> 0) ||
7341 !SeenGlobalValSummary
) &&
7342 "Expected early VST parse via VSTOffset record");
7343 if (Error Err
= Stream
.SkipBlock())
7346 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID
:
7347 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
:
7348 // Add the module if it is a per-module index (has a source file name).
7349 if (!SourceFileName
.empty())
7351 assert(!SeenValueSymbolTable
&&
7352 "Already read VST when parsing summary block?");
7353 // We might not have a VST if there were no values in the
7354 // summary. An empty summary block generated when we are
7355 // performing ThinLTO compiles so we don't later invoke
7356 // the regular LTO process on them.
7357 if (VSTOffset
> 0) {
7358 if (Error Err
= parseValueSymbolTable(VSTOffset
, ValueIdToLinkageMap
))
7360 SeenValueSymbolTable
= true;
7362 SeenGlobalValSummary
= true;
7363 if (Error Err
= parseEntireSummary(Entry
.ID
))
7366 case bitc::MODULE_STRTAB_BLOCK_ID
:
7367 if (Error Err
= parseModuleStringTable())
7373 case BitstreamEntry::Record
: {
7375 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
7377 return MaybeBitCode
.takeError();
7378 switch (MaybeBitCode
.get()) {
7380 break; // Default behavior, ignore unknown content.
7381 case bitc::MODULE_CODE_VERSION
: {
7382 if (Error Err
= parseVersionRecord(Record
).takeError())
7386 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7387 case bitc::MODULE_CODE_SOURCE_FILENAME
: {
7388 SmallString
<128> ValueName
;
7389 if (convertToString(Record
, 0, ValueName
))
7390 return error("Invalid record");
7391 SourceFileName
= ValueName
.c_str();
7394 /// MODULE_CODE_HASH: [5*i32]
7395 case bitc::MODULE_CODE_HASH
: {
7396 if (Record
.size() != 5)
7397 return error("Invalid hash length " + Twine(Record
.size()).str());
7398 auto &Hash
= getThisModule()->second
;
7400 for (auto &Val
: Record
) {
7401 assert(!(Val
>> 32) && "Unexpected high bits set");
7406 /// MODULE_CODE_VSTOFFSET: [offset]
7407 case bitc::MODULE_CODE_VSTOFFSET
:
7409 return error("Invalid record");
7410 // Note that we subtract 1 here because the offset is relative to one
7411 // word before the start of the identification or module block, which
7412 // was historically always the start of the regular bitcode header.
7413 VSTOffset
= Record
[0] - 1;
7415 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7416 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7417 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7418 // v2: [strtab offset, strtab size, v1]
7419 case bitc::MODULE_CODE_GLOBALVAR
:
7420 case bitc::MODULE_CODE_FUNCTION
:
7421 case bitc::MODULE_CODE_ALIAS
: {
7423 ArrayRef
<uint64_t> GVRecord
;
7424 std::tie(Name
, GVRecord
) = readNameFromStrtab(Record
);
7425 if (GVRecord
.size() <= 3)
7426 return error("Invalid record");
7427 uint64_t RawLinkage
= GVRecord
[3];
7428 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
7430 ValueIdToLinkageMap
[ValueId
++] = Linkage
;
7434 setValueGUID(ValueId
++, Name
, Linkage
, SourceFileName
);
7444 SmallVector
<ValueInfo
, 0>
7445 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef
<uint64_t> Record
) {
7446 SmallVector
<ValueInfo
, 0> Ret
;
7447 Ret
.reserve(Record
.size());
7448 for (uint64_t RefValueId
: Record
)
7449 Ret
.push_back(std::get
<0>(getValueInfoFromValueId(RefValueId
)));
7453 SmallVector
<FunctionSummary::EdgeTy
, 0>
7454 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef
<uint64_t> Record
,
7455 bool IsOldProfileFormat
,
7456 bool HasProfile
, bool HasRelBF
) {
7457 SmallVector
<FunctionSummary::EdgeTy
, 0> Ret
;
7458 // In the case of new profile formats, there are two Record entries per
7459 // Edge. Otherwise, conservatively reserve up to Record.size.
7460 if (!IsOldProfileFormat
&& (HasProfile
|| HasRelBF
))
7461 Ret
.reserve(Record
.size() / 2);
7463 Ret
.reserve(Record
.size());
7465 for (unsigned I
= 0, E
= Record
.size(); I
!= E
; ++I
) {
7466 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
7467 bool HasTailCall
= false;
7469 ValueInfo Callee
= std::get
<0>(getValueInfoFromValueId(Record
[I
]));
7470 if (IsOldProfileFormat
) {
7471 I
+= 1; // Skip old callsitecount field
7473 I
+= 1; // Skip old profilecount field
7474 } else if (HasProfile
)
7475 std::tie(Hotness
, HasTailCall
) =
7476 getDecodedHotnessCallEdgeInfo(Record
[++I
]);
7478 getDecodedRelBFCallEdgeInfo(Record
[++I
], RelBF
, HasTailCall
);
7479 Ret
.push_back(FunctionSummary::EdgeTy
{
7480 Callee
, CalleeInfo(Hotness
, HasTailCall
, RelBF
)});
7486 parseWholeProgramDevirtResolutionByArg(ArrayRef
<uint64_t> Record
, size_t &Slot
,
7487 WholeProgramDevirtResolution
&Wpd
) {
7488 uint64_t ArgNum
= Record
[Slot
++];
7489 WholeProgramDevirtResolution::ByArg
&B
=
7490 Wpd
.ResByArg
[{Record
.begin() + Slot
, Record
.begin() + Slot
+ ArgNum
}];
7494 static_cast<WholeProgramDevirtResolution::ByArg::Kind
>(Record
[Slot
++]);
7495 B
.Info
= Record
[Slot
++];
7496 B
.Byte
= Record
[Slot
++];
7497 B
.Bit
= Record
[Slot
++];
7500 static void parseWholeProgramDevirtResolution(ArrayRef
<uint64_t> Record
,
7501 StringRef Strtab
, size_t &Slot
,
7502 TypeIdSummary
&TypeId
) {
7503 uint64_t Id
= Record
[Slot
++];
7504 WholeProgramDevirtResolution
&Wpd
= TypeId
.WPDRes
[Id
];
7506 Wpd
.TheKind
= static_cast<WholeProgramDevirtResolution::Kind
>(Record
[Slot
++]);
7507 Wpd
.SingleImplName
= {Strtab
.data() + Record
[Slot
],
7508 static_cast<size_t>(Record
[Slot
+ 1])};
7511 uint64_t ResByArgNum
= Record
[Slot
++];
7512 for (uint64_t I
= 0; I
!= ResByArgNum
; ++I
)
7513 parseWholeProgramDevirtResolutionByArg(Record
, Slot
, Wpd
);
7516 static void parseTypeIdSummaryRecord(ArrayRef
<uint64_t> Record
,
7518 ModuleSummaryIndex
&TheIndex
) {
7520 TypeIdSummary
&TypeId
= TheIndex
.getOrInsertTypeIdSummary(
7521 {Strtab
.data() + Record
[Slot
], static_cast<size_t>(Record
[Slot
+ 1])});
7524 TypeId
.TTRes
.TheKind
= static_cast<TypeTestResolution::Kind
>(Record
[Slot
++]);
7525 TypeId
.TTRes
.SizeM1BitWidth
= Record
[Slot
++];
7526 TypeId
.TTRes
.AlignLog2
= Record
[Slot
++];
7527 TypeId
.TTRes
.SizeM1
= Record
[Slot
++];
7528 TypeId
.TTRes
.BitMask
= Record
[Slot
++];
7529 TypeId
.TTRes
.InlineBits
= Record
[Slot
++];
7531 while (Slot
< Record
.size())
7532 parseWholeProgramDevirtResolution(Record
, Strtab
, Slot
, TypeId
);
7535 std::vector
<FunctionSummary::ParamAccess
>
7536 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef
<uint64_t> Record
) {
7537 auto ReadRange
= [&]() {
7538 APInt
Lower(FunctionSummary::ParamAccess::RangeWidth
,
7539 BitcodeReader::decodeSignRotatedValue(Record
.front()));
7540 Record
= Record
.drop_front();
7541 APInt
Upper(FunctionSummary::ParamAccess::RangeWidth
,
7542 BitcodeReader::decodeSignRotatedValue(Record
.front()));
7543 Record
= Record
.drop_front();
7544 ConstantRange Range
{Lower
, Upper
};
7545 assert(!Range
.isFullSet());
7546 assert(!Range
.isUpperSignWrapped());
7550 std::vector
<FunctionSummary::ParamAccess
> PendingParamAccesses
;
7551 while (!Record
.empty()) {
7552 PendingParamAccesses
.emplace_back();
7553 FunctionSummary::ParamAccess
&ParamAccess
= PendingParamAccesses
.back();
7554 ParamAccess
.ParamNo
= Record
.front();
7555 Record
= Record
.drop_front();
7556 ParamAccess
.Use
= ReadRange();
7557 ParamAccess
.Calls
.resize(Record
.front());
7558 Record
= Record
.drop_front();
7559 for (auto &Call
: ParamAccess
.Calls
) {
7560 Call
.ParamNo
= Record
.front();
7561 Record
= Record
.drop_front();
7562 Call
.Callee
= std::get
<0>(getValueInfoFromValueId(Record
.front()));
7563 Record
= Record
.drop_front();
7564 Call
.Offsets
= ReadRange();
7567 return PendingParamAccesses
;
7570 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7571 ArrayRef
<uint64_t> Record
, size_t &Slot
,
7572 TypeIdCompatibleVtableInfo
&TypeId
) {
7573 uint64_t Offset
= Record
[Slot
++];
7574 ValueInfo Callee
= std::get
<0>(getValueInfoFromValueId(Record
[Slot
++]));
7575 TypeId
.push_back({Offset
, Callee
});
7578 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7579 ArrayRef
<uint64_t> Record
) {
7581 TypeIdCompatibleVtableInfo
&TypeId
=
7582 TheIndex
.getOrInsertTypeIdCompatibleVtableSummary(
7583 {Strtab
.data() + Record
[Slot
],
7584 static_cast<size_t>(Record
[Slot
+ 1])});
7587 while (Slot
< Record
.size())
7588 parseTypeIdCompatibleVtableInfo(Record
, Slot
, TypeId
);
7591 SmallVector
<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7592 ArrayRef
<uint64_t> Record
, unsigned &I
) {
7593 SmallVector
<unsigned> StackIdList
;
7594 // For backwards compatibility with old format before radix tree was
7595 // used, simply see if we found a radix tree array record (and thus if
7596 // the RadixArray is non-empty).
7597 if (RadixArray
.empty()) {
7598 unsigned NumStackEntries
= Record
[I
++];
7599 assert(Record
.size() - I
>= NumStackEntries
);
7600 StackIdList
.reserve(NumStackEntries
);
7601 for (unsigned J
= 0; J
< NumStackEntries
; J
++) {
7602 assert(Record
[I
] < StackIds
.size());
7603 StackIdList
.push_back(
7604 TheIndex
.addOrGetStackIdIndex(StackIds
[Record
[I
++]]));
7607 unsigned RadixIndex
= Record
[I
++];
7608 // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7609 // for a detailed description of the radix tree array format. Briefly, the
7610 // first entry will be the number of frames, any negative values are the
7611 // negative of the offset of the next frame, and otherwise the frames are in
7612 // increasing linear order.
7613 assert(RadixIndex
< RadixArray
.size());
7614 unsigned NumStackIds
= RadixArray
[RadixIndex
++];
7615 StackIdList
.reserve(NumStackIds
);
7616 while (NumStackIds
--) {
7617 assert(RadixIndex
< RadixArray
.size());
7618 unsigned Elem
= RadixArray
[RadixIndex
];
7619 if (static_cast<std::make_signed_t
<unsigned>>(Elem
) < 0) {
7620 RadixIndex
= RadixIndex
- Elem
;
7621 assert(RadixIndex
< RadixArray
.size());
7622 Elem
= RadixArray
[RadixIndex
];
7623 // We shouldn't encounter a second offset in a row.
7624 assert(static_cast<std::make_signed_t
<unsigned>>(Elem
) >= 0);
7627 StackIdList
.push_back(TheIndex
.addOrGetStackIdIndex(StackIds
[Elem
]));
7633 static void setSpecialRefs(SmallVectorImpl
<ValueInfo
> &Refs
, unsigned ROCnt
,
7635 // Readonly and writeonly refs are in the end of the refs list.
7636 assert(ROCnt
+ WOCnt
<= Refs
.size());
7637 unsigned FirstWORef
= Refs
.size() - WOCnt
;
7638 unsigned RefNo
= FirstWORef
- ROCnt
;
7639 for (; RefNo
< FirstWORef
; ++RefNo
)
7640 Refs
[RefNo
].setReadOnly();
7641 for (; RefNo
< Refs
.size(); ++RefNo
)
7642 Refs
[RefNo
].setWriteOnly();
7645 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
7646 // objects in the index.
7647 Error
ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID
) {
7648 if (Error Err
= Stream
.EnterSubBlock(ID
))
7650 SmallVector
<uint64_t, 64> Record
;
7654 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
7656 return MaybeEntry
.takeError();
7657 BitstreamEntry Entry
= MaybeEntry
.get();
7659 if (Entry
.Kind
!= BitstreamEntry::Record
)
7660 return error("Invalid Summary Block: record for version expected");
7661 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
7663 return MaybeRecord
.takeError();
7664 if (MaybeRecord
.get() != bitc::FS_VERSION
)
7665 return error("Invalid Summary Block: version expected");
7667 const uint64_t Version
= Record
[0];
7668 const bool IsOldProfileFormat
= Version
== 1;
7669 if (Version
< 1 || Version
> ModuleSummaryIndex::BitcodeSummaryVersion
)
7670 return error("Invalid summary version " + Twine(Version
) +
7671 ". Version should be in the range [1-" +
7672 Twine(ModuleSummaryIndex::BitcodeSummaryVersion
) +
7676 // Keep around the last seen summary to be used when we see an optional
7677 // "OriginalName" attachement.
7678 GlobalValueSummary
*LastSeenSummary
= nullptr;
7679 GlobalValue::GUID LastSeenGUID
= 0;
7681 // We can expect to see any number of type ID information records before
7682 // each function summary records; these variables store the information
7683 // collected so far so that it can be used to create the summary object.
7684 std::vector
<GlobalValue::GUID
> PendingTypeTests
;
7685 std::vector
<FunctionSummary::VFuncId
> PendingTypeTestAssumeVCalls
,
7686 PendingTypeCheckedLoadVCalls
;
7687 std::vector
<FunctionSummary::ConstVCall
> PendingTypeTestAssumeConstVCalls
,
7688 PendingTypeCheckedLoadConstVCalls
;
7689 std::vector
<FunctionSummary::ParamAccess
> PendingParamAccesses
;
7691 std::vector
<CallsiteInfo
> PendingCallsites
;
7692 std::vector
<AllocInfo
> PendingAllocs
;
7693 std::vector
<uint64_t> PendingContextIds
;
7696 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
7698 return MaybeEntry
.takeError();
7699 BitstreamEntry Entry
= MaybeEntry
.get();
7701 switch (Entry
.Kind
) {
7702 case BitstreamEntry::SubBlock
: // Handled for us already.
7703 case BitstreamEntry::Error
:
7704 return error("Malformed block");
7705 case BitstreamEntry::EndBlock
:
7706 return Error::success();
7707 case BitstreamEntry::Record
:
7708 // The interesting case.
7712 // Read a record. The record format depends on whether this
7713 // is a per-module index or a combined index file. In the per-module
7714 // case the records contain the associated value's ID for correlation
7715 // with VST entries. In the combined index the correlation is done
7716 // via the bitcode offset of the summary records (which were saved
7717 // in the combined index VST entries). The records also contain
7718 // information used for ThinLTO renaming and importing.
7720 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
7722 return MaybeBitCode
.takeError();
7723 switch (unsigned BitCode
= MaybeBitCode
.get()) {
7724 default: // Default behavior: ignore.
7726 case bitc::FS_FLAGS
: { // [flags]
7727 TheIndex
.setFlags(Record
[0]);
7730 case bitc::FS_VALUE_GUID
: { // [valueid, refguid_upper32, refguid_lower32]
7731 uint64_t ValueID
= Record
[0];
7732 GlobalValue::GUID RefGUID
;
7733 if (Version
>= 11) {
7734 RefGUID
= Record
[1] << 32 | Record
[2];
7736 RefGUID
= Record
[1];
7738 ValueIdToValueInfoMap
[ValueID
] =
7739 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
7742 // FS_PERMODULE is legacy and does not have support for the tail call flag.
7743 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7744 // numrefs x valueid, n x (valueid)]
7745 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7746 // numrefs x valueid,
7747 // n x (valueid, hotness+tailcall flags)]
7748 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7749 // numrefs x valueid,
7750 // n x (valueid, relblockfreq+tailcall)]
7751 case bitc::FS_PERMODULE
:
7752 case bitc::FS_PERMODULE_RELBF
:
7753 case bitc::FS_PERMODULE_PROFILE
: {
7754 unsigned ValueID
= Record
[0];
7755 uint64_t RawFlags
= Record
[1];
7756 unsigned InstCount
= Record
[2];
7757 uint64_t RawFunFlags
= 0;
7758 unsigned NumRefs
= Record
[3];
7759 unsigned NumRORefs
= 0, NumWORefs
= 0;
7760 int RefListStartIndex
= 4;
7762 RawFunFlags
= Record
[3];
7763 NumRefs
= Record
[4];
7764 RefListStartIndex
= 5;
7766 NumRORefs
= Record
[5];
7767 RefListStartIndex
= 6;
7769 NumWORefs
= Record
[6];
7770 RefListStartIndex
= 7;
7775 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7776 // The module path string ref set in the summary must be owned by the
7777 // index's module string table. Since we don't have a module path
7778 // string table section in the per-module index, we create a single
7779 // module path string table entry with an empty (0) ID to take
7781 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
7782 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
7783 "Record size inconsistent with number of references");
7784 SmallVector
<ValueInfo
, 0> Refs
= makeRefList(
7785 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
7786 bool HasProfile
= (BitCode
== bitc::FS_PERMODULE_PROFILE
);
7787 bool HasRelBF
= (BitCode
== bitc::FS_PERMODULE_RELBF
);
7788 SmallVector
<FunctionSummary::EdgeTy
, 0> Calls
= makeCallList(
7789 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
7790 IsOldProfileFormat
, HasProfile
, HasRelBF
);
7791 setSpecialRefs(Refs
, NumRORefs
, NumWORefs
);
7792 auto VIAndOriginalGUID
= getValueInfoFromValueId(ValueID
);
7793 // In order to save memory, only record the memprof summaries if this is
7794 // the prevailing copy of a symbol. The linker doesn't resolve local
7795 // linkage values so don't check whether those are prevailing.
7796 auto LT
= (GlobalValue::LinkageTypes
)Flags
.Linkage
;
7797 if (IsPrevailing
&& !GlobalValue::isLocalLinkage(LT
) &&
7798 !IsPrevailing(VIAndOriginalGUID
.first
.getGUID())) {
7799 PendingCallsites
.clear();
7800 PendingAllocs
.clear();
7802 auto FS
= std::make_unique
<FunctionSummary
>(
7803 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), std::move(Refs
),
7804 std::move(Calls
), std::move(PendingTypeTests
),
7805 std::move(PendingTypeTestAssumeVCalls
),
7806 std::move(PendingTypeCheckedLoadVCalls
),
7807 std::move(PendingTypeTestAssumeConstVCalls
),
7808 std::move(PendingTypeCheckedLoadConstVCalls
),
7809 std::move(PendingParamAccesses
), std::move(PendingCallsites
),
7810 std::move(PendingAllocs
));
7811 FS
->setModulePath(getThisModule()->first());
7812 FS
->setOriginalName(std::get
<1>(VIAndOriginalGUID
));
7813 TheIndex
.addGlobalValueSummary(std::get
<0>(VIAndOriginalGUID
),
7817 // FS_ALIAS: [valueid, flags, valueid]
7818 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7819 // they expect all aliasee summaries to be available.
7820 case bitc::FS_ALIAS
: {
7821 unsigned ValueID
= Record
[0];
7822 uint64_t RawFlags
= Record
[1];
7823 unsigned AliaseeID
= Record
[2];
7824 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7825 auto AS
= std::make_unique
<AliasSummary
>(Flags
);
7826 // The module path string ref set in the summary must be owned by the
7827 // index's module string table. Since we don't have a module path
7828 // string table section in the per-module index, we create a single
7829 // module path string table entry with an empty (0) ID to take
7831 AS
->setModulePath(getThisModule()->first());
7833 auto AliaseeVI
= std::get
<0>(getValueInfoFromValueId(AliaseeID
));
7834 auto AliaseeInModule
= TheIndex
.findSummaryInModule(AliaseeVI
, ModulePath
);
7835 if (!AliaseeInModule
)
7836 return error("Alias expects aliasee summary to be parsed");
7837 AS
->setAliasee(AliaseeVI
, AliaseeInModule
);
7839 auto GUID
= getValueInfoFromValueId(ValueID
);
7840 AS
->setOriginalName(std::get
<1>(GUID
));
7841 TheIndex
.addGlobalValueSummary(std::get
<0>(GUID
), std::move(AS
));
7844 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7845 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
: {
7846 unsigned ValueID
= Record
[0];
7847 uint64_t RawFlags
= Record
[1];
7848 unsigned RefArrayStart
= 2;
7849 GlobalVarSummary::GVarFlags
GVF(/* ReadOnly */ false,
7850 /* WriteOnly */ false,
7851 /* Constant */ false,
7852 GlobalObject::VCallVisibilityPublic
);
7853 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7855 GVF
= getDecodedGVarFlags(Record
[2]);
7858 SmallVector
<ValueInfo
, 0> Refs
=
7859 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
7861 std::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
7862 FS
->setModulePath(getThisModule()->first());
7863 auto GUID
= getValueInfoFromValueId(ValueID
);
7864 FS
->setOriginalName(std::get
<1>(GUID
));
7865 TheIndex
.addGlobalValueSummary(std::get
<0>(GUID
), std::move(FS
));
7868 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7869 // numrefs, numrefs x valueid,
7870 // n x (valueid, offset)]
7871 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
: {
7872 unsigned ValueID
= Record
[0];
7873 uint64_t RawFlags
= Record
[1];
7874 GlobalVarSummary::GVarFlags GVF
= getDecodedGVarFlags(Record
[2]);
7875 unsigned NumRefs
= Record
[3];
7876 unsigned RefListStartIndex
= 4;
7877 unsigned VTableListStartIndex
= RefListStartIndex
+ NumRefs
;
7878 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7879 SmallVector
<ValueInfo
, 0> Refs
= makeRefList(
7880 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
7881 VTableFuncList VTableFuncs
;
7882 for (unsigned I
= VTableListStartIndex
, E
= Record
.size(); I
!= E
; ++I
) {
7883 ValueInfo Callee
= std::get
<0>(getValueInfoFromValueId(Record
[I
]));
7884 uint64_t Offset
= Record
[++I
];
7885 VTableFuncs
.push_back({Callee
, Offset
});
7888 std::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
7889 VS
->setModulePath(getThisModule()->first());
7890 VS
->setVTableFuncs(VTableFuncs
);
7891 auto GUID
= getValueInfoFromValueId(ValueID
);
7892 VS
->setOriginalName(std::get
<1>(GUID
));
7893 TheIndex
.addGlobalValueSummary(std::get
<0>(GUID
), std::move(VS
));
7896 // FS_COMBINED is legacy and does not have support for the tail call flag.
7897 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7898 // numrefs x valueid, n x (valueid)]
7899 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7900 // numrefs x valueid,
7901 // n x (valueid, hotness+tailcall flags)]
7902 case bitc::FS_COMBINED
:
7903 case bitc::FS_COMBINED_PROFILE
: {
7904 unsigned ValueID
= Record
[0];
7905 uint64_t ModuleId
= Record
[1];
7906 uint64_t RawFlags
= Record
[2];
7907 unsigned InstCount
= Record
[3];
7908 uint64_t RawFunFlags
= 0;
7909 unsigned NumRefs
= Record
[4];
7910 unsigned NumRORefs
= 0, NumWORefs
= 0;
7911 int RefListStartIndex
= 5;
7914 RawFunFlags
= Record
[4];
7915 RefListStartIndex
= 6;
7916 size_t NumRefsIndex
= 5;
7918 unsigned NumRORefsOffset
= 1;
7919 RefListStartIndex
= 7;
7922 RefListStartIndex
= 8;
7924 RefListStartIndex
= 9;
7925 NumWORefs
= Record
[8];
7926 NumRORefsOffset
= 2;
7929 NumRORefs
= Record
[RefListStartIndex
- NumRORefsOffset
];
7931 NumRefs
= Record
[NumRefsIndex
];
7934 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7935 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
7936 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
7937 "Record size inconsistent with number of references");
7938 SmallVector
<ValueInfo
, 0> Refs
= makeRefList(
7939 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
7940 bool HasProfile
= (BitCode
== bitc::FS_COMBINED_PROFILE
);
7941 SmallVector
<FunctionSummary::EdgeTy
, 0> Edges
= makeCallList(
7942 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
7943 IsOldProfileFormat
, HasProfile
, false);
7944 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
7945 setSpecialRefs(Refs
, NumRORefs
, NumWORefs
);
7946 auto FS
= std::make_unique
<FunctionSummary
>(
7947 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), std::move(Refs
),
7948 std::move(Edges
), std::move(PendingTypeTests
),
7949 std::move(PendingTypeTestAssumeVCalls
),
7950 std::move(PendingTypeCheckedLoadVCalls
),
7951 std::move(PendingTypeTestAssumeConstVCalls
),
7952 std::move(PendingTypeCheckedLoadConstVCalls
),
7953 std::move(PendingParamAccesses
), std::move(PendingCallsites
),
7954 std::move(PendingAllocs
));
7955 LastSeenSummary
= FS
.get();
7956 LastSeenGUID
= VI
.getGUID();
7957 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
7958 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
7961 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7962 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7963 // they expect all aliasee summaries to be available.
7964 case bitc::FS_COMBINED_ALIAS
: {
7965 unsigned ValueID
= Record
[0];
7966 uint64_t ModuleId
= Record
[1];
7967 uint64_t RawFlags
= Record
[2];
7968 unsigned AliaseeValueId
= Record
[3];
7969 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7970 auto AS
= std::make_unique
<AliasSummary
>(Flags
);
7971 LastSeenSummary
= AS
.get();
7972 AS
->setModulePath(ModuleIdMap
[ModuleId
]);
7974 auto AliaseeVI
= std::get
<0>(getValueInfoFromValueId(AliaseeValueId
));
7975 auto AliaseeInModule
= TheIndex
.findSummaryInModule(AliaseeVI
, AS
->modulePath());
7976 AS
->setAliasee(AliaseeVI
, AliaseeInModule
);
7978 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
7979 LastSeenGUID
= VI
.getGUID();
7980 TheIndex
.addGlobalValueSummary(VI
, std::move(AS
));
7983 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7984 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
: {
7985 unsigned ValueID
= Record
[0];
7986 uint64_t ModuleId
= Record
[1];
7987 uint64_t RawFlags
= Record
[2];
7988 unsigned RefArrayStart
= 3;
7989 GlobalVarSummary::GVarFlags
GVF(/* ReadOnly */ false,
7990 /* WriteOnly */ false,
7991 /* Constant */ false,
7992 GlobalObject::VCallVisibilityPublic
);
7993 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7995 GVF
= getDecodedGVarFlags(Record
[3]);
7998 SmallVector
<ValueInfo
, 0> Refs
=
7999 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
8001 std::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
8002 LastSeenSummary
= FS
.get();
8003 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
8004 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
8005 LastSeenGUID
= VI
.getGUID();
8006 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
8009 // FS_COMBINED_ORIGINAL_NAME: [original_name]
8010 case bitc::FS_COMBINED_ORIGINAL_NAME
: {
8011 uint64_t OriginalName
= Record
[0];
8012 if (!LastSeenSummary
)
8013 return error("Name attachment that does not follow a combined record");
8014 LastSeenSummary
->setOriginalName(OriginalName
);
8015 TheIndex
.addOriginalName(LastSeenGUID
, OriginalName
);
8016 // Reset the LastSeenSummary
8017 LastSeenSummary
= nullptr;
8021 case bitc::FS_TYPE_TESTS
:
8022 assert(PendingTypeTests
.empty());
8023 llvm::append_range(PendingTypeTests
, Record
);
8026 case bitc::FS_TYPE_TEST_ASSUME_VCALLS
:
8027 assert(PendingTypeTestAssumeVCalls
.empty());
8028 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8029 PendingTypeTestAssumeVCalls
.push_back({Record
[I
], Record
[I
+1]});
8032 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS
:
8033 assert(PendingTypeCheckedLoadVCalls
.empty());
8034 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8035 PendingTypeCheckedLoadVCalls
.push_back({Record
[I
], Record
[I
+1]});
8038 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL
:
8039 PendingTypeTestAssumeConstVCalls
.push_back(
8040 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
8043 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL
:
8044 PendingTypeCheckedLoadConstVCalls
.push_back(
8045 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
8048 case bitc::FS_CFI_FUNCTION_DEFS
: {
8049 std::set
<std::string
, std::less
<>> &CfiFunctionDefs
=
8050 TheIndex
.cfiFunctionDefs();
8051 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8052 CfiFunctionDefs
.insert(
8053 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
8057 case bitc::FS_CFI_FUNCTION_DECLS
: {
8058 std::set
<std::string
, std::less
<>> &CfiFunctionDecls
=
8059 TheIndex
.cfiFunctionDecls();
8060 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8061 CfiFunctionDecls
.insert(
8062 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
8066 case bitc::FS_TYPE_ID
:
8067 parseTypeIdSummaryRecord(Record
, Strtab
, TheIndex
);
8070 case bitc::FS_TYPE_ID_METADATA
:
8071 parseTypeIdCompatibleVtableSummaryRecord(Record
);
8074 case bitc::FS_BLOCK_COUNT
:
8075 TheIndex
.addBlockCount(Record
[0]);
8078 case bitc::FS_PARAM_ACCESS
: {
8079 PendingParamAccesses
= parseParamAccesses(Record
);
8083 case bitc::FS_STACK_IDS
: { // [n x stackid]
8084 // Save stack ids in the reader to consult when adding stack ids from the
8085 // lists in the stack node and alloc node entries.
8086 if (Version
<= 11) {
8087 StackIds
= ArrayRef
<uint64_t>(Record
);
8090 // This is an array of 32-bit fixed-width values, holding each 64-bit
8091 // context id as a pair of adjacent (most significant first) 32-bit words.
8092 assert(Record
.size() % 2 == 0);
8093 StackIds
.reserve(Record
.size() / 2);
8094 for (auto R
= Record
.begin(); R
!= Record
.end(); R
+= 2)
8095 StackIds
.push_back(*R
<< 32 | *(R
+ 1));
8099 case bitc::FS_CONTEXT_RADIX_TREE_ARRAY
: { // [n x entry]
8100 RadixArray
= ArrayRef
<uint64_t>(Record
);
8104 case bitc::FS_PERMODULE_CALLSITE_INFO
: {
8105 unsigned ValueID
= Record
[0];
8106 SmallVector
<unsigned> StackIdList
;
8107 for (auto R
= Record
.begin() + 1; R
!= Record
.end(); R
++) {
8108 assert(*R
< StackIds
.size());
8109 StackIdList
.push_back(TheIndex
.addOrGetStackIdIndex(StackIds
[*R
]));
8111 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
8112 PendingCallsites
.push_back(CallsiteInfo({VI
, std::move(StackIdList
)}));
8116 case bitc::FS_COMBINED_CALLSITE_INFO
: {
8117 auto RecordIter
= Record
.begin();
8118 unsigned ValueID
= *RecordIter
++;
8119 unsigned NumStackIds
= *RecordIter
++;
8120 unsigned NumVersions
= *RecordIter
++;
8121 assert(Record
.size() == 3 + NumStackIds
+ NumVersions
);
8122 SmallVector
<unsigned> StackIdList
;
8123 for (unsigned J
= 0; J
< NumStackIds
; J
++) {
8124 assert(*RecordIter
< StackIds
.size());
8125 StackIdList
.push_back(
8126 TheIndex
.addOrGetStackIdIndex(StackIds
[*RecordIter
++]));
8128 SmallVector
<unsigned> Versions
;
8129 for (unsigned J
= 0; J
< NumVersions
; J
++)
8130 Versions
.push_back(*RecordIter
++);
8131 ValueInfo VI
= std::get
<0>(
8132 getValueInfoFromValueId
</*AllowNullValueInfo*/ true>(ValueID
));
8133 PendingCallsites
.push_back(
8134 CallsiteInfo({VI
, std::move(Versions
), std::move(StackIdList
)}));
8138 case bitc::FS_ALLOC_CONTEXT_IDS
: {
8139 // This is an array of 32-bit fixed-width values, holding each 64-bit
8140 // context id as a pair of adjacent (most significant first) 32-bit words.
8141 assert(Record
.size() % 2 == 0);
8142 PendingContextIds
.reserve(Record
.size() / 2);
8143 for (auto R
= Record
.begin(); R
!= Record
.end(); R
+= 2)
8144 PendingContextIds
.push_back(*R
<< 32 | *(R
+ 1));
8148 case bitc::FS_PERMODULE_ALLOC_INFO
: {
8150 std::vector
<MIBInfo
> MIBs
;
8151 unsigned NumMIBs
= 0;
8153 NumMIBs
= Record
[I
++];
8154 unsigned MIBsRead
= 0;
8155 while ((Version
>= 10 && MIBsRead
++ < NumMIBs
) ||
8156 (Version
< 10 && I
< Record
.size())) {
8157 assert(Record
.size() - I
>= 2);
8158 AllocationType AllocType
= (AllocationType
)Record
[I
++];
8159 auto StackIdList
= parseAllocInfoContext(Record
, I
);
8160 MIBs
.push_back(MIBInfo(AllocType
, std::move(StackIdList
)));
8162 // We either have nothing left or at least NumMIBs context size info
8163 // indices left (for the total sizes included when reporting of hinted
8164 // bytes is enabled).
8165 assert(I
== Record
.size() || Record
.size() - I
>= NumMIBs
);
8166 std::vector
<std::vector
<ContextTotalSize
>> AllContextSizes
;
8167 if (I
< Record
.size()) {
8168 assert(!PendingContextIds
.empty() &&
8169 "Missing context ids for alloc sizes");
8170 unsigned ContextIdIndex
= 0;
8172 // The sizes are a linearized array of sizes, where for each MIB there
8173 // is 1 or more sizes (due to context trimming, each MIB in the metadata
8174 // and summarized here can correspond to more than one original context
8175 // from the profile).
8176 while (MIBsRead
++ < NumMIBs
) {
8177 // First read the number of contexts recorded for this MIB.
8178 unsigned NumContextSizeInfoEntries
= Record
[I
++];
8179 assert(Record
.size() - I
>= NumContextSizeInfoEntries
);
8180 std::vector
<ContextTotalSize
> ContextSizes
;
8181 ContextSizes
.reserve(NumContextSizeInfoEntries
);
8182 for (unsigned J
= 0; J
< NumContextSizeInfoEntries
; J
++) {
8183 assert(ContextIdIndex
< PendingContextIds
.size());
8184 // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8185 // should be in the same order as the total sizes.
8186 ContextSizes
.push_back(
8187 {PendingContextIds
[ContextIdIndex
++], Record
[I
++]});
8189 AllContextSizes
.push_back(std::move(ContextSizes
));
8191 PendingContextIds
.clear();
8193 PendingAllocs
.push_back(AllocInfo(std::move(MIBs
)));
8194 if (!AllContextSizes
.empty()) {
8195 assert(PendingAllocs
.back().MIBs
.size() == AllContextSizes
.size());
8196 PendingAllocs
.back().ContextSizeInfos
= std::move(AllContextSizes
);
8201 case bitc::FS_COMBINED_ALLOC_INFO
: {
8203 std::vector
<MIBInfo
> MIBs
;
8204 unsigned NumMIBs
= Record
[I
++];
8205 unsigned NumVersions
= Record
[I
++];
8206 unsigned MIBsRead
= 0;
8207 while (MIBsRead
++ < NumMIBs
) {
8208 assert(Record
.size() - I
>= 2);
8209 AllocationType AllocType
= (AllocationType
)Record
[I
++];
8210 auto StackIdList
= parseAllocInfoContext(Record
, I
);
8211 MIBs
.push_back(MIBInfo(AllocType
, std::move(StackIdList
)));
8213 assert(Record
.size() - I
>= NumVersions
);
8214 SmallVector
<uint8_t> Versions
;
8215 for (unsigned J
= 0; J
< NumVersions
; J
++)
8216 Versions
.push_back(Record
[I
++]);
8217 assert(I
== Record
.size());
8218 PendingAllocs
.push_back(AllocInfo(std::move(Versions
), std::move(MIBs
)));
8223 llvm_unreachable("Exit infinite loop");
8226 // Parse the module string table block into the Index.
8227 // This populates the ModulePathStringTable map in the index.
8228 Error
ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8229 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID
))
8232 SmallVector
<uint64_t, 64> Record
;
8234 SmallString
<128> ModulePath
;
8235 ModuleSummaryIndex::ModuleInfo
*LastSeenModule
= nullptr;
8238 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
8240 return MaybeEntry
.takeError();
8241 BitstreamEntry Entry
= MaybeEntry
.get();
8243 switch (Entry
.Kind
) {
8244 case BitstreamEntry::SubBlock
: // Handled for us already.
8245 case BitstreamEntry::Error
:
8246 return error("Malformed block");
8247 case BitstreamEntry::EndBlock
:
8248 return Error::success();
8249 case BitstreamEntry::Record
:
8250 // The interesting case.
8255 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
8257 return MaybeRecord
.takeError();
8258 switch (MaybeRecord
.get()) {
8259 default: // Default behavior: ignore.
8261 case bitc::MST_CODE_ENTRY
: {
8262 // MST_ENTRY: [modid, namechar x N]
8263 uint64_t ModuleId
= Record
[0];
8265 if (convertToString(Record
, 1, ModulePath
))
8266 return error("Invalid record");
8268 LastSeenModule
= TheIndex
.addModule(ModulePath
);
8269 ModuleIdMap
[ModuleId
] = LastSeenModule
->first();
8274 /// MST_CODE_HASH: [5*i32]
8275 case bitc::MST_CODE_HASH
: {
8276 if (Record
.size() != 5)
8277 return error("Invalid hash length " + Twine(Record
.size()).str());
8278 if (!LastSeenModule
)
8279 return error("Invalid hash that does not follow a module path");
8281 for (auto &Val
: Record
) {
8282 assert(!(Val
>> 32) && "Unexpected high bits set");
8283 LastSeenModule
->second
[Pos
++] = Val
;
8285 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8286 LastSeenModule
= nullptr;
8291 llvm_unreachable("Exit infinite loop");
8296 // FIXME: This class is only here to support the transition to llvm::Error. It
8297 // will be removed once this transition is complete. Clients should prefer to
8298 // deal with the Error value directly, rather than converting to error_code.
8299 class BitcodeErrorCategoryType
: public std::error_category
{
8300 const char *name() const noexcept override
{
8301 return "llvm.bitcode";
8304 std::string
message(int IE
) const override
{
8305 BitcodeError E
= static_cast<BitcodeError
>(IE
);
8307 case BitcodeError::CorruptedBitcode
:
8308 return "Corrupted bitcode";
8310 llvm_unreachable("Unknown error type!");
8314 } // end anonymous namespace
8316 const std::error_category
&llvm::BitcodeErrorCategory() {
8317 static BitcodeErrorCategoryType ErrorCategory
;
8318 return ErrorCategory
;
8321 static Expected
<StringRef
> readBlobInRecord(BitstreamCursor
&Stream
,
8322 unsigned Block
, unsigned RecordID
) {
8323 if (Error Err
= Stream
.EnterSubBlock(Block
))
8324 return std::move(Err
);
8328 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
8330 return MaybeEntry
.takeError();
8331 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
8333 switch (Entry
.Kind
) {
8334 case BitstreamEntry::EndBlock
:
8337 case BitstreamEntry::Error
:
8338 return error("Malformed block");
8340 case BitstreamEntry::SubBlock
:
8341 if (Error Err
= Stream
.SkipBlock())
8342 return std::move(Err
);
8345 case BitstreamEntry::Record
:
8347 SmallVector
<uint64_t, 1> Record
;
8348 Expected
<unsigned> MaybeRecord
=
8349 Stream
.readRecord(Entry
.ID
, Record
, &Blob
);
8351 return MaybeRecord
.takeError();
8352 if (MaybeRecord
.get() == RecordID
)
8359 //===----------------------------------------------------------------------===//
8360 // External interface
8361 //===----------------------------------------------------------------------===//
8363 Expected
<std::vector
<BitcodeModule
>>
8364 llvm::getBitcodeModuleList(MemoryBufferRef Buffer
) {
8365 auto FOrErr
= getBitcodeFileContents(Buffer
);
8367 return FOrErr
.takeError();
8368 return std::move(FOrErr
->Mods
);
8371 Expected
<BitcodeFileContents
>
8372 llvm::getBitcodeFileContents(MemoryBufferRef Buffer
) {
8373 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8375 return StreamOrErr
.takeError();
8376 BitstreamCursor
&Stream
= *StreamOrErr
;
8378 BitcodeFileContents F
;
8380 uint64_t BCBegin
= Stream
.getCurrentByteNo();
8382 // We may be consuming bitcode from a client that leaves garbage at the end
8383 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8384 // the end that there cannot possibly be another module, stop looking.
8385 if (BCBegin
+ 8 >= Stream
.getBitcodeBytes().size())
8388 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
8390 return MaybeEntry
.takeError();
8391 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
8393 switch (Entry
.Kind
) {
8394 case BitstreamEntry::EndBlock
:
8395 case BitstreamEntry::Error
:
8396 return error("Malformed block");
8398 case BitstreamEntry::SubBlock
: {
8399 uint64_t IdentificationBit
= -1ull;
8400 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
) {
8401 IdentificationBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
8402 if (Error Err
= Stream
.SkipBlock())
8403 return std::move(Err
);
8406 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
8408 return MaybeEntry
.takeError();
8409 Entry
= MaybeEntry
.get();
8412 if (Entry
.Kind
!= BitstreamEntry::SubBlock
||
8413 Entry
.ID
!= bitc::MODULE_BLOCK_ID
)
8414 return error("Malformed block");
8417 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
) {
8418 uint64_t ModuleBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
8419 if (Error Err
= Stream
.SkipBlock())
8420 return std::move(Err
);
8422 F
.Mods
.push_back({Stream
.getBitcodeBytes().slice(
8423 BCBegin
, Stream
.getCurrentByteNo() - BCBegin
),
8424 Buffer
.getBufferIdentifier(), IdentificationBit
,
8429 if (Entry
.ID
== bitc::STRTAB_BLOCK_ID
) {
8430 Expected
<StringRef
> Strtab
=
8431 readBlobInRecord(Stream
, bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
);
8433 return Strtab
.takeError();
8434 // This string table is used by every preceding bitcode module that does
8435 // not have its own string table. A bitcode file may have multiple
8436 // string tables if it was created by binary concatenation, for example
8437 // with "llvm-cat -b".
8438 for (BitcodeModule
&I
: llvm::reverse(F
.Mods
)) {
8439 if (!I
.Strtab
.empty())
8443 // Similarly, the string table is used by every preceding symbol table;
8444 // normally there will be just one unless the bitcode file was created
8445 // by binary concatenation.
8446 if (!F
.Symtab
.empty() && F
.StrtabForSymtab
.empty())
8447 F
.StrtabForSymtab
= *Strtab
;
8451 if (Entry
.ID
== bitc::SYMTAB_BLOCK_ID
) {
8452 Expected
<StringRef
> SymtabOrErr
=
8453 readBlobInRecord(Stream
, bitc::SYMTAB_BLOCK_ID
, bitc::SYMTAB_BLOB
);
8455 return SymtabOrErr
.takeError();
8457 // We can expect the bitcode file to have multiple symbol tables if it
8458 // was created by binary concatenation. In that case we silently
8459 // ignore any subsequent symbol tables, which is fine because this is a
8460 // low level function. The client is expected to notice that the number
8461 // of modules in the symbol table does not match the number of modules
8462 // in the input file and regenerate the symbol table.
8463 if (F
.Symtab
.empty())
8464 F
.Symtab
= *SymtabOrErr
;
8468 if (Error Err
= Stream
.SkipBlock())
8469 return std::move(Err
);
8472 case BitstreamEntry::Record
:
8473 if (Error E
= Stream
.skipRecord(Entry
.ID
).takeError())
8474 return std::move(E
);
8480 /// Get a lazy one-at-time loading module from bitcode.
8482 /// This isn't always used in a lazy context. In particular, it's also used by
8483 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
8484 /// in forward-referenced functions from block address references.
8486 /// \param[in] MaterializeAll Set to \c true if we should materialize
8488 Expected
<std::unique_ptr
<Module
>>
8489 BitcodeModule::getModuleImpl(LLVMContext
&Context
, bool MaterializeAll
,
8490 bool ShouldLazyLoadMetadata
, bool IsImporting
,
8491 ParserCallbacks Callbacks
) {
8492 BitstreamCursor
Stream(Buffer
);
8494 std::string ProducerIdentification
;
8495 if (IdentificationBit
!= -1ull) {
8496 if (Error JumpFailed
= Stream
.JumpToBit(IdentificationBit
))
8497 return std::move(JumpFailed
);
8499 readIdentificationBlock(Stream
).moveInto(ProducerIdentification
))
8500 return std::move(E
);
8503 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8504 return std::move(JumpFailed
);
8505 auto *R
= new BitcodeReader(std::move(Stream
), Strtab
, ProducerIdentification
,
8508 std::unique_ptr
<Module
> M
=
8509 std::make_unique
<Module
>(ModuleIdentifier
, Context
);
8510 M
->setMaterializer(R
);
8512 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8513 if (Error Err
= R
->parseBitcodeInto(M
.get(), ShouldLazyLoadMetadata
,
8514 IsImporting
, Callbacks
))
8515 return std::move(Err
);
8517 if (MaterializeAll
) {
8518 // Read in the entire module, and destroy the BitcodeReader.
8519 if (Error Err
= M
->materializeAll())
8520 return std::move(Err
);
8522 // Resolve forward references from blockaddresses.
8523 if (Error Err
= R
->materializeForwardReferencedFunctions())
8524 return std::move(Err
);
8527 return std::move(M
);
8530 Expected
<std::unique_ptr
<Module
>>
8531 BitcodeModule::getLazyModule(LLVMContext
&Context
, bool ShouldLazyLoadMetadata
,
8532 bool IsImporting
, ParserCallbacks Callbacks
) {
8533 return getModuleImpl(Context
, false, ShouldLazyLoadMetadata
, IsImporting
,
8537 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
8538 // We don't use ModuleIdentifier here because the client may need to control the
8539 // module path used in the combined summary (e.g. when reading summaries for
8540 // regular LTO modules).
8541 Error
BitcodeModule::readSummary(
8542 ModuleSummaryIndex
&CombinedIndex
, StringRef ModulePath
,
8543 std::function
<bool(GlobalValue::GUID
)> IsPrevailing
) {
8544 BitstreamCursor
Stream(Buffer
);
8545 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8548 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, CombinedIndex
,
8549 ModulePath
, IsPrevailing
);
8550 return R
.parseModule();
8553 // Parse the specified bitcode buffer, returning the function info index.
8554 Expected
<std::unique_ptr
<ModuleSummaryIndex
>> BitcodeModule::getSummary() {
8555 BitstreamCursor
Stream(Buffer
);
8556 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8557 return std::move(JumpFailed
);
8559 auto Index
= std::make_unique
<ModuleSummaryIndex
>(/*HaveGVs=*/false);
8560 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, *Index
,
8561 ModuleIdentifier
, 0);
8563 if (Error Err
= R
.parseModule())
8564 return std::move(Err
);
8566 return std::move(Index
);
8569 static Expected
<std::pair
<bool, bool>>
8570 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor
&Stream
,
8572 BitcodeLTOInfo
<OInfo
) {
8573 if (Error Err
= Stream
.EnterSubBlock(ID
))
8574 return std::move(Err
);
8575 SmallVector
<uint64_t, 64> Record
;
8578 BitstreamEntry Entry
;
8579 std::pair
<bool, bool> Result
= {false,false};
8580 if (Error E
= Stream
.advanceSkippingSubblocks().moveInto(Entry
))
8581 return std::move(E
);
8583 switch (Entry
.Kind
) {
8584 case BitstreamEntry::SubBlock
: // Handled for us already.
8585 case BitstreamEntry::Error
:
8586 return error("Malformed block");
8587 case BitstreamEntry::EndBlock
: {
8588 // If no flags record found, set both flags to false.
8591 case BitstreamEntry::Record
:
8592 // The interesting case.
8596 // Look for the FS_FLAGS record.
8598 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
8600 return MaybeBitCode
.takeError();
8601 switch (MaybeBitCode
.get()) {
8602 default: // Default behavior: ignore.
8604 case bitc::FS_FLAGS
: { // [flags]
8605 uint64_t Flags
= Record
[0];
8607 assert(Flags
<= 0x2ff && "Unexpected bits in flag");
8609 bool EnableSplitLTOUnit
= Flags
& 0x8;
8610 bool UnifiedLTO
= Flags
& 0x200;
8611 Result
= {EnableSplitLTOUnit
, UnifiedLTO
};
8617 llvm_unreachable("Exit infinite loop");
8620 // Check if the given bitcode buffer contains a global value summary block.
8621 Expected
<BitcodeLTOInfo
> BitcodeModule::getLTOInfo() {
8622 BitstreamCursor
Stream(Buffer
);
8623 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8624 return std::move(JumpFailed
);
8626 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
8627 return std::move(Err
);
8630 llvm::BitstreamEntry Entry
;
8631 if (Error E
= Stream
.advance().moveInto(Entry
))
8632 return std::move(E
);
8634 switch (Entry
.Kind
) {
8635 case BitstreamEntry::Error
:
8636 return error("Malformed block");
8637 case BitstreamEntry::EndBlock
:
8638 return BitcodeLTOInfo
{/*IsThinLTO=*/false, /*HasSummary=*/false,
8639 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8641 case BitstreamEntry::SubBlock
:
8642 if (Entry
.ID
== bitc::GLOBALVAL_SUMMARY_BLOCK_ID
) {
8643 BitcodeLTOInfo LTOInfo
;
8644 Expected
<std::pair
<bool, bool>> Flags
=
8645 getEnableSplitLTOUnitAndUnifiedFlag(Stream
, Entry
.ID
, LTOInfo
);
8647 return Flags
.takeError();
8648 std::tie(LTOInfo
.EnableSplitLTOUnit
, LTOInfo
.UnifiedLTO
) = Flags
.get();
8649 LTOInfo
.IsThinLTO
= true;
8650 LTOInfo
.HasSummary
= true;
8654 if (Entry
.ID
== bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
) {
8655 BitcodeLTOInfo LTOInfo
;
8656 Expected
<std::pair
<bool, bool>> Flags
=
8657 getEnableSplitLTOUnitAndUnifiedFlag(Stream
, Entry
.ID
, LTOInfo
);
8659 return Flags
.takeError();
8660 std::tie(LTOInfo
.EnableSplitLTOUnit
, LTOInfo
.UnifiedLTO
) = Flags
.get();
8661 LTOInfo
.IsThinLTO
= false;
8662 LTOInfo
.HasSummary
= true;
8666 // Ignore other sub-blocks.
8667 if (Error Err
= Stream
.SkipBlock())
8668 return std::move(Err
);
8671 case BitstreamEntry::Record
:
8672 if (Expected
<unsigned> StreamFailed
= Stream
.skipRecord(Entry
.ID
))
8675 return StreamFailed
.takeError();
8680 static Expected
<BitcodeModule
> getSingleModule(MemoryBufferRef Buffer
) {
8681 Expected
<std::vector
<BitcodeModule
>> MsOrErr
= getBitcodeModuleList(Buffer
);
8683 return MsOrErr
.takeError();
8685 if (MsOrErr
->size() != 1)
8686 return error("Expected a single module");
8688 return (*MsOrErr
)[0];
8691 Expected
<std::unique_ptr
<Module
>>
8692 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer
, LLVMContext
&Context
,
8693 bool ShouldLazyLoadMetadata
, bool IsImporting
,
8694 ParserCallbacks Callbacks
) {
8695 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8697 return BM
.takeError();
8699 return BM
->getLazyModule(Context
, ShouldLazyLoadMetadata
, IsImporting
,
8703 Expected
<std::unique_ptr
<Module
>> llvm::getOwningLazyBitcodeModule(
8704 std::unique_ptr
<MemoryBuffer
> &&Buffer
, LLVMContext
&Context
,
8705 bool ShouldLazyLoadMetadata
, bool IsImporting
, ParserCallbacks Callbacks
) {
8706 auto MOrErr
= getLazyBitcodeModule(*Buffer
, Context
, ShouldLazyLoadMetadata
,
8707 IsImporting
, Callbacks
);
8709 (*MOrErr
)->setOwnedMemoryBuffer(std::move(Buffer
));
8713 Expected
<std::unique_ptr
<Module
>>
8714 BitcodeModule::parseModule(LLVMContext
&Context
, ParserCallbacks Callbacks
) {
8715 return getModuleImpl(Context
, true, false, false, Callbacks
);
8716 // TODO: Restore the use-lists to the in-memory state when the bitcode was
8717 // written. We must defer until the Module has been fully materialized.
8720 Expected
<std::unique_ptr
<Module
>>
8721 llvm::parseBitcodeFile(MemoryBufferRef Buffer
, LLVMContext
&Context
,
8722 ParserCallbacks Callbacks
) {
8723 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8725 return BM
.takeError();
8727 return BM
->parseModule(Context
, Callbacks
);
8730 Expected
<std::string
> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer
) {
8731 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8733 return StreamOrErr
.takeError();
8735 return readTriple(*StreamOrErr
);
8738 Expected
<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer
) {
8739 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8741 return StreamOrErr
.takeError();
8743 return hasObjCCategory(*StreamOrErr
);
8746 Expected
<std::string
> llvm::getBitcodeProducerString(MemoryBufferRef Buffer
) {
8747 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8749 return StreamOrErr
.takeError();
8751 return readIdentificationCode(*StreamOrErr
);
8754 Error
llvm::readModuleSummaryIndex(MemoryBufferRef Buffer
,
8755 ModuleSummaryIndex
&CombinedIndex
) {
8756 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8758 return BM
.takeError();
8760 return BM
->readSummary(CombinedIndex
, BM
->getModuleIdentifier());
8763 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
8764 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer
) {
8765 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8767 return BM
.takeError();
8769 return BM
->getSummary();
8772 Expected
<BitcodeLTOInfo
> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer
) {
8773 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8775 return BM
.takeError();
8777 return BM
->getLTOInfo();
8780 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
8781 llvm::getModuleSummaryIndexForFile(StringRef Path
,
8782 bool IgnoreEmptyThinLTOIndexFile
) {
8783 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> FileOrErr
=
8784 MemoryBuffer::getFileOrSTDIN(Path
);
8786 return errorCodeToError(FileOrErr
.getError());
8787 if (IgnoreEmptyThinLTOIndexFile
&& !(*FileOrErr
)->getBufferSize())
8789 return getModuleSummaryIndex(**FileOrErr
);