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