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