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