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) {
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>
160static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
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
469Expected<unsigned>
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;
524 uint8_t Flags;
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;
539 uint8_t Flags;
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) {
550 llvm::uninitialized_copy(OpIDs, getTrailingObjects());
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 {
581 LLVMContext &Context;
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.
597 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
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.
664 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
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
714 static uint64_t decodeSignRotatedValue(uint64_t V);
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
852 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
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
877 Expected<ConstantRange>
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,
902 ArrayRef<uint64_t> Record);
903
904 Error parseAttributeBlock();
905 Error parseAttributeGroupBlock();
906 Error parseTypeTable();
907 Error parseTypeTableBody();
908 Error parseOperandBundleTags();
909 Error parseSyncScopeNames();
910
911 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
912 unsigned NameIndex, Triple &TT);
913 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
914 ArrayRef<uint64_t> Record);
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.
959 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::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.
966 DenseMap<uint64_t, StringRef> ModuleIdMap;
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(
1000 uint64_t Offset,
1001 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1002 SmallVector<ValueInfo, 0> makeRefList(ArrayRef<uint64_t> Record);
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.
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;
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) {
1387 default: // Map unknown orderings to sequentially-consistent.
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: {
1713 SmallVector<int, 16> Mask;
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)) {
1742 "constexpr", InsertBB);
1743 } else if (Instruction::isBinaryOp(BC->Opcode)) {
1745 Ops[1], "constexpr", InsertBB);
1748 I->setHasNoSignedWrap();
1750 I->setHasNoUnsignedWrap();
1751 }
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) {
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
1919static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
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.
1939static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
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
2002 SmallVector<uint64_t, 64> Record;
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);
2039 decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
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::SanitizeAllocToken;
2209 return Attribute::SpeculativeLoadHardening;
2211 return Attribute::SwiftError;
2213 return Attribute::SwiftSelf;
2215 return Attribute::SwiftAsync;
2217 return Attribute::UWTable;
2219 return Attribute::VScaleRange;
2221 return Attribute::WillReturn;
2223 return Attribute::WriteOnly;
2225 return Attribute::ZExt;
2227 return Attribute::ImmArg;
2229 return Attribute::SanitizeMemTag;
2231 return Attribute::Preallocated;
2233 return Attribute::NoUndef;
2235 return Attribute::ByRef;
2237 return Attribute::MustProgress;
2239 return Attribute::Hot;
2241 return Attribute::PresplitCoroutine;
2243 return Attribute::Writable;
2245 return Attribute::CoroDestroyOnlyWhenComplete;
2247 return Attribute::DeadOnUnwind;
2249 return Attribute::Range;
2251 return Attribute::Initializes;
2253 return Attribute::CoroElideSafe;
2255 return Attribute::NoExt;
2257 return Attribute::Captures;
2259 return Attribute::DeadOnReturn;
2261 return Attribute::NoCreateUndefOrPoison;
2262 }
2263}
2264
2265Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
2266 MaybeAlign &Alignment) {
2267 // Note: Alignment in bitcode files is incremented by 1, so that zero
2268 // can be used for default alignment.
2269 if (Exponent > Value::MaxAlignmentExponent + 1)
2270 return error("Invalid alignment value");
2271 Alignment = decodeMaybeAlign(Exponent);
2272 return Error::success();
2273}
2274
2275Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2276 *Kind = getAttrFromCode(Code);
2277 if (*Kind == Attribute::None)
2278 return error("Unknown attribute kind (" + Twine(Code) + ")");
2279 return Error::success();
2280}
2281
2282static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2283 switch (EncodedKind) {
2285 ME &= MemoryEffects::none();
2286 return true;
2289 return true;
2292 return true;
2295 return true;
2298 return true;
2301 return true;
2302 default:
2303 return false;
2304 }
2305}
2306
2307Error BitcodeReader::parseAttributeGroupBlock() {
2308 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2309 return Err;
2310
2311 if (!MAttributeGroups.empty())
2312 return error("Invalid multiple blocks");
2313
2314 SmallVector<uint64_t, 64> Record;
2315
2316 // Read all the records.
2317 while (true) {
2318 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2319 if (!MaybeEntry)
2320 return MaybeEntry.takeError();
2321 BitstreamEntry Entry = MaybeEntry.get();
2322
2323 switch (Entry.Kind) {
2324 case BitstreamEntry::SubBlock: // Handled for us already.
2326 return error("Malformed block");
2328 return Error::success();
2330 // The interesting case.
2331 break;
2332 }
2333
2334 // Read a record.
2335 Record.clear();
2336 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2337 if (!MaybeRecord)
2338 return MaybeRecord.takeError();
2339 switch (MaybeRecord.get()) {
2340 default: // Default behavior: ignore.
2341 break;
2342 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2343 if (Record.size() < 3)
2344 return error("Invalid grp record");
2345
2346 uint64_t GrpID = Record[0];
2347 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2348
2349 AttrBuilder B(Context);
2351 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2352 if (Record[i] == 0) { // Enum attribute
2353 Attribute::AttrKind Kind;
2354 uint64_t EncodedKind = Record[++i];
2355 if (Idx == AttributeList::FunctionIndex &&
2356 upgradeOldMemoryAttribute(ME, EncodedKind))
2357 continue;
2358
2359 if (EncodedKind == bitc::ATTR_KIND_NO_CAPTURE) {
2360 B.addCapturesAttr(CaptureInfo::none());
2361 continue;
2362 }
2363
2364 if (Error Err = parseAttrKind(EncodedKind, &Kind))
2365 return Err;
2366
2367 // Upgrade old-style byval attribute to one with a type, even if it's
2368 // nullptr. We will have to insert the real type when we associate
2369 // this AttributeList with a function.
2370 if (Kind == Attribute::ByVal)
2371 B.addByValAttr(nullptr);
2372 else if (Kind == Attribute::StructRet)
2373 B.addStructRetAttr(nullptr);
2374 else if (Kind == Attribute::InAlloca)
2375 B.addInAllocaAttr(nullptr);
2376 else if (Kind == Attribute::UWTable)
2377 B.addUWTableAttr(UWTableKind::Default);
2378 else if (Attribute::isEnumAttrKind(Kind))
2379 B.addAttribute(Kind);
2380 else
2381 return error("Not an enum attribute");
2382 } else if (Record[i] == 1) { // Integer attribute
2383 Attribute::AttrKind Kind;
2384 if (Error Err = parseAttrKind(Record[++i], &Kind))
2385 return Err;
2386 if (!Attribute::isIntAttrKind(Kind))
2387 return error("Not an int attribute");
2388 if (Kind == Attribute::Alignment)
2389 B.addAlignmentAttr(Record[++i]);
2390 else if (Kind == Attribute::StackAlignment)
2391 B.addStackAlignmentAttr(Record[++i]);
2392 else if (Kind == Attribute::Dereferenceable)
2393 B.addDereferenceableAttr(Record[++i]);
2394 else if (Kind == Attribute::DereferenceableOrNull)
2395 B.addDereferenceableOrNullAttr(Record[++i]);
2396 else if (Kind == Attribute::AllocSize)
2397 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2398 else if (Kind == Attribute::VScaleRange)
2399 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2400 else if (Kind == Attribute::UWTable)
2401 B.addUWTableAttr(UWTableKind(Record[++i]));
2402 else if (Kind == Attribute::AllocKind)
2403 B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2404 else if (Kind == Attribute::Memory) {
2405 uint64_t EncodedME = Record[++i];
2406 const uint8_t Version = (EncodedME >> 56);
2407 if (Version == 0) {
2408 // Errno memory location was previously encompassed into default
2409 // memory. Ensure this is taken into account while reconstructing
2410 // the memory attribute prior to its introduction.
2411 ModRefInfo ArgMem = ModRefInfo((EncodedME >> 0) & 3);
2412 ModRefInfo InaccessibleMem = ModRefInfo((EncodedME >> 2) & 3);
2413 ModRefInfo OtherMem = ModRefInfo((EncodedME >> 4) & 3);
2416 MemoryEffects::errnoMemOnly(OtherMem) |
2418 B.addMemoryAttr(ME);
2419 } else {
2420 // Construct the memory attribute directly from the encoded base
2421 // on newer versions.
2423 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2424 }
2425 } else if (Kind == Attribute::Captures)
2426 B.addCapturesAttr(CaptureInfo::createFromIntValue(Record[++i]));
2427 else if (Kind == Attribute::NoFPClass)
2428 B.addNoFPClassAttr(
2429 static_cast<FPClassTest>(Record[++i] & fcAllFlags));
2430 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2431 bool HasValue = (Record[i++] == 4);
2432 SmallString<64> KindStr;
2433 SmallString<64> ValStr;
2434
2435 while (Record[i] != 0 && i != e)
2436 KindStr += Record[i++];
2437 assert(Record[i] == 0 && "Kind string not null terminated");
2438
2439 if (HasValue) {
2440 // Has a value associated with it.
2441 ++i; // Skip the '0' that terminates the "kind" string.
2442 while (Record[i] != 0 && i != e)
2443 ValStr += Record[i++];
2444 assert(Record[i] == 0 && "Value string not null terminated");
2445 }
2446
2447 B.addAttribute(KindStr.str(), ValStr.str());
2448 } else if (Record[i] == 5 || Record[i] == 6) {
2449 bool HasType = Record[i] == 6;
2450 Attribute::AttrKind Kind;
2451 if (Error Err = parseAttrKind(Record[++i], &Kind))
2452 return Err;
2453 if (!Attribute::isTypeAttrKind(Kind))
2454 return error("Not a type attribute");
2455
2456 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2457 } else if (Record[i] == 7) {
2458 Attribute::AttrKind Kind;
2459
2460 i++;
2461 if (Error Err = parseAttrKind(Record[i++], &Kind))
2462 return Err;
2463 if (!Attribute::isConstantRangeAttrKind(Kind))
2464 return error("Not a ConstantRange attribute");
2465
2466 Expected<ConstantRange> MaybeCR =
2467 readBitWidthAndConstantRange(Record, i);
2468 if (!MaybeCR)
2469 return MaybeCR.takeError();
2470 i--;
2471
2472 B.addConstantRangeAttr(Kind, MaybeCR.get());
2473 } else if (Record[i] == 8) {
2474 Attribute::AttrKind Kind;
2475
2476 i++;
2477 if (Error Err = parseAttrKind(Record[i++], &Kind))
2478 return Err;
2479 if (!Attribute::isConstantRangeListAttrKind(Kind))
2480 return error("Not a constant range list attribute");
2481
2483 if (i + 2 > e)
2484 return error("Too few records for constant range list");
2485 unsigned RangeSize = Record[i++];
2486 unsigned BitWidth = Record[i++];
2487 for (unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2488 Expected<ConstantRange> MaybeCR =
2489 readConstantRange(Record, i, BitWidth);
2490 if (!MaybeCR)
2491 return MaybeCR.takeError();
2492 Val.push_back(MaybeCR.get());
2493 }
2494 i--;
2495
2497 return error("Invalid (unordered or overlapping) range list");
2498 B.addConstantRangeListAttr(Kind, Val);
2499 } else {
2500 return error("Invalid attribute group entry");
2501 }
2502 }
2503
2504 if (ME != MemoryEffects::unknown())
2505 B.addMemoryAttr(ME);
2506
2508 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2509 break;
2510 }
2511 }
2512 }
2513}
2514
2515Error BitcodeReader::parseTypeTable() {
2516 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2517 return Err;
2518
2519 return parseTypeTableBody();
2520}
2521
2522Error BitcodeReader::parseTypeTableBody() {
2523 if (!TypeList.empty())
2524 return error("Invalid multiple blocks");
2525
2526 SmallVector<uint64_t, 64> Record;
2527 unsigned NumRecords = 0;
2528
2529 SmallString<64> TypeName;
2530
2531 // Read all the records for this type table.
2532 while (true) {
2533 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2534 if (!MaybeEntry)
2535 return MaybeEntry.takeError();
2536 BitstreamEntry Entry = MaybeEntry.get();
2537
2538 switch (Entry.Kind) {
2539 case BitstreamEntry::SubBlock: // Handled for us already.
2541 return error("Malformed block");
2543 if (NumRecords != TypeList.size())
2544 return error("Malformed block");
2545 return Error::success();
2547 // The interesting case.
2548 break;
2549 }
2550
2551 // Read a record.
2552 Record.clear();
2553 Type *ResultTy = nullptr;
2554 SmallVector<unsigned> ContainedIDs;
2555 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2556 if (!MaybeRecord)
2557 return MaybeRecord.takeError();
2558 switch (MaybeRecord.get()) {
2559 default:
2560 return error("Invalid value");
2561 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2562 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2563 // type list. This allows us to reserve space.
2564 if (Record.empty())
2565 return error("Invalid numentry record");
2566 TypeList.resize(Record[0]);
2567 continue;
2568 case bitc::TYPE_CODE_VOID: // VOID
2569 ResultTy = Type::getVoidTy(Context);
2570 break;
2571 case bitc::TYPE_CODE_HALF: // HALF
2572 ResultTy = Type::getHalfTy(Context);
2573 break;
2574 case bitc::TYPE_CODE_BFLOAT: // BFLOAT
2575 ResultTy = Type::getBFloatTy(Context);
2576 break;
2577 case bitc::TYPE_CODE_FLOAT: // FLOAT
2578 ResultTy = Type::getFloatTy(Context);
2579 break;
2580 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
2581 ResultTy = Type::getDoubleTy(Context);
2582 break;
2583 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
2584 ResultTy = Type::getX86_FP80Ty(Context);
2585 break;
2586 case bitc::TYPE_CODE_FP128: // FP128
2587 ResultTy = Type::getFP128Ty(Context);
2588 break;
2589 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2590 ResultTy = Type::getPPC_FP128Ty(Context);
2591 break;
2592 case bitc::TYPE_CODE_LABEL: // LABEL
2593 ResultTy = Type::getLabelTy(Context);
2594 break;
2595 case bitc::TYPE_CODE_METADATA: // METADATA
2596 ResultTy = Type::getMetadataTy(Context);
2597 break;
2598 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
2599 // Deprecated: decodes as <1 x i64>
2600 ResultTy =
2602 break;
2603 case bitc::TYPE_CODE_X86_AMX: // X86_AMX
2604 ResultTy = Type::getX86_AMXTy(Context);
2605 break;
2606 case bitc::TYPE_CODE_TOKEN: // TOKEN
2607 ResultTy = Type::getTokenTy(Context);
2608 break;
2609 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2610 if (Record.empty())
2611 return error("Invalid integer record");
2612
2613 uint64_t NumBits = Record[0];
2614 if (NumBits < IntegerType::MIN_INT_BITS ||
2615 NumBits > IntegerType::MAX_INT_BITS)
2616 return error("Bitwidth for integer type out of range");
2617 ResultTy = IntegerType::get(Context, NumBits);
2618 break;
2619 }
2620 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2621 // [pointee type, address space]
2622 if (Record.empty())
2623 return error("Invalid pointer record");
2624 unsigned AddressSpace = 0;
2625 if (Record.size() == 2)
2626 AddressSpace = Record[1];
2627 ResultTy = getTypeByID(Record[0]);
2628 if (!ResultTy ||
2629 !PointerType::isValidElementType(ResultTy))
2630 return error("Invalid type");
2631 ContainedIDs.push_back(Record[0]);
2632 ResultTy = PointerType::get(ResultTy->getContext(), AddressSpace);
2633 break;
2634 }
2635 case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2636 if (Record.size() != 1)
2637 return error("Invalid opaque pointer record");
2638 unsigned AddressSpace = Record[0];
2639 ResultTy = PointerType::get(Context, AddressSpace);
2640 break;
2641 }
2643 // Deprecated, but still needed to read old bitcode files.
2644 // FUNCTION: [vararg, attrid, retty, paramty x N]
2645 if (Record.size() < 3)
2646 return error("Invalid function record");
2647 SmallVector<Type*, 8> ArgTys;
2648 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2649 if (Type *T = getTypeByID(Record[i]))
2650 ArgTys.push_back(T);
2651 else
2652 break;
2653 }
2654
2655 ResultTy = getTypeByID(Record[2]);
2656 if (!ResultTy || ArgTys.size() < Record.size()-3)
2657 return error("Invalid type");
2658
2659 ContainedIDs.append(Record.begin() + 2, Record.end());
2660 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2661 break;
2662 }
2664 // FUNCTION: [vararg, retty, paramty x N]
2665 if (Record.size() < 2)
2666 return error("Invalid function record");
2667 SmallVector<Type*, 8> ArgTys;
2668 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2669 if (Type *T = getTypeByID(Record[i])) {
2670 if (!FunctionType::isValidArgumentType(T))
2671 return error("Invalid function argument type");
2672 ArgTys.push_back(T);
2673 }
2674 else
2675 break;
2676 }
2677
2678 ResultTy = getTypeByID(Record[1]);
2679 if (!ResultTy || ArgTys.size() < Record.size()-2)
2680 return error("Invalid type");
2681
2682 ContainedIDs.append(Record.begin() + 1, Record.end());
2683 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2684 break;
2685 }
2686 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
2687 if (Record.empty())
2688 return error("Invalid anon struct record");
2689 SmallVector<Type*, 8> EltTys;
2690 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2691 if (Type *T = getTypeByID(Record[i]))
2692 EltTys.push_back(T);
2693 else
2694 break;
2695 }
2696 if (EltTys.size() != Record.size()-1)
2697 return error("Invalid type");
2698 ContainedIDs.append(Record.begin() + 1, Record.end());
2699 ResultTy = StructType::get(Context, EltTys, Record[0]);
2700 break;
2701 }
2702 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
2703 if (convertToString(Record, 0, TypeName))
2704 return error("Invalid struct name record");
2705 continue;
2706
2707 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2708 if (Record.empty())
2709 return error("Invalid named struct record");
2710
2711 if (NumRecords >= TypeList.size())
2712 return error("Invalid TYPE table");
2713
2714 // Check to see if this was forward referenced, if so fill in the temp.
2715 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2716 if (Res) {
2717 Res->setName(TypeName);
2718 TypeList[NumRecords] = nullptr;
2719 } else // Otherwise, create a new struct.
2720 Res = createIdentifiedStructType(Context, TypeName);
2721 TypeName.clear();
2722
2723 SmallVector<Type*, 8> EltTys;
2724 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2725 if (Type *T = getTypeByID(Record[i]))
2726 EltTys.push_back(T);
2727 else
2728 break;
2729 }
2730 if (EltTys.size() != Record.size()-1)
2731 return error("Invalid named struct record");
2732 if (auto E = Res->setBodyOrError(EltTys, Record[0]))
2733 return E;
2734 ContainedIDs.append(Record.begin() + 1, Record.end());
2735 ResultTy = Res;
2736 break;
2737 }
2738 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
2739 if (Record.size() != 1)
2740 return error("Invalid opaque type record");
2741
2742 if (NumRecords >= TypeList.size())
2743 return error("Invalid TYPE table");
2744
2745 // Check to see if this was forward referenced, if so fill in the temp.
2746 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2747 if (Res) {
2748 Res->setName(TypeName);
2749 TypeList[NumRecords] = nullptr;
2750 } else // Otherwise, create a new struct with no body.
2751 Res = createIdentifiedStructType(Context, TypeName);
2752 TypeName.clear();
2753 ResultTy = Res;
2754 break;
2755 }
2756 case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2757 if (Record.size() < 1)
2758 return error("Invalid target extension type record");
2759
2760 if (NumRecords >= TypeList.size())
2761 return error("Invalid TYPE table");
2762
2763 if (Record[0] >= Record.size())
2764 return error("Too many type parameters");
2765
2766 unsigned NumTys = Record[0];
2767 SmallVector<Type *, 4> TypeParams;
2768 SmallVector<unsigned, 8> IntParams;
2769 for (unsigned i = 0; i < NumTys; i++) {
2770 if (Type *T = getTypeByID(Record[i + 1]))
2771 TypeParams.push_back(T);
2772 else
2773 return error("Invalid type");
2774 }
2775
2776 for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2777 if (Record[i] > UINT_MAX)
2778 return error("Integer parameter too large");
2779 IntParams.push_back(Record[i]);
2780 }
2781 auto TTy =
2782 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
2783 if (auto E = TTy.takeError())
2784 return E;
2785 ResultTy = *TTy;
2786 TypeName.clear();
2787 break;
2788 }
2789 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
2790 if (Record.size() < 2)
2791 return error("Invalid array type record");
2792 ResultTy = getTypeByID(Record[1]);
2793 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2794 return error("Invalid type");
2795 ContainedIDs.push_back(Record[1]);
2796 ResultTy = ArrayType::get(ResultTy, Record[0]);
2797 break;
2798 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
2799 // [numelts, eltty, scalable]
2800 if (Record.size() < 2)
2801 return error("Invalid vector type record");
2802 if (Record[0] == 0)
2803 return error("Invalid vector length");
2804 ResultTy = getTypeByID(Record[1]);
2805 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2806 return error("Invalid type");
2807 bool Scalable = Record.size() > 2 ? Record[2] : false;
2808 ContainedIDs.push_back(Record[1]);
2809 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2810 break;
2811 }
2812
2813 if (NumRecords >= TypeList.size())
2814 return error("Invalid TYPE table");
2815 if (TypeList[NumRecords])
2816 return error(
2817 "Invalid TYPE table: Only named structs can be forward referenced");
2818 assert(ResultTy && "Didn't read a type?");
2819 TypeList[NumRecords] = ResultTy;
2820 if (!ContainedIDs.empty())
2821 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2822 ++NumRecords;
2823 }
2824}
2825
2826Error BitcodeReader::parseOperandBundleTags() {
2827 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2828 return Err;
2829
2830 if (!BundleTags.empty())
2831 return error("Invalid multiple blocks");
2832
2833 SmallVector<uint64_t, 64> Record;
2834
2835 while (true) {
2836 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2837 if (!MaybeEntry)
2838 return MaybeEntry.takeError();
2839 BitstreamEntry Entry = MaybeEntry.get();
2840
2841 switch (Entry.Kind) {
2842 case BitstreamEntry::SubBlock: // Handled for us already.
2844 return error("Malformed block");
2846 return Error::success();
2848 // The interesting case.
2849 break;
2850 }
2851
2852 // Tags are implicitly mapped to integers by their order.
2853
2854 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2855 if (!MaybeRecord)
2856 return MaybeRecord.takeError();
2857 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2858 return error("Invalid operand bundle record");
2859
2860 // OPERAND_BUNDLE_TAG: [strchr x N]
2861 BundleTags.emplace_back();
2862 if (convertToString(Record, 0, BundleTags.back()))
2863 return error("Invalid operand bundle record");
2864 Record.clear();
2865 }
2866}
2867
2868Error BitcodeReader::parseSyncScopeNames() {
2869 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2870 return Err;
2871
2872 if (!SSIDs.empty())
2873 return error("Invalid multiple synchronization scope names blocks");
2874
2875 SmallVector<uint64_t, 64> Record;
2876 while (true) {
2877 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2878 if (!MaybeEntry)
2879 return MaybeEntry.takeError();
2880 BitstreamEntry Entry = MaybeEntry.get();
2881
2882 switch (Entry.Kind) {
2883 case BitstreamEntry::SubBlock: // Handled for us already.
2885 return error("Malformed block");
2887 if (SSIDs.empty())
2888 return error("Invalid empty synchronization scope names block");
2889 return Error::success();
2891 // The interesting case.
2892 break;
2893 }
2894
2895 // Synchronization scope names are implicitly mapped to synchronization
2896 // scope IDs by their order.
2897
2898 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2899 if (!MaybeRecord)
2900 return MaybeRecord.takeError();
2901 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2902 return error("Invalid sync scope record");
2903
2904 SmallString<16> SSN;
2905 if (convertToString(Record, 0, SSN))
2906 return error("Invalid sync scope record");
2907
2908 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2909 Record.clear();
2910 }
2911}
2912
2913/// Associate a value with its name from the given index in the provided record.
2914Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2915 unsigned NameIndex, Triple &TT) {
2916 SmallString<128> ValueName;
2917 if (convertToString(Record, NameIndex, ValueName))
2918 return error("Invalid record");
2919 unsigned ValueID = Record[0];
2920 if (ValueID >= ValueList.size() || !ValueList[ValueID])
2921 return error("Invalid record");
2922 Value *V = ValueList[ValueID];
2923
2924 StringRef NameStr(ValueName.data(), ValueName.size());
2925 if (NameStr.contains(0))
2926 return error("Invalid value name");
2927 V->setName(NameStr);
2928 auto *GO = dyn_cast<GlobalObject>(V);
2929 if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2930 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2931 return V;
2932}
2933
2934/// Helper to note and return the current location, and jump to the given
2935/// offset.
2937 BitstreamCursor &Stream) {
2938 // Save the current parsing location so we can jump back at the end
2939 // of the VST read.
2940 uint64_t CurrentBit = Stream.GetCurrentBitNo();
2941 if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2942 return std::move(JumpFailed);
2943 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2944 if (!MaybeEntry)
2945 return MaybeEntry.takeError();
2946 if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
2947 MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
2948 return error("Expected value symbol table subblock");
2949 return CurrentBit;
2950}
2951
2952void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2953 Function *F,
2954 ArrayRef<uint64_t> Record) {
2955 // Note that we subtract 1 here because the offset is relative to one word
2956 // before the start of the identification or module block, which was
2957 // historically always the start of the regular bitcode header.
2958 uint64_t FuncWordOffset = Record[1] - 1;
2959 uint64_t FuncBitOffset = FuncWordOffset * 32;
2960 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2961 // Set the LastFunctionBlockBit to point to the last function block.
2962 // Later when parsing is resumed after function materialization,
2963 // we can simply skip that last function block.
2964 if (FuncBitOffset > LastFunctionBlockBit)
2965 LastFunctionBlockBit = FuncBitOffset;
2966}
2967
2968/// Read a new-style GlobalValue symbol table.
2969Error BitcodeReader::parseGlobalValueSymbolTable() {
2970 unsigned FuncBitcodeOffsetDelta =
2971 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2972
2973 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2974 return Err;
2975
2976 SmallVector<uint64_t, 64> Record;
2977 while (true) {
2978 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2979 if (!MaybeEntry)
2980 return MaybeEntry.takeError();
2981 BitstreamEntry Entry = MaybeEntry.get();
2982
2983 switch (Entry.Kind) {
2986 return error("Malformed block");
2988 return Error::success();
2990 break;
2991 }
2992
2993 Record.clear();
2994 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2995 if (!MaybeRecord)
2996 return MaybeRecord.takeError();
2997 switch (MaybeRecord.get()) {
2998 case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
2999 unsigned ValueID = Record[0];
3000 if (ValueID >= ValueList.size() || !ValueList[ValueID])
3001 return error("Invalid value reference in symbol table");
3002 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3003 cast<Function>(ValueList[ValueID]), Record);
3004 break;
3005 }
3006 }
3007 }
3008}
3009
3010/// Parse the value symbol table at either the current parsing location or
3011/// at the given bit offset if provided.
3012Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
3013 uint64_t CurrentBit;
3014 // Pass in the Offset to distinguish between calling for the module-level
3015 // VST (where we want to jump to the VST offset) and the function-level
3016 // VST (where we don't).
3017 if (Offset > 0) {
3018 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
3019 if (!MaybeCurrentBit)
3020 return MaybeCurrentBit.takeError();
3021 CurrentBit = MaybeCurrentBit.get();
3022 // If this module uses a string table, read this as a module-level VST.
3023 if (UseStrtab) {
3024 if (Error Err = parseGlobalValueSymbolTable())
3025 return Err;
3026 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
3027 return JumpFailed;
3028 return Error::success();
3029 }
3030 // Otherwise, the VST will be in a similar format to a function-level VST,
3031 // and will contain symbol names.
3032 }
3033
3034 // Compute the delta between the bitcode indices in the VST (the word offset
3035 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
3036 // expected by the lazy reader. The reader's EnterSubBlock expects to have
3037 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
3038 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
3039 // just before entering the VST subblock because: 1) the EnterSubBlock
3040 // changes the AbbrevID width; 2) the VST block is nested within the same
3041 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
3042 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
3043 // jump to the FUNCTION_BLOCK using this offset later, we don't want
3044 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
3045 unsigned FuncBitcodeOffsetDelta =
3046 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
3047
3048 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
3049 return Err;
3050
3051 SmallVector<uint64_t, 64> Record;
3052
3053 Triple TT(TheModule->getTargetTriple());
3054
3055 // Read all the records for this value table.
3056 SmallString<128> ValueName;
3057
3058 while (true) {
3059 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3060 if (!MaybeEntry)
3061 return MaybeEntry.takeError();
3062 BitstreamEntry Entry = MaybeEntry.get();
3063
3064 switch (Entry.Kind) {
3065 case BitstreamEntry::SubBlock: // Handled for us already.
3067 return error("Malformed block");
3069 if (Offset > 0)
3070 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
3071 return JumpFailed;
3072 return Error::success();
3074 // The interesting case.
3075 break;
3076 }
3077
3078 // Read a record.
3079 Record.clear();
3080 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3081 if (!MaybeRecord)
3082 return MaybeRecord.takeError();
3083 switch (MaybeRecord.get()) {
3084 default: // Default behavior: unknown type.
3085 break;
3086 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
3087 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3088 if (Error Err = ValOrErr.takeError())
3089 return Err;
3090 ValOrErr.get();
3091 break;
3092 }
3094 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
3095 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3096 if (Error Err = ValOrErr.takeError())
3097 return Err;
3098 Value *V = ValOrErr.get();
3099
3100 // Ignore function offsets emitted for aliases of functions in older
3101 // versions of LLVM.
3102 if (auto *F = dyn_cast<Function>(V))
3103 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
3104 break;
3105 }
3107 if (convertToString(Record, 1, ValueName))
3108 return error("Invalid bbentry record");
3109 BasicBlock *BB = getBasicBlock(Record[0]);
3110 if (!BB)
3111 return error("Invalid bbentry record");
3112
3113 BB->setName(ValueName.str());
3114 ValueName.clear();
3115 break;
3116 }
3117 }
3118 }
3119}
3120
3121/// Decode a signed value stored with the sign bit in the LSB for dense VBR
3122/// encoding.
3123uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3124 if ((V & 1) == 0)
3125 return V >> 1;
3126 if (V != 1)
3127 return -(V >> 1);
3128 // There is no such thing as -0 with integers. "-0" really means MININT.
3129 return 1ULL << 63;
3130}
3131
3132/// Resolve all of the initializers for global values and aliases that we can.
3133Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3134 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3135 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3136 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3137
3138 GlobalInitWorklist.swap(GlobalInits);
3139 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3140 FunctionOperandWorklist.swap(FunctionOperands);
3141
3142 while (!GlobalInitWorklist.empty()) {
3143 unsigned ValID = GlobalInitWorklist.back().second;
3144 if (ValID >= ValueList.size()) {
3145 // Not ready to resolve this yet, it requires something later in the file.
3146 GlobalInits.push_back(GlobalInitWorklist.back());
3147 } else {
3148 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3149 if (!MaybeC)
3150 return MaybeC.takeError();
3151 GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
3152 }
3153 GlobalInitWorklist.pop_back();
3154 }
3155
3156 while (!IndirectSymbolInitWorklist.empty()) {
3157 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3158 if (ValID >= ValueList.size()) {
3159 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3160 } else {
3161 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3162 if (!MaybeC)
3163 return MaybeC.takeError();
3164 Constant *C = MaybeC.get();
3165 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3166 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
3167 if (C->getType() != GV->getType())
3168 return error("Alias and aliasee types don't match");
3169 GA->setAliasee(C);
3170 } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
3171 GI->setResolver(C);
3172 } else {
3173 return error("Expected an alias or an ifunc");
3174 }
3175 }
3176 IndirectSymbolInitWorklist.pop_back();
3177 }
3178
3179 while (!FunctionOperandWorklist.empty()) {
3180 FunctionOperandInfo &Info = FunctionOperandWorklist.back();
3181 if (Info.PersonalityFn) {
3182 unsigned ValID = Info.PersonalityFn - 1;
3183 if (ValID < ValueList.size()) {
3184 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3185 if (!MaybeC)
3186 return MaybeC.takeError();
3187 Info.F->setPersonalityFn(MaybeC.get());
3188 Info.PersonalityFn = 0;
3189 }
3190 }
3191 if (Info.Prefix) {
3192 unsigned ValID = Info.Prefix - 1;
3193 if (ValID < ValueList.size()) {
3194 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3195 if (!MaybeC)
3196 return MaybeC.takeError();
3197 Info.F->setPrefixData(MaybeC.get());
3198 Info.Prefix = 0;
3199 }
3200 }
3201 if (Info.Prologue) {
3202 unsigned ValID = Info.Prologue - 1;
3203 if (ValID < ValueList.size()) {
3204 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3205 if (!MaybeC)
3206 return MaybeC.takeError();
3207 Info.F->setPrologueData(MaybeC.get());
3208 Info.Prologue = 0;
3209 }
3210 }
3211 if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
3212 FunctionOperands.push_back(Info);
3213 FunctionOperandWorklist.pop_back();
3214 }
3215
3216 return Error::success();
3217}
3218
3220 SmallVector<uint64_t, 8> Words(Vals.size());
3221 transform(Vals, Words.begin(),
3222 BitcodeReader::decodeSignRotatedValue);
3223
3224 return APInt(TypeBits, Words);
3225}
3226
3227Error BitcodeReader::parseConstants() {
3228 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
3229 return Err;
3230
3232
3233 // Read all the records for this value table.
3234 Type *CurTy = Type::getInt32Ty(Context);
3235 unsigned Int32TyID = getVirtualTypeID(CurTy);
3236 unsigned CurTyID = Int32TyID;
3237 Type *CurElemTy = nullptr;
3238 unsigned NextCstNo = ValueList.size();
3239
3240 while (true) {
3241 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3242 if (!MaybeEntry)
3243 return MaybeEntry.takeError();
3244 BitstreamEntry Entry = MaybeEntry.get();
3245
3246 switch (Entry.Kind) {
3247 case BitstreamEntry::SubBlock: // Handled for us already.
3249 return error("Malformed block");
3251 if (NextCstNo != ValueList.size())
3252 return error("Invalid constant reference");
3253 return Error::success();
3255 // The interesting case.
3256 break;
3257 }
3258
3259 // Read a record.
3260 Record.clear();
3261 Type *VoidType = Type::getVoidTy(Context);
3262 Value *V = nullptr;
3263 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3264 if (!MaybeBitCode)
3265 return MaybeBitCode.takeError();
3266 switch (unsigned BitCode = MaybeBitCode.get()) {
3267 default: // Default behavior: unknown constant
3268 case bitc::CST_CODE_UNDEF: // UNDEF
3269 V = UndefValue::get(CurTy);
3270 break;
3271 case bitc::CST_CODE_POISON: // POISON
3272 V = PoisonValue::get(CurTy);
3273 break;
3274 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3275 if (Record.empty())
3276 return error("Invalid settype record");
3277 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3278 return error("Invalid settype record");
3279 if (TypeList[Record[0]] == VoidType)
3280 return error("Invalid constant type");
3281 CurTyID = Record[0];
3282 CurTy = TypeList[CurTyID];
3283 CurElemTy = getPtrElementTypeByID(CurTyID);
3284 continue; // Skip the ValueList manipulation.
3285 case bitc::CST_CODE_NULL: // NULL
3286 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
3287 return error("Invalid type for a constant null value");
3288 if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3289 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3290 return error("Invalid type for a constant null value");
3291 V = Constant::getNullValue(CurTy);
3292 break;
3293 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
3294 if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3295 return error("Invalid integer const record");
3296 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
3297 break;
3298 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3299 if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3300 return error("Invalid wide integer const record");
3301
3302 auto *ScalarTy = cast<IntegerType>(CurTy->getScalarType());
3303 APInt VInt = readWideAPInt(Record, ScalarTy->getBitWidth());
3304 V = ConstantInt::get(CurTy, VInt);
3305 break;
3306 }
3307 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
3308 if (Record.empty())
3309 return error("Invalid float const record");
3310
3311 auto *ScalarTy = CurTy->getScalarType();
3312 if (ScalarTy->isHalfTy())
3313 V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEhalf(),
3314 APInt(16, (uint16_t)Record[0])));
3315 else if (ScalarTy->isBFloatTy())
3316 V = ConstantFP::get(
3317 CurTy, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3318 else if (ScalarTy->isFloatTy())
3319 V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEsingle(),
3320 APInt(32, (uint32_t)Record[0])));
3321 else if (ScalarTy->isDoubleTy())
3322 V = ConstantFP::get(
3323 CurTy, APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3324 else if (ScalarTy->isX86_FP80Ty()) {
3325 // Bits are not stored the same way as a normal i80 APInt, compensate.
3326 uint64_t Rearrange[2];
3327 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3328 Rearrange[1] = Record[0] >> 48;
3329 V = ConstantFP::get(
3330 CurTy, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3331 } else if (ScalarTy->isFP128Ty())
3332 V = ConstantFP::get(CurTy,
3333 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3334 else if (ScalarTy->isPPC_FP128Ty())
3335 V = ConstantFP::get(
3336 CurTy, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3337 else
3338 V = PoisonValue::get(CurTy);
3339 break;
3340 }
3341
3342 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3343 if (Record.empty())
3344 return error("Invalid aggregate record");
3345
3346 SmallVector<unsigned, 16> Elts;
3347 llvm::append_range(Elts, Record);
3348
3349 if (isa<StructType>(CurTy)) {
3350 V = BitcodeConstant::create(
3351 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3352 } else if (isa<ArrayType>(CurTy)) {
3353 V = BitcodeConstant::create(Alloc, CurTy,
3354 BitcodeConstant::ConstantArrayOpcode, Elts);
3355 } else if (isa<VectorType>(CurTy)) {
3356 V = BitcodeConstant::create(
3357 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3358 } else {
3359 V = PoisonValue::get(CurTy);
3360 }
3361 break;
3362 }
3363 case bitc::CST_CODE_STRING: // STRING: [values]
3364 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3365 if (Record.empty())
3366 return error("Invalid string record");
3367
3368 SmallString<16> Elts(Record.begin(), Record.end());
3370 BitCode == bitc::CST_CODE_CSTRING);
3371 break;
3372 }
3373 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3374 if (Record.empty())
3375 return error("Invalid data record");
3376
3377 Type *EltTy;
3378 if (auto *Array = dyn_cast<ArrayType>(CurTy))
3379 EltTy = Array->getElementType();
3380 else
3381 EltTy = cast<VectorType>(CurTy)->getElementType();
3382 if (EltTy->isIntegerTy(8)) {
3383 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3384 if (isa<VectorType>(CurTy))
3386 else
3388 } else if (EltTy->isIntegerTy(16)) {
3389 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3390 if (isa<VectorType>(CurTy))
3392 else
3394 } else if (EltTy->isIntegerTy(32)) {
3395 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3396 if (isa<VectorType>(CurTy))
3398 else
3400 } else if (EltTy->isIntegerTy(64)) {
3401 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3402 if (isa<VectorType>(CurTy))
3404 else
3406 } else if (EltTy->isHalfTy()) {
3407 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3408 if (isa<VectorType>(CurTy))
3409 V = ConstantDataVector::getFP(EltTy, Elts);
3410 else
3411 V = ConstantDataArray::getFP(EltTy, Elts);
3412 } else if (EltTy->isBFloatTy()) {
3413 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3414 if (isa<VectorType>(CurTy))
3415 V = ConstantDataVector::getFP(EltTy, Elts);
3416 else
3417 V = ConstantDataArray::getFP(EltTy, Elts);
3418 } else if (EltTy->isFloatTy()) {
3419 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3420 if (isa<VectorType>(CurTy))
3421 V = ConstantDataVector::getFP(EltTy, Elts);
3422 else
3423 V = ConstantDataArray::getFP(EltTy, Elts);
3424 } else if (EltTy->isDoubleTy()) {
3425 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3426 if (isa<VectorType>(CurTy))
3427 V = ConstantDataVector::getFP(EltTy, Elts);
3428 else
3429 V = ConstantDataArray::getFP(EltTy, Elts);
3430 } else {
3431 return error("Invalid type for value");
3432 }
3433 break;
3434 }
3435 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
3436 if (Record.size() < 2)
3437 return error("Invalid unary op constexpr record");
3438 int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3439 if (Opc < 0) {
3440 V = PoisonValue::get(CurTy); // Unknown unop.
3441 } else {
3442 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3443 }
3444 break;
3445 }
3446 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3447 if (Record.size() < 3)
3448 return error("Invalid binary op constexpr record");
3449 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3450 if (Opc < 0) {
3451 V = PoisonValue::get(CurTy); // Unknown binop.
3452 } else {
3453 uint8_t Flags = 0;
3454 if (Record.size() >= 4) {
3455 if (Opc == Instruction::Add ||
3456 Opc == Instruction::Sub ||
3457 Opc == Instruction::Mul ||
3458 Opc == Instruction::Shl) {
3459 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3461 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3463 } else if (Opc == Instruction::SDiv ||
3464 Opc == Instruction::UDiv ||
3465 Opc == Instruction::LShr ||
3466 Opc == Instruction::AShr) {
3467 if (Record[3] & (1 << bitc::PEO_EXACT))
3469 }
3470 }
3471 V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3472 {(unsigned)Record[1], (unsigned)Record[2]});
3473 }
3474 break;
3475 }
3476 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3477 if (Record.size() < 3)
3478 return error("Invalid cast constexpr record");
3479 int Opc = getDecodedCastOpcode(Record[0]);
3480 if (Opc < 0) {
3481 V = PoisonValue::get(CurTy); // Unknown cast.
3482 } else {
3483 unsigned OpTyID = Record[1];
3484 Type *OpTy = getTypeByID(OpTyID);
3485 if (!OpTy)
3486 return error("Invalid cast constexpr record");
3487 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3488 }
3489 break;
3490 }
3491 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3492 case bitc::CST_CODE_CE_GEP_OLD: // [ty, n x operands]
3493 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD: // [ty, flags, n x
3494 // operands]
3495 case bitc::CST_CODE_CE_GEP: // [ty, flags, n x operands]
3496 case bitc::CST_CODE_CE_GEP_WITH_INRANGE: { // [ty, flags, start, end, n x
3497 // operands]
3498 if (Record.size() < 2)
3499 return error("Constant GEP record must have at least two elements");
3500 unsigned OpNum = 0;
3501 Type *PointeeType = nullptr;
3504 BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2)
3505 PointeeType = getTypeByID(Record[OpNum++]);
3506
3507 uint64_t Flags = 0;
3508 std::optional<ConstantRange> InRange;
3510 uint64_t Op = Record[OpNum++];
3511 Flags = Op & 1; // inbounds
3512 unsigned InRangeIndex = Op >> 1;
3513 // "Upgrade" inrange by dropping it. The feature is too niche to
3514 // bother.
3515 (void)InRangeIndex;
3516 } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) {
3517 Flags = Record[OpNum++];
3518 Expected<ConstantRange> MaybeInRange =
3519 readBitWidthAndConstantRange(Record, OpNum);
3520 if (!MaybeInRange)
3521 return MaybeInRange.takeError();
3522 InRange = MaybeInRange.get();
3523 } else if (BitCode == bitc::CST_CODE_CE_GEP) {
3524 Flags = Record[OpNum++];
3525 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3526 Flags = (1 << bitc::GEP_INBOUNDS);
3527
3528 SmallVector<unsigned, 16> Elts;
3529 unsigned BaseTypeID = Record[OpNum];
3530 while (OpNum != Record.size()) {
3531 unsigned ElTyID = Record[OpNum++];
3532 Type *ElTy = getTypeByID(ElTyID);
3533 if (!ElTy)
3534 return error("Invalid getelementptr constexpr record");
3535 Elts.push_back(Record[OpNum++]);
3536 }
3537
3538 if (Elts.size() < 1)
3539 return error("Invalid gep with no operands");
3540
3541 Type *BaseType = getTypeByID(BaseTypeID);
3543 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3544 BaseType = getTypeByID(BaseTypeID);
3545 }
3546
3548 if (!OrigPtrTy)
3549 return error("GEP base operand must be pointer or vector of pointer");
3550
3551 if (!PointeeType) {
3552 PointeeType = getPtrElementTypeByID(BaseTypeID);
3553 if (!PointeeType)
3554 return error("Missing element type for old-style constant GEP");
3555 }
3556
3557 V = BitcodeConstant::create(
3558 Alloc, CurTy,
3559 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange},
3560 Elts);
3561 break;
3562 }
3563 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3564 if (Record.size() < 3)
3565 return error("Invalid select constexpr record");
3566
3567 V = BitcodeConstant::create(
3568 Alloc, CurTy, Instruction::Select,
3569 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3570 break;
3571 }
3573 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3574 if (Record.size() < 3)
3575 return error("Invalid extractelement constexpr record");
3576 unsigned OpTyID = Record[0];
3577 VectorType *OpTy =
3578 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3579 if (!OpTy)
3580 return error("Invalid extractelement constexpr record");
3581 unsigned IdxRecord;
3582 if (Record.size() == 4) {
3583 unsigned IdxTyID = Record[2];
3584 Type *IdxTy = getTypeByID(IdxTyID);
3585 if (!IdxTy)
3586 return error("Invalid extractelement constexpr record");
3587 IdxRecord = Record[3];
3588 } else {
3589 // Deprecated, but still needed to read old bitcode files.
3590 IdxRecord = Record[2];
3591 }
3592 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3593 {(unsigned)Record[1], IdxRecord});
3594 break;
3595 }
3597 : { // CE_INSERTELT: [opval, opval, opty, opval]
3598 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3599 if (Record.size() < 3 || !OpTy)
3600 return error("Invalid insertelement constexpr record");
3601 unsigned IdxRecord;
3602 if (Record.size() == 4) {
3603 unsigned IdxTyID = Record[2];
3604 Type *IdxTy = getTypeByID(IdxTyID);
3605 if (!IdxTy)
3606 return error("Invalid insertelement constexpr record");
3607 IdxRecord = Record[3];
3608 } else {
3609 // Deprecated, but still needed to read old bitcode files.
3610 IdxRecord = Record[2];
3611 }
3612 V = BitcodeConstant::create(
3613 Alloc, CurTy, Instruction::InsertElement,
3614 {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3615 break;
3616 }
3617 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3618 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3619 if (Record.size() < 3 || !OpTy)
3620 return error("Invalid shufflevector constexpr record");
3621 V = BitcodeConstant::create(
3622 Alloc, CurTy, Instruction::ShuffleVector,
3623 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3624 break;
3625 }
3626 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3627 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3628 VectorType *OpTy =
3629 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3630 if (Record.size() < 4 || !RTy || !OpTy)
3631 return error("Invalid shufflevector constexpr record");
3632 V = BitcodeConstant::create(
3633 Alloc, CurTy, Instruction::ShuffleVector,
3634 {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3635 break;
3636 }
3637 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3638 if (Record.size() < 4)
3639 return error("Invalid cmp constexpt record");
3640 unsigned OpTyID = Record[0];
3641 Type *OpTy = getTypeByID(OpTyID);
3642 if (!OpTy)
3643 return error("Invalid cmp constexpr record");
3644 V = BitcodeConstant::create(
3645 Alloc, CurTy,
3646 {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3647 : Instruction::ICmp),
3648 (uint8_t)Record[3]},
3649 {(unsigned)Record[1], (unsigned)Record[2]});
3650 break;
3651 }
3652 // This maintains backward compatibility, pre-asm dialect keywords.
3653 // Deprecated, but still needed to read old bitcode files.
3655 if (Record.size() < 2)
3656 return error("Invalid inlineasm record");
3657 std::string AsmStr, ConstrStr;
3658 bool HasSideEffects = Record[0] & 1;
3659 bool IsAlignStack = Record[0] >> 1;
3660 unsigned AsmStrSize = Record[1];
3661 if (2+AsmStrSize >= Record.size())
3662 return error("Invalid inlineasm record");
3663 unsigned ConstStrSize = Record[2+AsmStrSize];
3664 if (3+AsmStrSize+ConstStrSize > Record.size())
3665 return error("Invalid inlineasm record");
3666
3667 for (unsigned i = 0; i != AsmStrSize; ++i)
3668 AsmStr += (char)Record[2+i];
3669 for (unsigned i = 0; i != ConstStrSize; ++i)
3670 ConstrStr += (char)Record[3+AsmStrSize+i];
3671 UpgradeInlineAsmString(&AsmStr);
3672 if (!CurElemTy)
3673 return error("Missing element type for old-style inlineasm");
3674 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3675 HasSideEffects, IsAlignStack);
3676 break;
3677 }
3678 // This version adds support for the asm dialect keywords (e.g.,
3679 // inteldialect).
3681 if (Record.size() < 2)
3682 return error("Invalid inlineasm record");
3683 std::string AsmStr, ConstrStr;
3684 bool HasSideEffects = Record[0] & 1;
3685 bool IsAlignStack = (Record[0] >> 1) & 1;
3686 unsigned AsmDialect = Record[0] >> 2;
3687 unsigned AsmStrSize = Record[1];
3688 if (2+AsmStrSize >= Record.size())
3689 return error("Invalid inlineasm record");
3690 unsigned ConstStrSize = Record[2+AsmStrSize];
3691 if (3+AsmStrSize+ConstStrSize > Record.size())
3692 return error("Invalid inlineasm record");
3693
3694 for (unsigned i = 0; i != AsmStrSize; ++i)
3695 AsmStr += (char)Record[2+i];
3696 for (unsigned i = 0; i != ConstStrSize; ++i)
3697 ConstrStr += (char)Record[3+AsmStrSize+i];
3698 UpgradeInlineAsmString(&AsmStr);
3699 if (!CurElemTy)
3700 return error("Missing element type for old-style inlineasm");
3701 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3702 HasSideEffects, IsAlignStack,
3703 InlineAsm::AsmDialect(AsmDialect));
3704 break;
3705 }
3706 // This version adds support for the unwind keyword.
3708 if (Record.size() < 2)
3709 return error("Invalid inlineasm record");
3710 unsigned OpNum = 0;
3711 std::string AsmStr, ConstrStr;
3712 bool HasSideEffects = Record[OpNum] & 1;
3713 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3714 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3715 bool CanThrow = (Record[OpNum] >> 3) & 1;
3716 ++OpNum;
3717 unsigned AsmStrSize = Record[OpNum];
3718 ++OpNum;
3719 if (OpNum + AsmStrSize >= Record.size())
3720 return error("Invalid inlineasm record");
3721 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3722 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3723 return error("Invalid inlineasm record");
3724
3725 for (unsigned i = 0; i != AsmStrSize; ++i)
3726 AsmStr += (char)Record[OpNum + i];
3727 ++OpNum;
3728 for (unsigned i = 0; i != ConstStrSize; ++i)
3729 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3730 UpgradeInlineAsmString(&AsmStr);
3731 if (!CurElemTy)
3732 return error("Missing element type for old-style inlineasm");
3733 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3734 HasSideEffects, IsAlignStack,
3735 InlineAsm::AsmDialect(AsmDialect), CanThrow);
3736 break;
3737 }
3738 // This version adds explicit function type.
3740 if (Record.size() < 3)
3741 return error("Invalid inlineasm record");
3742 unsigned OpNum = 0;
3743 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
3744 ++OpNum;
3745 if (!FnTy)
3746 return error("Invalid inlineasm record");
3747 std::string AsmStr, ConstrStr;
3748 bool HasSideEffects = Record[OpNum] & 1;
3749 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3750 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3751 bool CanThrow = (Record[OpNum] >> 3) & 1;
3752 ++OpNum;
3753 unsigned AsmStrSize = Record[OpNum];
3754 ++OpNum;
3755 if (OpNum + AsmStrSize >= Record.size())
3756 return error("Invalid inlineasm record");
3757 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3758 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3759 return error("Invalid inlineasm record");
3760
3761 for (unsigned i = 0; i != AsmStrSize; ++i)
3762 AsmStr += (char)Record[OpNum + i];
3763 ++OpNum;
3764 for (unsigned i = 0; i != ConstStrSize; ++i)
3765 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3766 UpgradeInlineAsmString(&AsmStr);
3767 V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3768 InlineAsm::AsmDialect(AsmDialect), CanThrow);
3769 break;
3770 }
3772 if (Record.size() < 3)
3773 return error("Invalid blockaddress record");
3774 unsigned FnTyID = Record[0];
3775 Type *FnTy = getTypeByID(FnTyID);
3776 if (!FnTy)
3777 return error("Invalid blockaddress record");
3778 V = BitcodeConstant::create(
3779 Alloc, CurTy,
3780 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3781 Record[1]);
3782 break;
3783 }
3785 if (Record.size() < 2)
3786 return error("Invalid dso_local record");
3787 unsigned GVTyID = Record[0];
3788 Type *GVTy = getTypeByID(GVTyID);
3789 if (!GVTy)
3790 return error("Invalid dso_local record");
3791 V = BitcodeConstant::create(
3792 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3793 break;
3794 }
3796 if (Record.size() < 2)
3797 return error("Invalid no_cfi record");
3798 unsigned GVTyID = Record[0];
3799 Type *GVTy = getTypeByID(GVTyID);
3800 if (!GVTy)
3801 return error("Invalid no_cfi record");
3802 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3803 Record[1]);
3804 break;
3805 }
3807 if (Record.size() < 4)
3808 return error("Invalid ptrauth record");
3809 // Ptr, Key, Disc, AddrDisc
3810 V = BitcodeConstant::create(Alloc, CurTy,
3811 BitcodeConstant::ConstantPtrAuthOpcode,
3812 {(unsigned)Record[0], (unsigned)Record[1],
3813 (unsigned)Record[2], (unsigned)Record[3]});
3814 break;
3815 }
3816 }
3817
3818 assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3819 if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3820 return Err;
3821 ++NextCstNo;
3822 }
3823}
3824
3825Error BitcodeReader::parseUseLists() {
3826 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3827 return Err;
3828
3829 // Read all the records.
3830 SmallVector<uint64_t, 64> Record;
3831
3832 while (true) {
3833 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3834 if (!MaybeEntry)
3835 return MaybeEntry.takeError();
3836 BitstreamEntry Entry = MaybeEntry.get();
3837
3838 switch (Entry.Kind) {
3839 case BitstreamEntry::SubBlock: // Handled for us already.
3841 return error("Malformed block");
3843 return Error::success();
3845 // The interesting case.
3846 break;
3847 }
3848
3849 // Read a use list record.
3850 Record.clear();
3851 bool IsBB = false;
3852 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3853 if (!MaybeRecord)
3854 return MaybeRecord.takeError();
3855 switch (MaybeRecord.get()) {
3856 default: // Default behavior: unknown type.
3857 break;
3859 IsBB = true;
3860 [[fallthrough]];
3862 unsigned RecordLength = Record.size();
3863 if (RecordLength < 3)
3864 // Records should have at least an ID and two indexes.
3865 return error("Invalid record");
3866 unsigned ID = Record.pop_back_val();
3867
3868 Value *V;
3869 if (IsBB) {
3870 assert(ID < FunctionBBs.size() && "Basic block not found");
3871 V = FunctionBBs[ID];
3872 } else
3873 V = ValueList[ID];
3874
3875 if (!V->hasUseList())
3876 break;
3877
3878 unsigned NumUses = 0;
3879 SmallDenseMap<const Use *, unsigned, 16> Order;
3880 for (const Use &U : V->materialized_uses()) {
3881 if (++NumUses > Record.size())
3882 break;
3883 Order[&U] = Record[NumUses - 1];
3884 }
3885 if (Order.size() != Record.size() || NumUses > Record.size())
3886 // Mismatches can happen if the functions are being materialized lazily
3887 // (out-of-order), or a value has been upgraded.
3888 break;
3889
3890 V->sortUseList([&](const Use &L, const Use &R) {
3891 return Order.lookup(&L) < Order.lookup(&R);
3892 });
3893 break;
3894 }
3895 }
3896 }
3897}
3898
3899/// When we see the block for metadata, remember where it is and then skip it.
3900/// This lets us lazily deserialize the metadata.
3901Error BitcodeReader::rememberAndSkipMetadata() {
3902 // Save the current stream state.
3903 uint64_t CurBit = Stream.GetCurrentBitNo();
3904 DeferredMetadataInfo.push_back(CurBit);
3905
3906 // Skip over the block for now.
3907 if (Error Err = Stream.SkipBlock())
3908 return Err;
3909 return Error::success();
3910}
3911
3912Error BitcodeReader::materializeMetadata() {
3913 for (uint64_t BitPos : DeferredMetadataInfo) {
3914 // Move the bit stream to the saved position.
3915 if (Error JumpFailed = Stream.JumpToBit(BitPos))
3916 return JumpFailed;
3917 if (Error Err = MDLoader->parseModuleMetadata())
3918 return Err;
3919 }
3920
3921 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3922 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3923 // multiple times.
3924 if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3925 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3926 NamedMDNode *LinkerOpts =
3927 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3928 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3929 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3930 }
3931 }
3932
3933 DeferredMetadataInfo.clear();
3934 return Error::success();
3935}
3936
3937void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3938
3939/// When we see the block for a function body, remember where it is and then
3940/// skip it. This lets us lazily deserialize the functions.
3941Error BitcodeReader::rememberAndSkipFunctionBody() {
3942 // Get the function we are talking about.
3943 if (FunctionsWithBodies.empty())
3944 return error("Insufficient function protos");
3945
3946 Function *Fn = FunctionsWithBodies.back();
3947 FunctionsWithBodies.pop_back();
3948
3949 // Save the current stream state.
3950 uint64_t CurBit = Stream.GetCurrentBitNo();
3951 assert(
3952 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3953 "Mismatch between VST and scanned function offsets");
3954 DeferredFunctionInfo[Fn] = CurBit;
3955
3956 // Skip over the function block for now.
3957 if (Error Err = Stream.SkipBlock())
3958 return Err;
3959 return Error::success();
3960}
3961
3962Error BitcodeReader::globalCleanup() {
3963 // Patch the initializers for globals and aliases up.
3964 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3965 return Err;
3966 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3967 return error("Malformed global initializer set");
3968
3969 // Look for intrinsic functions which need to be upgraded at some point
3970 // and functions that need to have their function attributes upgraded.
3971 for (Function &F : *TheModule) {
3972 MDLoader->upgradeDebugIntrinsics(F);
3973 Function *NewFn;
3974 if (UpgradeIntrinsicFunction(&F, NewFn))
3975 UpgradedIntrinsics[&F] = NewFn;
3976 // Look for functions that rely on old function attribute behavior.
3978 }
3979
3980 // Look for global variables which need to be renamed.
3981 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3982 for (GlobalVariable &GV : TheModule->globals())
3983 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3984 UpgradedVariables.emplace_back(&GV, Upgraded);
3985 for (auto &Pair : UpgradedVariables) {
3986 Pair.first->eraseFromParent();
3987 TheModule->insertGlobalVariable(Pair.second);
3988 }
3989
3990 // Force deallocation of memory for these vectors to favor the client that
3991 // want lazy deserialization.
3992 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3993 std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3994 return Error::success();
3995}
3996
3997/// Support for lazy parsing of function bodies. This is required if we
3998/// either have an old bitcode file without a VST forward declaration record,
3999/// or if we have an anonymous function being materialized, since anonymous
4000/// functions do not have a name and are therefore not in the VST.
4001Error BitcodeReader::rememberAndSkipFunctionBodies() {
4002 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
4003 return JumpFailed;
4004
4005 if (Stream.AtEndOfStream())
4006 return error("Could not find function in stream");
4007
4008 if (!SeenFirstFunctionBody)
4009 return error("Trying to materialize functions before seeing function blocks");
4010
4011 // An old bitcode file with the symbol table at the end would have
4012 // finished the parse greedily.
4013 assert(SeenValueSymbolTable);
4014
4015 while (true) {
4016 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4017 if (!MaybeEntry)
4018 return MaybeEntry.takeError();
4019 llvm::BitstreamEntry Entry = MaybeEntry.get();
4020
4021 switch (Entry.Kind) {
4022 default:
4023 return error("Expect SubBlock");
4025 switch (Entry.ID) {
4026 default:
4027 return error("Expect function block");
4029 if (Error Err = rememberAndSkipFunctionBody())
4030 return Err;
4031 NextUnreadBit = Stream.GetCurrentBitNo();
4032 return Error::success();
4033 }
4034 }
4035 }
4036}
4037
4038Error BitcodeReaderBase::readBlockInfo() {
4039 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4040 Stream.ReadBlockInfoBlock();
4041 if (!MaybeNewBlockInfo)
4042 return MaybeNewBlockInfo.takeError();
4043 std::optional<BitstreamBlockInfo> NewBlockInfo =
4044 std::move(MaybeNewBlockInfo.get());
4045 if (!NewBlockInfo)
4046 return error("Malformed block");
4047 BlockInfo = std::move(*NewBlockInfo);
4048 return Error::success();
4049}
4050
4051Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4052 // v1: [selection_kind, name]
4053 // v2: [strtab_offset, strtab_size, selection_kind]
4054 StringRef Name;
4055 std::tie(Name, Record) = readNameFromStrtab(Record);
4056
4057 if (Record.empty())
4058 return error("Invalid record");
4060 std::string OldFormatName;
4061 if (!UseStrtab) {
4062 if (Record.size() < 2)
4063 return error("Invalid record");
4064 unsigned ComdatNameSize = Record[1];
4065 if (ComdatNameSize > Record.size() - 2)
4066 return error("Comdat name size too large");
4067 OldFormatName.reserve(ComdatNameSize);
4068 for (unsigned i = 0; i != ComdatNameSize; ++i)
4069 OldFormatName += (char)Record[2 + i];
4070 Name = OldFormatName;
4071 }
4072 Comdat *C = TheModule->getOrInsertComdat(Name);
4073 C->setSelectionKind(SK);
4074 ComdatList.push_back(C);
4075 return Error::success();
4076}
4077
4078static void inferDSOLocal(GlobalValue *GV) {
4079 // infer dso_local from linkage and visibility if it is not encoded.
4080 if (GV->hasLocalLinkage() ||
4082 GV->setDSOLocal(true);
4083}
4084
4087 if (V & (1 << 0))
4088 Meta.NoAddress = true;
4089 if (V & (1 << 1))
4090 Meta.NoHWAddress = true;
4091 if (V & (1 << 2))
4092 Meta.Memtag = true;
4093 if (V & (1 << 3))
4094 Meta.IsDynInit = true;
4095 return Meta;
4096}
4097
4098Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4099 // v1: [pointer type, isconst, initid, linkage, alignment, section,
4100 // visibility, threadlocal, unnamed_addr, externally_initialized,
4101 // dllstorageclass, comdat, attributes, preemption specifier,
4102 // partition strtab offset, partition strtab size] (name in VST)
4103 // v2: [strtab_offset, strtab_size, v1]
4104 // v3: [v2, code_model]
4105 StringRef Name;
4106 std::tie(Name, Record) = readNameFromStrtab(Record);
4107
4108 if (Record.size() < 6)
4109 return error("Invalid record");
4110 unsigned TyID = Record[0];
4111 Type *Ty = getTypeByID(TyID);
4112 if (!Ty)
4113 return error("Invalid record");
4114 bool isConstant = Record[1] & 1;
4115 bool explicitType = Record[1] & 2;
4116 unsigned AddressSpace;
4117 if (explicitType) {
4118 AddressSpace = Record[1] >> 2;
4119 } else {
4120 if (!Ty->isPointerTy())
4121 return error("Invalid type for value");
4122 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
4123 TyID = getContainedTypeID(TyID);
4124 Ty = getTypeByID(TyID);
4125 if (!Ty)
4126 return error("Missing element type for old-style global");
4127 }
4128
4129 uint64_t RawLinkage = Record[3];
4131 MaybeAlign Alignment;
4132 if (Error Err = parseAlignmentValue(Record[4], Alignment))
4133 return Err;
4134 std::string Section;
4135 if (Record[5]) {
4136 if (Record[5] - 1 >= SectionTable.size())
4137 return error("Invalid ID");
4138 Section = SectionTable[Record[5] - 1];
4139 }
4141 // Local linkage must have default visibility.
4142 // auto-upgrade `hidden` and `protected` for old bitcode.
4143 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
4144 Visibility = getDecodedVisibility(Record[6]);
4145
4146 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4147 if (Record.size() > 7)
4148 TLM = getDecodedThreadLocalMode(Record[7]);
4149
4150 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4151 if (Record.size() > 8)
4152 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
4153
4154 bool ExternallyInitialized = false;
4155 if (Record.size() > 9)
4156 ExternallyInitialized = Record[9];
4157
4158 GlobalVariable *NewGV =
4159 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
4160 nullptr, TLM, AddressSpace, ExternallyInitialized);
4161 if (Alignment)
4162 NewGV->setAlignment(*Alignment);
4163 if (!Section.empty())
4164 NewGV->setSection(Section);
4165 NewGV->setVisibility(Visibility);
4166 NewGV->setUnnamedAddr(UnnamedAddr);
4167
4168 if (Record.size() > 10) {
4169 // A GlobalValue with local linkage cannot have a DLL storage class.
4170 if (!NewGV->hasLocalLinkage()) {
4172 }
4173 } else {
4174 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
4175 }
4176
4177 ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
4178
4179 // Remember which value to use for the global initializer.
4180 if (unsigned InitID = Record[2])
4181 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4182
4183 if (Record.size() > 11) {
4184 if (unsigned ComdatID = Record[11]) {
4185 if (ComdatID > ComdatList.size())
4186 return error("Invalid global variable comdat ID");
4187 NewGV->setComdat(ComdatList[ComdatID - 1]);
4188 }
4189 } else if (hasImplicitComdat(RawLinkage)) {
4190 ImplicitComdatObjects.insert(NewGV);
4191 }
4192
4193 if (Record.size() > 12) {
4194 auto AS = getAttributes(Record[12]).getFnAttrs();
4195 NewGV->setAttributes(AS);
4196 }
4197
4198 if (Record.size() > 13) {
4199 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
4200 }
4201 inferDSOLocal(NewGV);
4202
4203 // Check whether we have enough values to read a partition name.
4204 if (Record.size() > 15)
4205 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
4206
4207 if (Record.size() > 16 && Record[16]) {
4208 llvm::GlobalValue::SanitizerMetadata Meta =
4209 deserializeSanitizerMetadata(Record[16]);
4210 NewGV->setSanitizerMetadata(Meta);
4211 }
4212
4213 if (Record.size() > 17 && Record[17]) {
4214 if (auto CM = getDecodedCodeModel(Record[17]))
4215 NewGV->setCodeModel(*CM);
4216 else
4217 return error("Invalid global variable code model");
4218 }
4219
4220 return Error::success();
4221}
4222
4223void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
4224 if (ValueTypeCallback) {
4225 (*ValueTypeCallback)(
4226 F, TypeID, [this](unsigned I) { return getTypeByID(I); },
4227 [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
4228 }
4229}
4230
4231Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4232 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
4233 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
4234 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
4235 // v2: [strtab_offset, strtab_size, v1]
4236 StringRef Name;
4237 std::tie(Name, Record) = readNameFromStrtab(Record);
4238
4239 if (Record.size() < 8)
4240 return error("Invalid record");
4241 unsigned FTyID = Record[0];
4242 Type *FTy = getTypeByID(FTyID);
4243 if (!FTy)
4244 return error("Invalid record");
4245 if (isa<PointerType>(FTy)) {
4246 FTyID = getContainedTypeID(FTyID, 0);
4247 FTy = getTypeByID(FTyID);
4248 if (!FTy)
4249 return error("Missing element type for old-style function");
4250 }
4251
4252 if (!isa<FunctionType>(FTy))
4253 return error("Invalid type for value");
4254 auto CC = static_cast<CallingConv::ID>(Record[1]);
4255 if (CC & ~CallingConv::MaxID)
4256 return error("Invalid calling convention ID");
4257
4258 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4259 if (Record.size() > 16)
4260 AddrSpace = Record[16];
4261
4262 Function *Func =
4264 AddrSpace, Name, TheModule);
4265
4266 assert(Func->getFunctionType() == FTy &&
4267 "Incorrect fully specified type provided for function");
4268 FunctionTypeIDs[Func] = FTyID;
4269
4270 Func->setCallingConv(CC);
4271 bool isProto = Record[2];
4272 uint64_t RawLinkage = Record[3];
4273 Func->setLinkage(getDecodedLinkage(RawLinkage));
4274 Func->setAttributes(getAttributes(Record[4]));
4275 callValueTypeCallback(Func, FTyID);
4276
4277 // Upgrade any old-style byval or sret without a type by propagating the
4278 // argument's pointee type. There should be no opaque pointers where the byval
4279 // type is implicit.
4280 for (unsigned i = 0; i != Func->arg_size(); ++i) {
4281 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4282 Attribute::InAlloca}) {
4283 if (!Func->hasParamAttribute(i, Kind))
4284 continue;
4285
4286 if (Func->getParamAttribute(i, Kind).getValueAsType())
4287 continue;
4288
4289 Func->removeParamAttr(i, Kind);
4290
4291 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4292 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4293 if (!PtrEltTy)
4294 return error("Missing param element type for attribute upgrade");
4295
4296 Attribute NewAttr;
4297 switch (Kind) {
4298 case Attribute::ByVal:
4299 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4300 break;
4301 case Attribute::StructRet:
4302 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4303 break;
4304 case Attribute::InAlloca:
4305 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4306 break;
4307 default:
4308 llvm_unreachable("not an upgraded type attribute");
4309 }
4310
4311 Func->addParamAttr(i, NewAttr);
4312 }
4313 }
4314
4315 if (Func->getCallingConv() == CallingConv::X86_INTR &&
4316 !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
4317 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4318 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4319 if (!ByValTy)
4320 return error("Missing param element type for x86_intrcc upgrade");
4321 Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
4322 Func->addParamAttr(0, NewAttr);
4323 }
4324
4325 MaybeAlign Alignment;
4326 if (Error Err = parseAlignmentValue(Record[5], Alignment))
4327 return Err;
4328 if (Alignment)
4329 Func->setAlignment(*Alignment);
4330 if (Record[6]) {
4331 if (Record[6] - 1 >= SectionTable.size())
4332 return error("Invalid ID");
4333 Func->setSection(SectionTable[Record[6] - 1]);
4334 }
4335 // Local linkage must have default visibility.
4336 // auto-upgrade `hidden` and `protected` for old bitcode.
4337 if (!Func->hasLocalLinkage())
4338 Func->setVisibility(getDecodedVisibility(Record[7]));
4339 if (Record.size() > 8 && Record[8]) {
4340 if (Record[8] - 1 >= GCTable.size())
4341 return error("Invalid ID");
4342 Func->setGC(GCTable[Record[8] - 1]);
4343 }
4344 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4345 if (Record.size() > 9)
4346 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
4347 Func->setUnnamedAddr(UnnamedAddr);
4348
4349 FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4350 if (Record.size() > 10)
4351 OperandInfo.Prologue = Record[10];
4352
4353 if (Record.size() > 11) {
4354 // A GlobalValue with local linkage cannot have a DLL storage class.
4355 if (!Func->hasLocalLinkage()) {
4356 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4357 }
4358 } else {
4359 upgradeDLLImportExportLinkage(Func, RawLinkage);
4360 }
4361
4362 if (Record.size() > 12) {
4363 if (unsigned ComdatID = Record[12]) {
4364 if (ComdatID > ComdatList.size())
4365 return error("Invalid function comdat ID");
4366 Func->setComdat(ComdatList[ComdatID - 1]);
4367 }
4368 } else if (hasImplicitComdat(RawLinkage)) {
4369 ImplicitComdatObjects.insert(Func);
4370 }
4371
4372 if (Record.size() > 13)
4373 OperandInfo.Prefix = Record[13];
4374
4375 if (Record.size() > 14)
4376 OperandInfo.PersonalityFn = Record[14];
4377
4378 if (Record.size() > 15) {
4379 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
4380 }
4381 inferDSOLocal(Func);
4382
4383 // Record[16] is the address space number.
4384
4385 // Check whether we have enough values to read a partition name. Also make
4386 // sure Strtab has enough values.
4387 if (Record.size() > 18 && Strtab.data() &&
4388 Record[17] + Record[18] <= Strtab.size()) {
4389 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4390 }
4391
4392 ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
4393
4394 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4395 FunctionOperands.push_back(OperandInfo);
4396
4397 // If this is a function with a body, remember the prototype we are
4398 // creating now, so that we can match up the body with them later.
4399 if (!isProto) {
4400 Func->setIsMaterializable(true);
4401 FunctionsWithBodies.push_back(Func);
4402 DeferredFunctionInfo[Func] = 0;
4403 }
4404 return Error::success();
4405}
4406
4407Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4408 unsigned BitCode, ArrayRef<uint64_t> Record) {
4409 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4410 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4411 // dllstorageclass, threadlocal, unnamed_addr,
4412 // preemption specifier] (name in VST)
4413 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4414 // visibility, dllstorageclass, threadlocal, unnamed_addr,
4415 // preemption specifier] (name in VST)
4416 // v2: [strtab_offset, strtab_size, v1]
4417 StringRef Name;
4418 std::tie(Name, Record) = readNameFromStrtab(Record);
4419
4420 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4421 if (Record.size() < (3 + (unsigned)NewRecord))
4422 return error("Invalid record");
4423 unsigned OpNum = 0;
4424 unsigned TypeID = Record[OpNum++];
4425 Type *Ty = getTypeByID(TypeID);
4426 if (!Ty)
4427 return error("Invalid record");
4428
4429 unsigned AddrSpace;
4430 if (!NewRecord) {
4431 auto *PTy = dyn_cast<PointerType>(Ty);
4432 if (!PTy)
4433 return error("Invalid type for value");
4434 AddrSpace = PTy->getAddressSpace();
4435 TypeID = getContainedTypeID(TypeID);
4436 Ty = getTypeByID(TypeID);
4437 if (!Ty)
4438 return error("Missing element type for old-style indirect symbol");
4439 } else {
4440 AddrSpace = Record[OpNum++];
4441 }
4442
4443 auto Val = Record[OpNum++];
4444 auto Linkage = Record[OpNum++];
4445 GlobalValue *NewGA;
4446 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4447 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4448 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4449 TheModule);
4450 else
4451 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4452 nullptr, TheModule);
4453
4454 // Local linkage must have default visibility.
4455 // auto-upgrade `hidden` and `protected` for old bitcode.
4456 if (OpNum != Record.size()) {
4457 auto VisInd = OpNum++;
4458 if (!NewGA->hasLocalLinkage())
4459 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4460 }
4461 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4462 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4463 if (OpNum != Record.size()) {
4464 auto S = Record[OpNum++];
4465 // A GlobalValue with local linkage cannot have a DLL storage class.
4466 if (!NewGA->hasLocalLinkage())
4468 }
4469 else
4471 if (OpNum != Record.size())
4472 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4473 if (OpNum != Record.size())
4474 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4475 }
4476 if (OpNum != Record.size())
4477 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4478 inferDSOLocal(NewGA);
4479
4480 // Check whether we have enough values to read a partition name.
4481 if (OpNum + 1 < Record.size()) {
4482 // Check Strtab has enough values for the partition.
4483 if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4484 return error("Malformed partition, too large.");
4485 NewGA->setPartition(
4486 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4487 }
4488
4489 ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4490 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4491 return Error::success();
4492}
4493
4494Error BitcodeReader::parseModule(uint64_t ResumeBit,
4495 bool ShouldLazyLoadMetadata,
4496 ParserCallbacks Callbacks) {
4497 this->ValueTypeCallback = std::move(Callbacks.ValueType);
4498 if (ResumeBit) {
4499 if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4500 return JumpFailed;
4501 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4502 return Err;
4503
4504 SmallVector<uint64_t, 64> Record;
4505
4506 // Parts of bitcode parsing depend on the datalayout. Make sure we
4507 // finalize the datalayout before we run any of that code.
4508 bool ResolvedDataLayout = false;
4509 // In order to support importing modules with illegal data layout strings,
4510 // delay parsing the data layout string until after upgrades and overrides
4511 // have been applied, allowing to fix illegal data layout strings.
4512 // Initialize to the current module's layout string in case none is specified.
4513 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4514
4515 auto ResolveDataLayout = [&]() -> Error {
4516 if (ResolvedDataLayout)
4517 return Error::success();
4518
4519 // Datalayout and triple can't be parsed after this point.
4520 ResolvedDataLayout = true;
4521
4522 // Auto-upgrade the layout string
4523 TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4524 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4525
4526 // Apply override
4527 if (Callbacks.DataLayout) {
4528 if (auto LayoutOverride = (*Callbacks.DataLayout)(
4529 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4530 TentativeDataLayoutStr = *LayoutOverride;
4531 }
4532
4533 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4534 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4535 if (!MaybeDL)
4536 return MaybeDL.takeError();
4537
4538 TheModule->setDataLayout(MaybeDL.get());
4539 return Error::success();
4540 };
4541
4542 // Read all the records for this module.
4543 while (true) {
4544 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4545 if (!MaybeEntry)
4546 return MaybeEntry.takeError();
4547 llvm::BitstreamEntry Entry = MaybeEntry.get();
4548
4549 switch (Entry.Kind) {
4551 return error("Malformed block");
4553 if (Error Err = ResolveDataLayout())
4554 return Err;
4555 return globalCleanup();
4556
4558 switch (Entry.ID) {
4559 default: // Skip unknown content.
4560 if (Error Err = Stream.SkipBlock())
4561 return Err;
4562 break;
4564 if (Error Err = readBlockInfo())
4565 return Err;
4566 break;
4568 if (Error Err = parseAttributeBlock())
4569 return Err;
4570 break;
4572 if (Error Err = parseAttributeGroupBlock())
4573 return Err;
4574 break;
4576 if (Error Err = parseTypeTable())
4577 return Err;
4578 break;
4580 if (!SeenValueSymbolTable) {
4581 // Either this is an old form VST without function index and an
4582 // associated VST forward declaration record (which would have caused
4583 // the VST to be jumped to and parsed before it was encountered
4584 // normally in the stream), or there were no function blocks to
4585 // trigger an earlier parsing of the VST.
4586 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4587 if (Error Err = parseValueSymbolTable())
4588 return Err;
4589 SeenValueSymbolTable = true;
4590 } else {
4591 // We must have had a VST forward declaration record, which caused
4592 // the parser to jump to and parse the VST earlier.
4593 assert(VSTOffset > 0);
4594 if (Error Err = Stream.SkipBlock())
4595 return Err;
4596 }
4597 break;
4599 if (Error Err = parseConstants())
4600 return Err;
4601 if (Error Err = resolveGlobalAndIndirectSymbolInits())
4602 return Err;
4603 break;
4605 if (ShouldLazyLoadMetadata) {
4606 if (Error Err = rememberAndSkipMetadata())
4607 return Err;
4608 break;
4609 }
4610 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4611 if (Error Err = MDLoader->parseModuleMetadata())
4612 return Err;
4613 break;
4615 if (Error Err = MDLoader->parseMetadataKinds())
4616 return Err;
4617 break;
4619 if (Error Err = ResolveDataLayout())
4620 return Err;
4621
4622 // If this is the first function body we've seen, reverse the
4623 // FunctionsWithBodies list.
4624 if (!SeenFirstFunctionBody) {
4625 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4626 if (Error Err = globalCleanup())
4627 return Err;
4628 SeenFirstFunctionBody = true;
4629 }
4630
4631 if (VSTOffset > 0) {
4632 // If we have a VST forward declaration record, make sure we
4633 // parse the VST now if we haven't already. It is needed to
4634 // set up the DeferredFunctionInfo vector for lazy reading.
4635 if (!SeenValueSymbolTable) {
4636 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4637 return Err;
4638 SeenValueSymbolTable = true;
4639 // Fall through so that we record the NextUnreadBit below.
4640 // This is necessary in case we have an anonymous function that
4641 // is later materialized. Since it will not have a VST entry we
4642 // need to fall back to the lazy parse to find its offset.
4643 } else {
4644 // If we have a VST forward declaration record, but have already
4645 // parsed the VST (just above, when the first function body was
4646 // encountered here), then we are resuming the parse after
4647 // materializing functions. The ResumeBit points to the
4648 // start of the last function block recorded in the
4649 // DeferredFunctionInfo map. Skip it.
4650 if (Error Err = Stream.SkipBlock())
4651 return Err;
4652 continue;
4653 }
4654 }
4655
4656 // Support older bitcode files that did not have the function
4657 // index in the VST, nor a VST forward declaration record, as
4658 // well as anonymous functions that do not have VST entries.
4659 // Build the DeferredFunctionInfo vector on the fly.
4660 if (Error Err = rememberAndSkipFunctionBody())
4661 return Err;
4662
4663 // Suspend parsing when we reach the function bodies. Subsequent
4664 // materialization calls will resume it when necessary. If the bitcode
4665 // file is old, the symbol table will be at the end instead and will not
4666 // have been seen yet. In this case, just finish the parse now.
4667 if (SeenValueSymbolTable) {
4668 NextUnreadBit = Stream.GetCurrentBitNo();
4669 // After the VST has been parsed, we need to make sure intrinsic name
4670 // are auto-upgraded.
4671 return globalCleanup();
4672 }
4673 break;
4675 if (Error Err = parseUseLists())
4676 return Err;
4677 break;
4679 if (Error Err = parseOperandBundleTags())
4680 return Err;
4681 break;
4683 if (Error Err = parseSyncScopeNames())
4684 return Err;
4685 break;
4686 }
4687 continue;
4688
4690 // The interesting case.
4691 break;
4692 }
4693
4694 // Read a record.
4695 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4696 if (!MaybeBitCode)
4697 return MaybeBitCode.takeError();
4698 switch (unsigned BitCode = MaybeBitCode.get()) {
4699 default: break; // Default behavior, ignore unknown content.
4701 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4702 if (!VersionOrErr)
4703 return VersionOrErr.takeError();
4704 UseRelativeIDs = *VersionOrErr >= 1;
4705 break;
4706 }
4707 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4708 if (ResolvedDataLayout)
4709 return error("target triple too late in module");
4710 std::string S;
4711 if (convertToString(Record, 0, S))
4712 return error("Invalid record");
4713 TheModule->setTargetTriple(Triple(std::move(S)));
4714 break;
4715 }
4716 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
4717 if (ResolvedDataLayout)
4718 return error("datalayout too late in module");
4719 if (convertToString(Record, 0, TentativeDataLayoutStr))
4720 return error("Invalid record");
4721 break;
4722 }
4723 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
4724 std::string S;
4725 if (convertToString(Record, 0, S))
4726 return error("Invalid record");
4727 TheModule->setModuleInlineAsm(S);
4728 break;
4729 }
4730 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
4731 // Deprecated, but still needed to read old bitcode files.
4732 std::string S;
4733 if (convertToString(Record, 0, S))
4734 return error("Invalid record");
4735 // Ignore value.
4736 break;
4737 }
4738 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4739 std::string S;
4740 if (convertToString(Record, 0, S))
4741 return error("Invalid record");
4742 SectionTable.push_back(S);
4743 break;
4744 }
4745 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
4746 std::string S;
4747 if (convertToString(Record, 0, S))
4748 return error("Invalid record");
4749 GCTable.push_back(S);
4750 break;
4751 }
4753 if (Error Err = parseComdatRecord(Record))
4754 return Err;
4755 break;
4756 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4757 // written by ThinLinkBitcodeWriter. See
4758 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4759 // record
4760 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4762 if (Error Err = parseGlobalVarRecord(Record))
4763 return Err;
4764 break;
4766 if (Error Err = ResolveDataLayout())
4767 return Err;
4768 if (Error Err = parseFunctionRecord(Record))
4769 return Err;
4770 break;
4774 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4775 return Err;
4776 break;
4777 /// MODULE_CODE_VSTOFFSET: [offset]
4779 if (Record.empty())
4780 return error("Invalid record");
4781 // Note that we subtract 1 here because the offset is relative to one word
4782 // before the start of the identification or module block, which was
4783 // historically always the start of the regular bitcode header.
4784 VSTOffset = Record[0] - 1;
4785 break;
4786 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4788 SmallString<128> ValueName;
4789 if (convertToString(Record, 0, ValueName))
4790 return error("Invalid record");
4791 TheModule->setSourceFileName(ValueName);
4792 break;
4793 }
4794 Record.clear();
4795 }
4796 this->ValueTypeCallback = std::nullopt;
4797 return Error::success();
4798}
4799
4800Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4801 bool IsImporting,
4802 ParserCallbacks Callbacks) {
4803 TheModule = M;
4804 MetadataLoaderCallbacks MDCallbacks;
4805 MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4806 MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4807 return getContainedTypeID(I, J);
4808 };
4809 MDCallbacks.MDType = Callbacks.MDType;
4810 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4811 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4812}
4813
4814Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4815 if (!isa<PointerType>(PtrType))
4816 return error("Load/Store operand is not a pointer type");
4817 if (!PointerType::isLoadableOrStorableType(ValType))
4818 return error("Cannot load/store from pointer");
4819 return Error::success();
4820}
4821
4822Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4823 ArrayRef<unsigned> ArgTyIDs) {
4824 AttributeList Attrs = CB->getAttributes();
4825 for (unsigned i = 0; i != CB->arg_size(); ++i) {
4826 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4827 Attribute::InAlloca}) {
4828 if (!Attrs.hasParamAttr(i, Kind) ||
4829 Attrs.getParamAttr(i, Kind).getValueAsType())
4830 continue;
4831
4832 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4833 if (!PtrEltTy)
4834 return error("Missing element type for typed attribute upgrade");
4835
4836 Attribute NewAttr;
4837 switch (Kind) {
4838 case Attribute::ByVal:
4839 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4840 break;
4841 case Attribute::StructRet:
4842 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4843 break;
4844 case Attribute::InAlloca:
4845 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4846 break;
4847 default:
4848 llvm_unreachable("not an upgraded type attribute");
4849 }
4850
4851 Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4852 }
4853 }
4854
4855 if (CB->isInlineAsm()) {
4856 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4857 unsigned ArgNo = 0;
4858 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4859 if (!CI.hasArg())
4860 continue;
4861
4862 if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4863 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4864 if (!ElemTy)
4865 return error("Missing element type for inline asm upgrade");
4866 Attrs = Attrs.addParamAttribute(
4867 Context, ArgNo,
4868 Attribute::get(Context, Attribute::ElementType, ElemTy));
4869 }
4870
4871 ArgNo++;
4872 }
4873 }
4874
4875 switch (CB->getIntrinsicID()) {
4876 case Intrinsic::preserve_array_access_index:
4877 case Intrinsic::preserve_struct_access_index:
4878 case Intrinsic::aarch64_ldaxr:
4879 case Intrinsic::aarch64_ldxr:
4880 case Intrinsic::aarch64_stlxr:
4881 case Intrinsic::aarch64_stxr:
4882 case Intrinsic::arm_ldaex:
4883 case Intrinsic::arm_ldrex:
4884 case Intrinsic::arm_stlex:
4885 case Intrinsic::arm_strex: {
4886 unsigned ArgNo;
4887 switch (CB->getIntrinsicID()) {
4888 case Intrinsic::aarch64_stlxr:
4889 case Intrinsic::aarch64_stxr:
4890 case Intrinsic::arm_stlex:
4891 case Intrinsic::arm_strex:
4892 ArgNo = 1;
4893 break;
4894 default:
4895 ArgNo = 0;
4896 break;
4897 }
4898 if (!Attrs.getParamElementType(ArgNo)) {
4899 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4900 if (!ElTy)
4901 return error("Missing element type for elementtype upgrade");
4902 Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4903 Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4904 }
4905 break;
4906 }
4907 default:
4908 break;
4909 }
4910
4911 CB->setAttributes(Attrs);
4912 return Error::success();
4913}
4914
4915/// Lazily parse the specified function body block.
4916Error BitcodeReader::parseFunctionBody(Function *F) {
4917 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4918 return Err;
4919
4920 // Unexpected unresolved metadata when parsing function.
4921 if (MDLoader->hasFwdRefs())
4922 return error("Invalid function metadata: incoming forward references");
4923
4924 InstructionList.clear();
4925 unsigned ModuleValueListSize = ValueList.size();
4926 unsigned ModuleMDLoaderSize = MDLoader->size();
4927
4928 // Add all the function arguments to the value table.
4929 unsigned ArgNo = 0;
4930 unsigned FTyID = FunctionTypeIDs[F];
4931 for (Argument &I : F->args()) {
4932 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4933 assert(I.getType() == getTypeByID(ArgTyID) &&
4934 "Incorrect fully specified type for Function Argument");
4935 ValueList.push_back(&I, ArgTyID);
4936 ++ArgNo;
4937 }
4938 unsigned NextValueNo = ValueList.size();
4939 BasicBlock *CurBB = nullptr;
4940 unsigned CurBBNo = 0;
4941 // Block into which constant expressions from phi nodes are materialized.
4942 BasicBlock *PhiConstExprBB = nullptr;
4943 // Edge blocks for phi nodes into which constant expressions have been
4944 // expanded.
4945 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
4946 ConstExprEdgeBBs;
4947
4948 DebugLoc LastLoc;
4949 auto getLastInstruction = [&]() -> Instruction * {
4950 if (CurBB && !CurBB->empty())
4951 return &CurBB->back();
4952 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4953 !FunctionBBs[CurBBNo - 1]->empty())
4954 return &FunctionBBs[CurBBNo - 1]->back();
4955 return nullptr;
4956 };
4957
4958 std::vector<OperandBundleDef> OperandBundles;
4959
4960 // Read all the records.
4961 SmallVector<uint64_t, 64> Record;
4962
4963 while (true) {
4964 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4965 if (!MaybeEntry)
4966 return MaybeEntry.takeError();
4967 llvm::BitstreamEntry Entry = MaybeEntry.get();
4968
4969 switch (Entry.Kind) {
4971 return error("Malformed block");
4973 goto OutOfRecordLoop;
4974
4976 switch (Entry.ID) {
4977 default: // Skip unknown content.
4978 if (Error Err = Stream.SkipBlock())
4979 return Err;
4980 break;
4982 if (Error Err = parseConstants())
4983 return Err;
4984 NextValueNo = ValueList.size();
4985 break;
4987 if (Error Err = parseValueSymbolTable())
4988 return Err;
4989 break;
4991 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4992 return Err;
4993 break;
4995 assert(DeferredMetadataInfo.empty() &&
4996 "Must read all module-level metadata before function-level");
4997 if (Error Err = MDLoader->parseFunctionMetadata())
4998 return Err;
4999 break;
5001 if (Error Err = parseUseLists())
5002 return Err;
5003 break;
5004 }
5005 continue;
5006
5008 // The interesting case.
5009 break;
5010 }
5011
5012 // Read a record.
5013 Record.clear();
5014 Instruction *I = nullptr;
5015 unsigned ResTypeID = InvalidTypeID;
5016 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5017 if (!MaybeBitCode)
5018 return MaybeBitCode.takeError();
5019 switch (unsigned BitCode = MaybeBitCode.get()) {
5020 default: // Default behavior: reject
5021 return error("Invalid value");
5022 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
5023 if (Record.empty() || Record[0] == 0)
5024 return error("Invalid record");
5025 // Create all the basic blocks for the function.
5026 FunctionBBs.resize(Record[0]);
5027
5028 // See if anything took the address of blocks in this function.
5029 auto BBFRI = BasicBlockFwdRefs.find(F);
5030 if (BBFRI == BasicBlockFwdRefs.end()) {
5031 for (BasicBlock *&BB : FunctionBBs)
5032 BB = BasicBlock::Create(Context, "", F);
5033 } else {
5034 auto &BBRefs = BBFRI->second;
5035 // Check for invalid basic block references.
5036 if (BBRefs.size() > FunctionBBs.size())
5037 return error("Invalid ID");
5038 assert(!BBRefs.empty() && "Unexpected empty array");
5039 assert(!BBRefs.front() && "Invalid reference to entry block");
5040 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
5041 ++I)
5042 if (I < RE && BBRefs[I]) {
5043 BBRefs[I]->insertInto(F);
5044 FunctionBBs[I] = BBRefs[I];
5045 } else {
5046 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
5047 }
5048
5049 // Erase from the table.
5050 BasicBlockFwdRefs.erase(BBFRI);
5051 }
5052
5053 CurBB = FunctionBBs[0];
5054 continue;
5055 }
5056
5057 case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
5058 // The record should not be emitted if it's an empty list.
5059 if (Record.empty())
5060 return error("Invalid record");
5061 // When we have the RARE case of a BlockAddress Constant that is not
5062 // scoped to the Function it refers to, we need to conservatively
5063 // materialize the referred to Function, regardless of whether or not
5064 // that Function will ultimately be linked, otherwise users of
5065 // BitcodeReader might start splicing out Function bodies such that we
5066 // might no longer be able to materialize the BlockAddress since the
5067 // BasicBlock (and entire body of the Function) the BlockAddress refers
5068 // to may have been moved. In the case that the user of BitcodeReader
5069 // decides ultimately not to link the Function body, materializing here
5070 // could be considered wasteful, but it's better than a deserialization
5071 // failure as described. This keeps BitcodeReader unaware of complex
5072 // linkage policy decisions such as those use by LTO, leaving those
5073 // decisions "one layer up."
5074 for (uint64_t ValID : Record)
5075 if (auto *F = dyn_cast<Function>(ValueList[ValID]))
5076 BackwardRefFunctions.push_back(F);
5077 else
5078 return error("Invalid record");
5079
5080 continue;
5081
5082 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
5083 // This record indicates that the last instruction is at the same
5084 // location as the previous instruction with a location.
5085 I = getLastInstruction();
5086
5087 if (!I)
5088 return error("Invalid record");
5089 I->setDebugLoc(LastLoc);
5090 I = nullptr;
5091 continue;
5092
5093 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
5094 I = getLastInstruction();
5095 if (!I || Record.size() < 4)
5096 return error("Invalid record");
5097
5098 unsigned Line = Record[0], Col = Record[1];
5099 unsigned ScopeID = Record[2], IAID = Record[3];
5100 bool isImplicitCode = Record.size() >= 5 && Record[4];
5101 uint64_t AtomGroup = Record.size() == 7 ? Record[5] : 0;
5102 uint8_t AtomRank = Record.size() == 7 ? Record[6] : 0;
5103
5104 MDNode *Scope = nullptr, *IA = nullptr;
5105 if (ScopeID) {
5107 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5108 if (!Scope)
5109 return error("Invalid record");
5110 }
5111 if (IAID) {
5113 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5114 if (!IA)
5115 return error("Invalid record");
5116 }
5117
5118 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
5119 isImplicitCode, AtomGroup, AtomRank);
5120 I->setDebugLoc(LastLoc);
5121 I = nullptr;
5122 continue;
5123 }
5124 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
5125 unsigned OpNum = 0;
5126 Value *LHS;
5127 unsigned TypeID;
5128 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5129 OpNum+1 > Record.size())
5130 return error("Invalid record");
5131
5132 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
5133 if (Opc == -1)
5134 return error("Invalid record");
5136 ResTypeID = TypeID;
5137 InstructionList.push_back(I);
5138 if (OpNum < Record.size()) {
5139 if (isa<FPMathOperator>(I)) {
5140 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5141 if (FMF.any())
5142 I->setFastMathFlags(FMF);
5143 }
5144 }
5145 break;
5146 }
5147 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
5148 unsigned OpNum = 0;
5149 Value *LHS, *RHS;
5150 unsigned TypeID;
5151 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5152 popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
5153 CurBB) ||
5154 OpNum+1 > Record.size())
5155 return error("Invalid record");
5156
5157 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
5158 if (Opc == -1)
5159 return error("Invalid record");
5161 ResTypeID = TypeID;
5162 InstructionList.push_back(I);
5163 if (OpNum < Record.size()) {
5164 if (Opc == Instruction::Add ||
5165 Opc == Instruction::Sub ||
5166 Opc == Instruction::Mul ||
5167 Opc == Instruction::Shl) {
5168 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
5169 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
5170 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
5171 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
5172 } else if (Opc == Instruction::SDiv ||
5173 Opc == Instruction::UDiv ||
5174 Opc == Instruction::LShr ||
5175 Opc == Instruction::AShr) {
5176 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
5177 cast<BinaryOperator>(I)->setIsExact(true);
5178 } else if (Opc == Instruction::Or) {
5179 if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
5180 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
5181 } else if (isa<FPMathOperator>(I)) {
5182 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5183 if (FMF.any())
5184 I->setFastMathFlags(FMF);
5185 }
5186 }
5187 break;
5188 }
5189 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
5190 unsigned OpNum = 0;
5191 Value *Op;
5192 unsigned OpTypeID;
5193 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5194 OpNum + 1 > Record.size())
5195 return error("Invalid record");
5196
5197 ResTypeID = Record[OpNum++];
5198 Type *ResTy = getTypeByID(ResTypeID);
5199 int Opc = getDecodedCastOpcode(Record[OpNum++]);
5200
5201 if (Opc == -1 || !ResTy)
5202 return error("Invalid record");
5203 Instruction *Temp = nullptr;
5204 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
5205 if (Temp) {
5206 InstructionList.push_back(Temp);
5207 assert(CurBB && "No current BB?");
5208 Temp->insertInto(CurBB, CurBB->end());
5209 }
5210 } else {
5211 auto CastOp = (Instruction::CastOps)Opc;
5212 if (!CastInst::castIsValid(CastOp, Op, ResTy))
5213 return error("Invalid cast");
5214 I = CastInst::Create(CastOp, Op, ResTy);
5215 }
5216
5217 if (OpNum < Record.size()) {
5218 if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) {
5219 if (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))
5220 cast<PossiblyNonNegInst>(I)->setNonNeg(true);
5221 } else if (Opc == Instruction::Trunc) {
5222 if (Record[OpNum] & (1 << bitc::TIO_NO_UNSIGNED_WRAP))
5223 cast<TruncInst>(I)->setHasNoUnsignedWrap(true);
5224 if (Record[OpNum] & (1 << bitc::TIO_NO_SIGNED_WRAP))
5225 cast<TruncInst>(I)->setHasNoSignedWrap(true);
5226 }
5227 if (isa<FPMathOperator>(I)) {
5228 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5229 if (FMF.any())
5230 I->setFastMathFlags(FMF);
5231 }
5232 }
5233
5234 InstructionList.push_back(I);
5235 break;
5236 }
5239 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
5240 unsigned OpNum = 0;
5241
5242 unsigned TyID;
5243 Type *Ty;
5244 GEPNoWrapFlags NW;
5245
5246 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5247 NW = toGEPNoWrapFlags(Record[OpNum++]);
5248 TyID = Record[OpNum++];
5249 Ty = getTypeByID(TyID);
5250 } else {
5253 TyID = InvalidTypeID;
5254 Ty = nullptr;
5255 }
5256
5257 Value *BasePtr;
5258 unsigned BasePtrTypeID;
5259 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5260 CurBB))
5261 return error("Invalid record");
5262
5263 if (!Ty) {
5264 TyID = getContainedTypeID(BasePtrTypeID);
5265 if (BasePtr->getType()->isVectorTy())
5266 TyID = getContainedTypeID(TyID);
5267 Ty = getTypeByID(TyID);
5268 }
5269
5270 SmallVector<Value*, 16> GEPIdx;
5271 while (OpNum != Record.size()) {
5272 Value *Op;
5273 unsigned OpTypeID;
5274 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5275 return error("Invalid record");
5276 GEPIdx.push_back(Op);
5277 }
5278
5279 auto *GEP = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5280 I = GEP;
5281
5282 ResTypeID = TyID;
5283 if (cast<GEPOperator>(I)->getNumIndices() != 0) {
5284 auto GTI = std::next(gep_type_begin(I));
5285 for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
5286 unsigned SubType = 0;
5287 if (GTI.isStruct()) {
5288 ConstantInt *IdxC =
5289 Idx->getType()->isVectorTy()
5291 : cast<ConstantInt>(Idx);
5292 SubType = IdxC->getZExtValue();
5293 }
5294 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5295 ++GTI;
5296 }
5297 }
5298
5299 // At this point ResTypeID is the result element type. We need a pointer
5300 // or vector of pointer to it.
5301 ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
5302 if (I->getType()->isVectorTy())
5303 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5304
5305 InstructionList.push_back(I);
5306 GEP->setNoWrapFlags(NW);
5307 break;
5308 }
5309
5311 // EXTRACTVAL: [opty, opval, n x indices]
5312 unsigned OpNum = 0;
5313 Value *Agg;
5314 unsigned AggTypeID;
5315 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5316 return error("Invalid record");
5317 Type *Ty = Agg->getType();
5318
5319 unsigned RecSize = Record.size();
5320 if (OpNum == RecSize)
5321 return error("EXTRACTVAL: Invalid instruction with 0 indices");
5322
5323 SmallVector<unsigned, 4> EXTRACTVALIdx;
5324 ResTypeID = AggTypeID;
5325 for (; OpNum != RecSize; ++OpNum) {
5326 bool IsArray = Ty->isArrayTy();
5327 bool IsStruct = Ty->isStructTy();
5328 uint64_t Index = Record[OpNum];
5329
5330 if (!IsStruct && !IsArray)
5331 return error("EXTRACTVAL: Invalid type");
5332 if ((unsigned)Index != Index)
5333 return error("Invalid value");
5334 if (IsStruct && Index >= Ty->getStructNumElements())
5335 return error("EXTRACTVAL: Invalid struct index");
5336 if (IsArray && Index >= Ty->getArrayNumElements())
5337 return error("EXTRACTVAL: Invalid array index");
5338 EXTRACTVALIdx.push_back((unsigned)Index);
5339
5340 if (IsStruct) {
5341 Ty = Ty->getStructElementType(Index);
5342 ResTypeID = getContainedTypeID(ResTypeID, Index);
5343 } else {
5344 Ty = Ty->getArrayElementType();
5345 ResTypeID = getContainedTypeID(ResTypeID);
5346 }
5347 }
5348
5349 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
5350 InstructionList.push_back(I);
5351 break;
5352 }
5353
5355 // INSERTVAL: [opty, opval, opty, opval, n x indices]
5356 unsigned OpNum = 0;
5357 Value *Agg;
5358 unsigned AggTypeID;
5359 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5360 return error("Invalid record");
5361 Value *Val;
5362 unsigned ValTypeID;
5363 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5364 return error("Invalid record");
5365
5366 unsigned RecSize = Record.size();
5367 if (OpNum == RecSize)
5368 return error("INSERTVAL: Invalid instruction with 0 indices");
5369
5370 SmallVector<unsigned, 4> INSERTVALIdx;
5371 Type *CurTy = Agg->getType();
5372 for (; OpNum != RecSize; ++OpNum) {
5373 bool IsArray = CurTy->isArrayTy();
5374 bool IsStruct = CurTy->isStructTy();
5375 uint64_t Index = Record[OpNum];
5376
5377 if (!IsStruct && !IsArray)
5378 return error("INSERTVAL: Invalid type");
5379 if ((unsigned)Index != Index)
5380 return error("Invalid value");
5381 if (IsStruct && Index >= CurTy->getStructNumElements())
5382 return error("INSERTVAL: Invalid struct index");
5383 if (IsArray && Index >= CurTy->getArrayNumElements())
5384 return error("INSERTVAL: Invalid array index");
5385
5386 INSERTVALIdx.push_back((unsigned)Index);
5387 if (IsStruct)
5388 CurTy = CurTy->getStructElementType(Index);
5389 else
5390 CurTy = CurTy->getArrayElementType();
5391 }
5392
5393 if (CurTy != Val->getType())
5394 return error("Inserted value type doesn't match aggregate type");
5395
5396 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5397 ResTypeID = AggTypeID;
5398 InstructionList.push_back(I);
5399 break;
5400 }
5401
5402 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5403 // obsolete form of select
5404 // handles select i1 ... in old bitcode
5405 unsigned OpNum = 0;
5407 unsigned TypeID;
5408 Type *CondType = Type::getInt1Ty(Context);
5409 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5410 CurBB) ||
5411 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5412 FalseVal, CurBB) ||
5413 popValue(Record, OpNum, NextValueNo, CondType,
5414 getVirtualTypeID(CondType), Cond, CurBB))
5415 return error("Invalid record");
5416
5417 I = SelectInst::Create(Cond, TrueVal, FalseVal);
5418 ResTypeID = TypeID;
5419 InstructionList.push_back(I);
5420 break;
5421 }
5422
5423 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5424 // new form of select
5425 // handles select i1 or select [N x i1]
5426 unsigned OpNum = 0;
5428 unsigned ValTypeID, CondTypeID;
5429 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5430 CurBB) ||
5431 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5432 FalseVal, CurBB) ||
5433 getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
5434 return error("Invalid record");
5435
5436 // select condition can be either i1 or [N x i1]
5437 if (VectorType* vector_type =
5438 dyn_cast<VectorType>(Cond->getType())) {
5439 // expect <n x i1>
5440 if (vector_type->getElementType() != Type::getInt1Ty(Context))
5441 return error("Invalid type for value");
5442 } else {
5443 // expect i1
5444 if (Cond->getType() != Type::getInt1Ty(Context))
5445 return error("Invalid type for value");
5446 }
5447
5448 I = SelectInst::Create(Cond, TrueVal, FalseVal);
5449 ResTypeID = ValTypeID;
5450 InstructionList.push_back(I);
5451 if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5452 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5453 if (FMF.any())
5454 I->setFastMathFlags(FMF);
5455 }
5456 break;
5457 }
5458
5459 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5460 unsigned OpNum = 0;
5461 Value *Vec, *Idx;
5462 unsigned VecTypeID, IdxTypeID;
5463 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5464 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5465 return error("Invalid record");
5466 if (!Vec->getType()->isVectorTy())
5467 return error("Invalid type for value");
5468 I = ExtractElementInst::Create(Vec, Idx);
5469 ResTypeID = getContainedTypeID(VecTypeID);
5470 InstructionList.push_back(I);
5471 break;
5472 }
5473
5474 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5475 unsigned OpNum = 0;
5476 Value *Vec, *Elt, *Idx;
5477 unsigned VecTypeID, IdxTypeID;
5478 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5479 return error("Invalid record");
5480 if (!Vec->getType()->isVectorTy())
5481 return error("Invalid type for value");
5482 if (popValue(Record, OpNum, NextValueNo,
5483 cast<VectorType>(Vec->getType())->getElementType(),
5484 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5485 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5486 return error("Invalid record");
5487 I = InsertElementInst::Create(Vec, Elt, Idx);
5488 ResTypeID = VecTypeID;
5489 InstructionList.push_back(I);
5490 break;
5491 }
5492
5493 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5494 unsigned OpNum = 0;
5495 Value *Vec1, *Vec2, *Mask;
5496 unsigned Vec1TypeID;
5497 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5498 CurBB) ||
5499 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5500 Vec2, CurBB))
5501 return error("Invalid record");
5502
5503 unsigned MaskTypeID;
5504 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5505 return error("Invalid record");
5506 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5507 return error("Invalid type for value");
5508
5509 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5510 ResTypeID =
5511 getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5512 InstructionList.push_back(I);
5513 break;
5514 }
5515
5516 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
5517 // Old form of ICmp/FCmp returning bool
5518 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5519 // both legal on vectors but had different behaviour.
5520 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5521 // FCmp/ICmp returning bool or vector of bool
5522
5523 unsigned OpNum = 0;
5524 Value *LHS, *RHS;
5525 unsigned LHSTypeID;
5526 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5527 popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5528 CurBB))
5529 return error("Invalid record");
5530
5531 if (OpNum >= Record.size())
5532 return error(
5533 "Invalid record: operand number exceeded available operands");
5534
5535 CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5536 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5537 FastMathFlags FMF;
5538 if (IsFP && Record.size() > OpNum+1)
5539 FMF = getDecodedFastMathFlags(Record[++OpNum]);
5540
5541 if (IsFP) {
5542 if (!CmpInst::isFPPredicate(PredVal))
5543 return error("Invalid fcmp predicate");
5544 I = new FCmpInst(PredVal, LHS, RHS);
5545 } else {
5546 if (!CmpInst::isIntPredicate(PredVal))
5547 return error("Invalid icmp predicate");
5548 I = new ICmpInst(PredVal, LHS, RHS);
5549 if (Record.size() > OpNum + 1 &&
5550 (Record[++OpNum] & (1 << bitc::ICMP_SAME_SIGN)))
5551 cast<ICmpInst>(I)->setSameSign();
5552 }
5553
5554 if (OpNum + 1 != Record.size())
5555 return error("Invalid record");
5556
5557 ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5558 if (LHS->getType()->isVectorTy())
5559 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5560
5561 if (FMF.any())
5562 I->setFastMathFlags(FMF);
5563 InstructionList.push_back(I);
5564 break;
5565 }
5566
5567 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5568 {
5569 unsigned Size = Record.size();
5570 if (Size == 0) {
5572 InstructionList.push_back(I);
5573 break;
5574 }
5575
5576 unsigned OpNum = 0;
5577 Value *Op = nullptr;
5578 unsigned OpTypeID;
5579 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5580 return error("Invalid record");
5581 if (OpNum != Record.size())
5582 return error("Invalid record");
5583
5585 InstructionList.push_back(I);
5586 break;
5587 }
5588 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5589 if (Record.size() != 1 && Record.size() != 3)
5590 return error("Invalid record");
5591 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5592 if (!TrueDest)
5593 return error("Invalid record");
5594
5595 if (Record.size() == 1) {
5596 I = BranchInst::Create(TrueDest);
5597 InstructionList.push_back(I);
5598 }
5599 else {
5600 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5601 Type *CondType = Type::getInt1Ty(Context);
5602 Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5603 getVirtualTypeID(CondType), CurBB);
5604 if (!FalseDest || !Cond)
5605 return error("Invalid record");
5606 I = BranchInst::Create(TrueDest, FalseDest, Cond);
5607 InstructionList.push_back(I);
5608 }
5609 break;
5610 }
5611 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5612 if (Record.size() != 1 && Record.size() != 2)
5613 return error("Invalid record");
5614 unsigned Idx = 0;
5615 Type *TokenTy = Type::getTokenTy(Context);
5616 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5617 getVirtualTypeID(TokenTy), CurBB);
5618 if (!CleanupPad)
5619 return error("Invalid record");
5620 BasicBlock *UnwindDest = nullptr;
5621 if (Record.size() == 2) {
5622 UnwindDest = getBasicBlock(Record[Idx++]);
5623 if (!UnwindDest)
5624 return error("Invalid record");
5625 }
5626
5627 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5628 InstructionList.push_back(I);
5629 break;
5630 }
5631 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5632 if (Record.size() != 2)
5633 return error("Invalid record");
5634 unsigned Idx = 0;
5635 Type *TokenTy = Type::getTokenTy(Context);
5636 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5637 getVirtualTypeID(TokenTy), CurBB);
5638 if (!CatchPad)
5639 return error("Invalid record");
5640 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5641 if (!BB)
5642 return error("Invalid record");
5643
5644 I = CatchReturnInst::Create(CatchPad, BB);
5645 InstructionList.push_back(I);
5646 break;
5647 }
5648 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5649 // We must have, at minimum, the outer scope and the number of arguments.
5650 if (Record.size() < 2)
5651 return error("Invalid record");
5652
5653 unsigned Idx = 0;
5654
5655 Type *TokenTy = Type::getTokenTy(Context);
5656 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5657 getVirtualTypeID(TokenTy), CurBB);
5658 if (!ParentPad)
5659 return error("Invalid record");
5660
5661 unsigned NumHandlers = Record[Idx++];
5662
5664 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5665 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5666 if (!BB)
5667 return error("Invalid record");
5668 Handlers.push_back(BB);
5669 }
5670
5671 BasicBlock *UnwindDest = nullptr;
5672 if (Idx + 1 == Record.size()) {
5673 UnwindDest = getBasicBlock(Record[Idx++]);
5674 if (!UnwindDest)
5675 return error("Invalid record");
5676 }
5677
5678 if (Record.size() != Idx)
5679 return error("Invalid record");
5680
5681 auto *CatchSwitch =
5682 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5683 for (BasicBlock *Handler : Handlers)
5684 CatchSwitch->addHandler(Handler);
5685 I = CatchSwitch;
5686 ResTypeID = getVirtualTypeID(I->getType());
5687 InstructionList.push_back(I);
5688 break;
5689 }
5691 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5692 // We must have, at minimum, the outer scope and the number of arguments.
5693 if (Record.size() < 2)
5694 return error("Invalid record");
5695
5696 unsigned Idx = 0;
5697
5698 Type *TokenTy = Type::getTokenTy(Context);
5699 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5700 getVirtualTypeID(TokenTy), CurBB);
5701 if (!ParentPad)
5702 return error("Invald record");
5703
5704 unsigned NumArgOperands = Record[Idx++];
5705
5706 SmallVector<Value *, 2> Args;
5707 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5708 Value *Val;
5709 unsigned ValTypeID;
5710 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5711 return error("Invalid record");
5712 Args.push_back(Val);
5713 }
5714
5715 if (Record.size() != Idx)
5716 return error("Invalid record");
5717
5718 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5719 I = CleanupPadInst::Create(ParentPad, Args);
5720 else
5721 I = CatchPadInst::Create(ParentPad, Args);
5722 ResTypeID = getVirtualTypeID(I->getType());
5723 InstructionList.push_back(I);
5724 break;
5725 }
5726 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5727 // Check magic
5728 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5729 // "New" SwitchInst format with case ranges. The changes to write this
5730 // format were reverted but we still recognize bitcode that uses it.
5731 // Hopefully someday we will have support for case ranges and can use
5732 // this format again.
5733
5734 unsigned OpTyID = Record[1];
5735 Type *OpTy = getTypeByID(OpTyID);
5736 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5737
5738 Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5739 BasicBlock *Default = getBasicBlock(Record[3]);
5740 if (!OpTy || !Cond || !Default)
5741 return error("Invalid record");
5742
5743 unsigned NumCases = Record[4];
5744
5745 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5746 InstructionList.push_back(SI);
5747
5748 unsigned CurIdx = 5;
5749 for (unsigned i = 0; i != NumCases; ++i) {
5751 unsigned NumItems = Record[CurIdx++];
5752 for (unsigned ci = 0; ci != NumItems; ++ci) {
5753 bool isSingleNumber = Record[CurIdx++];
5754
5755 APInt Low;
5756 unsigned ActiveWords = 1;
5757 if (ValueBitWidth > 64)
5758 ActiveWords = Record[CurIdx++];
5759 Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5760 ValueBitWidth);
5761 CurIdx += ActiveWords;
5762
5763 if (!isSingleNumber) {
5764 ActiveWords = 1;
5765 if (ValueBitWidth > 64)
5766 ActiveWords = Record[CurIdx++];
5767 APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5768 ValueBitWidth);
5769 CurIdx += ActiveWords;
5770
5771 // FIXME: It is not clear whether values in the range should be
5772 // compared as signed or unsigned values. The partially
5773 // implemented changes that used this format in the past used
5774 // unsigned comparisons.
5775 for ( ; Low.ule(High); ++Low)
5776 CaseVals.push_back(ConstantInt::get(Context, Low));
5777 } else
5778 CaseVals.push_back(ConstantInt::get(Context, Low));
5779 }
5780 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5781 for (ConstantInt *Cst : CaseVals)
5782 SI->addCase(Cst, DestBB);
5783 }
5784 I = SI;
5785 break;
5786 }
5787
5788 // Old SwitchInst format without case ranges.
5789
5790 if (Record.size() < 3 || (Record.size() & 1) == 0)
5791 return error("Invalid record");
5792 unsigned OpTyID = Record[0];
5793 Type *OpTy = getTypeByID(OpTyID);
5794 Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5795 BasicBlock *Default = getBasicBlock(Record[2]);
5796 if (!OpTy || !Cond || !Default)
5797 return error("Invalid record");
5798 unsigned NumCases = (Record.size()-3)/2;
5799 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5800 InstructionList.push_back(SI);
5801 for (unsigned i = 0, e = NumCases; i != e; ++i) {
5802 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5803 getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5804 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5805 if (!CaseVal || !DestBB) {
5806 delete SI;
5807 return error("Invalid record");
5808 }
5809 SI->addCase(CaseVal, DestBB);
5810 }
5811 I = SI;
5812 break;
5813 }
5814 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5815 if (Record.size() < 2)
5816 return error("Invalid record");
5817 unsigned OpTyID = Record[0];
5818 Type *OpTy = getTypeByID(OpTyID);
5819 Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5820 if (!OpTy || !Address)
5821 return error("Invalid record");
5822 unsigned NumDests = Record.size()-2;
5823 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5824 InstructionList.push_back(IBI);
5825 for (unsigned i = 0, e = NumDests; i != e; ++i) {
5826 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5827 IBI->addDestination(DestBB);
5828 } else {
5829 delete IBI;
5830 return error("Invalid record");
5831 }
5832 }
5833 I = IBI;
5834 break;
5835 }
5836
5838 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5839 if (Record.size() < 4)
5840 return error("Invalid record");
5841 unsigned OpNum = 0;
5842 AttributeList PAL = getAttributes(Record[OpNum++]);
5843 unsigned CCInfo = Record[OpNum++];
5844 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5845 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5846
5847 unsigned FTyID = InvalidTypeID;
5848 FunctionType *FTy = nullptr;
5849 if ((CCInfo >> 13) & 1) {
5850 FTyID = Record[OpNum++];
5851 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5852 if (!FTy)
5853 return error("Explicit invoke type is not a function type");
5854 }
5855
5856 Value *Callee;
5857 unsigned CalleeTypeID;
5858 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5859 CurBB))
5860 return error("Invalid record");
5861
5862 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5863 if (!CalleeTy)
5864 return error("Callee is not a pointer");
5865 if (!FTy) {
5866 FTyID = getContainedTypeID(CalleeTypeID);
5867 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5868 if (!FTy)
5869 return error("Callee is not of pointer to function type");
5870 }
5871 if (Record.size() < FTy->getNumParams() + OpNum)
5872 return error("Insufficient operands to call");
5873
5874 SmallVector<Value*, 16> Ops;
5875 SmallVector<unsigned, 16> ArgTyIDs;
5876 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5877 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5878 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5879 ArgTyID, CurBB));
5880 ArgTyIDs.push_back(ArgTyID);
5881 if (!Ops.back())
5882 return error("Invalid record");
5883 }
5884
5885 if (!FTy->isVarArg()) {
5886 if (Record.size() != OpNum)
5887 return error("Invalid record");
5888 } else {
5889 // Read type/value pairs for varargs params.
5890 while (OpNum != Record.size()) {
5891 Value *Op;
5892 unsigned OpTypeID;
5893 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5894 return error("Invalid record");
5895 Ops.push_back(Op);
5896 ArgTyIDs.push_back(OpTypeID);
5897 }
5898 }
5899
5900 // Upgrade the bundles if needed.
5901 if (!OperandBundles.empty())
5902 UpgradeOperandBundles(OperandBundles);
5903
5904 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5905 OperandBundles);
5906 ResTypeID = getContainedTypeID(FTyID);
5907 OperandBundles.clear();
5908 InstructionList.push_back(I);
5909 cast<InvokeInst>(I)->setCallingConv(
5910 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5911 cast<InvokeInst>(I)->setAttributes(PAL);
5912 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5913 I->deleteValue();
5914 return Err;
5915 }
5916
5917 break;
5918 }
5919 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5920 unsigned Idx = 0;
5921 Value *Val = nullptr;
5922 unsigned ValTypeID;
5923 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5924 return error("Invalid record");
5925 I = ResumeInst::Create(Val);
5926 InstructionList.push_back(I);
5927 break;
5928 }
5930 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5931 unsigned OpNum = 0;
5932 AttributeList PAL = getAttributes(Record[OpNum++]);
5933 unsigned CCInfo = Record[OpNum++];
5934
5935 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5936 unsigned NumIndirectDests = Record[OpNum++];
5937 SmallVector<BasicBlock *, 16> IndirectDests;
5938 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5939 IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5940
5941 unsigned FTyID = InvalidTypeID;
5942 FunctionType *FTy = nullptr;
5943 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5944 FTyID = Record[OpNum++];
5945 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5946 if (!FTy)
5947 return error("Explicit call type is not a function type");
5948 }
5949
5950 Value *Callee;
5951 unsigned CalleeTypeID;
5952 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5953 CurBB))
5954 return error("Invalid record");
5955
5956 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5957 if (!OpTy)
5958 return error("Callee is not a pointer type");
5959 if (!FTy) {
5960 FTyID = getContainedTypeID(CalleeTypeID);
5961 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5962 if (!FTy)
5963 return error("Callee is not of pointer to function type");
5964 }
5965 if (Record.size() < FTy->getNumParams() + OpNum)
5966 return error("Insufficient operands to call");
5967
5968 SmallVector<Value*, 16> Args;
5969 SmallVector<unsigned, 16> ArgTyIDs;
5970 // Read the fixed params.
5971 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5972 Value *Arg;
5973 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5974 if (FTy->getParamType(i)->isLabelTy())
5975 Arg = getBasicBlock(Record[OpNum]);
5976 else
5977 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5978 ArgTyID, CurBB);
5979 if (!Arg)
5980 return error("Invalid record");
5981 Args.push_back(Arg);
5982 ArgTyIDs.push_back(ArgTyID);
5983 }
5984
5985 // Read type/value pairs for varargs params.
5986 if (!FTy->isVarArg()) {
5987 if (OpNum != Record.size())
5988 return error("Invalid record");
5989 } else {
5990 while (OpNum != Record.size()) {
5991 Value *Op;
5992 unsigned OpTypeID;
5993 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5994 return error("Invalid record");
5995 Args.push_back(Op);
5996 ArgTyIDs.push_back(OpTypeID);
5997 }
5998 }
5999
6000 // Upgrade the bundles if needed.
6001 if (!OperandBundles.empty())
6002 UpgradeOperandBundles(OperandBundles);
6003
6004 if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
6005 InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
6006 auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
6007 return CI.Type == InlineAsm::isLabel;
6008 };
6009 if (none_of(ConstraintInfo, IsLabelConstraint)) {
6010 // Upgrade explicit blockaddress arguments to label constraints.
6011 // Verify that the last arguments are blockaddress arguments that
6012 // match the indirect destinations. Clang always generates callbr
6013 // in this form. We could support reordering with more effort.
6014 unsigned FirstBlockArg = Args.size() - IndirectDests.size();
6015 for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
6016 unsigned LabelNo = ArgNo - FirstBlockArg;
6017 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
6018 if (!BA || BA->getFunction() != F ||
6019 LabelNo > IndirectDests.size() ||
6020 BA->getBasicBlock() != IndirectDests[LabelNo])
6021 return error("callbr argument does not match indirect dest");
6022 }
6023
6024 // Remove blockaddress arguments.
6025 Args.erase(Args.begin() + FirstBlockArg, Args.end());
6026 ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
6027
6028 // Recreate the function type with less arguments.
6029 SmallVector<Type *> ArgTys;
6030 for (Value *Arg : Args)
6031 ArgTys.push_back(Arg->getType());
6032 FTy =
6033 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6034
6035 // Update constraint string to use label constraints.
6036 std::string Constraints = IA->getConstraintString().str();
6037 unsigned ArgNo = 0;
6038 size_t Pos = 0;
6039 for (const auto &CI : ConstraintInfo) {
6040 if (CI.hasArg()) {
6041 if (ArgNo >= FirstBlockArg)
6042 Constraints.insert(Pos, "!");
6043 ++ArgNo;
6044 }
6045
6046 // Go to next constraint in string.
6047 Pos = Constraints.find(',', Pos);
6048 if (Pos == std::string::npos)
6049 break;
6050 ++Pos;
6051 }
6052
6053 Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
6054 IA->hasSideEffects(), IA->isAlignStack(),
6055 IA->getDialect(), IA->canThrow());
6056 }
6057 }
6058
6059 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
6060 OperandBundles);
6061 ResTypeID = getContainedTypeID(FTyID);
6062 OperandBundles.clear();
6063 InstructionList.push_back(I);
6064 cast<CallBrInst>(I)->setCallingConv(
6065 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6066 cast<CallBrInst>(I)->setAttributes(PAL);
6067 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6068 I->deleteValue();
6069 return Err;
6070 }
6071 break;
6072 }
6073 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
6074 I = new UnreachableInst(Context);
6075 InstructionList.push_back(I);
6076 break;
6077 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
6078 if (Record.empty())
6079 return error("Invalid phi record");
6080 // The first record specifies the type.
6081 unsigned TyID = Record[0];
6082 Type *Ty = getTypeByID(TyID);
6083 if (!Ty)
6084 return error("Invalid phi record");
6085
6086 // Phi arguments are pairs of records of [value, basic block].
6087 // There is an optional final record for fast-math-flags if this phi has a
6088 // floating-point type.
6089 size_t NumArgs = (Record.size() - 1) / 2;
6090 PHINode *PN = PHINode::Create(Ty, NumArgs);
6091 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
6092 PN->deleteValue();
6093 return error("Invalid phi record");
6094 }
6095 InstructionList.push_back(PN);
6096
6097 SmallDenseMap<BasicBlock *, Value *> Args;
6098 for (unsigned i = 0; i != NumArgs; i++) {
6099 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6100 if (!BB) {
6101 PN->deleteValue();
6102 return error("Invalid phi BB");
6103 }
6104
6105 // Phi nodes may contain the same predecessor multiple times, in which
6106 // case the incoming value must be identical. Directly reuse the already
6107 // seen value here, to avoid expanding a constant expression multiple
6108 // times.
6109 auto It = Args.find(BB);
6110 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
6111 if (It != Args.end()) {
6112 // If this predecessor was also replaced with a constexpr basic
6113 // block, it must be de-duplicated.
6114 if (!EdgeBB) {
6115 PN->addIncoming(It->second, BB);
6116 }
6117 continue;
6118 }
6119
6120 // If there already is a block for this edge (from a different phi),
6121 // use it.
6122 if (!EdgeBB) {
6123 // Otherwise, use a temporary block (that we will discard if it
6124 // turns out to be unnecessary).
6125 if (!PhiConstExprBB)
6126 PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
6127 EdgeBB = PhiConstExprBB;
6128 }
6129
6130 // With the new function encoding, it is possible that operands have
6131 // negative IDs (for forward references). Use a signed VBR
6132 // representation to keep the encoding small.
6133 Value *V;
6134 if (UseRelativeIDs)
6135 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6136 else
6137 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6138 if (!V) {
6139 PN->deleteValue();
6140 PhiConstExprBB->eraseFromParent();
6141 return error("Invalid phi record");
6142 }
6143
6144 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
6145 ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
6146 PhiConstExprBB = nullptr;
6147 }
6148 PN->addIncoming(V, BB);
6149 Args.insert({BB, V});
6150 }
6151 I = PN;
6152 ResTypeID = TyID;
6153
6154 // If there are an even number of records, the final record must be FMF.
6155 if (Record.size() % 2 == 0) {
6156 assert(isa<FPMathOperator>(I) && "Unexpected phi type");
6157 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
6158 if (FMF.any())
6159 I->setFastMathFlags(FMF);
6160 }
6161
6162 break;
6163 }
6164
6167 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6168 unsigned Idx = 0;
6169 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
6170 if (Record.size() < 3)
6171 return error("Invalid record");
6172 } else {
6174 if (Record.size() < 4)
6175 return error("Invalid record");
6176 }
6177 ResTypeID = Record[Idx++];
6178 Type *Ty = getTypeByID(ResTypeID);
6179 if (!Ty)
6180 return error("Invalid record");
6181 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
6182 Value *PersFn = nullptr;
6183 unsigned PersFnTypeID;
6184 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6185 nullptr))
6186 return error("Invalid record");
6187
6188 if (!F->hasPersonalityFn())
6189 F->setPersonalityFn(cast<Constant>(PersFn));
6190 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
6191 return error("Personality function mismatch");
6192 }
6193
6194 bool IsCleanup = !!Record[Idx++];
6195 unsigned NumClauses = Record[Idx++];
6196 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
6197 LP->setCleanup(IsCleanup);
6198 for (unsigned J = 0; J != NumClauses; ++J) {
6200 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
6201 Value *Val;
6202 unsigned ValTypeID;
6203
6204 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6205 nullptr)) {
6206 delete LP;
6207 return error("Invalid record");
6208 }
6209
6211 !isa<ArrayType>(Val->getType())) &&
6212 "Catch clause has a invalid type!");
6214 isa<ArrayType>(Val->getType())) &&
6215 "Filter clause has invalid type!");
6216 LP->addClause(cast<Constant>(Val));
6217 }
6218
6219 I = LP;
6220 InstructionList.push_back(I);
6221 break;
6222 }
6223
6224 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
6225 if (Record.size() != 4 && Record.size() != 5)
6226 return error("Invalid record");
6227 using APV = AllocaPackedValues;
6228 const uint64_t Rec = Record[3];
6229 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6230 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
6231 unsigned TyID = Record[0];
6232 Type *Ty = getTypeByID(TyID);
6234 TyID = getContainedTypeID(TyID);
6235 Ty = getTypeByID(TyID);
6236 if (!Ty)
6237 return error("Missing element type for old-style alloca");
6238 }
6239 unsigned OpTyID = Record[1];
6240 Type *OpTy = getTypeByID(OpTyID);
6241 Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6242 MaybeAlign Align;
6243 uint64_t AlignExp =
6245 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6246 if (Error Err = parseAlignmentValue(AlignExp, Align)) {
6247 return Err;
6248 }
6249 if (!Ty || !Size)
6250 return error("Invalid record");
6251
6252 const DataLayout &DL = TheModule->getDataLayout();
6253 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
6254
6255 SmallPtrSet<Type *, 4> Visited;
6256 if (!Align && !Ty->isSized(&Visited))
6257 return error("alloca of unsized type");
6258 if (!Align)
6259 Align = DL.getPrefTypeAlign(Ty);
6260
6261 if (!Size->getType()->isIntegerTy())
6262 return error("alloca element count must have integer type");
6263
6264 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
6265 AI->setUsedWithInAlloca(InAlloca);
6266 AI->setSwiftError(SwiftError);
6267 I = AI;
6268 ResTypeID = getVirtualTypeID(AI->getType(), TyID);
6269 InstructionList.push_back(I);
6270 break;
6271 }
6272 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
6273 unsigned OpNum = 0;
6274 Value *Op;
6275 unsigned OpTypeID;
6276 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6277 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
6278 return error("Invalid record");
6279
6280 if (!isa<PointerType>(Op->getType()))
6281 return error("Load operand is not a pointer type");
6282
6283 Type *Ty = nullptr;
6284 if (OpNum + 3 == Record.size()) {
6285 ResTypeID = Record[OpNum++];
6286 Ty = getTypeByID(ResTypeID);
6287 } else {
6288 ResTypeID = getContainedTypeID(OpTypeID);
6289 Ty = getTypeByID(ResTypeID);
6290 }
6291
6292 if (!Ty)
6293 return error("Missing load type");
6294
6295 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6296 return Err;
6297
6298 MaybeAlign Align;
6299 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6300 return Err;
6301 SmallPtrSet<Type *, 4> Visited;
6302 if (!Align && !Ty->isSized(&Visited))
6303 return error("load of unsized type");
6304 if (!Align)
6305 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6306 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6307 InstructionList.push_back(I);
6308 break;
6309 }
6311 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6312 unsigned OpNum = 0;
6313 Value *Op;
6314 unsigned OpTypeID;
6315 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6316 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6317 return error("Invalid record");
6318
6319 if (!isa<PointerType>(Op->getType()))
6320 return error("Load operand is not a pointer type");
6321
6322 Type *Ty = nullptr;
6323 if (OpNum + 5 == Record.size()) {
6324 ResTypeID = Record[OpNum++];
6325 Ty = getTypeByID(ResTypeID);
6326 } else {
6327 ResTypeID = getContainedTypeID(OpTypeID);
6328 Ty = getTypeByID(ResTypeID);
6329 }
6330
6331 if (!Ty)
6332 return error("Missing atomic load type");
6333
6334 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6335 return Err;
6336
6337 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6338 if (Ordering == AtomicOrdering::NotAtomic ||
6339 Ordering == AtomicOrdering::Release ||
6340 Ordering == AtomicOrdering::AcquireRelease)
6341 return error("Invalid record");
6342 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6343 return error("Invalid record");
6344 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6345
6346 MaybeAlign Align;
6347 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6348 return Err;
6349 if (!Align)
6350 return error("Alignment missing from atomic load");
6351 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
6352 InstructionList.push_back(I);
6353 break;
6354 }
6356 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6357 unsigned OpNum = 0;
6358 Value *Val, *Ptr;
6359 unsigned PtrTypeID, ValTypeID;
6360 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6361 return error("Invalid record");
6362
6363 if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6364 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6365 return error("Invalid record");
6366 } else {
6367 ValTypeID = getContainedTypeID(PtrTypeID);
6368 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6369 ValTypeID, Val, CurBB))
6370 return error("Invalid record");
6371 }
6372
6373 if (OpNum + 2 != Record.size())
6374 return error("Invalid record");
6375
6376 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6377 return Err;
6378 MaybeAlign Align;
6379 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6380 return Err;
6381 SmallPtrSet<Type *, 4> Visited;
6382 if (!Align && !Val->getType()->isSized(&Visited))
6383 return error("store of unsized type");
6384 if (!Align)
6385 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6386 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6387 InstructionList.push_back(I);
6388 break;
6389 }
6392 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6393 unsigned OpNum = 0;
6394 Value *Val, *Ptr;
6395 unsigned PtrTypeID, ValTypeID;
6396 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6397 !isa<PointerType>(Ptr->getType()))
6398 return error("Invalid record");
6399 if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6400 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6401 return error("Invalid record");
6402 } else {
6403 ValTypeID = getContainedTypeID(PtrTypeID);
6404 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6405 ValTypeID, Val, CurBB))
6406 return error("Invalid record");
6407 }
6408
6409 if (OpNum + 4 != Record.size())
6410 return error("Invalid record");
6411
6412 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6413 return Err;
6414 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6415 if (Ordering == AtomicOrdering::NotAtomic ||
6416 Ordering == AtomicOrdering::Acquire ||
6417 Ordering == AtomicOrdering::AcquireRelease)
6418 return error("Invalid record");
6419 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6420 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6421 return error("Invalid record");
6422
6423 MaybeAlign Align;
6424 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6425 return Err;
6426 if (!Align)
6427 return error("Alignment missing from atomic store");
6428 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6429 InstructionList.push_back(I);
6430 break;
6431 }
6433 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6434 // failure_ordering?, weak?]
6435 const size_t NumRecords = Record.size();
6436 unsigned OpNum = 0;
6437 Value *Ptr = nullptr;
6438 unsigned PtrTypeID;
6439 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6440 return error("Invalid record");
6441
6442 if (!isa<PointerType>(Ptr->getType()))
6443 return error("Cmpxchg operand is not a pointer type");
6444
6445 Value *Cmp = nullptr;
6446 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6447 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6448 CmpTypeID, Cmp, CurBB))
6449 return error("Invalid record");
6450
6451 Value *New = nullptr;
6452 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6453 New, CurBB) ||
6454 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6455 return error("Invalid record");
6456
6457 const AtomicOrdering SuccessOrdering =
6458 getDecodedOrdering(Record[OpNum + 1]);
6459 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6460 SuccessOrdering == AtomicOrdering::Unordered)
6461 return error("Invalid record");
6462
6463 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6464
6465 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6466 return Err;
6467
6468 const AtomicOrdering FailureOrdering =
6469 NumRecords < 7
6471 : getDecodedOrdering(Record[OpNum + 3]);
6472
6473 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6474 FailureOrdering == AtomicOrdering::Unordered)
6475 return error("Invalid record");
6476
6477 const Align Alignment(
6478 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6479
6480 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6481 FailureOrdering, SSID);
6482 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
6483
6484 if (NumRecords < 8) {
6485 // Before weak cmpxchgs existed, the instruction simply returned the
6486 // value loaded from memory, so bitcode files from that era will be
6487 // expecting the first component of a modern cmpxchg.
6488 I->insertInto(CurBB, CurBB->end());
6490 ResTypeID = CmpTypeID;
6491 } else {
6492 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6493 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6494 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6495 }
6496
6497 InstructionList.push_back(I);
6498 break;
6499 }
6501 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6502 // failure_ordering, weak, align?]
6503 const size_t NumRecords = Record.size();
6504 unsigned OpNum = 0;
6505 Value *Ptr = nullptr;
6506 unsigned PtrTypeID;
6507 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6508 return error("Invalid record");
6509
6510 if (!isa<PointerType>(Ptr->getType()))
6511 return error("Cmpxchg operand is not a pointer type");
6512
6513 Value *Cmp = nullptr;
6514 unsigned CmpTypeID;
6515 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6516 return error("Invalid record");
6517
6518 Value *Val = nullptr;
6519 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6520 CurBB))
6521 return error("Invalid record");
6522
6523 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6524 return error("Invalid record");
6525
6526 const bool IsVol = Record[OpNum];
6527
6528 const AtomicOrdering SuccessOrdering =
6529 getDecodedOrdering(Record[OpNum + 1]);
6530 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6531 return error("Invalid cmpxchg success ordering");
6532
6533 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6534
6535 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6536 return Err;
6537
6538 const AtomicOrdering FailureOrdering =
6539 getDecodedOrdering(Record[OpNum + 3]);
6540 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6541 return error("Invalid cmpxchg failure ordering");
6542
6543 const bool IsWeak = Record[OpNum + 4];
6544
6545 MaybeAlign Alignment;
6546
6547 if (NumRecords == (OpNum + 6)) {
6548 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6549 return Err;
6550 }
6551 if (!Alignment)
6552 Alignment =
6553 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6554
6555 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6556 FailureOrdering, SSID);
6557 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6558 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6559
6560 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6561 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6562
6563 InstructionList.push_back(I);
6564 break;
6565 }
6568 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6569 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6570 const size_t NumRecords = Record.size();
6571 unsigned OpNum = 0;
6572
6573 Value *Ptr = nullptr;
6574 unsigned PtrTypeID;
6575 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6576 return error("Invalid record");
6577
6578 if (!isa<PointerType>(Ptr->getType()))
6579 return error("Invalid record");
6580
6581 Value *Val = nullptr;
6582 unsigned ValTypeID = InvalidTypeID;
6583 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6584 ValTypeID = getContainedTypeID(PtrTypeID);
6585 if (popValue(Record, OpNum, NextValueNo,
6586 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6587 return error("Invalid record");
6588 } else {
6589 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6590 return error("Invalid record");
6591 }
6592
6593 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6594 return error("Invalid record");
6595
6597 getDecodedRMWOperation(Record[OpNum]);
6600 return error("Invalid record");
6601
6602 const bool IsVol = Record[OpNum + 1];
6603
6604 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6605 if (Ordering == AtomicOrdering::NotAtomic ||
6606 Ordering == AtomicOrdering::Unordered)
6607 return error("Invalid record");
6608
6609 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6610
6611 MaybeAlign Alignment;
6612
6613 if (NumRecords == (OpNum + 5)) {
6614 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6615 return Err;
6616 }
6617
6618 if (!Alignment)
6619 Alignment =
6620 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6621
6622 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6623 ResTypeID = ValTypeID;
6624 cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6625
6626 InstructionList.push_back(I);
6627 break;
6628 }
6629 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6630 if (2 != Record.size())
6631 return error("Invalid record");
6633 if (Ordering == AtomicOrdering::NotAtomic ||
6634 Ordering == AtomicOrdering::Unordered ||
6635 Ordering == AtomicOrdering::Monotonic)
6636 return error("Invalid record");
6637 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6638 I = new FenceInst(Context, Ordering, SSID);
6639 InstructionList.push_back(I);
6640 break;
6641 }
6643 // DbgLabelRecords are placed after the Instructions that they are
6644 // attached to.
6645 SeenDebugRecord = true;
6646 Instruction *Inst = getLastInstruction();
6647 if (!Inst)
6648 return error("Invalid dbg record: missing instruction");
6649 DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[0]));
6650 DILabel *Label = cast<DILabel>(getFnMetadataByID(Record[1]));
6651 Inst->getParent()->insertDbgRecordBefore(
6652 new DbgLabelRecord(Label, DebugLoc(DIL)), Inst->getIterator());
6653 continue; // This isn't an instruction.
6654 }
6659 // DbgVariableRecords are placed after the Instructions that they are
6660 // attached to.
6661 SeenDebugRecord = true;
6662 Instruction *Inst = getLastInstruction();
6663 if (!Inst)
6664 return error("Invalid dbg record: missing instruction");
6665
6666 // First 3 fields are common to all kinds:
6667 // DILocation, DILocalVariable, DIExpression
6668 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6669 // ..., LocationMetadata
6670 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6671 // ..., Value
6672 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6673 // ..., LocationMetadata
6674 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6675 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6676 unsigned Slot = 0;
6677 // Common fields (0-2).
6678 DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[Slot++]));
6679 DILocalVariable *Var =
6680 cast<DILocalVariable>(getFnMetadataByID(Record[Slot++]));
6681 DIExpression *Expr =
6682 cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6683
6684 // Union field (3: LocationMetadata | Value).
6685 Metadata *RawLocation = nullptr;
6687 Value *V = nullptr;
6688 unsigned TyID = 0;
6689 // We never expect to see a fwd reference value here because
6690 // use-before-defs are encoded with the standard non-abbrev record
6691 // type (they'd require encoding the type too, and they're rare). As a
6692 // result, getValueTypePair only ever increments Slot by one here (once
6693 // for the value, never twice for value and type).
6694 unsigned SlotBefore = Slot;
6695 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6696 return error("Invalid dbg record: invalid value");
6697 (void)SlotBefore;
6698 assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6699 RawLocation = ValueAsMetadata::get(V);
6700 } else {
6701 RawLocation = getFnMetadataByID(Record[Slot++]);
6702 }
6703
6704 DbgVariableRecord *DVR = nullptr;
6705 switch (BitCode) {
6708 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6709 DbgVariableRecord::LocationType::Value);
6710 break;
6712 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6713 DbgVariableRecord::LocationType::Declare);
6714 break;
6716 DIAssignID *ID = cast<DIAssignID>(getFnMetadataByID(Record[Slot++]));
6717 DIExpression *AddrExpr =
6718 cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6719 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6720 DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6721 DIL);
6722 break;
6723 }
6724 default:
6725 llvm_unreachable("Unknown DbgVariableRecord bitcode");
6726 }
6727 Inst->getParent()->insertDbgRecordBefore(DVR, Inst->getIterator());
6728 continue; // This isn't an instruction.
6729 }
6731 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6732 if (Record.size() < 3)
6733 return error("Invalid record");
6734
6735 unsigned OpNum = 0;
6736 AttributeList PAL = getAttributes(Record[OpNum++]);
6737 unsigned CCInfo = Record[OpNum++];
6738
6739 FastMathFlags FMF;
6740 if ((CCInfo >> bitc::CALL_FMF) & 1) {
6741 FMF = getDecodedFastMathFlags(Record[OpNum++]);
6742 if (!FMF.any())
6743 return error("Fast math flags indicator set for call with no FMF");
6744 }
6745
6746 unsigned FTyID = InvalidTypeID;
6747 FunctionType *FTy = nullptr;
6748 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6749 FTyID = Record[OpNum++];
6750 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6751 if (!FTy)
6752 return error("Explicit call type is not a function type");
6753 }
6754
6755 Value *Callee;
6756 unsigned CalleeTypeID;
6757 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6758 CurBB))
6759 return error("Invalid record");
6760
6761 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6762 if (!OpTy)
6763 return error("Callee is not a pointer type");
6764 if (!FTy) {
6765 FTyID = getContainedTypeID(CalleeTypeID);
6766 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6767 if (!FTy)
6768 return error("Callee is not of pointer to function type");
6769 }
6770 if (Record.size() < FTy->getNumParams() + OpNum)
6771 return error("Insufficient operands to call");
6772
6773 SmallVector<Value*, 16> Args;
6774 SmallVector<unsigned, 16> ArgTyIDs;
6775 // Read the fixed params.
6776 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6777 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6778 if (FTy->getParamType(i)->isLabelTy())
6779 Args.push_back(getBasicBlock(Record[OpNum]));
6780 else
6781 Args.push_back(getValue(Record, OpNum, NextValueNo,
6782 FTy->getParamType(i), ArgTyID, CurBB));
6783 ArgTyIDs.push_back(ArgTyID);
6784 if (!Args.back())
6785 return error("Invalid record");
6786 }
6787
6788 // Read type/value pairs for varargs params.
6789 if (!FTy->isVarArg()) {
6790 if (OpNum != Record.size())
6791 return error("Invalid record");
6792 } else {
6793 while (OpNum != Record.size()) {
6794 Value *Op;
6795 unsigned OpTypeID;
6796 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6797 return error("Invalid record");
6798 Args.push_back(Op);
6799 ArgTyIDs.push_back(OpTypeID);
6800 }
6801 }
6802
6803 // Upgrade the bundles if needed.
6804 if (!OperandBundles.empty())
6805 UpgradeOperandBundles(OperandBundles);
6806
6807 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
6808 ResTypeID = getContainedTypeID(FTyID);
6809 OperandBundles.clear();
6810 InstructionList.push_back(I);
6811 cast<CallInst>(I)->setCallingConv(
6812 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6814 if (CCInfo & (1 << bitc::CALL_TAIL))
6815 TCK = CallInst::TCK_Tail;
6816 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6818 if (CCInfo & (1 << bitc::CALL_NOTAIL))
6820 cast<CallInst>(I)->setTailCallKind(TCK);
6821 cast<CallInst>(I)->setAttributes(PAL);
6823 SeenDebugIntrinsic = true;
6824 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6825 I->deleteValue();
6826 return Err;
6827 }
6828 if (FMF.any()) {
6829 if (!isa<FPMathOperator>(I))
6830 return error("Fast-math-flags specified for call without "
6831 "floating-point scalar or vector return type");
6832 I->setFastMathFlags(FMF);
6833 }
6834 break;
6835 }
6836 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6837 if (Record.size() < 3)
6838 return error("Invalid record");
6839 unsigned OpTyID = Record[0];
6840 Type *OpTy = getTypeByID(OpTyID);
6841 Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6842 ResTypeID = Record[2];
6843 Type *ResTy = getTypeByID(ResTypeID);
6844 if (!OpTy || !Op || !ResTy)
6845 return error("Invalid record");
6846 I = new VAArgInst(Op, ResTy);
6847 InstructionList.push_back(I);
6848 break;
6849 }
6850
6852 // A call or an invoke can be optionally prefixed with some variable
6853 // number of operand bundle blocks. These blocks are read into
6854 // OperandBundles and consumed at the next call or invoke instruction.
6855
6856 if (Record.empty() || Record[0] >= BundleTags.size())
6857 return error("Invalid record");
6858
6859 std::vector<Value *> Inputs;
6860
6861 unsigned OpNum = 1;
6862 while (OpNum != Record.size()) {
6863 Value *Op;
6864 if (getValueOrMetadata(Record, OpNum, NextValueNo, Op, CurBB))
6865 return error("Invalid record");
6866 Inputs.push_back(Op);
6867 }
6868
6869 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6870 continue;
6871 }
6872
6873 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6874 unsigned OpNum = 0;
6875 Value *Op = nullptr;
6876 unsigned OpTypeID;
6877 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6878 return error("Invalid record");
6879 if (OpNum != Record.size())
6880 return error("Invalid record");
6881
6882 I = new FreezeInst(Op);
6883 ResTypeID = OpTypeID;
6884 InstructionList.push_back(I);
6885 break;
6886 }
6887 }
6888
6889 // Add instruction to end of current BB. If there is no current BB, reject
6890 // this file.
6891 if (!CurBB) {
6892 I->deleteValue();
6893 return error("Invalid instruction with no BB");
6894 }
6895 if (!OperandBundles.empty()) {
6896 I->deleteValue();
6897 return error("Operand bundles found with no consumer");
6898 }
6899 I->insertInto(CurBB, CurBB->end());
6900
6901 // If this was a terminator instruction, move to the next block.
6902 if (I->isTerminator()) {
6903 ++CurBBNo;
6904 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6905 }
6906
6907 // Non-void values get registered in the value table for future use.
6908 if (!I->getType()->isVoidTy()) {
6909 assert(I->getType() == getTypeByID(ResTypeID) &&
6910 "Incorrect result type ID");
6911 if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
6912 return Err;
6913 }
6914 }
6915
6916OutOfRecordLoop:
6917
6918 if (!OperandBundles.empty())
6919 return error("Operand bundles found with no consumer");
6920
6921 // Check the function list for unresolved values.
6922 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
6923 if (!A->getParent()) {
6924 // We found at least one unresolved value. Nuke them all to avoid leaks.
6925 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
6926 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6927 A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6928 delete A;
6929 }
6930 }
6931 return error("Never resolved value found in function");
6932 }
6933 }
6934
6935 // Unexpected unresolved metadata about to be dropped.
6936 if (MDLoader->hasFwdRefs())
6937 return error("Invalid function metadata: outgoing forward refs");
6938
6939 if (PhiConstExprBB)
6940 PhiConstExprBB->eraseFromParent();
6941
6942 for (const auto &Pair : ConstExprEdgeBBs) {
6943 BasicBlock *From = Pair.first.first;
6944 BasicBlock *To = Pair.first.second;
6945 BasicBlock *EdgeBB = Pair.second;
6946 BranchInst::Create(To, EdgeBB);
6947 From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6948 To->replacePhiUsesWith(From, EdgeBB);
6949 EdgeBB->moveBefore(To);
6950 }
6951
6952 // Trim the value list down to the size it was before we parsed this function.
6953 ValueList.shrinkTo(ModuleValueListSize);
6954 MDLoader->shrinkTo(ModuleMDLoaderSize);
6955 std::vector<BasicBlock*>().swap(FunctionBBs);
6956 return Error::success();
6957}
6958
6959/// Find the function body in the bitcode stream
6960Error BitcodeReader::findFunctionInStream(
6961 Function *F,
6962 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6963 while (DeferredFunctionInfoIterator->second == 0) {
6964 // This is the fallback handling for the old format bitcode that
6965 // didn't contain the function index in the VST, or when we have
6966 // an anonymous function which would not have a VST entry.
6967 // Assert that we have one of those two cases.
6968 assert(VSTOffset == 0 || !F->hasName());
6969 // Parse the next body in the stream and set its position in the
6970 // DeferredFunctionInfo map.
6971 if (Error Err = rememberAndSkipFunctionBodies())
6972 return Err;
6973 }
6974 return Error::success();
6975}
6976
6977SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
6978 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
6979 return SyncScope::ID(Val);
6980 if (Val >= SSIDs.size())
6981 return SyncScope::System; // Map unknown synchronization scopes to system.
6982 return SSIDs[Val];
6983}
6984
6985//===----------------------------------------------------------------------===//
6986// GVMaterializer implementation
6987//===----------------------------------------------------------------------===//
6988
6989Error BitcodeReader::materialize(GlobalValue *GV) {
6991 // If it's not a function or is already material, ignore the request.
6992 if (!F || !F->isMaterializable())
6993 return Error::success();
6994
6995 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
6996 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
6997 // If its position is recorded as 0, its body is somewhere in the stream
6998 // but we haven't seen it yet.
6999 if (DFII->second == 0)
7000 if (Error Err = findFunctionInStream(F, DFII))
7001 return Err;
7002
7003 // Materialize metadata before parsing any function bodies.
7004 if (Error Err = materializeMetadata())
7005 return Err;
7006
7007 // Move the bit stream to the saved position of the deferred function body.
7008 if (Error JumpFailed = Stream.JumpToBit(DFII->second))
7009 return JumpFailed;
7010
7011 if (Error Err = parseFunctionBody(F))
7012 return Err;
7013 F->setIsMaterializable(false);
7014
7015 // All parsed Functions should load into the debug info format dictated by the
7016 // Module.
7017 if (SeenDebugIntrinsic && SeenDebugRecord)
7018 return error("Mixed debug intrinsics and debug records in bitcode module!");
7019
7020 if (StripDebugInfo)
7021 stripDebugInfo(*F);
7022
7023 // Finish fn->subprogram upgrade for materialized functions.
7024 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
7025 F->setSubprogram(SP);
7026
7027 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
7028 if (!MDLoader->isStrippingTBAA()) {
7029 for (auto &I : instructions(F)) {
7030 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
7031 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(&I, TBAA))
7032 continue;
7033 MDLoader->setStripTBAA(true);
7034 stripTBAA(F->getParent());
7035 }
7036 }
7037
7038 for (auto &I : make_early_inc_range(instructions(F))) {
7039 // "Upgrade" older incorrect branch weights by dropping them.
7040 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
7041 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
7042 MDString *MDS = cast<MDString>(MD->getOperand(0));
7043 StringRef ProfName = MDS->getString();
7044 // Check consistency of !prof branch_weights metadata.
7045 if (ProfName != MDProfLabels::BranchWeights)
7046 continue;
7047 unsigned ExpectedNumOperands = 0;
7048 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
7049 ExpectedNumOperands = BI->getNumSuccessors();
7050 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
7051 ExpectedNumOperands = SI->getNumSuccessors();
7052 else if (isa<CallInst>(&I))
7053 ExpectedNumOperands = 1;
7054 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
7055 ExpectedNumOperands = IBI->getNumDestinations();
7056 else if (isa<SelectInst>(&I))
7057 ExpectedNumOperands = 2;
7058 else
7059 continue; // ignore and continue.
7060
7061 unsigned Offset = getBranchWeightOffset(MD);
7062
7063 // If branch weight doesn't match, just strip branch weight.
7064 if (MD->getNumOperands() != Offset + ExpectedNumOperands)
7065 I.setMetadata(LLVMContext::MD_prof, nullptr);
7066 }
7067 }
7068
7069 if (auto *CI = dyn_cast<CallBase>(&I)) {
7070 // Remove incompatible attributes on function calls.
7071 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7072 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7073
7074 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7075 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7076 CI->getArgOperand(ArgNo)->getType(),
7077 CI->getParamAttributes(ArgNo)));
7078
7079 // Upgrade intrinsics.
7080 if (Function *OldFn = CI->getCalledFunction()) {
7081 auto It = UpgradedIntrinsics.find(OldFn);
7082 if (It != UpgradedIntrinsics.end())
7083 UpgradeIntrinsicCall(CI, It->second);
7084 }
7085 }
7086 }
7087
7088 // Look for functions that rely on old function attribute behavior.
7090
7091 // Bring in any functions that this function forward-referenced via
7092 // blockaddresses.
7093 return materializeForwardReferencedFunctions();
7094}
7095
7096Error BitcodeReader::materializeModule() {
7097 if (Error Err = materializeMetadata())
7098 return Err;
7099
7100 // Promise to materialize all forward references.
7101 WillMaterializeAllForwardRefs = true;
7102
7103 // Iterate over the module, deserializing any functions that are still on
7104 // disk.
7105 for (Function &F : *TheModule) {
7106 if (Error Err = materialize(&F))
7107 return Err;
7108 }
7109 // At this point, if there are any function bodies, parse the rest of
7110 // the bits in the module past the last function block we have recorded
7111 // through either lazy scanning or the VST.
7112 if (LastFunctionBlockBit || NextUnreadBit)
7113 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
7114 ? LastFunctionBlockBit
7115 : NextUnreadBit))
7116 return Err;
7117
7118 // Check that all block address forward references got resolved (as we
7119 // promised above).
7120 if (!BasicBlockFwdRefs.empty())
7121 return error("Never resolved function from blockaddress");
7122
7123 // Upgrade any intrinsic calls that slipped through (should not happen!) and
7124 // delete the old functions to clean up. We can't do this unless the entire
7125 // module is materialized because there could always be another function body
7126 // with calls to the old function.
7127 for (auto &I : UpgradedIntrinsics) {
7128 for (auto *U : I.first->users()) {
7129 if (CallInst *CI = dyn_cast<CallInst>(U))
7130 UpgradeIntrinsicCall(CI, I.second);
7131 }
7132 if (I.first != I.second) {
7133 if (!I.first->use_empty())
7134 I.first->replaceAllUsesWith(I.second);
7135 I.first->eraseFromParent();
7136 }
7137 }
7138 UpgradedIntrinsics.clear();
7139
7140 UpgradeDebugInfo(*TheModule);
7141
7142 UpgradeModuleFlags(*TheModule);
7143
7144 UpgradeNVVMAnnotations(*TheModule);
7145
7146 UpgradeARCRuntime(*TheModule);
7147
7148 copyModuleAttrToFunctions(*TheModule);
7149
7150 return Error::success();
7151}
7152
7153std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
7154 return IdentifiedStructTypes;
7155}
7156
7157ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7158 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7159 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
7160 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
7161 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7162
7163void ModuleSummaryIndexBitcodeReader::addThisModule() {
7164 TheIndex.addModule(ModulePath);
7165}
7166
7168ModuleSummaryIndexBitcodeReader::getThisModule() {
7169 return TheIndex.getModule(ModulePath);
7170}
7171
7172template <bool AllowNullValueInfo>
7173std::pair<ValueInfo, GlobalValue::GUID>
7174ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
7175 auto VGI = ValueIdToValueInfoMap[ValueId];
7176 // We can have a null value info for memprof callsite info records in
7177 // distributed ThinLTO index files when the callee function summary is not
7178 // included in the index. The bitcode writer records 0 in that case,
7179 // and the caller of this helper will set AllowNullValueInfo to true.
7180 assert(AllowNullValueInfo || std::get<0>(VGI));
7181 return VGI;
7182}
7183
7184void ModuleSummaryIndexBitcodeReader::setValueGUID(
7185 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
7186 StringRef SourceFileName) {
7187 std::string GlobalId =
7189 auto ValueGUID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalId);
7190 auto OriginalNameID = ValueGUID;
7194 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
7195 << ValueName << "\n";
7196
7197 // UseStrtab is false for legacy summary formats and value names are
7198 // created on stack. In that case we save the name in a string saver in
7199 // the index so that the value name can be recorded.
7200 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7201 TheIndex.getOrInsertValueInfo(
7202 ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
7203 OriginalNameID);
7204}
7205
7206// Specialized value symbol table parser used when reading module index
7207// blocks where we don't actually create global values. The parsed information
7208// is saved in the bitcode reader for use when later parsing summaries.
7209Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7210 uint64_t Offset,
7211 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7212 // With a strtab the VST is not required to parse the summary.
7213 if (UseStrtab)
7214 return Error::success();
7215
7216 assert(Offset > 0 && "Expected non-zero VST offset");
7217 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
7218 if (!MaybeCurrentBit)
7219 return MaybeCurrentBit.takeError();
7220 uint64_t CurrentBit = MaybeCurrentBit.get();
7221
7222 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
7223 return Err;
7224
7225 SmallVector<uint64_t, 64> Record;
7226
7227 // Read all the records for this value table.
7228 SmallString<128> ValueName;
7229
7230 while (true) {
7231 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7232 if (!MaybeEntry)
7233 return MaybeEntry.takeError();
7234 BitstreamEntry Entry = MaybeEntry.get();
7235
7236 switch (Entry.Kind) {
7237 case BitstreamEntry::SubBlock: // Handled for us already.
7239 return error("Malformed block");
7241 // Done parsing VST, jump back to wherever we came from.
7242 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
7243 return JumpFailed;
7244 return Error::success();
7246 // The interesting case.
7247 break;
7248 }
7249
7250 // Read a record.
7251 Record.clear();
7252 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7253 if (!MaybeRecord)
7254 return MaybeRecord.takeError();
7255 switch (MaybeRecord.get()) {
7256 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7257 break;
7258 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
7259 if (convertToString(Record, 1, ValueName))
7260 return error("Invalid record");
7261 unsigned ValueID = Record[0];
7262 assert(!SourceFileName.empty());
7263 auto VLI = ValueIdToLinkageMap.find(ValueID);
7264 assert(VLI != ValueIdToLinkageMap.end() &&
7265 "No linkage found for VST entry?");
7266 auto Linkage = VLI->second;
7267 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7268 ValueName.clear();
7269 break;
7270 }
7272 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7273 if (convertToString(Record, 2, ValueName))
7274 return error("Invalid record");
7275 unsigned ValueID = Record[0];
7276 assert(!SourceFileName.empty());
7277 auto VLI = ValueIdToLinkageMap.find(ValueID);
7278 assert(VLI != ValueIdToLinkageMap.end() &&
7279 "No linkage found for VST entry?");
7280 auto Linkage = VLI->second;
7281 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7282 ValueName.clear();
7283 break;
7284 }
7286 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7287 unsigned ValueID = Record[0];
7288 GlobalValue::GUID RefGUID = Record[1];
7289 // The "original name", which is the second value of the pair will be
7290 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7291 ValueIdToValueInfoMap[ValueID] =
7292 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7293 break;
7294 }
7295 }
7296 }
7297}
7298
7299// Parse just the blocks needed for building the index out of the module.
7300// At the end of this routine the module Index is populated with a map
7301// from global value id to GlobalValueSummary objects.
7302Error ModuleSummaryIndexBitcodeReader::parseModule() {
7303 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7304 return Err;
7305
7306 SmallVector<uint64_t, 64> Record;
7307 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7308 unsigned ValueId = 0;
7309
7310 // Read the index for this module.
7311 while (true) {
7312 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7313 if (!MaybeEntry)
7314 return MaybeEntry.takeError();
7315 llvm::BitstreamEntry Entry = MaybeEntry.get();
7316
7317 switch (Entry.Kind) {
7319 return error("Malformed block");
7321 return Error::success();
7322
7324 switch (Entry.ID) {
7325 default: // Skip unknown content.
7326 if (Error Err = Stream.SkipBlock())
7327 return Err;
7328 break;
7330 // Need to parse these to get abbrev ids (e.g. for VST)
7331 if (Error Err = readBlockInfo())
7332 return Err;
7333 break;
7335 // Should have been parsed earlier via VSTOffset, unless there
7336 // is no summary section.
7337 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7338 !SeenGlobalValSummary) &&
7339 "Expected early VST parse via VSTOffset record");
7340 if (Error Err = Stream.SkipBlock())
7341 return Err;
7342 break;
7345 // Add the module if it is a per-module index (has a source file name).
7346 if (!SourceFileName.empty())
7347 addThisModule();
7348 assert(!SeenValueSymbolTable &&
7349 "Already read VST when parsing summary block?");
7350 // We might not have a VST if there were no values in the
7351 // summary. An empty summary block generated when we are
7352 // performing ThinLTO compiles so we don't later invoke
7353 // the regular LTO process on them.
7354 if (VSTOffset > 0) {
7355 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7356 return Err;
7357 SeenValueSymbolTable = true;
7358 }
7359 SeenGlobalValSummary = true;
7360 if (Error Err = parseEntireSummary(Entry.ID))
7361 return Err;
7362 break;
7364 if (Error Err = parseModuleStringTable())
7365 return Err;
7366 break;
7367 }
7368 continue;
7369
7371 Record.clear();
7372 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7373 if (!MaybeBitCode)
7374 return MaybeBitCode.takeError();
7375 switch (MaybeBitCode.get()) {
7376 default:
7377 break; // Default behavior, ignore unknown content.
7379 if (Error Err = parseVersionRecord(Record).takeError())
7380 return Err;
7381 break;
7382 }
7383 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7385 SmallString<128> ValueName;
7386 if (convertToString(Record, 0, ValueName))
7387 return error("Invalid record");
7388 SourceFileName = ValueName.c_str();
7389 break;
7390 }
7391 /// MODULE_CODE_HASH: [5*i32]
7393 if (Record.size() != 5)
7394 return error("Invalid hash length " + Twine(Record.size()).str());
7395 auto &Hash = getThisModule()->second;
7396 int Pos = 0;
7397 for (auto &Val : Record) {
7398 assert(!(Val >> 32) && "Unexpected high bits set");
7399 Hash[Pos++] = Val;
7400 }
7401 break;
7402 }
7403 /// MODULE_CODE_VSTOFFSET: [offset]
7405 if (Record.empty())
7406 return error("Invalid record");
7407 // Note that we subtract 1 here because the offset is relative to one
7408 // word before the start of the identification or module block, which
7409 // was historically always the start of the regular bitcode header.
7410 VSTOffset = Record[0] - 1;
7411 break;
7412 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7413 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7414 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7415 // v2: [strtab offset, strtab size, v1]
7419 StringRef Name;
7420 ArrayRef<uint64_t> GVRecord;
7421 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7422 if (GVRecord.size() <= 3)
7423 return error("Invalid record");
7424 uint64_t RawLinkage = GVRecord[3];
7426 if (!UseStrtab) {
7427 ValueIdToLinkageMap[ValueId++] = Linkage;
7428 break;
7429 }
7430
7431 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7432 break;
7433 }
7434 }
7435 }
7436 continue;
7437 }
7438 }
7439}
7440
7442ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7444 Ret.reserve(Record.size());
7445 for (uint64_t RefValueId : Record)
7446 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7447 return Ret;
7448}
7449
7451ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7452 bool IsOldProfileFormat,
7453 bool HasProfile, bool HasRelBF) {
7455 // In the case of new profile formats, there are two Record entries per
7456 // Edge. Otherwise, conservatively reserve up to Record.size.
7457 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7458 Ret.reserve(Record.size() / 2);
7459 else
7460 Ret.reserve(Record.size());
7461
7462 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7463 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7464 bool HasTailCall = false;
7465 uint64_t RelBF = 0;
7466 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7467 if (IsOldProfileFormat) {
7468 I += 1; // Skip old callsitecount field
7469 if (HasProfile)
7470 I += 1; // Skip old profilecount field
7471 } else if (HasProfile)
7472 std::tie(Hotness, HasTailCall) =
7474 else if (HasRelBF)
7475 getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7476 Ret.push_back(FunctionSummary::EdgeTy{
7477 Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7478 }
7479 return Ret;
7480}
7481
7482static void
7485 uint64_t ArgNum = Record[Slot++];
7487 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7488 Slot += ArgNum;
7489
7490 B.TheKind =
7492 B.Info = Record[Slot++];
7493 B.Byte = Record[Slot++];
7494 B.Bit = Record[Slot++];
7495}
7496
7498 StringRef Strtab, size_t &Slot,
7499 TypeIdSummary &TypeId) {
7500 uint64_t Id = Record[Slot++];
7501 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7502
7503 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7504 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7505 static_cast<size_t>(Record[Slot + 1])};
7506 Slot += 2;
7507
7508 uint64_t ResByArgNum = Record[Slot++];
7509 for (uint64_t I = 0; I != ResByArgNum; ++I)
7511}
7512
7514 StringRef Strtab,
7515 ModuleSummaryIndex &TheIndex) {
7516 size_t Slot = 0;
7517 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7518 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7519 Slot += 2;
7520
7521 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7522 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7523 TypeId.TTRes.AlignLog2 = Record[Slot++];
7524 TypeId.TTRes.SizeM1 = Record[Slot++];
7525 TypeId.TTRes.BitMask = Record[Slot++];
7526 TypeId.TTRes.InlineBits = Record[Slot++];
7527
7528 while (Slot < Record.size())
7529 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7530}
7531
7532std::vector<FunctionSummary::ParamAccess>
7533ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7534 auto ReadRange = [&]() {
7536 BitcodeReader::decodeSignRotatedValue(Record.consume_front()));
7538 BitcodeReader::decodeSignRotatedValue(Record.consume_front()));
7539 ConstantRange Range{Lower, Upper};
7542 return Range;
7543 };
7544
7545 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7546 while (!Record.empty()) {
7547 PendingParamAccesses.emplace_back();
7548 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7549 ParamAccess.ParamNo = Record.consume_front();
7550 ParamAccess.Use = ReadRange();
7551 ParamAccess.Calls.resize(Record.consume_front());
7552 for (auto &Call : ParamAccess.Calls) {
7553 Call.ParamNo = Record.consume_front();
7554 Call.Callee =
7555 std::get<0>(getValueInfoFromValueId(Record.consume_front()));
7556 Call.Offsets = ReadRange();
7557 }
7558 }
7559 return PendingParamAccesses;
7560}
7561
7562void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7563 ArrayRef<uint64_t> Record, size_t &Slot,
7565 uint64_t Offset = Record[Slot++];
7566 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7567 TypeId.push_back({Offset, Callee});
7568}
7569
7570void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7571 ArrayRef<uint64_t> Record) {
7572 size_t Slot = 0;
7575 {Strtab.data() + Record[Slot],
7576 static_cast<size_t>(Record[Slot + 1])});
7577 Slot += 2;
7578
7579 while (Slot < Record.size())
7580 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7581}
7582
7583SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7584 ArrayRef<uint64_t> Record, unsigned &I) {
7585 SmallVector<unsigned> StackIdList;
7586 // For backwards compatibility with old format before radix tree was
7587 // used, simply see if we found a radix tree array record (and thus if
7588 // the RadixArray is non-empty).
7589 if (RadixArray.empty()) {
7590 unsigned NumStackEntries = Record[I++];
7591 assert(Record.size() - I >= NumStackEntries);
7592 StackIdList.reserve(NumStackEntries);
7593 for (unsigned J = 0; J < NumStackEntries; J++) {
7594 assert(Record[I] < StackIds.size());
7595 StackIdList.push_back(
7596 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7597 }
7598 } else {
7599 unsigned RadixIndex = Record[I++];
7600 // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7601 // for a detailed description of the radix tree array format. Briefly, the
7602 // first entry will be the number of frames, any negative values are the
7603 // negative of the offset of the next frame, and otherwise the frames are in
7604 // increasing linear order.
7605 assert(RadixIndex < RadixArray.size());
7606 unsigned NumStackIds = RadixArray[RadixIndex++];
7607 StackIdList.reserve(NumStackIds);
7608 while (NumStackIds--) {
7609 assert(RadixIndex < RadixArray.size());
7610 unsigned Elem = RadixArray[RadixIndex];
7611 if (static_cast<std::make_signed_t<unsigned>>(Elem) < 0) {
7612 RadixIndex = RadixIndex - Elem;
7613 assert(RadixIndex < RadixArray.size());
7614 Elem = RadixArray[RadixIndex];
7615 // We shouldn't encounter a second offset in a row.
7616 assert(static_cast<std::make_signed_t<unsigned>>(Elem) >= 0);
7617 }
7618 RadixIndex++;
7619 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[Elem]));
7620 }
7621 }
7622 return StackIdList;
7623}
7624
7625static void setSpecialRefs(SmallVectorImpl<ValueInfo> &Refs, unsigned ROCnt,
7626 unsigned WOCnt) {
7627 // Readonly and writeonly refs are in the end of the refs list.
7628 assert(ROCnt + WOCnt <= Refs.size());
7629 unsigned FirstWORef = Refs.size() - WOCnt;
7630 unsigned RefNo = FirstWORef - ROCnt;
7631 for (; RefNo < FirstWORef; ++RefNo)
7632 Refs[RefNo].setReadOnly();
7633 for (; RefNo < Refs.size(); ++RefNo)
7634 Refs[RefNo].setWriteOnly();
7635}
7636
7637// Eagerly parse the entire summary block. This populates the GlobalValueSummary
7638// objects in the index.
7639Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7640 if (Error Err = Stream.EnterSubBlock(ID))
7641 return Err;
7642 SmallVector<uint64_t, 64> Record;
7643
7644 // Parse version
7645 {
7646 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7647 if (!MaybeEntry)
7648 return MaybeEntry.takeError();
7649 BitstreamEntry Entry = MaybeEntry.get();
7650
7651 if (Entry.Kind != BitstreamEntry::Record)
7652 return error("Invalid Summary Block: record for version expected");
7653 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7654 if (!MaybeRecord)
7655 return MaybeRecord.takeError();
7656 if (MaybeRecord.get() != bitc::FS_VERSION)
7657 return error("Invalid Summary Block: version expected");
7658 }
7659 const uint64_t Version = Record[0];
7660 const bool IsOldProfileFormat = Version == 1;
7662 return error("Invalid summary version " + Twine(Version) +
7663 ". Version should be in the range [1-" +
7665 "].");
7666 Record.clear();
7667
7668 // Keep around the last seen summary to be used when we see an optional
7669 // "OriginalName" attachement.
7670 GlobalValueSummary *LastSeenSummary = nullptr;
7671 GlobalValue::GUID LastSeenGUID = 0;
7672
7673 // We can expect to see any number of type ID information records before
7674 // each function summary records; these variables store the information
7675 // collected so far so that it can be used to create the summary object.
7676 std::vector<GlobalValue::GUID> PendingTypeTests;
7677 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7678 PendingTypeCheckedLoadVCalls;
7679 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7680 PendingTypeCheckedLoadConstVCalls;
7681 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7682
7683 std::vector<CallsiteInfo> PendingCallsites;
7684 std::vector<AllocInfo> PendingAllocs;
7685 std::vector<uint64_t> PendingContextIds;
7686
7687 while (true) {
7688 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7689 if (!MaybeEntry)
7690 return MaybeEntry.takeError();
7691 BitstreamEntry Entry = MaybeEntry.get();
7692
7693 switch (Entry.Kind) {
7694 case BitstreamEntry::SubBlock: // Handled for us already.
7696 return error("Malformed block");
7698 return Error::success();
7700 // The interesting case.
7701 break;
7702 }
7703
7704 // Read a record. The record format depends on whether this
7705 // is a per-module index or a combined index file. In the per-module
7706 // case the records contain the associated value's ID for correlation
7707 // with VST entries. In the combined index the correlation is done
7708 // via the bitcode offset of the summary records (which were saved
7709 // in the combined index VST entries). The records also contain
7710 // information used for ThinLTO renaming and importing.
7711 Record.clear();
7712 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7713 if (!MaybeBitCode)
7714 return MaybeBitCode.takeError();
7715 switch (unsigned BitCode = MaybeBitCode.get()) {
7716 default: // Default behavior: ignore.
7717 break;
7718 case bitc::FS_FLAGS: { // [flags]
7719 TheIndex.setFlags(Record[0]);
7720 break;
7721 }
7722 case bitc::FS_VALUE_GUID: { // [valueid, refguid_upper32, refguid_lower32]
7723 uint64_t ValueID = Record[0];
7724 GlobalValue::GUID RefGUID;
7725 if (Version >= 11) {
7726 RefGUID = Record[1] << 32 | Record[2];
7727 } else {
7728 RefGUID = Record[1];
7729 }
7730 ValueIdToValueInfoMap[ValueID] =
7731 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7732 break;
7733 }
7734 // FS_PERMODULE is legacy and does not have support for the tail call flag.
7735 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7736 // numrefs x valueid, n x (valueid)]
7737 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7738 // numrefs x valueid,
7739 // n x (valueid, hotness+tailcall flags)]
7740 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7741 // numrefs x valueid,
7742 // n x (valueid, relblockfreq+tailcall)]
7743 case bitc::FS_PERMODULE:
7746 unsigned ValueID = Record[0];
7747 uint64_t RawFlags = Record[1];
7748 unsigned InstCount = Record[2];
7749 uint64_t RawFunFlags = 0;
7750 unsigned NumRefs = Record[3];
7751 unsigned NumRORefs = 0, NumWORefs = 0;
7752 int RefListStartIndex = 4;
7753 if (Version >= 4) {
7754 RawFunFlags = Record[3];
7755 NumRefs = Record[4];
7756 RefListStartIndex = 5;
7757 if (Version >= 5) {
7758 NumRORefs = Record[5];
7759 RefListStartIndex = 6;
7760 if (Version >= 7) {
7761 NumWORefs = Record[6];
7762 RefListStartIndex = 7;
7763 }
7764 }
7765 }
7766
7767 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7768 // The module path string ref set in the summary must be owned by the
7769 // index's module string table. Since we don't have a module path
7770 // string table section in the per-module index, we create a single
7771 // module path string table entry with an empty (0) ID to take
7772 // ownership.
7773 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7774 assert(Record.size() >= RefListStartIndex + NumRefs &&
7775 "Record size inconsistent with number of references");
7776 SmallVector<ValueInfo, 0> Refs = makeRefList(
7777 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7778 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7779 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7780 SmallVector<FunctionSummary::EdgeTy, 0> Calls = makeCallList(
7781 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7782 IsOldProfileFormat, HasProfile, HasRelBF);
7783 setSpecialRefs(Refs, NumRORefs, NumWORefs);
7784 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7785 // In order to save memory, only record the memprof summaries if this is
7786 // the prevailing copy of a symbol. The linker doesn't resolve local
7787 // linkage values so don't check whether those are prevailing.
7788 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7789 if (IsPrevailing && !GlobalValue::isLocalLinkage(LT) &&
7790 !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7791 PendingCallsites.clear();
7792 PendingAllocs.clear();
7793 }
7794 auto FS = std::make_unique<FunctionSummary>(
7795 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7796 std::move(Calls), std::move(PendingTypeTests),
7797 std::move(PendingTypeTestAssumeVCalls),
7798 std::move(PendingTypeCheckedLoadVCalls),
7799 std::move(PendingTypeTestAssumeConstVCalls),
7800 std::move(PendingTypeCheckedLoadConstVCalls),
7801 std::move(PendingParamAccesses), std::move(PendingCallsites),
7802 std::move(PendingAllocs));
7803 FS->setModulePath(getThisModule()->first());
7804 FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7805 TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7806 std::move(FS));
7807 break;
7808 }
7809 // FS_ALIAS: [valueid, flags, valueid]
7810 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7811 // they expect all aliasee summaries to be available.
7812 case bitc::FS_ALIAS: {
7813 unsigned ValueID = Record[0];
7814 uint64_t RawFlags = Record[1];
7815 unsigned AliaseeID = Record[2];
7816 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7817 auto AS = std::make_unique<AliasSummary>(Flags);
7818 // The module path string ref set in the summary must be owned by the
7819 // index's module string table. Since we don't have a module path
7820 // string table section in the per-module index, we create a single
7821 // module path string table entry with an empty (0) ID to take
7822 // ownership.
7823 AS->setModulePath(getThisModule()->first());
7824
7825 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7826 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7827 if (!AliaseeInModule)
7828 return error("Alias expects aliasee summary to be parsed");
7829 AS->setAliasee(AliaseeVI, AliaseeInModule);
7830
7831 auto GUID = getValueInfoFromValueId(ValueID);
7832 AS->setOriginalName(std::get<1>(GUID));
7833 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
7834 break;
7835 }
7836 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7838 unsigned ValueID = Record[0];
7839 uint64_t RawFlags = Record[1];
7840 unsigned RefArrayStart = 2;
7841 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7842 /* WriteOnly */ false,
7843 /* Constant */ false,
7845 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7846 if (Version >= 5) {
7847 GVF = getDecodedGVarFlags(Record[2]);
7848 RefArrayStart = 3;
7849 }
7851 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7852 auto FS =
7853 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7854 FS->setModulePath(getThisModule()->first());
7855 auto GUID = getValueInfoFromValueId(ValueID);
7856 FS->setOriginalName(std::get<1>(GUID));
7857 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
7858 break;
7859 }
7860 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7861 // numrefs, numrefs x valueid,
7862 // n x (valueid, offset)]
7864 unsigned ValueID = Record[0];
7865 uint64_t RawFlags = Record[1];
7866 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7867 unsigned NumRefs = Record[3];
7868 unsigned RefListStartIndex = 4;
7869 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7870 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7871 SmallVector<ValueInfo, 0> Refs = makeRefList(
7872 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7873 VTableFuncList VTableFuncs;
7874 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7875 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7876 uint64_t Offset = Record[++I];
7877 VTableFuncs.push_back({Callee, Offset});
7878 }
7879 auto VS =
7880 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7881 VS->setModulePath(getThisModule()->first());
7882 VS->setVTableFuncs(VTableFuncs);
7883 auto GUID = getValueInfoFromValueId(ValueID);
7884 VS->setOriginalName(std::get<1>(GUID));
7885 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
7886 break;
7887 }
7888 // FS_COMBINED is legacy and does not have support for the tail call flag.
7889 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7890 // numrefs x valueid, n x (valueid)]
7891 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7892 // numrefs x valueid,
7893 // n x (valueid, hotness+tailcall flags)]
7894 case bitc::FS_COMBINED:
7896 unsigned ValueID = Record[0];
7897 uint64_t ModuleId = Record[1];
7898 uint64_t RawFlags = Record[2];
7899 unsigned InstCount = Record[3];
7900 uint64_t RawFunFlags = 0;
7901 unsigned NumRefs = Record[4];
7902 unsigned NumRORefs = 0, NumWORefs = 0;
7903 int RefListStartIndex = 5;
7904
7905 if (Version >= 4) {
7906 RawFunFlags = Record[4];
7907 RefListStartIndex = 6;
7908 size_t NumRefsIndex = 5;
7909 if (Version >= 5) {
7910 unsigned NumRORefsOffset = 1;
7911 RefListStartIndex = 7;
7912 if (Version >= 6) {
7913 NumRefsIndex = 6;
7914 RefListStartIndex = 8;
7915 if (Version >= 7) {
7916 RefListStartIndex = 9;
7917 NumWORefs = Record[8];
7918 NumRORefsOffset = 2;
7919 }
7920 }
7921 NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7922 }
7923 NumRefs = Record[NumRefsIndex];
7924 }
7925
7926 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7927 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7928 assert(Record.size() >= RefListStartIndex + NumRefs &&
7929 "Record size inconsistent with number of references");
7930 SmallVector<ValueInfo, 0> Refs = makeRefList(
7931 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7932 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7933 SmallVector<FunctionSummary::EdgeTy, 0> Edges = makeCallList(
7934 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7935 IsOldProfileFormat, HasProfile, false);
7936 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7937 setSpecialRefs(Refs, NumRORefs, NumWORefs);
7938 auto FS = std::make_unique<FunctionSummary>(
7939 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7940 std::move(Edges), std::move(PendingTypeTests),
7941 std::move(PendingTypeTestAssumeVCalls),
7942 std::move(PendingTypeCheckedLoadVCalls),
7943 std::move(PendingTypeTestAssumeConstVCalls),
7944 std::move(PendingTypeCheckedLoadConstVCalls),
7945 std::move(PendingParamAccesses), std::move(PendingCallsites),
7946 std::move(PendingAllocs));
7947 LastSeenSummary = FS.get();
7948 LastSeenGUID = VI.getGUID();
7949 FS->setModulePath(ModuleIdMap[ModuleId]);
7950 TheIndex.addGlobalValueSummary(VI, std::move(FS));
7951 break;
7952 }
7953 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7954 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7955 // they expect all aliasee summaries to be available.
7957 unsigned ValueID = Record[0];
7958 uint64_t ModuleId = Record[1];
7959 uint64_t RawFlags = Record[2];
7960 unsigned AliaseeValueId = Record[3];
7961 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7962 auto AS = std::make_unique<AliasSummary>(Flags);
7963 LastSeenSummary = AS.get();
7964 AS->setModulePath(ModuleIdMap[ModuleId]);
7965
7966 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7967 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7968 AS->setAliasee(AliaseeVI, AliaseeInModule);
7969
7970 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7971 LastSeenGUID = VI.getGUID();
7972 TheIndex.addGlobalValueSummary(VI, std::move(AS));
7973 break;
7974 }
7975 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7977 unsigned ValueID = Record[0];
7978 uint64_t ModuleId = Record[1];
7979 uint64_t RawFlags = Record[2];
7980 unsigned RefArrayStart = 3;
7981 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7982 /* WriteOnly */ false,
7983 /* Constant */ false,
7985 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7986 if (Version >= 5) {
7987 GVF = getDecodedGVarFlags(Record[3]);
7988 RefArrayStart = 4;
7989 }
7991 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7992 auto FS =
7993 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7994 LastSeenSummary = FS.get();
7995 FS->setModulePath(ModuleIdMap[ModuleId]);
7996 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7997 LastSeenGUID = VI.getGUID();
7998 TheIndex.addGlobalValueSummary(VI, std::move(FS));
7999 break;
8000 }
8001 // FS_COMBINED_ORIGINAL_NAME: [original_name]
8003 uint64_t OriginalName = Record[0];
8004 if (!LastSeenSummary)
8005 return error("Name attachment that does not follow a combined record");
8006 LastSeenSummary->setOriginalName(OriginalName);
8007 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
8008 // Reset the LastSeenSummary
8009 LastSeenSummary = nullptr;
8010 LastSeenGUID = 0;
8011 break;
8012 }
8014 assert(PendingTypeTests.empty());
8015 llvm::append_range(PendingTypeTests, Record);
8016 break;
8017
8019 assert(PendingTypeTestAssumeVCalls.empty());
8020 for (unsigned I = 0; I != Record.size(); I += 2)
8021 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8022 break;
8023
8025 assert(PendingTypeCheckedLoadVCalls.empty());
8026 for (unsigned I = 0; I != Record.size(); I += 2)
8027 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8028 break;
8029
8031 PendingTypeTestAssumeConstVCalls.push_back(
8032 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8033 break;
8034
8036 PendingTypeCheckedLoadConstVCalls.push_back(
8037 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8038 break;
8039
8041 auto &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
8042 for (unsigned I = 0; I != Record.size(); I += 2)
8043 CfiFunctionDefs.emplace(Strtab.data() + Record[I],
8044 static_cast<size_t>(Record[I + 1]));
8045 break;
8046 }
8047
8049 auto &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
8050 for (unsigned I = 0; I != Record.size(); I += 2)
8051 CfiFunctionDecls.emplace(Strtab.data() + Record[I],
8052 static_cast<size_t>(Record[I + 1]));
8053 break;
8054 }
8055
8056 case bitc::FS_TYPE_ID:
8057 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
8058 break;
8059
8061 parseTypeIdCompatibleVtableSummaryRecord(Record);
8062 break;
8063
8065 TheIndex.addBlockCount(Record[0]);
8066 break;
8067
8068 case bitc::FS_PARAM_ACCESS: {
8069 PendingParamAccesses = parseParamAccesses(Record);
8070 break;
8071 }
8072
8073 case bitc::FS_STACK_IDS: { // [n x stackid]
8074 // Save stack ids in the reader to consult when adding stack ids from the
8075 // lists in the stack node and alloc node entries.
8076 if (Version <= 11) {
8077 StackIds = ArrayRef<uint64_t>(Record);
8078 break;
8079 }
8080 // This is an array of 32-bit fixed-width values, holding each 64-bit
8081 // context id as a pair of adjacent (most significant first) 32-bit words.
8082 assert(Record.size() % 2 == 0);
8083 StackIds.reserve(Record.size() / 2);
8084 for (auto R = Record.begin(); R != Record.end(); R += 2)
8085 StackIds.push_back(*R << 32 | *(R + 1));
8086 break;
8087 }
8088
8089 case bitc::FS_CONTEXT_RADIX_TREE_ARRAY: { // [n x entry]
8090 RadixArray = ArrayRef<uint64_t>(Record);
8091 break;
8092 }
8093
8095 unsigned ValueID = Record[0];
8096 SmallVector<unsigned> StackIdList;
8097 for (uint64_t R : drop_begin(Record)) {
8098 assert(R < StackIds.size());
8099 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[R]));
8100 }
8101 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8102 PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
8103 break;
8104 }
8105
8107 auto RecordIter = Record.begin();
8108 unsigned ValueID = *RecordIter++;
8109 unsigned NumStackIds = *RecordIter++;
8110 unsigned NumVersions = *RecordIter++;
8111 assert(Record.size() == 3 + NumStackIds + NumVersions);
8112 SmallVector<unsigned> StackIdList;
8113 for (unsigned J = 0; J < NumStackIds; J++) {
8114 assert(*RecordIter < StackIds.size());
8115 StackIdList.push_back(
8116 TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
8117 }
8118 SmallVector<unsigned> Versions;
8119 for (unsigned J = 0; J < NumVersions; J++)
8120 Versions.push_back(*RecordIter++);
8121 ValueInfo VI = std::get<0>(
8122 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8123 PendingCallsites.push_back(
8124 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8125 break;
8126 }
8127
8129 // This is an array of 32-bit fixed-width values, holding each 64-bit
8130 // context id as a pair of adjacent (most significant first) 32-bit words.
8131 assert(Record.size() % 2 == 0);
8132 PendingContextIds.reserve(Record.size() / 2);
8133 for (auto R = Record.begin(); R != Record.end(); R += 2)
8134 PendingContextIds.push_back(*R << 32 | *(R + 1));
8135 break;
8136 }
8137
8139 unsigned I = 0;
8140 std::vector<MIBInfo> MIBs;
8141 unsigned NumMIBs = 0;
8142 if (Version >= 10)
8143 NumMIBs = Record[I++];
8144 unsigned MIBsRead = 0;
8145 while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8146 (Version < 10 && I < Record.size())) {
8147 assert(Record.size() - I >= 2);
8149 auto StackIdList = parseAllocInfoContext(Record, I);
8150 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8151 }
8152 // We either have nothing left or at least NumMIBs context size info
8153 // indices left (for the total sizes included when reporting of hinted
8154 // bytes is enabled).
8155 assert(I == Record.size() || Record.size() - I >= NumMIBs);
8156 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8157 if (I < Record.size()) {
8158 assert(!PendingContextIds.empty() &&
8159 "Missing context ids for alloc sizes");
8160 unsigned ContextIdIndex = 0;
8161 MIBsRead = 0;
8162 // The sizes are a linearized array of sizes, where for each MIB there
8163 // is 1 or more sizes (due to context trimming, each MIB in the metadata
8164 // and summarized here can correspond to more than one original context
8165 // from the profile).
8166 while (MIBsRead++ < NumMIBs) {
8167 // First read the number of contexts recorded for this MIB.
8168 unsigned NumContextSizeInfoEntries = Record[I++];
8169 assert(Record.size() - I >= NumContextSizeInfoEntries);
8170 std::vector<ContextTotalSize> ContextSizes;
8171 ContextSizes.reserve(NumContextSizeInfoEntries);
8172 for (unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8173 assert(ContextIdIndex < PendingContextIds.size());
8174 // Skip any 0 entries for MIBs without the context size info.
8175 if (PendingContextIds[ContextIdIndex] == 0) {
8176 // The size should also be 0 if the context was 0.
8177 assert(!Record[I]);
8178 ContextIdIndex++;
8179 I++;
8180 continue;
8181 }
8182 // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8183 // should be in the same order as the total sizes.
8184 ContextSizes.push_back(
8185 {PendingContextIds[ContextIdIndex++], Record[I++]});
8186 }
8187 AllContextSizes.push_back(std::move(ContextSizes));
8188 }
8189 PendingContextIds.clear();
8190 }
8191 PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8192 if (!AllContextSizes.empty()) {
8193 assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8194 PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8195 }
8196 break;
8197 }
8198
8201 unsigned I = 0;
8202 std::vector<MIBInfo> MIBs;
8203 unsigned NumMIBs = Record[I++];
8204 unsigned NumVersions = Record[I++];
8205 unsigned MIBsRead = 0;
8206 while (MIBsRead++ < NumMIBs) {
8207 assert(Record.size() - I >= 2);
8209 SmallVector<unsigned> StackIdList;
8210 if (BitCode == bitc::FS_COMBINED_ALLOC_INFO)
8211 StackIdList = parseAllocInfoContext(Record, I);
8212 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8213 }
8214 assert(Record.size() - I >= NumVersions);
8215 SmallVector<uint8_t> Versions;
8216 for (unsigned J = 0; J < NumVersions; J++)
8217 Versions.push_back(Record[I++]);
8218 assert(I == Record.size());
8219 PendingAllocs.push_back(AllocInfo(std::move(Versions), std::move(MIBs)));
8220 break;
8221 }
8222 }
8223 }
8224 llvm_unreachable("Exit infinite loop");
8225}
8226
8227// Parse the module string table block into the Index.
8228// This populates the ModulePathStringTable map in the index.
8229Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8230 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
8231 return Err;
8232
8233 SmallVector<uint64_t, 64> Record;
8234
8235 SmallString<128> ModulePath;
8236 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
8237
8238 while (true) {
8239 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8240 if (!MaybeEntry)
8241 return MaybeEntry.takeError();
8242 BitstreamEntry Entry = MaybeEntry.get();
8243
8244 switch (Entry.Kind) {
8245 case BitstreamEntry::SubBlock: // Handled for us already.
8247 return error("Malformed block");
8249 return Error::success();
8251 // The interesting case.
8252 break;
8253 }
8254
8255 Record.clear();
8256 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
8257 if (!MaybeRecord)
8258 return MaybeRecord.takeError();
8259 switch (MaybeRecord.get()) {
8260 default: // Default behavior: ignore.
8261 break;
8262 case bitc::MST_CODE_ENTRY: {
8263 // MST_ENTRY: [modid, namechar x N]
8264 uint64_t ModuleId = Record[0];
8265
8266 if (convertToString(Record, 1, ModulePath))
8267 return error("Invalid record");
8268
8269 LastSeenModule = TheIndex.addModule(ModulePath);
8270 ModuleIdMap[ModuleId] = LastSeenModule->first();
8271
8272 ModulePath.clear();
8273 break;
8274 }
8275 /// MST_CODE_HASH: [5*i32]
8276 case bitc::MST_CODE_HASH: {
8277 if (Record.size() != 5)
8278 return error("Invalid hash length " + Twine(Record.size()).str());
8279 if (!LastSeenModule)
8280 return error("Invalid hash that does not follow a module path");
8281 int Pos = 0;
8282 for (auto &Val : Record) {
8283 assert(!(Val >> 32) && "Unexpected high bits set");
8284 LastSeenModule->second[Pos++] = Val;
8285 }
8286 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8287 LastSeenModule = nullptr;
8288 break;
8289 }
8290 }
8291 }
8292 llvm_unreachable("Exit infinite loop");
8293}
8294
8295namespace {
8296
8297// FIXME: This class is only here to support the transition to llvm::Error. It
8298// will be removed once this transition is complete. Clients should prefer to
8299// deal with the Error value directly, rather than converting to error_code.
8300class BitcodeErrorCategoryType : public std::error_category {
8301 const char *name() const noexcept override {
8302 return "llvm.bitcode";
8303 }
8304
8305 std::string message(int IE) const override {
8306 BitcodeError E = static_cast<BitcodeError>(IE);
8307 switch (E) {
8308 case BitcodeError::CorruptedBitcode:
8309 return "Corrupted bitcode";
8310 }
8311 llvm_unreachable("Unknown error type!");
8312 }
8313};
8314
8315} // end anonymous namespace
8316
8317const std::error_category &llvm::BitcodeErrorCategory() {
8318 static BitcodeErrorCategoryType ErrorCategory;
8319 return ErrorCategory;
8320}
8321
8323 unsigned Block, unsigned RecordID) {
8324 if (Error Err = Stream.EnterSubBlock(Block))
8325 return std::move(Err);
8326
8327 StringRef Strtab;
8328 while (true) {
8329 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8330 if (!MaybeEntry)
8331 return MaybeEntry.takeError();
8332 llvm::BitstreamEntry Entry = MaybeEntry.get();
8333
8334 switch (Entry.Kind) {
8336 return Strtab;
8337
8339 return error("Malformed block");
8340
8342 if (Error Err = Stream.SkipBlock())
8343 return std::move(Err);
8344 break;
8345
8347 StringRef Blob;
8349 Expected<unsigned> MaybeRecord =
8350 Stream.readRecord(Entry.ID, Record, &Blob);
8351 if (!MaybeRecord)
8352 return MaybeRecord.takeError();
8353 if (MaybeRecord.get() == RecordID)
8354 Strtab = Blob;
8355 break;
8356 }
8357 }
8358}
8359
8360//===----------------------------------------------------------------------===//
8361// External interface
8362//===----------------------------------------------------------------------===//
8363
8364Expected<std::vector<BitcodeModule>>
8366 auto FOrErr = getBitcodeFileContents(Buffer);
8367 if (!FOrErr)
8368 return FOrErr.takeError();
8369 return std::move(FOrErr->Mods);
8370}
8371
8374 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8375 if (!StreamOrErr)
8376 return StreamOrErr.takeError();
8377 BitstreamCursor &Stream = *StreamOrErr;
8378
8380 while (true) {
8381 uint64_t BCBegin = Stream.getCurrentByteNo();
8382
8383 // We may be consuming bitcode from a client that leaves garbage at the end
8384 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8385 // the end that there cannot possibly be another module, stop looking.
8386 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
8387 return F;
8388
8389 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8390 if (!MaybeEntry)
8391 return MaybeEntry.takeError();
8392 llvm::BitstreamEntry Entry = MaybeEntry.get();
8393
8394 switch (Entry.Kind) {
8397 return error("Malformed block");
8398
8400 uint64_t IdentificationBit = -1ull;
8401 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
8402 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8403 if (Error Err = Stream.SkipBlock())
8404 return std::move(Err);
8405
8406 {
8407 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8408 if (!MaybeEntry)
8409 return MaybeEntry.takeError();
8410 Entry = MaybeEntry.get();
8411 }
8412
8413 if (Entry.Kind != BitstreamEntry::SubBlock ||
8414 Entry.ID != bitc::MODULE_BLOCK_ID)
8415 return error("Malformed block");
8416 }
8417
8418 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
8419 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8420 if (Error Err = Stream.SkipBlock())
8421 return std::move(Err);
8422
8423 F.Mods.push_back({Stream.getBitcodeBytes().slice(
8424 BCBegin, Stream.getCurrentByteNo() - BCBegin),
8425 Buffer.getBufferIdentifier(), IdentificationBit,
8426 ModuleBit});
8427 continue;
8428 }
8429
8430 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
8431 Expected<StringRef> Strtab =
8433 if (!Strtab)
8434 return Strtab.takeError();
8435 // This string table is used by every preceding bitcode module that does
8436 // not have its own string table. A bitcode file may have multiple
8437 // string tables if it was created by binary concatenation, for example
8438 // with "llvm-cat -b".
8439 for (BitcodeModule &I : llvm::reverse(F.Mods)) {
8440 if (!I.Strtab.empty())
8441 break;
8442 I.Strtab = *Strtab;
8443 }
8444 // Similarly, the string table is used by every preceding symbol table;
8445 // normally there will be just one unless the bitcode file was created
8446 // by binary concatenation.
8447 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
8448 F.StrtabForSymtab = *Strtab;
8449 continue;
8450 }
8451
8452 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
8453 Expected<StringRef> SymtabOrErr =
8455 if (!SymtabOrErr)
8456 return SymtabOrErr.takeError();
8457
8458 // We can expect the bitcode file to have multiple symbol tables if it
8459 // was created by binary concatenation. In that case we silently
8460 // ignore any subsequent symbol tables, which is fine because this is a
8461 // low level function. The client is expected to notice that the number
8462 // of modules in the symbol table does not match the number of modules
8463 // in the input file and regenerate the symbol table.
8464 if (F.Symtab.empty())
8465 F.Symtab = *SymtabOrErr;
8466 continue;
8467 }
8468
8469 if (Error Err = Stream.SkipBlock())
8470 return std::move(Err);
8471 continue;
8472 }
8474 if (Error E = Stream.skipRecord(Entry.ID).takeError())
8475 return std::move(E);
8476 continue;
8477 }
8478 }
8479}
8480
8481/// Get a lazy one-at-time loading module from bitcode.
8482///
8483/// This isn't always used in a lazy context. In particular, it's also used by
8484/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
8485/// in forward-referenced functions from block address references.
8486///
8487/// \param[in] MaterializeAll Set to \c true if we should materialize
8488/// everything.
8490BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
8491 bool ShouldLazyLoadMetadata, bool IsImporting,
8492 ParserCallbacks Callbacks) {
8493 BitstreamCursor Stream(Buffer);
8494
8495 std::string ProducerIdentification;
8496 if (IdentificationBit != -1ull) {
8497 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8498 return std::move(JumpFailed);
8499 if (Error E =
8500 readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8501 return std::move(E);
8502 }
8503
8504 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8505 return std::move(JumpFailed);
8506 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8507 Context);
8508
8509 std::unique_ptr<Module> M =
8510 std::make_unique<Module>(ModuleIdentifier, Context);
8511 M->setMaterializer(R);
8512
8513 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8514 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8515 IsImporting, Callbacks))
8516 return std::move(Err);
8517
8518 if (MaterializeAll) {
8519 // Read in the entire module, and destroy the BitcodeReader.
8520 if (Error Err = M->materializeAll())
8521 return std::move(Err);
8522 } else {
8523 // Resolve forward references from blockaddresses.
8524 if (Error Err = R->materializeForwardReferencedFunctions())
8525 return std::move(Err);
8526 }
8527
8528 return std::move(M);
8529}
8530
8531Expected<std::unique_ptr<Module>>
8532BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8533 bool IsImporting, ParserCallbacks Callbacks) {
8534 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8535 Callbacks);
8536}
8537
8538// Parse the specified bitcode buffer and merge the index into CombinedIndex.
8539// We don't use ModuleIdentifier here because the client may need to control the
8540// module path used in the combined summary (e.g. when reading summaries for
8541// regular LTO modules).
8543 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8544 std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8545 BitstreamCursor Stream(Buffer);
8546 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8547 return JumpFailed;
8548
8549 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8550 ModulePath, IsPrevailing);
8551 return R.parseModule();
8552}
8553
8554// Parse the specified bitcode buffer, returning the function info index.
8556 BitstreamCursor Stream(Buffer);
8557 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8558 return std::move(JumpFailed);
8559
8560 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8561 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8562 ModuleIdentifier, 0);
8563
8564 if (Error Err = R.parseModule())
8565 return std::move(Err);
8566
8567 return std::move(Index);
8568}
8569
8572 if (Error Err = Stream.EnterSubBlock(ID))
8573 return std::move(Err);
8574
8576 while (true) {
8577 BitstreamEntry Entry;
8578 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8579 return std::move(E);
8580
8581 switch (Entry.Kind) {
8582 case BitstreamEntry::SubBlock: // Handled for us already.
8584 return error("Malformed block");
8586 // If no flags record found, return both flags as false.
8587 return std::make_pair(false, false);
8588 }
8590 // The interesting case.
8591 break;
8592 }
8593
8594 // Look for the FS_FLAGS record.
8595 Record.clear();
8596 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8597 if (!MaybeBitCode)
8598 return MaybeBitCode.takeError();
8599 switch (MaybeBitCode.get()) {
8600 default: // Default behavior: ignore.
8601 break;
8602 case bitc::FS_FLAGS: { // [flags]
8603 uint64_t Flags = Record[0];
8604 // Scan flags.
8605 assert(Flags <= 0x7ff && "Unexpected bits in flag");
8606
8607 bool EnableSplitLTOUnit = Flags & 0x8;
8608 bool UnifiedLTO = Flags & 0x200;
8609 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8610 }
8611 }
8612 }
8613 llvm_unreachable("Exit infinite loop");
8614}
8615
8616// Check if the given bitcode buffer contains a global value summary block.
8618 BitstreamCursor Stream(Buffer);
8619 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8620 return std::move(JumpFailed);
8621
8622 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8623 return std::move(Err);
8624
8625 while (true) {
8627 if (Error E = Stream.advance().moveInto(Entry))
8628 return std::move(E);
8629
8630 switch (Entry.Kind) {
8632 return error("Malformed block");
8634 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8635 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8636
8638 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID ||
8641 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID);
8642 if (!Flags)
8643 return Flags.takeError();
8644 BitcodeLTOInfo LTOInfo;
8645 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8646 LTOInfo.IsThinLTO = (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID);
8647 LTOInfo.HasSummary = true;
8648 return LTOInfo;
8649 }
8650
8651 // Ignore other sub-blocks.
8652 if (Error Err = Stream.SkipBlock())
8653 return std::move(Err);
8654 continue;
8655
8657 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8658 continue;
8659 else
8660 return StreamFailed.takeError();
8661 }
8662 }
8663}
8664
8667 if (!MsOrErr)
8668 return MsOrErr.takeError();
8669
8670 if (MsOrErr->size() != 1)
8671 return error("Expected a single module");
8672
8673 return (*MsOrErr)[0];
8674}
8675
8676Expected<std::unique_ptr<Module>>
8678 bool ShouldLazyLoadMetadata, bool IsImporting,
8679 ParserCallbacks Callbacks) {
8681 if (!BM)
8682 return BM.takeError();
8683
8684 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8685 Callbacks);
8686}
8687
8689 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8690 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8691 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8692 IsImporting, Callbacks);
8693 if (MOrErr)
8694 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8695 return MOrErr;
8696}
8697
8700 return getModuleImpl(Context, true, false, false, Callbacks);
8701 // TODO: Restore the use-lists to the in-memory state when the bitcode was
8702 // written. We must defer until the Module has been fully materialized.
8703}
8704
8707 ParserCallbacks Callbacks) {
8709 if (!BM)
8710 return BM.takeError();
8711
8712 return BM->parseModule(Context, Callbacks);
8713}
8714
8716 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8717 if (!StreamOrErr)
8718 return StreamOrErr.takeError();
8719
8720 return readTriple(*StreamOrErr);
8721}
8722
8724 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8725 if (!StreamOrErr)
8726 return StreamOrErr.takeError();
8727
8728 return hasObjCCategory(*StreamOrErr);
8729}
8730
8732 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8733 if (!StreamOrErr)
8734 return StreamOrErr.takeError();
8735
8736 return readIdentificationCode(*StreamOrErr);
8737}
8738
8740 ModuleSummaryIndex &CombinedIndex) {
8742 if (!BM)
8743 return BM.takeError();
8744
8745 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8746}
8747
8751 if (!BM)
8752 return BM.takeError();
8753
8754 return BM->getSummary();
8755}
8756
8759 if (!BM)
8760 return BM.takeError();
8761
8762 return BM->getLTOInfo();
8763}
8764
8767 bool IgnoreEmptyThinLTOIndexFile) {
8770 if (!FileOrErr)
8771 return errorCodeToError(FileOrErr.getError());
8772 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8773 return nullptr;
8774 return getModuleSummaryIndex(**FileOrErr);
8775}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static bool isConstant(const MachineInstr &MI)
AMDGPU Prepare AGPR Alloc
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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)
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
Machine Check Debug Module
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
PowerPC Reduce CR logical Operation
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
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
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
PointerType * getType() const
Overload to return most specific pointer type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:143
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:138
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:187
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:158
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
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
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
bool empty() const
Definition BasicBlock.h:481
const Instruction & back() const
Definition BasicBlock.h:484
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:386
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
Definition ValueList.cpp:50
void push_back(Value *V, unsigned TypeID)
Definition ValueList.h:52
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Definition ValueList.h:81
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
Definition ValueList.cpp:21
void shrinkTo(unsigned N)
Definition ValueList.h:76
unsigned getTypeID(unsigned ValNo) const
Definition ValueList.h:65
unsigned size() const
Definition ValueList.h:48
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
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.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
Definition ModRef.h: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:676
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
Definition InstrTypes.h:782
bool isIntPredicate() const
Definition InstrTypes.h:783
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
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 ...
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...
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...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h: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.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1274
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
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.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool erase(const KeyT &Val)
Definition DenseMap.h:322
unsigned size() const
Definition DenseMap.h:110
bool empty() const
Definition DenseMap.h:109
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
iterator end()
Definition DenseMap.h:81
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:233
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h: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
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:803
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
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()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:598
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:655
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
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)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
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:566
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
std::vector< ConstraintInfo > ConstraintInfoVector
Definition InlineAsm.h:123
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool isCast() const
bool isBinaryOp() const
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
bool isUnaryOp() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:319
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:618
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:119
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:103
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
Definition ModRef.h:125
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:141
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:146
static MemoryEffectsBase createFromIntValue(uint32_t Data)
Definition ModRef.h:177
static MemoryEffectsBase writeOnly()
Definition ModRef.h:130
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:151
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:158
static MemoryEffectsBase none()
Definition ModRef.h:120
static MemoryEffectsBase unknown()
Definition ModRef.h:115
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:281
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:296
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:303
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition Module.cpp:616
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:353
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef first() const
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:702
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
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
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:914
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
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:297
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
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
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
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
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
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
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.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
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:382
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
Definition GOFF.h:28
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:55
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ TYPE_CODE_TARGET_TYPE
@ TYPE_CODE_STRUCT_ANON
@ TYPE_CODE_STRUCT_NAME
@ TYPE_CODE_OPAQUE_POINTER
@ TYPE_CODE_FUNCTION_OLD
@ TYPE_CODE_STRUCT_NAMED
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_CFI_FUNCTION_DECLS
@ FS_COMBINED_CALLSITE_INFO
@ FS_COMBINED_ALLOC_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ BITCODE_CURRENT_EPOCH
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_BLOCKADDRESS
@ CST_CODE_NO_CFI_VALUE
@ CST_CODE_CE_SHUFVEC_EX
@ CST_CODE_CE_EXTRACTELT
@ CST_CODE_INLINEASM_OLD
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_CE_SHUFFLEVEC
@ CST_CODE_WIDE_INTEGER
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_INSERTELT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_SWIFT_ERROR
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_NO_CALLBACK
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_INLINE_HINT
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_MUSTPROGRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_INITIALIZES
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_SKIP_PROFILE
@ ATTR_KIND_ELEMENTTYPE
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NO_DUPLICATE
@ ATTR_KIND_ALLOC_ALIGN
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_NO_RED_ZONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_VSCALE_RANGE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_SPECULATABLE
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ ATTR_KIND_PREALLOCATED
@ ATTR_KIND_SWIFT_ASYNC
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ METADATA_KIND_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ METADATA_ATTACHMENT_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ MODULE_STRTAB_BLOCK_ID
@ VALUE_SYMTAB_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_VERSION
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_DATALAYOUT
@ MODULE_CODE_GLOBALVAR
@ MODULE_CODE_ALIAS_OLD
@ MODULE_CODE_VSTOFFSET
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_RESUME
@ FUNC_CODE_INST_CALLBR
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_VSELECT
@ FUNC_CODE_INST_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_INST_INVOKE
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_SWITCH
@ FUNC_CODE_INST_ALLOCA
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_INST_SELECT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_FREEZE
@ FUNC_CODE_INST_CMPXCHG
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
constexpr double e
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp: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:829
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
Definition Value.h:56
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1655
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:2472
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
AllocFnKind
Definition Attributes.h: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.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
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:632
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:296
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2053
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).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:1968
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:302
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:406
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:279
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
Definition Error.h:221
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
Definition Alignment.h:209
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp: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.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:869
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
Definition Bitfields.h:207
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
static constexpr unsigned RelBlockFreqBits
The value stored in RelBlockFreq has to be interpreted as the digits of a scaled number with a scale ...
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
GetContainedTypeIDTy GetContainedTypeID
std::optional< MDTypeCallbackTy > MDType
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...