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