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