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