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