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