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